answer
stringlengths 17
10.2M
|
|---|
package com.luanthanhthai.android.liteworkouttimer;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.concurrent.TimeUnit;
public class TimerFragment extends Fragment implements View.OnClickListener {
private Button mPauseButton;
private TextView mMinutesView;
private TextView mSecondsView;
private TextView mColonView;
private ViewGroup timerClockView;
private ViewGroup keypadPanel;
private ViewGroup pauseBarPanel;
private int[] keypadButtons = {
R.id.button_0, R.id.button_1, R.id.button_2,
R.id.button_3, R.id.button_4, R.id.button_5,
R.id.button_6, R.id.button_7, R.id.button_8,
R.id.button_9
};
private MyTimer userInputTimer;
private final long countDownInterval = 250;
private long totalMillis = 0;
private long pausedMillis = 0;
private int finalMinutesValue = 0;
private int finalSecondsValue = 0;
private final int timerColor = R.color.Black_opacity_87;
private final int delayColor = R.color.Black_opacity_54;
private final int restColor = R.color.LightBlue_500;
private boolean firstDigitHasValue = false;
private boolean enableRepeat = true;
private boolean enableDelay = true;
private boolean isDelayRunning = false;
private boolean isStartPressed = false;
private long timerRestMillis = 4 * 1000;
private long timerDelayMillis = 3 * 1000;
public static TimerFragment newInstance() {
return new TimerFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public void configureTimerViews(View view) {
// The sliding panels
keypadPanel = (ViewGroup) view.findViewById(R.id.start_button_bar_with_keypad);
pauseBarPanel = (ViewGroup) view.findViewById(R.id.pause_button_bar);
// Timer buttons
Button startButton = (Button) view.findViewById(R.id.button_start);
startButton.setOnClickListener(this);
Button restButton = (Button) view.findViewById(R.id.button_rest);
restButton.setOnClickListener(this);
mPauseButton = (Button) view.findViewById(R.id.button_pause);
mPauseButton.setOnClickListener(this);
Button restartButton = (Button) view.findViewById(R.id.button_restart);
restartButton.setOnClickListener(this);
Button resetButton = (Button) view.findViewById(R.id.button_reset);
resetButton.setOnClickListener(this);
// Keypad numeric buttons
for (int keypadId : keypadButtons) {
Button keypadButtonId = (Button) view.findViewById(keypadId);
keypadButtonId.setOnClickListener(keypadListener);
}
// Keypad backspace button
ImageButton mDelButton = (ImageButton) view.findViewById(R.id.button_del);
mDelButton.setOnClickListener(this);
// Digital timer view
mMinutesView = (TextView) view.findViewById(R.id.timer_minutes_text_view);
mSecondsView = (TextView) view.findViewById(R.id.timer_seconds_text_view);
mColonView = (TextView) view.findViewById(R.id.timer_colon_view);
mMinutesView.setOnClickListener(timerTextViewListener);
mSecondsView.setOnClickListener(timerTextViewListener);
// Timer text view
timerClockView = (ViewGroup) view.findViewById(R.id.timer_clock_view);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_timer, container, false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
configureTimerViews(view);
// For backwards compatibility set this
// near the end
setHasOptionsMenu(true);
return view;
}
public class MyTimer extends CountDownTimer {
public MyTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
pausedMillis = millisUntilFinished;
String FORMAT = "%02d";
mMinutesView.setText(String.format(FORMAT,
millisToMinutes(millisUntilFinished)));
mSecondsView.setText(String.format(FORMAT,
getRemainderSeconds(millisUntilFinished)));
}
@Override
public void onFinish() {
if (enableRepeat && isStartPressed) {
if (isDelayRunning) {
isDelayRunning = false;
setTimer(totalMillis);
switchTimeColor(timerColor);
} else {
isDelayRunning = true;
setTimer(timerDelayMillis);
switchTimeColor(delayColor);
}
} else {
timerReset();
}
}
}
public void setTimer(long runTime) {
userInputTimer = new MyTimer(runTime, countDownInterval);
userInputTimer.start();
}
public void runTimer() {
if (isStartPressed) {
if (enableDelay) {
isDelayRunning = true;
userInputTimer = new MyTimer(timerDelayMillis, countDownInterval);
switchTimeColor(delayColor);
} else {
isDelayRunning = false;
userInputTimer = new MyTimer(totalMillis, countDownInterval);
switchTimeColor(timerColor);
}
} else {
userInputTimer = new MyTimer(timerRestMillis, countDownInterval);
}
userInputTimer.start();
}
public long millisToMinutes(long millis) {
return TimeUnit.MILLISECONDS.toMinutes(millis);
}
// Millis to seconds - minutes to seconds
public long getRemainderSeconds(long millisUntilFinished) {
return TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(millisToMinutes(millisUntilFinished));
}
public long clockTimeToMillis(int minutes, int seconds) {
return TimeUnit.MINUTES.toMillis(minutes) +
TimeUnit.SECONDS.toMillis(seconds);
}
View.OnClickListener keypadListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedButton = v.getId();
for (int digit = 0; digit < keypadButtons.length; ++digit) {
if (selectedButton == keypadButtons[digit]) {
if (mMinutesView.isSelected()) {
if (!firstDigitHasValue) {
setTimerClock(mMinutesView, true, digit);
} else {
setTimerClock(mMinutesView, false, digit);
}
} else if (mSecondsView.isSelected()) {
if (!firstDigitHasValue) {
setTimerClock(mSecondsView, true, digit);
} else {
setTimerClock(mSecondsView, false, digit);
}
}
return;
}
}
}
};
public void setTimerClock(TextView selectedTimerView, boolean firstDigitEntered, int input) {
if (firstDigitEntered) {
firstDigitHasValue = true;
setFirstDigit(selectedTimerView, input);
} else {
firstDigitHasValue = false;
setFinalValue(selectedTimerView, input);
if (selectedTimerView == mMinutesView) {
selectTimerTextView(mSecondsView, mMinutesView);
}
}
totalMillis = clockTimeToMillis(finalMinutesValue, finalSecondsValue);
selectedTimerView.setText(String.format("%02d", getFinalValue(selectedTimerView)));
}
public void setFirstDigit(TextView selectedTimerView, int value) {
if (selectedTimerView == mMinutesView) {
finalMinutesValue = value;
} else {
finalSecondsValue = value;
}
}
public void setFinalValue(TextView selectedTimerView, int value) {
if (selectedTimerView == mMinutesView) {
finalMinutesValue = checkValidValue(
concatenateDigits(finalMinutesValue, value));
} else {
finalSecondsValue = checkValidValue(
concatenateDigits(finalSecondsValue, value));
}
}
public int getFinalValue(TextView selectedTimerView) {
if (selectedTimerView == mMinutesView) {
return finalMinutesValue;
} else {
return finalSecondsValue;
}
}
public int concatenateDigits(int second, int first) {
return (second * 10) + first;
}
public int checkValidValue(int userInput) {
if (userInput < 60) {
return userInput;
} else {
return 59;
}
}
View.OnClickListener timerTextViewListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView selectedView = (TextView) v;
if (selectedView == mMinutesView) {
selectTimerTextView(mMinutesView, mSecondsView);
} else if (selectedView == mSecondsView) {
selectTimerTextView(mSecondsView, mMinutesView);
}
}
};
public void selectTimerTextView(TextView selectView, TextView deselectView) {
selectView.setSelected(true);
deselectView.setSelected(false);
selectView.setTextColor(getColor(getContext(), restColor));
deselectView.setTextColor(getColor(getContext(), timerColor));
firstDigitHasValue = false;
}
public void switchTimeColor(int colorId) {
mMinutesView.setTextColor(getColor(getContext(), colorId));
mColonView.setTextColor(getColor(getContext(), colorId));
mSecondsView.setTextColor(getColor(getContext(), colorId));
}
@SuppressWarnings("deprecation")
public static int getColor(Context context, int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= Build.VERSION_CODES.M) {
return ContextCompat.getColor(context, id);
} else {
// getColor deprecated on Android Marshmallow(API 23)
return context.getResources().getColor(id);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_start:
timerStart();
break;
case R.id.button_rest:
timerRest();
break;
case R.id.button_pause:
timerPause();
break;
case R.id.button_restart:
timerRestart();
break;
case R.id.button_reset:
timerReset();
break;
case R.id.button_del:
// Backspace insert later
break;
default:
break;
}
}
public void timerStart() {
animSlidePanelDown(keypadPanel);
animSlidePanelUp(pauseBarPanel);
//animSlideClockToCenter(timerClockView);
isStartPressed = true;
runTimer();
}
public void timerRest() {
animSlidePanelDown(keypadPanel);
animSlidePanelUp(pauseBarPanel);
//animSlideClockToCenter(timerClockView);
isStartPressed = false;
runTimer();
switchTimeColor(restColor);
}
public void timerPause() {
mPauseButton.setVisibility(View.INVISIBLE);
userInputTimer.cancel();
}
public void timerRestart() {
mPauseButton.setVisibility(View.VISIBLE);
setTimer(pausedMillis);
}
public void timerReset() {
animSlideClockUp(timerClockView);
animSlidePanelDown(pauseBarPanel);
animSlidePanelUp(keypadPanel);
mPauseButton.setVisibility(View.VISIBLE);
userInputTimer.cancel();
mMinutesView.setText(String.format("%02d", finalMinutesValue));
mSecondsView.setText(String.format("%02d", finalSecondsValue));
switchTimeColor(timerColor);
}
public void animSlideClockToCenter(ViewGroup slideClockToCenter) {
Animation slideToCenter = AnimationUtils.loadAnimation(getContext(), R.anim.timer_clock_slide_to_center);
slideClockToCenter.startAnimation(slideToCenter);
}
public void animSlideClockUp(ViewGroup slideClockUp) {
Animation slideLayoutUp = AnimationUtils.loadAnimation(getContext(), R.anim.timer_clock_slide_up);
slideClockUp.startAnimation(slideLayoutUp);
}
public void animSlidePanelUp(ViewGroup slidePanelUp) {
Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.panel_slide_up);
slidePanelUp.startAnimation(slideUp);
slidePanelUp.setVisibility(View.VISIBLE);
}
public void animSlidePanelDown(ViewGroup slidePanelDown) {
Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.panel_slide_down);
slidePanelDown.startAnimation(slideDown);
slidePanelDown.setVisibility(View.GONE);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_timer, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment;
switch (item.getItemId()) {
case R.id.menu_ic_create_routine:
fragment = new CreateRoutinesFragment();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
return true;
case R.id.menu_ic_settings:
fragment = new SettingsFragment();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package info.nightscout.androidaps.plugins.PumpCombo;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.Date;
import de.jotomo.ruffy.spi.BasalProfile;
import de.jotomo.ruffy.spi.BolusProgressReporter;
import de.jotomo.ruffy.spi.CommandResult;
import de.jotomo.ruffy.spi.PumpState;
import de.jotomo.ruffy.spi.PumpWarningCodes;
import de.jotomo.ruffy.spi.RuffyCommands;
import de.jotomo.ruffy.spi.WarningOrErrorCode;
import de.jotomo.ruffy.spi.history.Bolus;
import de.jotomo.ruffy.spi.history.PumpHistory;
import de.jotomo.ruffy.spi.history.PumpHistoryRequest;
import de.jotomo.ruffy.spi.history.Tbr;
import de.jotomo.ruffyscripter.RuffyCommandsV1Impl;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.PumpCombo.events.EventComboPumpUpdateGUI;
import info.nightscout.utils.DateUtil;
import static de.jotomo.ruffy.spi.BolusProgressReporter.State.FINISHED;
public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(ComboPlugin.class);
private static ComboPlugin plugin = null;
private boolean fragmentEnabled = false;
private boolean fragmentVisible = false;
private final static PumpDescription pumpDescription = new PumpDescription();
static {
// these properties can't be changed on the pump, some via desktop configuration software
pumpDescription.isBolusCapable = true;
pumpDescription.bolusStep = 0.1d;
pumpDescription.isExtendedBolusCapable = false;
pumpDescription.extendedBolusStep = 0.1d;
pumpDescription.extendedBolusDurationStep = 15;
pumpDescription.extendedBolusMaxDuration = 12 * 60;
pumpDescription.isTempBasalCapable = true;
pumpDescription.tempBasalStyle = PumpDescription.PERCENT;
pumpDescription.maxTempPercent = 500;
pumpDescription.tempPercentStep = 10;
pumpDescription.tempDurationStep = 15;
pumpDescription.tempMaxDuration = 24 * 60;
pumpDescription.isSetBasalProfileCapable = false;
pumpDescription.basalStep = 0.01d;
pumpDescription.basalMinimumRate = 0.0d;
pumpDescription.isRefillingCapable = true;
}
@NonNull
private final RuffyCommands ruffyScripter;
private static ComboPump pump = new ComboPump();
private volatile boolean bolusInProgress;
private volatile boolean cancelBolus;
private Bolus lastRequestedBolus;
private long pumpHistoryLastChecked;
public static ComboPlugin getPlugin() {
if (plugin == null)
plugin = new ComboPlugin();
return plugin;
}
private static PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult()
.success(false).enacted(false).comment(MainApp.sResources.getString(R.string.combo_pump_unsupported_operation));
private ComboPlugin() {
ruffyScripter = RuffyCommandsV1Impl.getInstance(MainApp.instance());
}
public ComboPump getPump() {
return pump;
}
@Override
public String getFragmentClass() {
return ComboFragment.class.getName();
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.combopump);
}
@Override
public String getNameShort() {
String name = MainApp.sResources.getString(R.string.combopump_shortname);
if (!name.trim().isEmpty()) {
//only if translation exists
return name;
}
// use long name as fallback
return getName();
}
String getStateSummary() {
PumpState ps = pump.state;
if (ps.activeAlert != null) {
return ps.activeAlert.errorCode != null
? "E" + ps.activeAlert.errorCode + ": " + ps.activeAlert.message
: "W" + ps.activeAlert.warningCode + ": " + ps.activeAlert.message;
} else if (ps.menu == null)
return MainApp.sResources.getString(R.string.combo_pump_state_disconnected);
else if (ps.suspended && (ps.batteryState == PumpState.EMPTY || ps.insulinState == PumpState.EMPTY))
return MainApp.sResources.getString(R.string.combo_pump_state_suspended_due_to_error);
else if (ps.suspended)
return MainApp.sResources.getString(R.string.combo_pump_state_suspended_by_user);
return MainApp.sResources.getString(R.string.combo_pump_state_running);
}
@Override
public boolean isEnabled(int type) {
if (type == PluginBase.PUMP) return fragmentEnabled;
else if (type == PluginBase.CONSTRAINTS) return fragmentEnabled;
return false;
}
@Override
public boolean isVisibleInTabs(int type) {
return type == PUMP && fragmentVisible;
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public boolean hasFragment() {
return true;
}
@Override
public boolean showInList(int type) {
return true;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == PUMP) this.fragmentEnabled = fragmentEnabled;
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == PUMP) this.fragmentVisible = fragmentVisible;
}
@Override
public int getPreferencesId() {
return R.xml.pref_combo;
}
@Override
public int getType() {
return PluginBase.PUMP;
}
@Override
public boolean isInitialized() {
return pump.initialized;
}
@Override
public boolean isSuspended() {
return pump.state.suspended;
}
@Override
public boolean isBusy() {
return ruffyScripter.isPumpBusy();
}
@Override
public boolean isConnected() {
return true;
}
@Override
public boolean isConnecting() {
return false;
}
@Override
public void connect(String reason) {
// ruffyscripter establishes a connection as needed
}
@Override
public void disconnect(String reason) {
ruffyScripter.disconnect();
}
@Override
public void stopConnecting() {
// we're not doing that
}
@Override
public synchronized PumpEnactResult setNewBasalProfile(Profile profile) {
if (!isInitialized()) {
log.error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.sResources.getString(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
return new PumpEnactResult().success(false).enacted(false).comment(MainApp.sResources.getString(R.string.pumpNotInitializedProfileNotSet));
}
BasalProfile requestedBasalProfile = convertProfileToComboProfile(profile);
if (pump.basalProfile.equals(requestedBasalProfile)) {
//dismiss previously "FAILED" overview notifications
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
return new PumpEnactResult().success(true).enacted(false);
}
CommandResult setResult = runCommand(MainApp.sResources.getString(R.string.combo_activity_setting_basal_profile), 2,
() -> ruffyScripter.setBasalProfile(requestedBasalProfile));
if (!setResult.success) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.sResources.getString(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
return new PumpEnactResult().success(false).enacted(false);
}
/* don't re-read basal profile to not trigger pump bug; setBasalProfile command checks the total at the end, which must suffice
CommandResult readResult = runCommand(MainApp.sResources.getString(R.string.combo_activity_setting_basal_profile), 2,
ruffyScripter::readBasalProfile);
*/
pump.basalProfile = requestedBasalProfile;
//dismiss previously "FAILED" overview notifications
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
//issue success notification
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.sResources.getString(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
return new PumpEnactResult().success(true).enacted(true);
}
@Override
public boolean isThisProfileSet(Profile profile) {
if (!isInitialized()) {
// This is called too soon (for the Combo) on startup, so ignore this.
// The Combo init (refreshDataFromPump) will read the profile and update the pump's
// profile if the pref is set;
return true;
}
return pump.basalProfile.equals(convertProfileToComboProfile(profile));
}
@NonNull
private BasalProfile convertProfileToComboProfile(Profile profile) {
BasalProfile basalProfile = new BasalProfile();
for (int i = 0; i < 24; i++) {
double rate = profile.getBasal(Integer.valueOf(i * 60 * 60));
/*The Combo pump does hava a different granularity for basal rate:
* 0.01 - if below 1U/h
* 0.05 - if above 1U/h
* */
if (rate < 1) {
//round to 0.01 granularity;
rate = Math.round(rate / 0.01) * 0.01;
} else {
//round to 0.05 granularity;
rate = Math.round(rate / 0.05) * 0.05;
}
basalProfile.hourlyRates[i] = rate;
}
return basalProfile;
}
@NonNull
@Override
public Date lastDataTime() {
return new Date(pump.lastSuccessfulCmdTime);
}
/**
* Runs pump initializing if needed, checks for boluses given on the pump, updates the
* reservoir level and checks the running TBR on the pump.
*/
@Override
public synchronized void getPumpStatus() {
log.debug("getPumpStatus called");
if (!pump.initialized) {
long maxWait = System.currentTimeMillis() + 15 * 1000;
while (!ruffyScripter.isPumpAvailable()) {
log.debug("Waiting for ruffy service to come up ...");
SystemClock.sleep(100);
if (System.currentTimeMillis() > maxWait) {
log.debug("ruffy service unavailable, wtf");
return;
}
}
}
CommandResult stateResult = runCommand(pump.initialized ? MainApp.sResources.getString(R.string.combo_pump_action_refreshing) : MainApp.sResources.getString(R.string.combo_pump_action_initializing),
1, ruffyScripter::readPumpState);
if (!stateResult.success) {
return;
}
// read basal profile into cache and update pump profile if needed
if (!pump.initialized) {
CommandResult readBasalResult = runCommand("Reading basal profile", 2, ruffyScripter::readBasalProfile);
if (!readBasalResult.success) {
return;
}
pump.basalProfile = readBasalResult.basalProfile;
Profile profile = MainApp.getConfigBuilder().getProfile();
if (!pump.basalProfile.equals(convertProfileToComboProfile(profile))) {
setNewBasalProfile(profile);
}
}
if (!pump.initialized) {
pump.initialized = true;
MainApp.bus().post(new EventInitializationChanged());
}
// ComboFragment updates state fully only after the pump has initialized,
// this fetches state again and updates the UI proper
runCommand(null, 0, ruffyScripter::readPumpState);
}
private void updateLocalData(CommandResult result) {
if (result.state.menu != null) {
pump.state = result.state;
}
MainApp.bus().post(new EventComboPumpUpdateGUI());
}
@Override
public double getBaseBasalRate() {
int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
return pump.basalProfile.hourlyRates[currentHour];
}
private static BolusProgressReporter nullBolusProgressReporter = (state, percent, delivered) -> {
};
private static BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> {
EventOverviewBolusProgress event = EventOverviewBolusProgress.getInstance();
switch (state) {
case PROGRAMMING:
event.status = MainApp.sResources.getString(R.string.combo_programming_bolus);
break;
case DELIVERING:
event.status = String.format(MainApp.sResources.getString(R.string.bolusdelivering), delivered);
break;
case DELIVERED:
event.status = String.format(MainApp.sResources.getString(R.string.bolusdelivered), delivered);
break;
case STOPPING:
event.status = MainApp.sResources.getString(R.string.bolusstopping);
break;
case STOPPED:
event.status = MainApp.sResources.getString(R.string.bolusstopped);
break;
case FINISHED:
// no state, just percent below to close bolus progress dialog
break;
}
event.percent = percent;
MainApp.bus().post(event);
};
/**
* Updates Treatment records with carbs and boluses and delivers a bolus if needed
*/
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
try {
if (detailedBolusInfo.insulin == 0 && detailedBolusInfo.carbs == 0) {
// neither carbs nor bolus requested
log.error("deliverTreatment: Invalid input");
return new PumpEnactResult().success(false).enacted(false)
.bolusDelivered(0d).carbsDelivered(0d)
.comment(MainApp.instance().getString(R.string.danar_invalidinput));
} else if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it
return deliverBolus(detailedBolusInfo);
} else {
// no bolus required, carb only treatment
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
bolusingEvent.percent = 100;
MainApp.bus().post(bolusingEvent);
return new PumpEnactResult().success(true).enacted(true)
.bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs)
.comment(MainApp.instance().getString(R.string.virtualpump_resultok));
}
} finally {
MainApp.bus().post(new EventComboPumpUpdateGUI());
}
}
@NonNull
private PumpEnactResult deliverBolus(final DetailedBolusInfo detailedBolusInfo) {
// guard against boluses issued multiple times within a minute
if (lastRequestedBolus != null
&& Math.abs(lastRequestedBolus.amount - detailedBolusInfo.insulin) < 0.01
&& lastRequestedBolus.timestamp + 60 * 1000 > System.currentTimeMillis()) {
log.error("Bolus delivery failure at stage 0", new Exception());
return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.sResources.getString(R.string.bolus_frequency_exceeded));
}
lastRequestedBolus = new Bolus(System.currentTimeMillis(), detailedBolusInfo.insulin, true);
try {
pump.activity = MainApp.sResources.getString(R.string.combo_pump_action_bolusing, detailedBolusInfo.insulin);
MainApp.bus().post(new EventComboPumpUpdateGUI());
if (cancelBolus) {
return new PumpEnactResult().success(true).enacted(false);
}
// start bolus delivery
bolusInProgress = true;
CommandResult bolusCmdResult = runCommand(null, 0,
() -> ruffyScripter.deliverBolus(detailedBolusInfo.insulin,
detailedBolusInfo.isSMB ? nullBolusProgressReporter : bolusProgressReporter));
bolusInProgress = false;
if (bolusCmdResult.delivered > 0) {
detailedBolusInfo.insulin = bolusCmdResult.delivered;
detailedBolusInfo.source = Source.USER;
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
}
return new PumpEnactResult()
.success(bolusCmdResult.success)
.enacted(bolusCmdResult.delivered > 0)
.bolusDelivered(bolusCmdResult.delivered)
.carbsDelivered(detailedBolusInfo.carbs);
} finally {
// BolusCommand.execute() intentionally doesn't close the progress dialog (indirectly
// by reporting 100% progress) if an error occurred so it stays open while the connection
// was re-established if needed and/or this method did recovery
bolusProgressReporter.report(FINISHED, 100, 0);
pump.activity = null;
MainApp.bus().post(new EventComboPumpUpdateGUI());
MainApp.bus().post(new EventRefreshOverview("Combo Bolus"));
cancelBolus = false;
}
}
@Override
public void stopBolusDelivering() {
if (bolusInProgress) {
ruffyScripter.cancelBolus();
}
cancelBolus = true;
}
// Note: AAPS calls this solely to enact OpenAPS suggestions
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, boolean force) {
// the force parameter isn't used currently since we always set the tbr - there might be room for optimization to
// first test the currently running tbr and only change it if it differs (as the DanaR plugin does).
// This approach might have other issues though (what happens if the tbr which wasn't re-set to the new value
// (and thus still has the old duration of e.g. 1 min) expires?)
log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min.");
int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10);
if (unroundedPercentage != roundedPercentage) {
log.debug("Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%");
}
return setTempBasalPercent(roundedPercentage, durationInMinutes);
}
// Note: AAPS calls this directly only for setting a temp basal issued by the user
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes) {
log.debug("setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min");
int adjustedPercent = percent;
if (adjustedPercent > pumpDescription.maxTempPercent) {
log.debug("Reducing requested TBR to the maximum support by the pump: " + percent + " -> " + pumpDescription.maxTempPercent);
adjustedPercent = pumpDescription.maxTempPercent;
}
if (adjustedPercent % 10 != 0) {
Long rounded = Math.round(adjustedPercent / 10d) * 10;
log.debug("Rounded requested percentage:" + adjustedPercent + " -> " + rounded);
adjustedPercent = rounded.intValue();
}
// do a soft TBR-cancel when requested rate was rounded to 100% (>94% && <104%)
if (adjustedPercent == 100) {
return cancelTempBasal(false);
}
int finalAdjustedPercent = adjustedPercent;
CommandResult commandResult = runCommand(MainApp.sResources.getString(R.string.combo_pump_action_setting_tbr, percent, durationInMinutes),
3, () -> ruffyScripter.setTbr(finalAdjustedPercent, durationInMinutes));
if (!commandResult.success) {
return new PumpEnactResult().success(false).enacted(false);
}
PumpState state = commandResult.state;
if (state.tbrActive && state.tbrPercent == percent
&& (state.tbrRemainingDuration == durationInMinutes || state.tbrRemainingDuration == durationInMinutes - 1)) {
TemporaryBasal tempStart = new TemporaryBasal();
tempStart.date = state.timestamp;
tempStart.durationInMinutes = durationInMinutes;
tempStart.percentRate = adjustedPercent;
tempStart.isAbsolute = false;
tempStart.source = Source.USER;
ConfigBuilderPlugin treatmentsInterface = MainApp.getConfigBuilder();
treatmentsInterface.addToHistoryTempBasal(tempStart);
MainApp.bus().post(new EventComboPumpUpdateGUI());
}
return new PumpEnactResult().success(true).enacted(true).isPercent(true)
.percent(state.tbrPercent).duration(state.tbrRemainingDuration);
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
return OPERATION_NOT_SUPPORTED;
}
@Override
public PumpEnactResult cancelTempBasal(boolean userRequested) {
log.debug("cancelTempBasal called");
final TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
if (userRequested) {
log.debug("cancelTempBasal: hard-cancelling TBR since user requested");
CommandResult commandResult = runCommand(MainApp.sResources.getString(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr);
if (!commandResult.state.tbrActive) {
TemporaryBasal tempBasal = new TemporaryBasal();
tempBasal.date = commandResult.state.timestamp;
tempBasal.durationInMinutes = 0;
tempBasal.source = Source.USER;
MainApp.getConfigBuilder().addToHistoryTempBasal(tempBasal);
return new PumpEnactResult().isTempCancel(true).success(true).enacted(true);
} else {
return new PumpEnactResult().success(false).enacted(false);
}
} else if (activeTemp == null) {
return new PumpEnactResult().success(true).enacted(false);
} else if ((activeTemp.percentRate >= 90 && activeTemp.percentRate <= 110) && activeTemp.getPlannedRemainingMinutes() <= 15) {
// Let fake neutral temp keep run (see below)
// Note that a connection to the pump is still opened, since the queue issues a getPumpStatus() call whenever an empty
// queue receives a new command. Probably not worth optimizing.
log.debug("cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins.");
return new PumpEnactResult().success(true).enacted(true)
.comment("cancelTempBasal skipping changing tbr since it already is at "
+ activeTemp.percentRate + "% and running for another "
+ activeTemp.getPlannedRemainingMinutes() + " mins.");
} else {
// Set a fake neutral temp to avoid TBR cancel alert. Decide 90% vs 110% based on
// on whether the TBR we're cancelling is above or below 100%.
final int percentage = (activeTemp.percentRate > 100) ? 110 : 90;
log.debug("cancelTempBasal: changing TBR to " + percentage + "% for 15 mins.");
return setTempBasalPercent(percentage, 15);
}
}
private interface CommandExecution {
CommandResult execute();
}
/**
* Runs a command, sets an activity if provided, retries if requested and updates fields
* concerned with last connection.
* NO history, reservoir level fields are updated, this make be done separately if desired.
*/
private synchronized CommandResult runCommand(String activity, int retries, CommandExecution commandExecution) {
CommandResult commandResult;
try {
if (activity != null) {
pump.activity = activity;
MainApp.bus().post(new EventComboPumpUpdateGUI());
}
if (!ruffyScripter.isConnected()) {
CommandResult preCheckError = runOnConnectChecks();
if (preCheckError != null) {
updateLocalData(preCheckError);
return preCheckError;
}
}
// Pass this to qeueue??
// hm, now that each PumpInterface method is basically one RuffyCommand again ....
commandResult = commandExecution.execute();
if (!commandResult.success && retries > 0) {
for (int retryAttempts = 1; !commandResult.success && retryAttempts <= retries; retryAttempts++) {
log.debug("Command was not successful, retries requested, doing retry #" + retryAttempts);
commandResult = commandExecution.execute();
}
}
for (Integer forwardedWarning : commandResult.forwardedWarnings) {
notifyAboutPumpWarning(new WarningOrErrorCode(forwardedWarning, null, null));
}
if (commandResult.success) {
pump.lastSuccessfulCmdTime = System.currentTimeMillis();
}
if (commandResult.success) {
updateLocalData(commandResult);
}
} finally {
if (activity != null) {
pump.activity = null;
MainApp.bus().post(new EventComboPumpUpdateGUI());
}
}
checkForUnsafeUsage(commandResult);
return commandResult;
}
/**
* Returns the command result of running ReadPumpState if it wasn't successful, indicating
* an error condition. Returns null otherwise.
*/
private CommandResult runOnConnectChecks() {
// connect, get status and check if an alarm is active
CommandResult preCheckResult = ruffyScripter.readPumpState();
if (!preCheckResult.success) {
return preCheckResult;
}
WarningOrErrorCode activeAlert = preCheckResult.state.activeAlert;
// note if multiple alerts are active this will and should fail; e.g. if pump was stopped
// due to empty cartridge alert, which might also trigger TBR cancelled alert
if (activeAlert != null) {
if (activeAlert.warningCode != null
&& (activeAlert.warningCode == PumpWarningCodes.CARTRIDGE_LOW ||
activeAlert.warningCode == PumpWarningCodes.BATTERY_LOW ||
activeAlert.warningCode == PumpWarningCodes.TBR_CANCELLED)) {
// turn benign warnings into notifications
notifyAboutPumpWarning(activeAlert);
ruffyScripter.confirmAlert(activeAlert.warningCode);
} else {
Notification notification = new Notification();
notification.date = new Date();
notification.id = Notification.COMBO_PUMP_ALARM;
notification.level = Notification.URGENT;
notification.text = MainApp.sResources.getString(R.string.combo_is_in_error_state);
MainApp.bus().post(new EventNewNotification(notification));
return preCheckResult.success(false);
}
}
checkAndResolveTbrMismatch(preCheckResult.state);
checkPumpTime(preCheckResult.state);
return null;
}
/** check pump time (main menu) and raise notification if clock is off by more than 2m
* (setting clock is not supported by ruffy) */
private void checkPumpTime(PumpState state) {
if (state.pumpTime != 0 && Math.abs(state.pumpTime - System.currentTimeMillis()) > 2 * 60 * 1000) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.sResources.getString(R.string.combo_notification_check_time_date), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
}
}
private void notifyAboutPumpWarning(WarningOrErrorCode activeAlert) {
if (activeAlert.warningCode == null ||
(!activeAlert.warningCode.equals(PumpWarningCodes.CARTRIDGE_LOW)
&& !activeAlert.warningCode.equals(PumpWarningCodes.BATTERY_LOW)
&& !activeAlert.warningCode.equals(PumpWarningCodes.TBR_CANCELLED))) {
throw new IllegalArgumentException(activeAlert.toString());
}
Notification notification = new Notification();
notification.date = new Date();
notification.id = Notification.COMBO_PUMP_ALARM;
notification.level = Notification.NORMAL;
if (activeAlert.warningCode == PumpWarningCodes.CARTRIDGE_LOW) {
notification.text = MainApp.sResources.getString(R.string.combo_pump_cartridge_low_warrning);
} else if (activeAlert.warningCode == PumpWarningCodes.BATTERY_LOW) {
notification.text = MainApp.sResources.getString(R.string.combo_pump_battery_low_warrning);
} else if (activeAlert.warningCode == PumpWarningCodes.TBR_CANCELLED) {
notification.text = MainApp.sResources.getString(R.string.combo_pump_tbr_cancelled_warrning);
}
MainApp.bus().post(new EventNewNotification(notification));
}
private void checkForUnsafeUsage(CommandResult commandResult) {
long lastViolation = 0;
if (commandResult.state.unsafeUsageDetected) {
lastViolation = System.currentTimeMillis();
} else if (commandResult.lastBolus != null && !commandResult.lastBolus.isValid) {
lastViolation = commandResult.lastBolus.timestamp;
} else if (commandResult.history != null) {
for (Bolus bolus : commandResult.history.bolusHistory) {
if (!bolus.isValid && bolus.timestamp > lastViolation) {
lastViolation = bolus.timestamp;
}
}
}
if (lastViolation > 0) {
lowSuspendOnlyLoopEnforcetTill = lastViolation + 6 * 60 * 60 * 1000;
if (lowSuspendOnlyLoopEnforcetTill > System.currentTimeMillis() && violationWarningRaisedFor != lowSuspendOnlyLoopEnforcetTill) {
Notification n = new Notification(Notification.COMBO_PUMP_ALARM,
MainApp.sResources.getString(R.string.combo_force_disabled_notification),
Notification.URGENT);
n.soundId = R.raw.alarm;
MainApp.bus().post(new EventNewNotification(n));
violationWarningRaisedFor = lowSuspendOnlyLoopEnforcetTill;
}
}
}
/**
* Checks the main screen to determine if TBR on pump matches app state.
*/
private void checkAndResolveTbrMismatch(PumpState state) {
TemporaryBasal aapsTbr = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) {
log.debug("Creating temp basal from pump TBR");
TemporaryBasal newTempBasal = new TemporaryBasal();
newTempBasal.date = System.currentTimeMillis();
newTempBasal.percentRate = state.tbrPercent;
newTempBasal.isAbsolute = false;
newTempBasal.durationInMinutes = state.tbrRemainingDuration;
newTempBasal.source = Source.USER;
MainApp.getConfigBuilder().addToHistoryTempBasal(newTempBasal);
} else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) {
log.debug("Ending AAPS-TBR since pump has no TBR active");
TemporaryBasal tempStop = new TemporaryBasal();
tempStop.date = aapsTbr.date;
tempStop.durationInMinutes = 0;
tempStop.source = Source.USER;
MainApp.getConfigBuilder().addToHistoryTempBasal(tempStop);
} else if (aapsTbr != null && state.tbrActive
&& (aapsTbr.percentRate != state.tbrPercent ||
Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) {
log.debug("AAPSs and pump-TBR differ; Ending AAPS-TBR and creating new TBR based on pump TBR");
TemporaryBasal tempStop = new TemporaryBasal();
tempStop.date = aapsTbr.date;
tempStop.durationInMinutes = 0;
tempStop.source = Source.USER;
MainApp.getConfigBuilder().addToHistoryTempBasal(tempStop);
TemporaryBasal newTempBasal = new TemporaryBasal();
newTempBasal.date = System.currentTimeMillis();
newTempBasal.percentRate = state.tbrPercent;
newTempBasal.isAbsolute = false;
newTempBasal.durationInMinutes = state.tbrRemainingDuration;
newTempBasal.source = Source.USER;
MainApp.getConfigBuilder().addToHistoryTempBasal(newTempBasal);
}
}
/**
* Reads the pump's history and updates the DB accordingly.
*
* Only ever called by #readAllPumpData which is triggered by the user via the combo fragment
* which warns the user against doing this.
*/
private boolean readHistory(final PumpHistoryRequest request) {
CommandResult historyResult = runCommand(MainApp.sResources.getString(R.string.combo_activity_reading_pump_history), 3, () -> ruffyScripter.readHistory(request));
if (!historyResult.success) {
return false;
}
PumpHistory history = historyResult.history;
updateDbFromPumpHistory(history);
// update local cache
if (!history.pumpAlertHistory.isEmpty()) {
pump.errorHistory = history.pumpAlertHistory;
}
if (!history.tddHistory.isEmpty()) {
pump.tddHistory = history.tddHistory;
}
return historyResult.success;
}
private synchronized void updateDbFromPumpHistory(@NonNull PumpHistory history) {
DatabaseHelper dbHelper = MainApp.getDbHelper();
// boluses
for (Bolus pumpBolus : history.bolusHistory) {
Treatment aapsBolus = dbHelper.getTreatmentByDate(pumpBolus.timestamp);
if (aapsBolus == null) {
log.debug("Creating bolus record from pump bolus: " + pumpBolus);
DetailedBolusInfo dbi = new DetailedBolusInfo();
dbi.date = pumpBolus.timestamp;
dbi.pumpId = pumpBolus.timestamp;
dbi.source = Source.PUMP;
dbi.insulin = pumpBolus.amount;
dbi.eventType = CareportalEvent.CORRECTIONBOLUS;
MainApp.getConfigBuilder().addToHistoryTreatment(dbi);
}
}
// TBRs
for (Tbr pumpTbr : history.tbrHistory) {
TemporaryBasal aapsTbr = dbHelper.getTemporaryBasalsDataByDate(pumpTbr.timestamp);
if (aapsTbr == null) {
log.debug("Creating TBR from pump TBR: " + pumpTbr);
TemporaryBasal temporaryBasal = new TemporaryBasal();
temporaryBasal.date = pumpTbr.timestamp;
temporaryBasal.pumpId = pumpTbr.timestamp;
temporaryBasal.source = Source.PUMP;
temporaryBasal.percentRate = pumpTbr.percent;
temporaryBasal.durationInMinutes = pumpTbr.duration;
temporaryBasal.isAbsolute = false;
MainApp.getConfigBuilder().addToHistoryTempBasal(temporaryBasal);
}
}
}
void readAllPumpData() {
long lastCheckInitiated = System.currentTimeMillis();
boolean readHistorySuccess = readHistory(new PumpHistoryRequest()
.bolusHistory(pumpHistoryLastChecked)
.tbrHistory(pumpHistoryLastChecked)
.pumpErrorHistory(PumpHistoryRequest.FULL)
.tddHistory(PumpHistoryRequest.FULL));
if (!readHistorySuccess) {
return;
}
pumpHistoryLastChecked = lastCheckInitiated;
/* not displayed in the UI anymore due to pump bug
CommandResult reservoirResult = runCommand("Checking reservoir level", 2,
ruffyScripter::readReservoirLevelAndLastBolus);
if (!reservoirResult.success) {
return;
}
*/
CommandResult basalResult = runCommand("Reading basal profile", 2, ruffyScripter::readBasalProfile);
if (!basalResult.success) {
return;
}
pump.basalProfile = basalResult.basalProfile;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
return OPERATION_NOT_SUPPORTED;
}
@Override
public JSONObject getJSONStatus() {
if (!pump.initialized) {
return null;
}
try {
JSONObject pumpJson = new JSONObject();
pumpJson.put("clock", DateUtil.toISOString(pump.lastSuccessfulCmdTime));
int level = 250;
if (pump.state.insulinState == PumpState.LOW) level = 50;
if (pump.state.insulinState == PumpState.EMPTY) level = 0;
pumpJson.put("reservoir", level);
JSONObject statusJson = new JSONObject();
statusJson.put("status", getStateSummary());
statusJson.put("timestamp", pump.lastSuccessfulCmdTime);
pumpJson.put("status", statusJson);
JSONObject extendedJson = new JSONObject();
extendedJson.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
extendedJson.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
PumpState ps = pump.state;
if (ps.tbrActive) {
extendedJson.put("TempBasalAbsoluteRate", ps.tbrRate);
extendedJson.put("TempBasalPercent", ps.tbrPercent);
extendedJson.put("TempBasalRemaining", ps.tbrRemainingDuration);
}
if (ps.activeAlert != null && ps.activeAlert.errorCode != null) {
extendedJson.put("ErrorCode", ps.activeAlert.errorCode);
}
pumpJson.put("extended", extendedJson);
JSONObject batteryJson = new JSONObject();
int battery;
switch (ps.batteryState) {
case PumpState.EMPTY:
battery = 0;
break;
case PumpState.LOW:
battery = 25;
break;
default:
battery = 100;
break;
}
batteryJson.put("percent", battery);
pumpJson.put("battery", batteryJson);
return pumpJson;
} catch (Exception e) {
log.warn("Failed to gather device status for upload", e);
}
return null;
}
@Override
public String deviceID() {
return "Combo";
}
@Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@Override
public String shortStatus(boolean veryShort) {
return getStateSummary();
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return false;
}
// Constraints interface
private long lowSuspendOnlyLoopEnforcetTill = 0;
private long violationWarningRaisedFor = 0;
@Override
public boolean isLoopEnabled() {
return true;
}
@Override
public boolean isClosedModeEnabled() {
return true;
}
@Override
public boolean isAutosensModeEnabled() {
return true;
}
@Override
public boolean isAMAModeEnabled() {
return true;
}
@Override
public Double applyBasalConstraints(Double absoluteRate) {
return absoluteRate;
}
@Override
public Integer applyBasalConstraints(Integer percentRate) {
return percentRate;
}
@Override
public Double applyBolusConstraints(Double insulin) {
return insulin;
}
@Override
public Integer applyCarbsConstraints(Integer carbs) {
return carbs;
}
@Override
public Double applyMaxIOBConstraints(Double maxIob) {
return lowSuspendOnlyLoopEnforcetTill < System.currentTimeMillis() ? maxIob : 0;
}
}
|
package info.nightscout.androidaps.plugins.PumpCombo;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import com.squareup.otto.Subscribe;
import org.json.JSONObject;
import org.monkey.d.ruffy.ruffy.driver.IRuffyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import de.jotomo.ruffyscripter.PumpState;
import de.jotomo.ruffyscripter.RuffyScripter;
import de.jotomo.ruffyscripter.commands.BolusCommand;
import de.jotomo.ruffyscripter.commands.CancelTbrCommand;
import de.jotomo.ruffyscripter.commands.Command;
import de.jotomo.ruffyscripter.commands.CommandResult;
import de.jotomo.ruffyscripter.commands.ProgressReportCallback;
import de.jotomo.ruffyscripter.commands.DetermineCapabilitiesCommand;
import de.jotomo.ruffyscripter.commands.ReadPumpStateCommand;
import de.jotomo.ruffyscripter.commands.SetTbrCommand;
import de.jotomo.ruffyscripter.commands.SetTbrCommandAlt;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.PumpCombo.events.EventComboPumpUpdateGUI;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP;
import info.nightscout.utils.ToastUtils;
public class ComboPlugin implements PluginBase, PumpInterface {
public static final String COMBO_MAX_TEMP_PERCENT_SP = "combo_maxTempPercent";
private static Logger log = LoggerFactory.getLogger(ComboPlugin.class);
private boolean fragmentEnabled = false;
private boolean fragmentVisible = false;
private PumpDescription pumpDescription = new PumpDescription();
private RuffyScripter ruffyScripter;
private ServiceConnection mRuffyServiceConnection;
// package-protected only so ComboFragment can access these
@NonNull
volatile String statusSummary = "Initializing";
@Nullable
volatile Command lastCmd;
@Nullable
volatile CommandResult lastCmdResult;
@NonNull
volatile Date lastCmdTime = new Date(0);
volatile PumpState pumpState = new PumpState();
@Nullable
private volatile BolusCommand runningBolusCommand;
private static PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult();
static {
OPERATION_NOT_SUPPORTED.success = false;
OPERATION_NOT_SUPPORTED.enacted = false;
OPERATION_NOT_SUPPORTED.comment = "Requested operation not supported by pump";
}
public ComboPlugin() {
definePumpCapabilities();
MainApp.bus().register(this);
bindRuffyService();
startAlerter();
ruffyScripter = new RuffyScripter();
}
private void definePumpCapabilities() {
pumpDescription.isBolusCapable = true;
pumpDescription.bolusStep = 0.1d;
pumpDescription.isExtendedBolusCapable = false;
pumpDescription.extendedBolusStep = 0.1d;
pumpDescription.extendedBolusDurationStep = 15;
pumpDescription.extendedBolusMaxDuration = 12 * 60;
pumpDescription.isTempBasalCapable = true;
pumpDescription.tempBasalStyle = PumpDescription.PERCENT;
pumpDescription.maxTempPercent = SP.getInt(COMBO_MAX_TEMP_PERCENT_SP, 500);
pumpDescription.tempPercentStep = 10;
pumpDescription.tempDurationStep = 15;
pumpDescription.tempMaxDuration = 24 * 60;
pumpDescription.isSetBasalProfileCapable = false; // TODO
pumpDescription.basalStep = 0.01d;
pumpDescription.basalMinimumRate = 0.0d;
pumpDescription.isRefillingCapable = true;
}
/**
* The alerter frequently checks the result of the last executed command via the lastCmdResult
* field and shows a notification with sound and vibration if an error occurred.
* More details on the error can then be looked up in the Combo tab.
* <p>
* The alarm is re-raised every 5 minutes for as long as the error persist. As soon
* as a command succeeds no more new alerts are raised.
*/
private void startAlerter() {
new Thread(new Runnable() {
@Override
public void run() {
Context context = MainApp.instance().getApplicationContext();
NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int id = 1000;
long lastAlarmTime = 0;
while (true) {
Command localLastCmd = lastCmd;
CommandResult localLastCmdResult = lastCmdResult;
if (localLastCmdResult != null && !localLastCmdResult.success) {
long now = System.currentTimeMillis();
long fiveMinutesSinceLastAlarm = lastAlarmTime + (5 * 60 * 1000) + (15 * 1000);
if (now > fiveMinutesSinceLastAlarm) {
log.error("Command failed: " + localLastCmd);
log.error("Command result: " + localLastCmdResult);
PumpState localPumpState = pumpState;
if (localPumpState != null && localPumpState.errorMsg != null) {
log.warn("Pump is in error state, displaying; " + localPumpState.errorMsg);
}
long[] vibratePattern = new long[]{1000, 2000, 1000, 2000, 1000};
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notif_icon)
.setSmallIcon(R.drawable.icon_bolus)
.setContentTitle("Combo communication error")
.setContentText(localLastCmdResult.message)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setLights(Color.BLUE, 1000, 0)
.setSound(uri)
.setVibrate(vibratePattern);
mgr.notify(id, notificationBuilder.build());
lastAlarmTime = now;
} else {
// TODO would it be useful to have a 'last error' field in the ui showing the most recent
// failed command? the next command that runs successful with will override this error
log.warn("Pump still in error state, but alarm raised recently, so not triggering again: " + localLastCmdResult.message);
refreshDataFromPump("from Error Recovery");
}
}
SystemClock.sleep(5 * 1000);
}
}
}, "combo-alerter").start();
}
private boolean bindRuffyService() {
Context context = MainApp.instance().getApplicationContext();
boolean boundSucceeded = false;
try {
Intent intent = new Intent()
.setComponent(new ComponentName(
// this must be the base package of the app (check package attribute in
// manifest element in the manifest file of the providing app)
"org.monkey.d.ruffy.ruffy",
// full path to the driver
// in the logs this service is mentioned as (note the slash)
// "org.monkey.d.ruffy.ruffy/.driver.Ruffy"
//org.monkey.d.ruffy.ruffy is the base package identifier and /.driver.Ruffy the service within the package
"org.monkey.d.ruffy.ruffy.driver.Ruffy"
));
context.startService(intent);
mRuffyServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
keepUnbound = false;
ruffyScripter.start(IRuffyService.Stub.asInterface(service));
log.debug("ruffy serivce connected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
ruffyScripter.stop();
log.debug("ruffy service disconnected");
// try to reconnect ruffy service unless unbind was explicitely requested
// via unbindRuffyService
if (!keepUnbound) {
SystemClock.sleep(250);
bindRuffyService();
}
}
};
boundSucceeded = context.bindService(intent, mRuffyServiceConnection, Context.BIND_AUTO_CREATE);
} catch (Exception e) {
log.error("Binding to ruffy service failed", e);
}
if (!boundSucceeded) {
statusSummary = "No connection to ruffy. Pump control not available.";
}
return true;
}
private boolean keepUnbound = false;
private void unbindRuffyService() {
keepUnbound = true;
ruffyScripter.unbind();
MainApp.instance().getApplicationContext().unbindService(mRuffyServiceConnection);
}
@Override
public String getFragmentClass() {
return ComboFragment.class.getName();
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.combopump);
}
@Override
public String getNameShort() {
String name = MainApp.sResources.getString(R.string.combopump_shortname);
if (!name.trim().isEmpty()) {
//only if translation exists
return name;
}
// use long name as fallback
return getName();
}
@Override
public boolean isEnabled(int type) {
return type == PUMP && fragmentEnabled;
}
@Override
public boolean isVisibleInTabs(int type) {
return type == PUMP && fragmentVisible;
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public boolean hasFragment() {
return true;
}
@Override
public boolean showInList(int type) {
return true;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == PUMP) this.fragmentEnabled = fragmentEnabled;
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == PUMP) this.fragmentVisible = fragmentVisible;
}
@Override
public int getType() {
return PluginBase.PUMP;
}
@Override
public boolean isInitialized() {
// consider initialized when the pump's state was initially fetched,
// after that lastCmd* variables will have values
return lastCmdTime.getTime() > 0;
}
@Override
public boolean isSuspended() {
return pumpState != null && pumpState.suspended;
}
@Override
public boolean isBusy() {
return ruffyScripter == null || ruffyScripter.isPumpBusy();
}
// TODO
@Override
public int setNewBasalProfile(Profile profile) {
return FAILED;
}
// TODO
@Override
public boolean isThisProfileSet(Profile profile) {
return false;
}
@Override
public Date lastDataTime() {
return lastCmdTime;
}
// this method is regularly called from info.nightscout.androidaps.receivers.KeepAliveReceiver
@Override
public void refreshDataFromPump(String reason) {
log.debug("RefreshDataFromPump called");
// if Android is sluggish this might get called before ruffy is bound
if (ruffyScripter == null) {
log.warn("Rejecting call to RefreshDataFromPump: ruffy service not bound (yet)");
return;
}
boolean notAUserRequest = !reason.toLowerCase().contains("user");
boolean wasRunAtLeastOnce = lastCmdTime.getTime() > 0;
boolean ranWithinTheLastMinute = System.currentTimeMillis() < lastCmdTime.getTime() + 60 * 1000;
if (notAUserRequest && wasRunAtLeastOnce && ranWithinTheLastMinute) {
log.debug("Not fetching state from pump, since we did already within the last 60 seconds");
} else {
runCommand(new ReadPumpStateCommand());
}
}
// TODO uses profile values for the time being
// this get's called mulitple times a minute, must absolutely be cached
@Override
public double getBaseBasalRate() {
Profile profile = MainApp.getConfigBuilder().getProfile();
Double basal = profile.getBasal();
log.trace("getBaseBasalrate returning " + basal);
return basal;
}
private static ProgressReportCallback bolusProgressReportCallback = new ProgressReportCallback() {
@Override
public void report(ProgressReportCallback.State state, int percent, double delivered) {
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
switch (state) {
// TODO move into enum as toString or so and make it translateb
case DELIVERING:
bolusingEvent.status = String.format(MainApp.sResources.getString(R.string.bolusdelivering), delivered);
break;
case DELIVERED:
bolusingEvent.status = "Bolus delivery finished successfully";
break;
case STOPPED:
bolusingEvent.status = "Bolus delivery was cancelled";
break;
case STOPPING:
bolusingEvent.status = "Cancelling bolus delivery";
break;
}
bolusingEvent.percent = percent;
MainApp.bus().post(bolusingEvent);
}
};
// what a mess: pump integration code reading carb info from Detailed**Bolus**Info,
// writing carb treatments to the history table. What's PumpEnactResult for again?
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) {
if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
MainApp.bus().post(bolusingEvent);
runningBolusCommand = new BolusCommand(detailedBolusInfo.insulin, bolusProgressReportCallback);
CommandResult bolusCmdResult = runCommand(runningBolusCommand);
runningBolusCommand = null;
PumpEnactResult pumpEnactResult = new PumpEnactResult();
pumpEnactResult.success = bolusCmdResult.success;
pumpEnactResult.enacted = bolusCmdResult.enacted;
pumpEnactResult.comment = bolusCmdResult.message;
// if enacted, add bolus and carbs to treatment history
if (pumpEnactResult.enacted) {
// TODO if no error occurred, the requested bolus is what the pump delievered,
// that has been checked. If an error occurred, we should check how much insulin
// was delivered, e.g. when the cartridge went empty mid-bolus
// For the first iteration, the alert the pump raises must suffice
pumpEnactResult.bolusDelivered = detailedBolusInfo.insulin;
pumpEnactResult.carbsDelivered = detailedBolusInfo.carbs;
detailedBolusInfo.date = bolusCmdResult.completionTime;
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
} else {
pumpEnactResult.bolusDelivered = 0d;
pumpEnactResult.carbsDelivered = 0d;
}
return pumpEnactResult;
} else {
// no bolus required, carb only treatment
// TODO the ui freezes when the calculator issues a carb-only treatment
// so just wait, yeah, this is dumb. for now; proper fix via GL
// info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog.scheduleDismiss()
// send event to indicate popup can be dismissed?
SystemClock.sleep(6000);
PumpEnactResult pumpEnactResult = new PumpEnactResult();
pumpEnactResult.success = true;
pumpEnactResult.enacted = true;
pumpEnactResult.bolusDelivered = 0d;
pumpEnactResult.carbsDelivered = detailedBolusInfo.carbs;
pumpEnactResult.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
return pumpEnactResult;
}
} else {
// neither carbs nor bolus requested
PumpEnactResult pumpEnactResult = new PumpEnactResult();
pumpEnactResult.success = false;
pumpEnactResult.enacted = false;
pumpEnactResult.bolusDelivered = 0d;
pumpEnactResult.carbsDelivered = 0d;
pumpEnactResult.comment = MainApp.instance().getString(R.string.danar_invalidinput);
log.error("deliverTreatment: Invalid input");
return pumpEnactResult;
}
}
private CommandResult runCommand(Command command) {
if (ruffyScripter == null) {
String msg = "No connection to ruffy. Pump control not available.";
statusSummary = msg;
return new CommandResult().message(msg);
}
statusSummary = "Executing " + command;
MainApp.bus().post(new EventComboPumpUpdateGUI());
CommandResult commandResult = ruffyScripter.runCommand(command);
log.debug("RuffyScripter returned from command invocation, result: " + commandResult);
if (commandResult.exception != null) {
log.error("Exception received from pump", commandResult.exception);
}
lastCmd = command;
lastCmdTime = new Date();
lastCmdResult = commandResult;
pumpState = commandResult.state;
if (commandResult.success && commandResult.state.suspended) {
statusSummary = "Suspended";
} else if (commandResult.success) {
statusSummary = "Idle";
} else {
statusSummary = "Error";
}
MainApp.bus().post(new EventComboPumpUpdateGUI());
return commandResult;
}
@Override
public void stopBolusDelivering() {
if (runningBolusCommand != null) runningBolusCommand.requestCancellation();
}
// Note: AAPS calls this only to enact OpenAPS recommendations
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, boolean force) {
// the force parameter isn't used currently since we always set the tbr - there might be room for optimization to
// first test the currently running tbr and only change it if it differs (as the DanaR plugin does).
// This approach might have other issues though (what happens if the tbr which wasn't re-set to the new value
// (and thus still has the old duration of e.g. 1 min) expires?)
log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min.");
int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10);
if (unroundedPercentage != roundedPercentage) {
log.debug("Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%");
}
return setTempBasalPercent(roundedPercentage, durationInMinutes);
}
// Note: AAPS calls this only for setting a temp basal issued by the user
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
log.debug("setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min");
int adjustedPercent = percent;
if (adjustedPercent > pumpDescription.maxTempPercent) {
log.debug("Reducing requested TBR to the maximum support by the pump: " + percent + " -> " + pumpDescription.maxTempPercent);
adjustedPercent = pumpDescription.maxTempPercent;
}
if (adjustedPercent % 10 != 0) {
Long rounded = Math.round(adjustedPercent / 10d) * 10;
log.debug("Rounded requested percentage:" + adjustedPercent + " -> " + rounded);
adjustedPercent = rounded.intValue();
}
Command cmd = !BuildConfig.VERSION.contains("joe")
? new SetTbrCommand(adjustedPercent, durationInMinutes)
: new SetTbrCommandAlt(adjustedPercent, durationInMinutes);
CommandResult commandResult = runCommand(cmd);
if (commandResult.enacted) {
TemporaryBasal tempStart = new TemporaryBasal(commandResult.completionTime);
// TODO commandResult.state.tbrRemainingDuration might already display 29 if 30 was set, since 29:59 is shown as 29 ...
// we should check this, but really ... something must be really screwed up if that number was anything different
// TODO actually ... might setting 29 help with gaps between TBRs? w/o the hack in TemporaryBasal?
tempStart.durationInMinutes = durationInMinutes;
tempStart.percentRate = adjustedPercent;
tempStart.isAbsolute = false;
tempStart.source = Source.USER;
ConfigBuilderPlugin treatmentsInterface = MainApp.getConfigBuilder();
treatmentsInterface.addToHistoryTempBasal(tempStart);
}
PumpEnactResult pumpEnactResult = new PumpEnactResult();
pumpEnactResult.success = commandResult.success;
pumpEnactResult.enacted = commandResult.enacted;
pumpEnactResult.comment = commandResult.message;
pumpEnactResult.isPercent = true;
// Combo would have bailed if this wasn't set properly. Maybe we should
// have the command return this anyways ...
pumpEnactResult.percent = adjustedPercent;
pumpEnactResult.duration = durationInMinutes;
return pumpEnactResult;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
return OPERATION_NOT_SUPPORTED;
}
@Override
public PumpEnactResult cancelTempBasal(boolean userRequested) {
log.debug("cancelTempBasal called");
CommandResult commandResult = null;
TemporaryBasal tempBasal = null;
PumpEnactResult pumpEnactResult = new PumpEnactResult();
final TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
if (activeTemp == null || userRequested) {
/* v1 compatibility to sync DB to pump if they diverged (activeTemp == null) */
log.debug("cancelTempBasal: hard-cancelling TBR since user requested");
commandResult = runCommand(new CancelTbrCommand());
if (commandResult.enacted) {
tempBasal = new TemporaryBasal(commandResult.completionTime);
tempBasal.durationInMinutes = 0;
tempBasal.source = Source.USER;
pumpEnactResult.isTempCancel = true;
}
} else if ((activeTemp.percentRate >= 90 && activeTemp.percentRate <= 110) && activeTemp.getPlannedRemainingMinutes() <= 15) {
// Let fake neutral temp keep running (see below)
log.debug("cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins.");
pumpEnactResult.comment = "cancelTempBasal skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins.";
// TODO check what AAPS does with this; no DB update is required;
// looking at info/nightscout/androidaps/plugins/Loop/LoopPlugin.java:280
// both values are used as one:
// if (applyResult.enacted || applyResult.success) { ...
pumpEnactResult.enacted = true; // all fine though...
pumpEnactResult.success = true; // just roll with it...
} else {
// Set a fake neutral temp to avoid TBR cancel alert. Decide 90% vs 110% based on
// on whether the TBR we're cancelling is above or below 100%.
long percentage = (activeTemp.percentRate > 100) ? 110 : 90;
log.debug("cancelTempBasal: changing tbr to " + percentage + "% for 15 mins.");
commandResult = runCommand(new SetTbrCommand(percentage, 15));
if (commandResult.enacted) {
tempBasal = new TemporaryBasal(commandResult.completionTime);
tempBasal.durationInMinutes = 15;
tempBasal.source = Source.USER;
tempBasal.percentRate = (int) percentage;
tempBasal.isAbsolute = false;
}
}
if (tempBasal != null) {
ConfigBuilderPlugin treatmentsInterface = MainApp.getConfigBuilder();
treatmentsInterface.addToHistoryTempBasal(tempBasal);
}
if (commandResult != null) {
pumpEnactResult.success = commandResult.success;
pumpEnactResult.enacted = commandResult.enacted;
pumpEnactResult.comment = commandResult.message;
}
return pumpEnactResult;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
return OPERATION_NOT_SUPPORTED;
}
// Returns the state of the pump as it was received during last pump comms.
// TODO v2 add battery, reservoir info when we start reading that and clean up the code
@Override
public JSONObject getJSONStatus() {
if (lastCmdTime.getTime() + 5 * 60 * 1000L < System.currentTimeMillis()) {
return null;
}
try {
JSONObject pump = new JSONObject();
JSONObject status = new JSONObject();
JSONObject extended = new JSONObject();
status.put("status", statusSummary);
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
try {
extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
} catch (Exception e) {
}
status.put("timestamp", lastCmdTime);
PumpState ps = pumpState;
if (ps != null) {
if (ps.tbrActive) {
extended.put("TempBasalAbsoluteRate", ps.tbrRate);
extended.put("TempBasalPercent", ps.tbrPercent);
extended.put("TempBasalRemaining", ps.tbrRemainingDuration);
}
if (ps.errorMsg != null) {
extended.put("ErrorMessage", ps.errorMsg);
}
}
// more info here .... look at dana plugin
pump.put("status", status);
pump.put("extended", extended);
pump.put("clock", DateUtil.toISOString(lastCmdTime));
return pump;
} catch (Exception e) {
log.warn("Failed to gather device status for upload", e);
}
return null;
}
// TODO
@Override
public String deviceID() {
// Serial number here
return "Combo";
}
@Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@Override
public String shortStatus(boolean veryShort) {
return statusSummary;
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return false;
}
@SuppressWarnings("UnusedParameters")
@Subscribe
public void onStatusEvent(final EventAppExit e) {
unbindRuffyService();
}
public void updateCapabilities() {
// if Android is sluggish this might get called before ruffy is bound
if (ruffyScripter == null) {
log.warn("Rejecting call to RefreshDataFromPump: ruffy service not bound (yet)");
ToastUtils.showToastInUiThread(MainApp.instance(), "Ruffy not initialized.");
return;
}
if (isBusy()) {
ToastUtils.showToastInUiThread(MainApp.instance(), "Pump busy!");
return;
}
CommandResult result = runCommand(new DetermineCapabilitiesCommand());
if (result.success) {
pumpDescription.maxTempPercent = (int) result.capabilities.maxTempPercent;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance());
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(COMBO_MAX_TEMP_PERCENT_SP, pumpDescription.maxTempPercent);
editor.commit();
MainApp.bus().post(new EventComboPumpUpdateGUI());
} else {
ToastUtils.showToastInUiThread(MainApp.instance(), "No success.");
}
}
}
// If you want update fragment call
// MainApp.bus().post(new EventComboPumpUpdateGUI());
// fragment should fetch data from plugin and display status, buttons etc ...
|
package com.jmpmain.lvslrpg;
import java.util.ArrayList;
import java.util.Vector;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.jmpmain.lvslrpg.Map.TileType;
import com.jmpmain.lvslrpg.entities.*;
import com.jmpmain.lvslrpg.entities.Item.ItemType;
import com.jmpmain.lvslrpg.particles.Particle;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Spinner;
/**
* Main game thread.
* All game logic is managed here.
*/
public class GameThread extends Thread
implements SensorEventListener, OnClickListener, OnItemSelectedListener{
/** Counter for updates per second(ups). */
private int updateCallCount;
/** The updates per second of the previous second. */
public int ups;
/** Last time fps second had elapsed. */
private long lastUpdateCallReset;
/** Last time game was updated. */
private long lastUpdate;
/** GameSurface Surface Holder. */
private SurfaceHolder surfaceHolder;
/** Main surface game is drawn to. */
private GameSurface gameSurface;
/** Layout for UI elements. Above the game surface. */
public RelativeLayout uiLayout;
/** List of screen types. */
public enum Screen{
START,
OPTIONS,
MENU,
BATTLE
}
/** Current screen of game. */
public Screen currentScreen;
//Start screen ui elements.
private RelativeLayout startScreen;
private Button startButton;
private Button optionsButton;
//Options screen ui elements.
private RelativeLayout optionsScreen;
private Spinner controlsSpinner;
private Button audioButton;
//Menu screen ui elements.
private Button continueButton;
//Battle screen ui elements.
private ImageButton leftButton;
private ImageButton rightButton;
/** Thread running state. */
public boolean running;
public enum Controls{
Button_Static(0),
Button_Clockwise(1),
Swipe(2),
Tilt(3);
private final int value;
private Controls(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public Controls gameControls;
public static boolean SoundOn;
public int startTouchX;
public int startTouchY;
public int touchX;
public int touchY;
/** Current game map. */
public Map map;
public LineEntity line;
public Vector<LineEntity> enemies;
public Vector<Item> items;
public Vector<Item> playerItems;
public Vector<Particle> particles;
/** View for ads. */
private AdView adView;
public static GameThread instance;
public int level;
public GameThread(SurfaceHolder holder, GameSurface surface){
gameSurface = surface;
surfaceHolder = holder;
instance = this;
SharedPreferences settings = MainActivity.context.getSharedPreferences("settings", 0);
SoundOn = settings.getBoolean("sound", true);
gameControls = Controls.values()[settings.getInt("controls", 0)];
updateCallCount = 0;
ups = 0;
lastUpdateCallReset = 0;
particles = new Vector<Particle>();
//Create UI elements.
//Create the ad
adView = new AdView(MainActivity.context);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(MainActivity.context.getResources().getString(R.string.AdId));
AdRequest.Builder adBuilder = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
for(int i = 0; i < MainActivity.context.getResources().getStringArray(R.array.TestDevices).length; i++){
adBuilder.addTestDevice(MainActivity.context.getResources().getStringArray(R.array.TestDevices)[i]);
}
AdRequest adRequest = adBuilder.build();
//Load ad
if(adRequest != null){
adView.loadAd(adRequest);
}
adView.setId(1);
LayoutInflater inflater = (LayoutInflater)MainActivity.context.getSystemService(MainActivity.context.LAYOUT_INFLATER_SERVICE );
startScreen = (RelativeLayout) inflater.inflate(R.layout.start_screen, uiLayout);
startButton = (Button) startScreen.findViewById(R.id.start_button);
startButton.setOnClickListener(this);
optionsButton = (Button) startScreen.findViewById(R.id.options_button);
optionsButton.setOnClickListener(this);
optionsScreen = (RelativeLayout) inflater.inflate(R.layout.options_screen, uiLayout);
controlsSpinner = (Spinner) optionsScreen.findViewById(R.id.controls_spinner);
OptionsAdapter adapter = new OptionsAdapter(MainActivity.context, R.layout.spinner_item_layout,
MainActivity.context.getResources().getStringArray(R.array.ControlsOptions));
// Apply the adapter to the spinner
controlsSpinner.setAdapter(adapter);
controlsSpinner.setSelection(gameControls.getValue());
controlsSpinner.setOnItemSelectedListener(this);
audioButton = (Button) optionsScreen.findViewById(R.id.audio_button);
audioButton.setOnClickListener(this);
if(!SoundOn){
audioButton.setText("Sound Off");
}
continueButton = new Button(MainActivity.context);
continueButton.setOnClickListener(this);
continueButton.setText("Continue");
leftButton = new ImageButton(MainActivity.context);
leftButton.setOnClickListener(this);
leftButton.setImageResource(R.drawable.arrow_l);
leftButton.setScaleType(ScaleType.FIT_CENTER);
leftButton.setBackgroundColor(Color.TRANSPARENT);
rightButton = new ImageButton(MainActivity.context);
rightButton.setOnClickListener(this);
rightButton.setImageResource(R.drawable.arrow_r);
rightButton.setScaleType(ScaleType.FIT_CENTER);
rightButton.setBackgroundColor(Color.TRANSPARENT);
startButton.setTypeface(MainActivity.pixelFont);
optionsButton.setTypeface(MainActivity.pixelFont);
continueButton.setTypeface(MainActivity.pixelFont);
audioButton.setTypeface(MainActivity.pixelFont);
setRunning(false);
}
/**
* Starts a brand new game.
*/
public void resetGame(){
line = new PlayerLineEntity(0, 0);
line.character = GameSurface.character;
line.setColor(128, 0, 255, 0);
level = 0;
setTurnButtons();
newLevel();
}
/**
* Creates new level.
*/
public void newLevel(){
level++;
map = MapGenerator.GenerateMap(gameSurface.getWidth(), gameSurface.getHeight(), 14);
line.setMap(map);
line.setDirection(0, -1);
line.setX(map.playerStart.x);
line.setY(map.playerStart.y);
enemies = new Vector<LineEntity>();
for(int i = 0; i < map.enemyStarts.size(); i++){
LineEntity enemy = new AILineEntity(map.enemyStarts.get(i).x, map.enemyStarts.get(i).y);
enemy.setColor(128, (int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255));
enemy.setDirection(0, 1);
enemy.setMap(map);
enemy.setMaxHealth(enemy.maxHealth + level);
enemy.character = GameSurface.enemy;
enemies.add(enemy);
}
items = new Vector<Item>();
for(int i = 0; i < 10; i++){
int x = (int)(Math.random()*map.width*map.tileSize);
int y = (int)(Math.random()*map.height*map.tileSize);
if(Math.random() > 0.5)
items.add(new Item(ItemType.Coin, x, y));
else
items.add(new Item(ItemType.Potion, x, y));
}
}
/**
* Called when the game can be initialized.
* This means the graphics and application has been setup
* and ready to be used.
*/
public void initGame(){
resetGame();
setScreen(Screen.START);
}
/**
* Change screens.
* @param screen Screen to change to.
*/
public void setScreen(Screen screen){
currentScreen = screen;
//Make sure running on UI thread.
((MainActivity)MainActivity.context).runOnUiThread(new Runnable() {
@Override
public void run() {
uiLayout.removeAllViews();
if(currentScreen == Screen.START){
LayoutParams params = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
uiLayout.addView(adView, params);
uiLayout.addView(startScreen, new LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
}
else if(currentScreen == Screen.OPTIONS){
LayoutParams params = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
uiLayout.addView(adView, params);
uiLayout.addView(optionsScreen, new LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
}
else if(currentScreen == Screen.MENU){
LayoutParams params = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
uiLayout.addView(adView, params);
params = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(RelativeLayout.CENTER_VERTICAL);
uiLayout.addView(continueButton, params);
}
else if(currentScreen == Screen.BATTLE){
if(gameControls == Controls.Button_Clockwise || gameControls == Controls.Button_Static){
LayoutParams params = new LayoutParams(150, 150);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
uiLayout.addView(rightButton, params);
params = new LayoutParams(150, 150);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
uiLayout.addView(leftButton, params);
setTurnButtons();
}
}
}
});
}
/**
* Set thread running state.
*/
public void setRunning(boolean r){
running = r;
}
@SuppressLint("WrongCall")
private void drawCall(Canvas gameCanvas){
//Draw game state.
gameCanvas = surfaceHolder.lockCanvas();
if(gameCanvas != null){
synchronized (surfaceHolder) {
gameSurface.onDraw(gameCanvas);
}
surfaceHolder.unlockCanvasAndPost(gameCanvas);
}
}
@Override
/**
* Main game loop.
*/
public void run() {
Canvas gameCanvas = null;
//Game loop.
while (running) {
if(currentScreen == Screen.MENU){
}
else if(currentScreen == Screen.BATTLE){
//Check if game state should be updated.
if(System.currentTimeMillis() - lastUpdate < 25){
drawCall(gameCanvas);
continue;
}
lastUpdate = System.currentTimeMillis();
long currentTimeMillis = System.currentTimeMillis();
//Update debug parameters.
if(BuildConfig.DEBUG){
updateCallCount++;
if(System.currentTimeMillis() - lastUpdateCallReset > 1000){
lastUpdateCallReset = System.currentTimeMillis();
ups = updateCallCount;
updateCallCount = 0;
}
}
line.update(currentTimeMillis);
//Check for item pickups
for(int i = 0; i < items.size(); i++){
if(new Rect((int)line.getX()*map.tileSize - 16, (int)line.getY()*map.tileSize- 16, (int)line.getX()*map.tileSize+16, (int)line.getY()*map.tileSize+16).intersect(
new Rect(items.get(i).x, items.get(i).y, items.get(i).x + items.get(i).width, items.get(i).y + items.get(i).height))){
if(items.get(i).type == ItemType.Potion){
line.addHealth(5);
AudioPlayer.playSound(AudioPlayer.potion);
}else if(items.get(i).type == ItemType.Coin){
AudioPlayer.playSound(AudioPlayer.coin);
}
items.remove(i);
i
}
}
//Check if player entered city.
if(new Rect((int)line.getX()*map.tileSize - 16, (int)line.getY()*map.tileSize - 16, (int)line.getX()*map.tileSize+16, (int)line.getY()*map.tileSize+16).intersect(
new Rect(map.city.x, map.city.y, map.city.x + 64, map.city.y + 64))){
AudioPlayer.playSound(AudioPlayer.city);
setScreen(Screen.MENU);
}
for(int i = 0; i < enemies.size(); i++){
enemies.get(i).update(currentTimeMillis);
}
if(line.dead){
setScreen(Screen.START);
}
for(int i = 0; i < particles.size(); i++){
if(particles.get(i).destroy == true){
particles.remove(i);
i
}
}
for(int i = 0; i < particles.size(); i++){
particles.get(i).update(currentTimeMillis);
}
drawCall(gameCanvas);
}
}
}
/**
* Save game settings.
*/
private void saveSettings(){
SharedPreferences settings = MainActivity.context.getSharedPreferences("settings", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("sound", SoundOn);
editor.putInt("controls", gameControls.getValue());
editor.commit();
}
/**
* Set turning buttons to show correct turning
* images depending on player movement.
*/
public void setTurnButtons(){
//Reset all previous transforms.
leftButton.setRotation(0);
rightButton.setRotation(0);
leftButton.setScaleX(1);
rightButton.setScaleX(1);
leftButton.setScaleY(1);
rightButton.setScaleY(1);
if(gameControls == Controls.Button_Static){
if(line.getYVelocity() > 0){
leftButton.setRotation(0);
leftButton.setScaleY(-1);
rightButton.setRotation(0);
rightButton.setScaleY(-1);
}else if(line.getYVelocity() < 0){
rightButton.setRotation(0);
leftButton.setRotation(0);
}else if(line.getXVelocity() > 0){
leftButton.setScaleY(-1);
rightButton.setScaleY(-1);
leftButton.setRotation(270);
rightButton.setRotation(270);
}else if(line.getXVelocity() < 0){
rightButton.setRotation(270);
leftButton.setRotation(270);
}
}else if(gameControls == Controls.Button_Clockwise){
if(line.getYVelocity() > 0){
leftButton.setRotation(180);
rightButton.setRotation(180);
}else if(line.getYVelocity() < 0){
rightButton.setRotation(0);
leftButton.setRotation(0);
}else if(line.getXVelocity() > 0){
leftButton.setRotation(90);
rightButton.setRotation(90);
}else if(line.getXVelocity() < 0){
rightButton.setRotation(270);
leftButton.setRotation(270);
}
}
}
/**
* Back button pressed handler.
* @return true if back was handled, else false.
*/
public boolean onBackPressed(){
if(currentScreen == Screen.START){
return false;
}else if(currentScreen == Screen.OPTIONS){
setScreen(Screen.START);
}else if(currentScreen == Screen.BATTLE){
setScreen(Screen.START);
}else if(currentScreen == Screen.MENU){
setScreen(Screen.START);
}
return true;
}
@Override
/**
* Button clicked handler.
*/
public void onClick(View v) {
if(currentScreen == Screen.START){
if(v == startButton){
resetGame();
setScreen(Screen.BATTLE);
}else if(v == optionsButton){
setScreen(Screen.OPTIONS);
}
}
else if(currentScreen == Screen.OPTIONS){
if(v == audioButton){
SoundOn = !SoundOn;
if(SoundOn){
audioButton.setText("Sound On");
AudioPlayer.playSound(AudioPlayer.coin);
}else{
audioButton.setText("Sound Off");
}
saveSettings();
}
}
else if(currentScreen == Screen.MENU){
if(v == continueButton){
newLevel();
setScreen(Screen.BATTLE);
}
}
else if(currentScreen == Screen.BATTLE){
if(v == rightButton){
if(gameControls == Controls.Button_Static){
if(line.getYVelocity() != 0){
line.setDirection(1, 0);
}else if(line.getXVelocity() != 0){
line.setDirection(0, -1);
}
}else if(gameControls == Controls.Button_Clockwise){
if(line.getYVelocity() > 0){
line.setDirection(-1, 0);
}else if(line.getYVelocity() < 0){
line.setDirection(1, 0);
}else if(line.getXVelocity() > 0){
line.setDirection(0, 1);
}else if(line.getXVelocity() < 0){
line.setDirection(0, -1);
}
}
setTurnButtons();
}else if(v == leftButton){
if(gameControls == Controls.Button_Static){
if(line.getYVelocity() != 0){
line.setDirection(-1, 0);
}else if(line.getXVelocity() != 0){
line.setDirection(0, 1);
}
}else if(gameControls == Controls.Button_Clockwise){
if(line.getYVelocity() > 0){
line.setDirection(1, 0);
}else if(line.getYVelocity() < 0){
line.setDirection(-1, 0);
}else if(line.getXVelocity() > 0){
line.setDirection(0, -1);
}else if(line.getXVelocity() < 0){
line.setDirection(0, 1);
}
}
setTurnButtons();
}
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
if(id == 0){
gameControls = Controls.Button_Static;
}else if(id == 1){
gameControls = Controls.Button_Clockwise;
}else if(id == 2){
gameControls = Controls.Swipe;
}else if(id == 3){
gameControls = Controls.Tilt;
}
saveSettings();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
/**
* Screen touch handler.
*/
public void onTouchEvent(MotionEvent event){
//Record where touch began, used for swiping.
if(event.getAction() == MotionEvent.ACTION_DOWN){
startTouchX = (int) event.getX();
startTouchY = (int) event.getY();
}
//Record current touch location.
if(event.getAction() == MotionEvent.ACTION_DOWN ||
event.getAction() == MotionEvent.ACTION_MOVE){
touchX = (int) event.getX();
touchY = (int) event.getY();
}
//Handle swipe input if playing with swipe controls.
if(gameControls == Controls.Swipe && event.getAction() == MotionEvent.ACTION_UP){
int xDelta = startTouchX - (int) event.getX();
int yDelta = startTouchY - (int) event.getY();
//If player is moving in Y direction and swipe was in x direction.
if(line.getYVelocity() != 0 && Math.abs(xDelta) > Math.abs(yDelta)){
line.setDirection(-Math.signum(xDelta), 0);
}else if(line.getXVelocity() != 0 && Math.abs(yDelta) > Math.abs(xDelta)){
//If player is moving in X direction and swipe was in y direction.
line.setDirection(0, -Math.signum(yDelta));
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
@Override
/**
* Handle tilt input if playing with tilt controls.
*/
public void onSensorChanged(SensorEvent event) {
if(gameControls == Controls.Tilt){
float x = event.values[0];
float y = event.values[1];
if(Math.abs(x) >= 0.5 && line.getYVelocity() != 0 && Math.abs(x) > Math.abs(y)){
line.setDirection(-Math.signum(x), 0);
}else if(Math.abs(y) >= 0.5 && line.getXVelocity() != 0 && Math.abs(x) < Math.abs(y)){
line.setDirection(0, Math.signum(y));
}
}
}
}
|
package org.neo4j.graphdb;
import java.util.Collection;
import java.util.Iterator;
public interface Traverser extends Iterable<Node>
{
/**
* Defines a traversal order as used by the traversal framework.
*/
public static enum Order
{
/**
* Sets a depth first traversal meaning the traverser will
* go as deep as possible (increasing depth for each traversal) before
* traversing next relationship on same depth.
*/
DEPTH_FIRST,
/**
* Sets a breadth first traversal meaning the traverser will traverse
* all relationships on the current depth before going deeper.
*/
BREADTH_FIRST
}
/**
* Returns the current traversal postion.
* @return The current traversal position
*/
public TraversalPosition currentPosition();
/**
* Returns a collection of all nodes for this traversal. It traverses
* through the graph (according to given filters and evaluators) and
* collects those encountered nodes along the way. When this method has
* returned, this traverser will be at the end of its traversal, such that
* a call to {@code hasNext()} for the {@link #iterator()} will return
* {@code false}.
*
* @return A collection of all nodes for this this traversal.
*/
public Collection<Node> getAllNodes();
// Doc: especially remove() thing
/**
* Returns an iterator for this traverser.
* @return An iterator for this traverser
*/
// Doc: does it create a new iterator or reuse the existing one? This is
// very important! It must be re-use, how else would currentPosition()
// make sense?
public Iterator<Node> iterator();
}
|
package org.ccnx.ccn.protocol;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import org.ccnx.ccn.impl.encoding.GenericXMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLDecoder;
import org.ccnx.ccn.impl.encoding.XMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLEncoder;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.io.content.ContentDecodingException;
import org.ccnx.ccn.io.content.ContentEncodingException;
/**
* ContentNames consist of a sequence of byte[] components which may not
* be assumed to follow any string encoding, or any other particular encoding.
* The constructors therefore provide for creation only from byte[]s.
* To create a ContentName from Strings, a client must call one of the static
* methods that implements a conversion.
*/
public class ContentName extends GenericXMLEncodable implements XMLEncodable, Comparable<ContentName> {
/**
* Official CCN URI scheme.
*/
public static final String SCHEME = "ccnx:";
/**
* This scheme has been deprecated, but we still want to accept it.
*/
public static final String ORIGINAL_SCHEME = "ccn:";
public static final String SEPARATOR = "/";
public static final ContentName ROOT = new ContentName(0, (ArrayList<byte []>)null);
public static final String CONTENT_NAME_ELEMENT = "Name";
private static final String COMPONENT_ELEMENT = "Component";
protected ArrayList<byte []> _components;
public static class DotDotComponent extends Exception { // Need to strip off a component
private static final long serialVersionUID = 4667513234636853164L;
};
// Constructors
public ContentName() {
this(0, (ArrayList<byte[]>)null);
}
public ContentName(byte components[][]) {
if (null == components) {
_components = null;
} else {
_components = new ArrayList<byte []>(components.length);
for (int i=0; i < components.length; ++i) {
_components.add(components[i].clone());
}
}
}
/**
* Constructor given another ContentName, appends an extra component.
* @param parent used for the base of the name, if null, no prefix
* added.
* @param name component to be appended; if null, just copy parent
*/
public ContentName(ContentName parent, byte [] name) {
this(((parent != null) ? parent.count() : 0) +
((null != name) ? 1 : 0),
((parent != null) ? parent.components() : null));
if (null != name) {
byte [] c = new byte[name.length];
System.arraycopy(name,0,c,0,name.length);
_components.add(c);
}
}
/**
* Constructor given another ContentName, appends extra components.
* @param parent used for the base of the name.
* @param childComponents components to be appended.
*/
public ContentName(ContentName parent, byte [][] childComponents) {
this(parent.count() +
((null != childComponents) ? childComponents.length : 0), parent.components());
if (null != childComponents) {
for (byte [] b : childComponents) {
if (null == b)
continue;
byte [] c = new byte[b.length];
System.arraycopy(b,0,c,0,b.length);
_components.add(c);
}
}
}
/**
* Now that components() returns an ArrayList<byte []>, make a constructor that takes that
* as input.
* @param parent used for the base of the name.
* @param childComponents the additional name components to add at the end of parent
*/
public ContentName(ContentName parent, ArrayList<byte []> childComponents) {
this(parent.count() +
((null != childComponents) ? childComponents.size() : 0), parent.components());
if (null != childComponents) {
for (byte [] b : childComponents) {
if (null == b)
continue;
byte [] c = new byte[b.length];
System.arraycopy(b,0,c,0,b.length);
_components.add(c);
}
}
}
public ContentName(ContentName parent, byte[] name1, byte[] name2) {
this (parent.count() +
((null != name1) ? 1 : 0) +
((null != name2) ? 1 : 0), parent.components());
if (null != name1) {
byte [] c = new byte[name1.length];
System.arraycopy(name1,0,c,0,name1.length);
_components.add(c);
}
if (null != name2) {
byte [] c = new byte[name2.length];
System.arraycopy(name2,0,c,0,name2.length);
_components.add(c);
}
}
/**
* Constructor for extending or contracting names.
* @param count only this number of name components are taken from components.
* @param components
*/
public ContentName(int count, byte components[][]) {
if (0 >= count) {
_components = new ArrayList<byte []>(0);
} else {
int max = (null == components) ? 0 :
((count > components.length) ?
components.length : count);
_components = new ArrayList<byte []>(max);
for (int i=0; i < max; ++i) {
byte [] c = new byte[components[i].length];
System.arraycopy(components[i],0,c,0,components[i].length);
_components.add(c);
}
}
}
/**
* Constructor for extending or contracting names.
* Performs a faster shallow copy of the components, as we don't tend to alter name components
* once created.
* @param count Only this number of name components are copied into the new name.
* @param components These are the name components to be copied. Can be null, empty, or longer or shorter than count.
*/
public ContentName(int count, ArrayList<byte []>components) {
if (0 >= count) {
_components = new ArrayList<byte[]>(0);
} else {
int max = (null == components) ? 0 :
((count > components.size()) ?
components.size() : count);
_components = new ArrayList<byte []>(max);
for (int i=0; i < max; ++i) {
_components.add(components.get(i));
}
}
}
/**
* Subname constructor for extending or contracting names, extracts particular
* subcomponents from an existing set.
* Performs a faster shallow copy of the components, as we don't tend to alter name components
* once created.
* @param start This is index (0-based) of the first component to copy.
* @param count Only this number of name components are copied into the new name. If count-start is
* greater than the last component in the components array, only copies count-start.
* @param components These are the name components to be copied. Can be null, empty, or longer or shorter than count.
*/
public ContentName(int start, int count, ArrayList<byte []>components) {
if (0 >= count) {
_components = new ArrayList<byte[]>(0);
} else {
int max = (null == components) ? 0 :
((count > (components.size()-start)) ?
(components.size()-start) : count);
_components = new ArrayList<byte []>(max);
for (int i=start; i < max+start; ++i) {
_components.add(components.get(i));
}
}
}
/**
* Copy constructor, also used by subclasses merely wanting a different
* name in encoding/decoding.
* @param otherName
*/
public ContentName(ContentName otherName) {
this(((null == otherName) ? 0 : otherName.count()), ((null == otherName) ? null : otherName.components()));
}
public static ContentName fromURI(String name) throws MalformedContentNameStringException {
try {
ContentName result = new ContentName();
if((name == null) || (name.length() == 0)) {
result._components = null;
} else {
String[] parts;
String justname = name;
if (!name.startsWith(SEPARATOR)){
if ((!name.startsWith(SCHEME + SEPARATOR)) && (!name.startsWith(ORIGINAL_SCHEME + SEPARATOR))) {
throw new MalformedContentNameStringException("ContentName strings must begin with " + SEPARATOR + " or " + SCHEME + SEPARATOR);
}
if (name.startsWith(SCHEME)) {
justname = name.substring(SCHEME.length());
} else if (name.startsWith(ORIGINAL_SCHEME)) {
justname = name.substring(ORIGINAL_SCHEME.length());
}
}
parts = justname.split(SEPARATOR);
if (parts.length == 0) {
// We've been asked to parse the root name.
result._components = new ArrayList<byte []>(0);
} else {
result._components = new ArrayList<byte []>(parts.length - 1);
}
// Leave off initial empty component
for (int i=1; i < parts.length; ++i) {
try {
byte[] component = componentParseURI(parts[i]);
if (null != component) {
result._components.add(component);
}
} catch (DotDotComponent c) {
// Need to strip "parent"
if (result._components.size() < 1) {
throw new MalformedContentNameStringException("ContentName string contains too many .. components: " + name);
} else {
result._components.remove(result._components.size()-1);
}
}
}
}
return result;
} catch (URISyntaxException e) {
throw new MalformedContentNameStringException(e.getMessage());
}
}
/**
* Given an array of strings, apply URI decoding and create a ContentName
* @see fromURI(String)
* @throws MalformedContentNameStringException
*/
public static ContentName fromURI(String parts[]) throws MalformedContentNameStringException {
try {
ContentName result = new ContentName();
if ((parts == null) || (parts.length == 0)) {
result._components = null;
} else {
result._components = new ArrayList<byte []>(parts.length);
for (int i=0; i < parts.length; ++i) {
try {
byte[] component = componentParseURI(parts[i]);
if (null != component) {
result._components.add(component);
}
} catch (DotDotComponent c) {
// Need to strip "parent"
if (result._components.size() < 1) {
throw new MalformedContentNameStringException("ContentName parts contains too many .. components");
} else {
result._components.remove(result._components.size()-1);
}
}
}
}
return result;
} catch (URISyntaxException e) {
throw new MalformedContentNameStringException(e.getMessage());
}
}
public static ContentName fromURI(ContentName parent, String name) throws MalformedContentNameStringException {
try {
ContentName result = new ContentName(parent.count(), parent.components());
if (null != name) {
try {
byte[] decodedName = componentParseURI(name);
if (null != decodedName) {
result._components.add(decodedName);
}
} catch (DotDotComponent c) {
// Need to strip "parent"
if (result._components.size() < 1) {
throw new MalformedContentNameStringException("ContentName parts contains too many .. components");
} else {
result._components.remove(result._components.size()-1);
}
}
}
return result;
} catch (URISyntaxException e) {
throw new MalformedContentNameStringException(e.getMessage());
}
}
/**
* Return the <code>ContentName</code> created from a native Java String.
* In native strings only "/" is special, interpreted as component delimiter,
* while all other characters will be encoded as UTF-8 in the output <code>ContentName</code>
* Native String representations do not incorporate a URI scheme, and so must
* begin with the component delimiter "/".
* TODO use Java string escaping rules?
* @param name
* @throws MalformedContentNameStringException if name does not start with "/"
*/
public static ContentName fromNative(String name) throws MalformedContentNameStringException {
ContentName result = new ContentName();
if (!name.startsWith(SEPARATOR)){
throw new MalformedContentNameStringException("ContentName native strings must begin with " + SEPARATOR);
}
if((name == null) || (name.length() == 0)) {
result._components = null;
} else {
String[] parts;
parts = name.split(SEPARATOR);
if (parts.length == 0) {
// We've been asked to parse the root name.
result._components = new ArrayList<byte []>(0);
} else {
result._components = new ArrayList<byte []>(parts.length - 1);
}
// Leave off initial empty component
for (int i=1; i < parts.length; ++i) {
byte[] component = componentParseNative(parts[i]);
if (null != component) {
result._components.add(component);
}
}
}
return result;
}
public static ContentName fromNative(ContentName parent, String name) {
ContentName result = new ContentName(parent.count(), parent.components());
if (null != name) {
byte[] decodedName = componentParseNative(name);
if (null != decodedName) {
result._components.add(decodedName);
}
}
return result;
}
public static ContentName fromNative(ContentName parent, byte [] name) {
ContentName result = new ContentName(parent.count(), parent.components());
result._components.add(name);
return result;
}
public static ContentName fromNative(ContentName parent, String name1, String name2) {
return fromNative(parent, new String[]{name1, name2});
}
public static ContentName fromNative(String [] parts) {
return fromNative(new ContentName(), parts);
}
public static ContentName fromNative(ContentName parent, String [] parts) {
ContentName result = new ContentName(parent.count(), parent._components);
if ((null != parts) && (parts.length > 0)) {
for (int i=0; i < parts.length; ++i) {
byte[] component = componentParseNative(parts[i]);
if (null != component) {
result._components.add(component);
}
}
}
return result;
}
public ContentName clone() {
return new ContentName(count(), components());
}
/**
* Returns a new name with the last component removed.
*/
public ContentName parent() {
return new ContentName(count()-1, components());
}
public String toString() {
if (null == _components) return null;
// toString of root name is "/"
if (0 == _components.size()) return SEPARATOR;
StringBuffer nameBuf = new StringBuffer();
for (int i=0; i < _components.size(); ++i) {
nameBuf.append(SEPARATOR);
nameBuf.append(componentPrintURI(_components.get(i)));
}
return nameBuf.toString();
}
public static String componentPrintURI(byte[] bs, int offset, int length) {
if (null == bs || bs.length == 0) {
// Empty component represented by three '.'
return "...";
}
// To get enough control over the encoding, we use
// our own loop and NOT simply new String(bs) (or java.net.URLEncoder) because
// with Unicode "Replacement Character" U+FFFD. We could use a CharsetDecoder
// except that this is almost certainly less efficient and some versions of Java
// Also, it is much easier to verify what this is doing and compare to the C library implementation.
StringBuffer result = new StringBuffer();
for (int i = 0; i < bs.length; i++) {
byte ch = bs[i];
if (('a' <= ch && ch <= 'z') ||
('A' <= ch && ch <= 'Z') ||
('0' <= ch && ch <= '9') ||
ch == '-' || ch == '.' || ch == '_' || ch == '~')
// Since these are all BMP characters, the can be represented in one Java Character
result.append(Character.toChars(ch)[0]);
else
result.append(String.format("%%%02X", ch));
}
int i = 0;
for (i = 0; i < result.length() && result.charAt(i) == '.'; i++) {
continue;
}
if (i == result.length()) {
// all dots
result.append("...");
}
return result.toString();
}
public static String componentPrintURI(byte [] bs) {
return componentPrintURI(bs, 0, bs.length);
}
public static String componentPrintNative(byte[] bs) {
// Native string print is the one place where we can just use
// Java native platform decoding. Note that this is not
// necessarily invertible, since there may be byte sequences
// that may be converted to e.g. Unicode "Replacement Character" U+FFFD.
return new String(bs);
}
// UrlEncoded in case we want variant compatible with java.net.URLEncoder
// again in future
// protected static String componentPrintUrlEncoded(byte[] bs) {
// // NHB: Van is expecting the URI encoding rules
// if (null == bs || bs.length == 0) {
// // Empty component represented by three '.'
// return "...";
// try {
// // Note that this would probably be more efficient as simple loop:
// // In order to use the URLEncoder class to handle the
// // parts that are UTF-8 already, we decode the bytes into Java String
// // as though they were UTF-8. Wherever that fails
// // we directly convert those bytes to the %xy output format.
// // To get enough control over the decoding, we must use
// // the charset decoder and NOT simply new String(bs) because
// // with Unicode "Replacement Character" U+FFFD.
// StringBuffer result = new StringBuffer();
// Charset charset = Charset.forName("UTF-8");
// CharsetDecoder decoder = charset.newDecoder();
// decoder.onMalformedInput(CodingErrorAction.REPORT);
// decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
// ByteBuffer input = ByteBuffer.wrap(bs);
// CharBuffer output = CharBuffer.allocate(((int)decoder.maxCharsPerByte()*bs.length)+1);
// while (input.remaining() > 0) {
// CoderResult cr = decoder.decode(input, output, true);
// assert(!cr.isOverflow());
// // URLEncode whatever was successfully decoded from UTF-8
// output.flip();
// result.append(URLEncoder.encode(output.toString(), "UTF-8"));
// output.clear();
// if (cr.isError()) {
// for (int i=0; i<cr.length(); i++) {
// result.append(String.format("%%%02X", input.get()));
// int i = 0;
// for (i = 0; i < result.length() && result.charAt(i) == '.'; i++) {
// continue;
// if (i == result.length()) {
// // all dots
// result.append("...");
// return result.toString();
// } catch (UnsupportedCharsetException e) {
// throw new RuntimeException("UTF-8 not supported charset", e);
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("UTF-8 not supported", e);
public static String hexPrint(byte [] bs) {
if (null == bs)
return new String();
BigInteger bi = new BigInteger(1,bs);
return bi.toString(16);
}
public static byte[] componentParseURI(String name) throws DotDotComponent, URISyntaxException {
byte[] decodedName = null;
boolean alldots = true; // does this component contain only dots after unescaping?
boolean quitEarly = false;
ByteBuffer result = ByteBuffer.allocate(name.length());
for (int i = 0; i < name.length() && !quitEarly; i++) {
char ch = name.charAt(i);
switch (ch) {
case '%':
// This is a byte string %xy where xy are hex digits
// Since the input string must be compatible with the output
// of componentPrint(), we may convert the byte values directly.
// There is no need to go through a character representation.
if (name.length()-1 < i+2) {
throw new URISyntaxException(name, "malformed %xy byte representation: too short", i);
}
if (name.charAt(i+1) == '-') {
throw new URISyntaxException(name, "malformed %xy byte representation: negative value not permitted", i);
}
try {
result.put(new Integer(Integer.parseInt(name.substring(i+1, i+3),16)).byteValue());
} catch (NumberFormatException e) {
throw new URISyntaxException(name, "malformed %xy byte representation: not legal hex number: " + name.substring(i+1, i+3), i);
}
i+=2; // for loop will increment by one more to get net +3 so past byte string
break;
// Note in C lib case 0 is handled like the two general delimiters below that terminate processing
// but that case should never arise in Java which uses real unicode characters.
case '/':
case '?':
case '
quitEarly = true; // early exit from containing loop
break;
case ':': case '[': case ']': case '@':
case '!': case '$': case '&': case '\'': case '(': case ')':
case '*': case '+': case ',': case ';': case '=':
// Permit unescaped reserved characters
result.put(DataUtils.getBytesFromUTF8String(name.substring(i, i+1)));
break;
default:
if (('a' <= ch && ch <= 'z') ||
('A' <= ch && ch <= 'Z') ||
('0' <= ch && ch <= '9') ||
ch == '-' || ch == '.' || ch == '_' || ch == '~') {
// This character remains the same
result.put(DataUtils.getBytesFromUTF8String(name.substring(i, i+1)));
} else {
throw new URISyntaxException(name, "Illegal characters in URI", i);
}
break;
}
if (!quitEarly && result.get(result.position()-1) != '.') {
alldots = false;
}
}
result.flip();
if (alldots) {
if (result.limit() <= 1) {
return null;
} else if (result.limit() == 2) {
throw new DotDotComponent();
} else {
// Remove the three '.' extra
result.limit(result.limit()-3);
}
}
decodedName = new byte[result.limit()];
System.arraycopy(result.array(), 0, decodedName, 0, result.limit());
return decodedName;
}
/**
* Parse native string component: just UTF-8 encode
* For full names in native strings only "/" is special
* but for an individual component we will even allow that.
* This method intentionally throws no declared exceptions
* so you can be confident in encoding any native Java String
* TODO make this use Java string escaping rules?
* @param name Component as native Java string
*/
public static byte[] componentParseNative(String name) {
// Handle exception s around missing UTF-8
return DataUtils.getBytesFromUTF8String(name);
}
// UrlEncoded in case we want to enable it again
// protected static byte[] componentParseUrlEncoded(String name) throws DotDotComponent {
// byte[] decodedName = null;
// boolean alldots = true; // does this component contain only dots after unescaping?
// try {
// ByteBuffer result = ByteBuffer.allocate(name.length());
// for (int i = 0; i < name.length(); i++) {
// if (name.charAt(i) == '%') {
// // This is a byte string %xy where xy are hex digits
// // Since the input string must be compatible with the output
// // of componentPrint(), we may convert the byte values directly.
// // There is no need to go through a character representation.
// if (name.length()-1 < i+2) {
// if (name.charAt(i+1) == '-') {
// try {
// result.put(new Integer(Integer.parseInt(name.substring(i+1, i+3),16)).byteValue());
// } catch (NumberFormatException e) {
// i+=2; // for loop will increment by one more to get net +3 so past byte string
// } else if (name.charAt(i) == '+') {
// // This is the one character translated to a different one
// result.put(" ".getBytes("UTF-8"));
// } else {
// // This character remains the same
// result.put(name.substring(i, i+1).getBytes("UTF-8"));
// if (result.get(result.position()-1) != '.') {
// alldots = false;
// result.flip();
// if (alldots) {
// if (result.limit() <= 1) {
// return null;
// } else if (result.limit() == 2) {
// throw new DotDotComponent();
// } else {
// // Remove the three '.' extra
// result.limit(result.limit()-3);
// decodedName = new byte[result.limit()];
// System.arraycopy(result.array(), 0, decodedName, 0, result.limit());
// } catch (UnsupportedEncodingException e) {
// Library.severe("UTF-8 not supported.");
// throw new RuntimeException("UTF-8 not supported", e);
// return decodedName;
public ArrayList<byte[]> components() { return _components; }
/**
* @return The number of components in the name.
*/
public int count() {
if (null == _components) return 0;
return _components.size();
}
/**
* Append a segmented name to this name.
*/
public ContentName append(ContentName other) {
return new ContentName(this, other.components());
}
/**
* Append a name to this one, where the child name might have more than one
* path component -- e.g. foo/bar/bash. Will add leading / to postfix for
* parsing, if one not present.
* @throws MalformedContentNameStringException
*/
public ContentName append(String postfix) throws MalformedContentNameStringException {
if (!postfix.startsWith("/")) {
postfix = "/" + postfix;
}
ContentName postfixName = ContentName.fromNative(postfix);
return this.append(postfixName);
}
/**
* Get the i'th component, indexed from 0.
* @param i
* @return null if i is out of range.
*/
public final byte[] component(int i) {
if ((null == _components) || (i >= _components.size())) return null;
return _components.get(i);
}
public final byte [] lastComponent() {
if (null == _components || _components.size() == 0)
return null;
return _components.get(_components.size()-1);
}
/**
* @return The i'th component, converted using URI encoding.
*/
public String stringComponent(int i) {
if ((null == _components) || (i >= _components.size())) return null;
return componentPrintURI(_components.get(i));
}
/**
* Used by NetworkObject to decode the object from a network stream.
* @see org.ccnx.ccn.impl.encoding.XMLEncodable
*/
public void decode(XMLDecoder decoder) throws ContentDecodingException {
decoder.readStartElement(getElementLabel());
_components = new ArrayList<byte []>();
while (decoder.peekStartElement(COMPONENT_ELEMENT)) {
_components.add(decoder.readBinaryElement(COMPONENT_ELEMENT));
}
decoder.readEndElement();
}
/**
* Test if this name is a prefix of another name - i.e. do all components in this name exist in the
* name being compared with. Note there do not need to be any more components in the name
* being compared with.
* @param name name being compared with.
*/
public boolean isPrefixOf(ContentName name) {
return isPrefixOf(name, count());
}
/**
* Tests if the first n components are a prefix of name
* @param name
* @param count number of components to check
*/
public boolean isPrefixOf(ContentName name, int count) {
if (null == name)
return false;
if (count > name.count())
return false;
for (int i=0; i < count; ++i) {
if (!Arrays.equals(name.component(i), component(i)))
return false;
}
return true;
}
/**
* Compare our name to the name of the ContentObject.
* If our name is 1 component longer than the ContentObject
* and no prefix count is set, our name might contain a digest.
* In that case, try matching the content to the last component as
* a digest.
*
* @param other
* @return
*/
public boolean isPrefixOf(ContentObject other) {
return isPrefixOf(other, count());
}
public boolean isPrefixOf(ContentObject other, int count) {
boolean match = isPrefixOf(other.name(), count);
if (match || count() != count)
return match;
if (count() == other.name().count() + 1) {
if (DataUtils.compare(component(count() - 1), other.digest()) == 0) {
return true;
}
}
return false;
}
/**
* hashCode and equals not auto-generated, ArrayList does not do the right thing.
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (! (obj instanceof ContentName))
return false;
final ContentName other = (ContentName)obj;
if (other.count() != this.count())
return false;
for (int i=0; i < count(); ++i) {
if (!Arrays.equals(other.component(i), this.component(i)))
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
for (int i=0; i < count(); ++i) {
result = prime * result + Arrays.hashCode(component(i));
}
return result;
}
/**
* Parses the canonical URI representation.
* @param str
* @return
* @throws MalformedContentNameStringException
*/
public static ContentName parse(String str) throws MalformedContentNameStringException {
if(str == null) return null;
if(str.length() == 0) return ROOT;
return fromURI(str);
}
/**
* Uses the canonical URI representation
* @param str
* @return
*/
public boolean contains(String str) throws URISyntaxException {
try {
byte[] parsed = componentParseURI(str);
if (null == parsed) {
return false;
} else {
return contains(parsed);
}
} catch (DotDotComponent c) {
return false;
}
}
public boolean contains(byte [] component) {
return (containsWhere(component) >= 0);
}
/**
* Looks for a component.
* @param str Component to search for, encoded using URI encoding.
* @return The index of the first component that matched. Starts at 0.
* @throws URISyntaxException
*/
public int containsWhere(String str) throws URISyntaxException {
try {
byte[] parsed = componentParseURI(str);
if (null == parsed) {
return -1;
} else {
return containsWhere(parsed);
}
} catch (DotDotComponent c) {
return -1;
}
}
/**
* Return component index of the first matching component if it exists.
* @param component Component to search for.
* @return -1 on failure, component index otherwise (starts at 0).
*/
public int containsWhere(byte [] component) {
int i=0;
boolean result = false;
for (i=0; i < _components.size(); ++i) {
if (Arrays.equals(_components.get(i),component)) {
result = true;
break;
}
}
if (result)
return i;
return -1;
}
/**
* Return the first componentNumber components of this name as a new name.
* @param componentNumber
* @return
*/
public ContentName cut(int componentCount) {
if ((componentCount < 0) || (componentCount > count())) {
throw new IllegalArgumentException("Illegal component count: " + componentCount);
}
if (componentCount == count())
return this;
return new ContentName(componentCount, this.components());
}
/**
* Slice the name off right before the given component
* @param component
*/
public ContentName cut(byte [] component) {
int offset = this.containsWhere(component);
if (offset < 0) {
// unfragmented
return this;
}
// else need to cut it
return new ContentName(offset, this.components());
}
/**
* Slice the name off right before the given component
* @param component In URI encoded form.
*/
public ContentName cut(String component) throws URISyntaxException {
try {
byte[] parsed = componentParseURI(component);
if (null == parsed) {
return this;
} else {
return cut(parsed);
}
} catch (DotDotComponent c) {
return this;
}
}
/**
* Return a subname of this name as a new name.
* @param start the starting component index (0-based)
* @param componentCount the number of components to include beginning with start.
* @return the new name.
*/
public ContentName subname(int start, int componentCount) {
return new ContentName(start, componentCount, components());
}
/**
* Return the remainder of this name after the prefix, if the prefix
* is a prefix of this name. Otherwise return null. If the prefix is
* identical to this name, return the root (empty) name.
*/
public ContentName postfix(ContentName prefix) {
if (!prefix.isPrefixOf(this))
return null;
if (prefix.count() == count()) {
return ROOT;
}
return subname(prefix.count(), count()-prefix.count());
}
/**
* Used by NetworkObject to encode the object to a network stream.
* @see org.ccnx.ccn.impl.encoding.XMLEncodable
*/
public void encode(XMLEncoder encoder) throws ContentEncodingException {
if (!validate()) {
throw new ContentEncodingException("Cannot encode " + this.getClass().getName() + ": field values missing.");
}
encoder.writeStartElement(getElementLabel());
for (int i=0; i < count(); ++i) {
encoder.writeElement(COMPONENT_ELEMENT, _components.get(i));
}
encoder.writeEndElement();
}
@Override
public boolean validate() {
return (null != _components);
}
@Override
public String getElementLabel() {
return CONTENT_NAME_ELEMENT;
}
public ContentName copy(int nameComponentCount) {
return new ContentName(nameComponentCount, this.components());
}
public int compareTo(ContentName o) {
if (this == o)
return 0;
int len = (this.count() > o.count()) ? this.count() : o.count();
int componentResult = 0;
for (int i=0; i < len; ++i) {
componentResult = DataUtils.compare(this.component(i), o.component(i));
if (0 != componentResult)
return componentResult;
}
if (this.count() < o.count())
return -1;
else if (this.count() > o.count())
return 1;
return 0;
}
}
|
package com.alibaba.akita.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ViewSwitcher;
import com.alibaba.akita.Akita;
import com.alibaba.akita.R;
import com.alibaba.akita.util.AndroidUtil;
import com.alibaba.akita.util.Log;
import com.alibaba.akita.widget.remoteimageview.ImageView_;
import com.alibaba.akita.widget.remoteimageview.RemoteImageLoader;
import com.alibaba.akita.widget.remoteimageview.RemoteImageLoaderHandler;
/**
* An remoteimageview view that fetches its remoteimageview off the web using the supplied URL. While the remoteimageview is being
* downloaded, a progress indicator will be shown. The following attributes are supported:
* <ul>
* <li>android:src (Drawable) -- The default/placeholder remoteimageview that is shown if no remoteimageview can be
* downloaded, or before the remoteimageview download starts (see {@link android.R.attr#src})
* <li>android:indeterminateDrawable (Drawable) -- The progress drawable to use while the remoteimageview is
* being downloaded (see {@link android.R.attr#indeterminateDrawable})</li>
* <li>ignition:imageUrl (String) -- The URL at which the remoteimageview is found online</li>
* <li>ignition:autoLoad (Boolean) -- Whether the download should start immediately after view
* inflation</li>
* <li>ignition:errorDrawable (Drawable) -- The drawable to display if the remoteimageview download fails</li>
* </ul>
*
* @author Matthias Kaeppler original.
* @author Justin Yang modified.
*
*/
public class RemoteImageView extends ViewSwitcher {
private static final String TAG = "akita.RemoteImageView";
public static final int DEFAULT_ERROR_DRAWABLE_RES_ID = R.drawable.ic_akita_image_alert;
private static final String ATTR_AUTO_LOAD = "autoLoad";
private static final String ATTR_IMAGE_URL = "imageUrl";
private static final String ATTR_ERROR_DRAWABLE = "errorDrawable";
private static final String ATTR_IMGBOX_WIDTH = "imgBoxWidth";
private static final String ATTR_IMGBOX_HEIGHT = "imgBoxHeight";
private static final String ATTR_ROUND_CORNER = "roundCorner";
private static final String ATTR_NO_CACHE = "noCache";
private static final String ATTR_PINCH_ZOOM = "pinchZoom";
private static final String ATTR_FADE_IN = "fadeIn";
private static final String ATTR_SHOW_PROGRESS = "showProgress";
private static final int[] ANDROID_VIEW_ATTRS = { android.R.attr.indeterminateDrawable };
private static final int ATTR_INDET_DRAWABLE = 0;
private String imageUrl;
private String httpReferer;
/**
* remoteimageview real Width in px
* wrap_content (<=0)
*/
private int imgBoxWidth = 0;
/**
* remoteimageview real Height in px
* wrap_content (<=0)
*/
private int imgBoxHeight = 0;
/**
* 0: no round corner
* >0: round corner px size
*/
private int roundCornerPx = 0;
/**
* cache
* trueCache
*/
private boolean noCache = false;
/**
* if true, then use PinchZoomImageView instead.
*/
private boolean pinchZoom;
/**
* fade in
*/
private boolean fadeIn;
/**
* show exact progress
*/
private boolean showProgress;
private boolean autoLoad, isLoaded;
private ProgressBar loadingSpinner;
private ImageView_ imageView;
private Drawable progressDrawable;
private int errorDrawable;
private RemoteImageLoader imageLoader;
private static RemoteImageLoader sharedImageLoader;
/**
* Use this method to inject an remoteimageview loader that will be shared across all instances of this
* class. If the shared reference is null, a new {@link RemoteImageLoader} will be instantiated
* for every instance of this class.
*
* @param imageLoader
* the shared remoteimageview loader
*/
public static void setSharedImageLoader(RemoteImageLoader imageLoader) {
sharedImageLoader = imageLoader;
}
/**
* @param context
* the view's current context
* @param imageUrl
* the URL of the remoteimageview to download and show
* @param autoLoad
* Whether the download should start immediately after creating the view. If set to
* false, use {@link #loadImage()} to manually trigger the remoteimageview download.
*/
public RemoteImageView(Context context, String imageUrl, boolean autoLoad,
boolean fadeIn, boolean pinchZoom, boolean showProgress) {
super(context);
initialize(context, imageUrl, null, 0, autoLoad, fadeIn, pinchZoom, showProgress, null);
}
/**
* @param context
* the view's current context
* @param imageUrl
* the URL of the remoteimageview to download and show
* @param progressDrawable
* the drawable to be used for the {@link android.widget.ProgressBar} which is displayed while the
* remoteimageview is loading
* @param errorDrawable
* the drawable to be used if a download error occurs
* @param autoLoad
* Whether the download should start immediately after creating the view. If set to
* false, use {@link #loadImage()} to manually trigger the remoteimageview download.
*/
public RemoteImageView(Context context, String imageUrl, Drawable progressDrawable,
int errorDrawable, boolean autoLoad, boolean fadeIn,
boolean pinchZoom, boolean showProgress) {
super(context);
initialize(context, imageUrl, progressDrawable, errorDrawable, autoLoad, fadeIn, pinchZoom, showProgress,
null);
}
public RemoteImageView(Context context, AttributeSet attributes) {
super(context, attributes);
// Read all Android specific view attributes into a typed array first.
// These are attributes that are specific to RemoteImageView, but which are not in the
// ignition XML namespace.
TypedArray imageViewAttrs = context.getTheme().obtainStyledAttributes(attributes,
ANDROID_VIEW_ATTRS, 0, 0);
int progressDrawableId = imageViewAttrs.getResourceId(ATTR_INDET_DRAWABLE, 0);
imageViewAttrs.recycle();
TypedArray a = context.getTheme().obtainStyledAttributes(attributes, R.styleable.RemoteImageView, 0, 0);
roundCornerPx = (int)a.getDimension(R.styleable.RemoteImageView_roundCorner, 0.0f);
noCache = a.getBoolean(R.styleable.RemoteImageView_noCache, false);
a.recycle();
int errorDrawableId = attributes.getAttributeResourceValue(Akita.XMLNS,
ATTR_ERROR_DRAWABLE, DEFAULT_ERROR_DRAWABLE_RES_ID);
int errorDrawable = errorDrawableId;
Drawable progressDrawable = null;
if (progressDrawableId > 0) {
progressDrawable = context.getResources().getDrawable(progressDrawableId);
}
String imageUrl = attributes.getAttributeValue(Akita.XMLNS, ATTR_IMAGE_URL);
boolean autoLoad = attributes
.getAttributeBooleanValue(Akita.XMLNS, ATTR_AUTO_LOAD, true);
imgBoxWidth = AndroidUtil.dp2px(context,
attributes.getAttributeIntValue(Akita.XMLNS, ATTR_IMGBOX_WIDTH, 0) );
imgBoxHeight = AndroidUtil.dp2px(context,
attributes.getAttributeIntValue(Akita.XMLNS, ATTR_IMGBOX_HEIGHT, 0) );
boolean pinchZoom = attributes.getAttributeBooleanValue(Akita.XMLNS, ATTR_PINCH_ZOOM, false);
boolean fadeIn = attributes.getAttributeBooleanValue(Akita.XMLNS, ATTR_FADE_IN, false);
boolean showProgress = attributes.getAttributeBooleanValue(Akita.XMLNS, ATTR_SHOW_PROGRESS, false);
initialize(context, imageUrl, progressDrawable, errorDrawable, autoLoad, fadeIn, pinchZoom, showProgress,
attributes);
}
public void setDownloadFailedImageRes(int imgRes) {
this.errorDrawable = imgRes;
}
private void initialize(Context context, String imageUrl, Drawable progressDrawable,
int errorDrawable, boolean autoLoad, boolean fadeIn, boolean pinchZoom, boolean showProgress,
AttributeSet attributes) {
this.imageUrl = imageUrl;
this.autoLoad = autoLoad;
this.fadeIn = fadeIn;
this.pinchZoom = pinchZoom;
this.showProgress = showProgress;
this.progressDrawable = progressDrawable;
this.errorDrawable = errorDrawable;
if (sharedImageLoader == null) {
this.imageLoader = new RemoteImageLoader(context);
} else {
this.imageLoader = sharedImageLoader;
}
// ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
// 125.0f, preferredItemHeight / 2.0f);
// anim.setDuration(500L);
if (fadeIn) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(500L);
setInAnimation(anim);
}
addLoadingSpinnerView(context);
addImageView(context, attributes);
if (autoLoad && imageUrl != null) {
loadImage();
} else {
// if we don't have anything to load yet, don't show the progress element
setDisplayedChild(1);
}
}
private void addLoadingSpinnerView(Context context) {
LayoutParams lp;
if (showProgress) {
loadingSpinner = (ProgressBar) ProgressBar.inflate(context, R.layout.processbar_horizontal, null);
lp = new LayoutParams(AndroidUtil.dp2px(context, 36), AndroidUtil.dp2px(context, 36));
lp.gravity = Gravity.CENTER;
} else {
loadingSpinner = new ProgressBar(context);
loadingSpinner.setIndeterminate(true);
if (this.progressDrawable == null) {
this.progressDrawable = loadingSpinner.getIndeterminateDrawable();
} else {
loadingSpinner.setIndeterminateDrawable(progressDrawable);
if (progressDrawable instanceof AnimationDrawable) {
((AnimationDrawable) progressDrawable).start();
}
}
lp = new LayoutParams(progressDrawable.getIntrinsicWidth(),
progressDrawable.getIntrinsicHeight());
lp.gravity = Gravity.CENTER;
}
addView(loadingSpinner, 0, lp);
}
private void addImageView(final Context context, AttributeSet attributes) {
if (pinchZoom) {
if (attributes != null) {
// pass along any view attribtues inflated from XML to the remoteimageview view
imageView = new PinchZoomImageView(context, attributes);
} else {
imageView = new PinchZoomImageView(context);
}
} else {
if (attributes != null) {
// pass along any view attribtues inflated from XML to the remoteimageview view
imageView = new ImageView_(context, attributes);
} else {
imageView = new ImageView_(context);
}
}
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.gravity = Gravity.CENTER;
addView(imageView, 1, lp);
}
public void setScaleType(ImageView.ScaleType scaleType) {
if (imageView != null) {
imageView.setScaleType(scaleType);
}
}
public void setDummyImageDrawable(Drawable drawable) {
if (imageLoader != null) {
imageLoader.setDefaultDummyDrawable(drawable);
}
}
/**
* Use this method to trigger the remoteimageview download if you had previously set autoLoad to false.
*/
public void loadImage() {
if (imageUrl == null) {
Exception e = new IllegalStateException(
"remoteimageview URL is null; did you forget to set it for this view?");
Log.e(TAG, e.toString(), e);
return;
}
setDisplayedChild(0);
if (showProgress) {
loadingSpinner.setProgress(0);
imageLoader.loadImage(imageUrl, httpReferer, noCache, loadingSpinner, imageView,
new DefaultImageLoaderHandler(imgBoxWidth, imgBoxHeight, roundCornerPx));
} else {
imageLoader.loadImage(imageUrl, httpReferer, noCache, null, imageView,
new DefaultImageLoaderHandler(imgBoxWidth, imgBoxHeight, roundCornerPx));
}
}
/**
* reset dummy image
*/
public void resetDummyImage() {
imageView.setImageResource(android.R.drawable.ic_menu_gallery);
}
public boolean isLoaded() {
return isLoaded;
}
/**
* set the url of remote image.
* use this method, then call loadImage().
* @param imageUrl
*/
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
/**
* to that kind of image which must be filled with referring url
* @param httpReferer referring url
*/
public void setHttpReferer(String httpReferer) {
this.httpReferer = httpReferer;
}
/**
* Set noCache or not
* @param noCache If true, use no cache every loading
*/
public void setNoCache(boolean noCache) {
this.noCache = noCache;
}
/**
* Box size in px.
* wrap_contant: <=0
* Set it to scale the remoteimageview using this box
* @param imgMaxWidth
* @param imgMaxHeight
*/
public void setImageBoxSize(int imgMaxWidth, int imgMaxHeight) {
this.imgBoxWidth = imgMaxWidth;
this.imgBoxHeight = imgMaxHeight;
}
/**
* Often you have resources which usually have an remoteimageview, but some don't. For these cases, use
* this method to supply a placeholder drawable which will be loaded instead of a web remoteimageview.
*
* Use this method to set local image.
*
* @param imageResourceId
* the resource of the placeholder remoteimageview drawable
*/
public void setLocalImage(int imageResourceId) {
try {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageResourceId);
imageView.setImageBitmap(bitmap);
imageView.setTag(R.id.ll_griditem, bitmap);
} catch (OutOfMemoryError ooe) {
Log.e(TAG, ooe.toString(), ooe);
}
setDisplayedChild(1);
}
/**
* Often you have resources which usually have an remoteimageview, but some don't. For these cases, use
* this method to supply a placeholder bitmap which will be loaded instead of a web remoteimageview.
*
* Use this method to set local image.
*
* @param bitmap
* the bitmap of the placeholder remoteimageview drawable
*/
public void setLocalImage(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
setDisplayedChild(1);
}
@Override
public void reset() {
super.reset();
this.setDisplayedChild(0);
}
/**
* setImageBoxSizerivonDestroy
*
*/
public void release() {
Bitmap bitmap = (Bitmap) imageView.getTag(R.id.ll_griditem);
if (bitmap != null && !bitmap.isRecycled()) bitmap.recycle();
}
private class DefaultImageLoaderHandler extends RemoteImageLoaderHandler {
public DefaultImageLoaderHandler(int imgMaxWidth, int imgMaxHeight, int roundCornerPx) {
super(imageView, imageUrl, errorDrawable, imgMaxWidth, imgMaxHeight, roundCornerPx);
}
@Override
protected boolean handleImageLoaded(Bitmap bitmap, Message msg) {
if(onImageLoadedListener != null ){
onImageLoadedListener.onImageLoaded(bitmap);
}
boolean wasUpdated = super.handleImageLoaded(bitmap, msg);
if (wasUpdated) {
isLoaded = true;
setDisplayedChild(1);
}
return wasUpdated;
}
}
/**
* Returns the URL of the remoteimageview to show. Corresponds to the view attribute ignition:imageUrl.
*
* @return the remoteimageview URL
*/
public String getImageUrl() {
return imageUrl;
}
/**
* Whether or not the remoteimageview should be downloaded immediately after view inflation. Corresponds
* to the view attribute ignition:autoLoad (default: true).
*
* @return true if auto downloading of the remoteimageview is enabled
*/
public boolean isAutoLoad() {
return autoLoad;
}
/**
* The drawable that should be used to indicate progress while downloading the remoteimageview.
* Corresponds to the view attribute ignition:progressDrawable. If left blank, the platform's
* standard indeterminate progress drawable will be used.
*
* @return the progress drawable
*/
public Drawable getProgressDrawable() {
return progressDrawable;
}
/**
* The drawable that will be shown when the remoteimageview download fails. Corresponds to the view
* attribute ignition:errorDrawable. If left blank, a stock alert icon from the Android platform
* will be used.
*
* @return the error drawable res
*/
public int getErrorDrawableRes() {
return errorDrawable;
}
/**
* The remoteimageview view that will render the downloaded remoteimageview.
*
* @return the {@link android.widget.ImageView}
*/
public ImageView getImageView() {
return imageView;
}
/**
* The progress bar that is shown while the remoteimageview is loaded.
*
* @return the {@link android.widget.ProgressBar}
*/
public ProgressBar getProgressBar() {
return loadingSpinner;
}
private OnImageLoadedListener onImageLoadedListener;
public void setOnLoadOverListener(OnImageLoadedListener onImageLoadedListener) {
this.onImageLoadedListener = onImageLoadedListener;
}
public interface OnImageLoadedListener{
void onImageLoaded(Bitmap bitmap);
}
}
|
package cgeo.geocaching.ui;
import cgeo.geocaching.R;
import cgeo.geocaching.activity.Keyboard;
import cgeo.geocaching.ui.dialog.Dialogs;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
import org.apache.commons.lang3.StringUtils;
public class EditNoteDialog extends DialogFragment {
public static final String ARGUMENT_INITIAL_NOTE = "initialNote";
public static final String ARGUMENT_INITIAL_PREVENT = "initialPrevent";
private EditText mEditText;
private CheckBox mPreventCheckbox;
public interface EditNoteDialogListener {
void onFinishEditNoteDialog(String inputText, boolean preventWaypointsFromNote);
}
/**
* Create a new dialog to edit a note.
* <em>This fragment must be inserted into an activity implementing the EditNoteDialogListener interface.</em>
*
* @param initialNote the initial note to insert in the edit dialog
*/
public static EditNoteDialog newInstance(final String initialNote, final boolean preventWaypointsFromNote) {
final EditNoteDialog dialog = new EditNoteDialog();
final Bundle arguments = new Bundle();
arguments.putString(ARGUMENT_INITIAL_NOTE, initialNote);
arguments.putBoolean(ARGUMENT_INITIAL_PREVENT, preventWaypointsFromNote);
dialog.setArguments(arguments);
return dialog;
}
@Override
@androidx.annotation.NonNull
public Dialog onCreateDialog(final Bundle savedInstanceState) {
final FragmentActivity activity = getActivity();
final View view = View.inflate(activity, R.layout.fragment_edit_note, null);
mEditText = view.findViewById(R.id.note);
String initialNote = getArguments().getString(ARGUMENT_INITIAL_NOTE);
if (initialNote != null) {
// add a new line when editing existing text, to avoid accidental overwriting of the last line
if (StringUtils.isNotBlank(initialNote) && !initialNote.endsWith("\n")) {
initialNote = initialNote + "\n";
}
mEditText.setText(initialNote);
Dialogs.moveCursorToEnd(mEditText);
getArguments().remove(ARGUMENT_INITIAL_NOTE);
}
mPreventCheckbox = view.findViewById(R.id.preventWaypointsFromNote);
final boolean preventWaypointsFromNote = getArguments().getBoolean(ARGUMENT_INITIAL_PREVENT);
mPreventCheckbox.setChecked(preventWaypointsFromNote);
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setView(view);
final AlertDialog dialog = builder.create();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
final TextView title = view.findViewById(R.id.dialog_title_title);
title.setText(R.string.cache_personal_note);
title.setVisibility(View.VISIBLE);
final ImageButton cancel = view.findViewById(R.id.dialog_title_cancel);
cancel.setOnClickListener(view1 -> dialog.dismiss());
cancel.setVisibility(View.VISIBLE);
final ImageButton done = view.findViewById(R.id.dialog_title_done);
done.setOnClickListener(view12 -> {
// trim note to avoid unnecessary uploads for whitespace only changes
final String personalNote = StringUtils.trim(mEditText.getText().toString());
((EditNoteDialogListener) getActivity()).onFinishEditNoteDialog(personalNote, mPreventCheckbox.isChecked());
dialog.dismiss();
});
done.setVisibility(View.VISIBLE);
mEditText.requestFocus();
new Keyboard(activity).showDelayed(mEditText);
//prevent popup window to extend under the virtual keyboard or above the top of phone display (see #8793)
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
return dialog;
}
}
|
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JOptionPane;
public class GUIframe{
private JFrame window;
private JPanel mainPanel; //the main Panel will have sub panels
private JPanel canvasPanel;
private JPanel buttonsPanel;
BufferedImage image;
private MyCanvas canvas;
String suffices[];
private Engine engine;
private JButton startFilter;
private Timer timer;
private long startTime;
private long timeToRun;
public GUIframe(int width, int height) throws FileNotFoundException, IOException {
window = new JFrame("Dot Vinci");
window.setSize(width, height);
//add canvasPanel objects
canvas = new MyCanvas();
//image = ImageIO.read(new FileInputStream("C:/Users/Pranav/Pictures/doge.jpeg"));
canvas.setSize(width, height);
canvas.setBounds(0, 0, 300, 300);
canvas.setBackground(Color.WHITE);
//intialize engine
engine = new Engine();
//add buttonsPanel objects
// - add buttons
JButton openImage = new JButton("Open Image");
openImage.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(startTime != -1) {
JOptionPane.showMessageDialog(window, "Cannot open new image while timer is running");
return;
}
//open a JFilesChooser when the open button is clicked
JFileChooser chooser = new JFileChooser();
// Get array of available formats (only once)
if(suffices == null){
suffices = ImageIO.getReaderFileSuffixes();
// Add a file filter for each one
for (int i = 0; i < suffices.length; i++) {
FileNameExtensionFilter filter = new FileNameExtensionFilter(suffices[i] + " files", suffices[i]);
System.out.println(suffices[i]+"\n");
chooser.addChoosableFileFilter(filter);
}
}
chooser.setFileFilter(new ImageFilter());
chooser.setAcceptAllFileFilterUsed(false);
int ret = chooser.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
//add the selected file to the canvas
File file = chooser.getSelectedFile();
try {
image = ImageIO.read(new FileInputStream(file.toString()));
engine.loadImageFromFile(file);
canvas.repaint();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(file);
}
}
});
JButton saveImage = new JButton("Save Image");
// - add filters
JLabel filterText = new JLabel("Filters:");
final JRadioButton noFilter = new JRadioButton("None");
noFilter.setSelected(true);
final JRadioButton sepiaFilter = new JRadioButton("Sepia");
final JRadioButton grayscaleFilter = new JRadioButton("Gray Scale");
final JRadioButton negativeFilter = new JRadioButton("Negative");
//prevent user from unchecking a radio button
noFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(noFilter.isSelected() == false)
noFilter.setSelected(true);
}
});
sepiaFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(sepiaFilter.isSelected() == false)
sepiaFilter.setSelected(true);
}
});
negativeFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(negativeFilter.isSelected() == false)
negativeFilter.setSelected(true);
}
});
grayscaleFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(grayscaleFilter.isSelected() == false)
grayscaleFilter.setSelected(true);
}
});
//uncheck all other radio buttons when the user checks a radio button
noFilter.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(noFilter.isSelected() == true){
sepiaFilter.setSelected(false);
grayscaleFilter.setSelected(false);
negativeFilter.setSelected(false);
}
}
});
sepiaFilter.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(sepiaFilter.isSelected() == true){
noFilter.setSelected(false);
grayscaleFilter.setSelected(false);
negativeFilter.setSelected(false);
}
}
});
negativeFilter.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(negativeFilter.isSelected() == true){
sepiaFilter.setSelected(false);
grayscaleFilter.setSelected(false);
noFilter.setSelected(false);
}
}
});
grayscaleFilter.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(grayscaleFilter.isSelected() == true){
sepiaFilter.setSelected(false);
noFilter.setSelected(false);
negativeFilter.setSelected(false);
}
}
});
// - add slider
JLabel renderSpeedText = new JLabel("Render Speed:");
final JSlider renderSpeed_slider = new JSlider(1, 100);
final JTextField renderSpeed_value = new JTextField(3);
Dimension dim = new Dimension(40, 30);
renderSpeed_value.setSize(20, 20);
renderSpeed_value.setMaximumSize(dim);
renderSpeed_value.setText("50%");
renderSpeed_slider.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e) {
renderSpeed_value.setText(String.valueOf(renderSpeed_slider.getValue() + "%"));
}
});
//setup the panels
mainPanel = new JPanel();
canvasPanel = new JPanel();
buttonsPanel = new JPanel();
//buttonsPanel.setBounds(0, 0, 300, 300);
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS));
canvas.setBounds(0, 0, 1024, 800);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
//setup the button panel
Container contentPane = window.getContentPane();
buttonsPanel.add(openImage);
buttonsPanel.add(Box.createRigidArea(new Dimension(5,10)));
buttonsPanel.add(saveImage);
buttonsPanel.add(Box.createRigidArea(new Dimension(5,20)));
buttonsPanel.add(filterText);
buttonsPanel.add(Box.createRigidArea(new Dimension(5,10)));
JPanel filterPanel = new JPanel();
filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.X_AXIS));
filterPanel.add(Box.createRigidArea(new Dimension(10,20)));
filterPanel.add(filterText);
filterPanel.add(Box.createRigidArea(new Dimension(10,20)));
filterPanel.add(noFilter);
filterPanel.add(sepiaFilter);
filterPanel.add(grayscaleFilter);
filterPanel.add(negativeFilter);
buttonsPanel.add(filterPanel);
buttonsPanel.add(Box.createRigidArea(new Dimension(5,10)));
buttonsPanel.add(renderSpeedText);
buttonsPanel.add(Box.createRigidArea(new Dimension(5,10)));
buttonsPanel.add(renderSpeed_slider);
buttonsPanel.add(Box.createRigidArea(new Dimension(5,10)));
buttonsPanel.add(renderSpeed_value);
startFilter = new JButton("Start filter");
timer = new Timer();
buttonsPanel.add(startFilter);
startTime = -1;
timeToRun = -1;
startFilter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(image == null) {
JOptionPane.showMessageDialog(window, "Cannot start timer without an image open");
return;
}
if(startTime == -1) {
startTime = System.currentTimeMillis();
long maxTimeToTake = 1000;
long sliderVal = renderSpeed_slider.getValue();
sliderVal *= 10;
timeToRun = maxTimeToTake - sliderVal;
timer.scheduleAtFixedRate(new UpdateImage(), 0, 10);
}
else {
System.out.println("timer already running!");
}
}
});
canvasPanel.add(canvas);
mainPanel.add(buttonsPanel);
mainPanel.add(canvasPanel);
//add the main panel to the window
window.add(mainPanel);
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setResizable(true);
window.setVisible(true);
}
class MyCanvas extends Canvas {
@Override
public void paint(Graphics g) {
if(engine.hasImage()) {
g.drawImage(engine.getImage(), 0, 0, this);
}
}
}
class UpdateImage extends TimerTask {
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
canvas.repaint();
}
});
if(System.currentTimeMillis() - startTime >= timeToRun) {
System.out.println("timer end! " + (System.currentTimeMillis() - startTime));
startTime = -1;
cancel();
}
}
}
}
|
package com.eegeo.photos;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import com.eegeo.helpers.IActivityIntentResultHandler;
import com.eegeo.mobileexampleapp.MainActivity;
// This class handles the dispatching of intents related to fetching an image via photo or gallery selection.
public class PhotoIntentDispatcher
{
public static final int REQUEST_IMAGE_CAPTURE = 1;
public static final int SELECT_PHOTO_FROM_GALLERY = 2;
private MainActivity m_activity = null;
private List<IActivityIntentResultHandler> m_activityCallbacks = new ArrayList<IActivityIntentResultHandler>();
private Uri m_currentPhotoPath;
public PhotoIntentDispatcher(MainActivity activity)
{
m_activity = activity;
}
public void takePhoto()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(m_activity.getPackageManager()) != null)
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String filePath = timeStamp + ".jpg";
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), filePath);
m_currentPhotoPath = Uri.fromFile(file);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, m_currentPhotoPath);
m_activity.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
public void selectPhotoFromGallery()
{
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
m_activity.startActivityForResult(intent, SELECT_PHOTO_FROM_GALLERY);
}
public void addActivityIntentResultHandler(IActivityIntentResultHandler handler)
{
if(!m_activityCallbacks.contains(handler))
{
m_activityCallbacks.add(handler);
}
}
public void removeActivityIntentResultHandler(IActivityIntentResultHandler handler)
{
if(m_activityCallbacks.contains(handler))
{
m_activityCallbacks.remove(handler);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode != REQUEST_IMAGE_CAPTURE && requestCode != SELECT_PHOTO_FROM_GALLERY)
return;
for(IActivityIntentResultHandler handler : m_activityCallbacks)
{
handler.onActivityResult(requestCode, resultCode, data);
}
}
public Uri getCurrentPhotoPath() {
return m_currentPhotoPath;
}
}
|
package com.mapzen.tangram;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class HttpHandler {
private OkHttpClient okClient;
protected Request.Builder okRequestBuilder;
public HttpHandler() {
okRequestBuilder = new Request.Builder();
okClient = new OkHttpClient();
okClient.setConnectTimeout(10, TimeUnit.SECONDS);
okClient.setReadTimeout(30, TimeUnit.SECONDS);
}
/**
* Begin an HTTP request
* @param url URL for the requested resource
* @param cb Callback for handling request result
* @return true if request was successfully started
*/
public boolean onRequest(String url, Callback cb) {
Request request = okRequestBuilder.tag(url).url(url).build();
okClient.newCall(request).enqueue(cb);
return true;
}
/**
* Cancel an HTTP request
* @param url URL of the request to be cancelled
*/
public void onCancel(String url) {
okClient.cancel(url);
}
/**
* Cache map data in a directory with a specified size limit
* @param directory Directory in which map data will be cached
* @param maxSize Maximum size of data to cache, in bytes
* @return true if cache was successfully created
*/
public boolean setCache(File directory, long maxSize) {
Cache okTileCache = new Cache(directory, maxSize);
okClient.setCache(okTileCache);
return true;
}
}
|
package info.loenwind.processor;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
@SupportedAnnotationTypes("info.loenwind.processor.RemoteCall")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class Processor extends AbstractProcessor {
// Java
private static final ClassName STRING = ClassName.get(String.class);
private final static ClassName CONSUMER = ClassName.get(Consumer.class);
// Minecraft
private final static ClassName MINECRAFT = ClassName.get("net.minecraft.client", "Minecraft");
private final static String CONTAINER = "net.minecraft.inventory.Container";
private final static ClassName ITEM_STACK = ClassName.get("net.minecraft.item", "ItemStack");
private final static ClassName NBT_TAG_COMPOUND = ClassName.get("net.minecraft.nbt", "NBTTagCompound");
private final static ClassName ENTITY_PLAYER_MP = ClassName.get("net.minecraft.entity.player", "EntityPlayerMP");
private final static ClassName BLOCKPOS = ClassName.get("net.minecraft.util.math", "BlockPos");
// Minecraft libs
private final static ClassName BYTE_BUF = ClassName.get("io.netty.buffer", "ByteBuf");
// Forge
private final static ClassName EVENT_BUS_SUBSCRIBER = ClassName.get("net.minecraftforge.fml.common.Mod", "EventBusSubscriber");
private final static ClassName SUBSCRIBE_EVENT = ClassName.get("net.minecraftforge.fml.common.eventhandler", "SubscribeEvent");
private final static ClassName I_FORGE_REGISTRY_ENTRY__IMPL = ClassName.get("net.minecraftforge.registries", "IForgeRegistryEntry", "Impl");
private final static ClassName REGISTRY_EVENT__REGISTER = ClassName.get("net.minecraftforge.event.RegistryEvent", "Register");
private final static ClassName BYTE_BUF_UTILS = ClassName.get("net.minecraftforge.fml.common.network", "ByteBufUtils");
private final static ClassName MOD = ClassName.get("net.minecraftforge.fml.common", "Mod");
// Ender IO
private final static ClassName I_REMOTE_EXEC = ClassName.get("crazypants.enderio.base.network.ExecPacket", "IServerExec");
private final static ClassName EXEC_PACKET = ClassName.get("crazypants.enderio.base.network", "ExecPacket");
private final static ClassName ENUM_READER = ClassName.get("crazypants.enderio.util", "EnumReader");
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Types typeUtils = processingEnv.getTypeUtils();
TypeMirror containerType = processingEnv.getElementUtils().getTypeElement(CONTAINER).asType();
for (TypeElement annotation : annotations) {
for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
if (element.getKind() == ElementKind.CLASS) {
TypeElement typeElement = (TypeElement) element;
TypeMirror typeMirror = typeElement.asType();
if (typeUtils.isAssignable(typeMirror, containerType)) {
try {
generateContainerProxy(typeElement);
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.OTHER, "Internal error: " + e.getMessage(), element);
e.printStackTrace();
}
} else {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Unsupported type '" + typeMirror + "' for @RemoteCall", element);
}
}
}
}
return false;
}
private String findModid(Element e) {
for (Entry<String, String> entry : PREMAPPED.entrySet()) {
if (e.toString().startsWith(entry.getKey())) {
return entry.getValue();
}
}
// processingEnv.getMessager().printMessage(Diagnostic.Kind.OTHER, "Looking for " + e);
e = e.getEnclosingElement();
// processingEnv.getMessager().printMessage(Diagnostic.Kind.OTHER, "Looking at " + e);
while (true) {
if (e == null) {
return null;
}
if (e instanceof PackageElement) {
Name qualifiedName = ((PackageElement) e).getQualifiedName();
if (!qualifiedName.toString().contains(".")) {
// technically there are still 2 packages to look at, but we never go that far up with our mod classes
return null;
}
String sup = qualifiedName.toString().replaceFirst("\\.[^.]+$", ""); // is there a better way?
e = processingEnv.getElementUtils().getPackageElement(sup);
// processingEnv.getMessager().printMessage(Diagnostic.Kind.OTHER, "Looking at " + e);
}
for (Element c : e.getEnclosedElements()) {
// processingEnv.getMessager().printMessage(Diagnostic.Kind.OTHER, "Looking at " + c);
for (AnnotationMirror m : c.getAnnotationMirrors()) {
// processingEnv.getMessager().printMessage(Diagnostic.Kind.OTHER, "Looking at " + m);
if (MOD.equals(ClassName.get(m.getAnnotationType()))) {
for (Entry<? extends ExecutableElement, ? extends AnnotationValue> b : m.getElementValues().entrySet()) {
// processingEnv.getMessager().printMessage(Diagnostic.Kind.OTHER, "Looking at " + b.getKey());
if (b.getKey().getSimpleName().toString().equals("modid")) { // is there a better way?
return b.getValue().getValue().toString();
}
}
}
}
}
}
}
private void generateContainerProxy(TypeElement typeElement) throws IOException {
Filer filer = processingEnv.getFiler();
String modid = typeElement.getAnnotation(RemoteCall.class).modid();
if (modid == null || modid.isEmpty()) {
modid = findModid(typeElement);
if (modid == null || modid.isEmpty()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Parameter 'modid' must be set on class level if there's no @Mod class in hierarchy",
typeElement);
return;
}
}
if (modid.equals("enderiobase")) {
// I hate hardcoding this stuff
modid = "enderio";
}
String packageName = ((PackageElement) typeElement.getEnclosingElement()).getQualifiedName().toString();
String sourceClassName = typeElement.getSimpleName().toString();
String proxyInterfaceClassName = sourceClassName + "Proxy";
TypeSpec.Builder proxyInterfaceBuilder = TypeSpec.interfaceBuilder(proxyInterfaceClassName);
for (ExecutableElement method : processingEnv.getElementUtils().getAllMembers(typeElement).stream().filter(el -> el.getKind() == ElementKind.METHOD)
.map(el -> (ExecutableElement) el).filter(el -> el.getAnnotation(RemoteCall.class) != null).collect(Collectors.toList())) {
String methodName = method.getSimpleName().toString();
String methodProxyClassName = proxyInterfaceClassName + "$" + methodName;
if (method.getAnnotation(RemoteCall.class).modid() != null && !method.getAnnotation(RemoteCall.class).modid().isEmpty()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Parameter 'modid' must NOT be set on method level", method);
return;
}
FieldSpec instanceField = FieldSpec.builder(I_REMOTE_EXEC, "INSTANCE", Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC)
.initializer("new $1L().setRegistryName($2S, $3S)", methodProxyClassName, modid, (sourceClassName + "_" + methodName).toLowerCase(Locale.ENGLISH))
.build();
TypeSpec.Builder methodProxyClassBuilder = TypeSpec.classBuilder(methodProxyClassName).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(AnnotationSpec.builder(EVENT_BUS_SUBSCRIBER).addMember("modid", "$S", modid).build())
.superclass(ParameterizedTypeName.get(I_FORGE_REGISTRY_ENTRY__IMPL, I_REMOTE_EXEC)).addSuperinterface(I_REMOTE_EXEC).addField(instanceField)
.addMethod(MethodSpec
.methodBuilder("register")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(void.class).addAnnotation(SUBSCRIBE_EVENT)
.addParameter(ParameterizedTypeName.get(REGISTRY_EVENT__REGISTER, I_REMOTE_EXEC), "event")
.addStatement("event.getRegistry().register($N)", instanceField).build());
MethodSpec.Builder proxyMethodBuilder = MethodSpec.methodBuilder(methodName).addModifiers(Modifier.PUBLIC, Modifier.DEFAULT).returns(void.class);
CodeBlock.Builder parameterListCode = null;
MethodSpec.Builder writerBuilder = MethodSpec.methodBuilder("makeWriter").addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(ParameterizedTypeName.get(CONSUMER, BYTE_BUF)).beginControlFlow("return buf ->")
.addStatement("buf.writeInt($T.getMinecraft().player.openContainer.windowId)", MINECRAFT);
MethodSpec.Builder runnerBuilder = MethodSpec.methodBuilder("apply").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class)
.returns(ParameterizedTypeName.get(CONSUMER, ENTITY_PLAYER_MP)).addParameter(BYTE_BUF, "buf").addStatement("final int _windowId = buf.readInt()");
Networkbuilder b = Networkbuilder.builder(writerBuilder, runnerBuilder);
for (VariableElement parameter : method.getParameters()) {
TypeMirror paramTypeMirror = parameter.asType();
TypeName typeName = TypeName.get(paramTypeMirror);
ParameterSpec parameterSpec = ParameterSpec_get(parameter);
writerBuilder.addParameter(parameterSpec);
proxyMethodBuilder.addParameter(parameterSpec);
if (parameterListCode == null) {
parameterListCode = CodeBlock.builder().add("$N", parameterSpec);
} else {
parameterListCode.add(", $N", parameterSpec);
}
if (typeName.isPrimitive()) {
String byteBuffCall = ucfirst(typeName.toString());
b.addWriterStatement("buf.write$2L($1N)", parameterSpec, byteBuffCall);
b.addReaderStatement("final $2T $1N = buf.read$3L()", parameterSpec, typeName, byteBuffCall);
} else {
if (!isNonnull(parameter)) {
b.beginNullable(parameterSpec);
}
if (typeName.isBoxedPrimitive()) {
String byteBuffCall = ucfirst(typeName.unbox().toString());
b.addWriterStatement("buf.write$1L($2N)", byteBuffCall, parameterSpec);
b.addReaderStatement(typeName, parameterSpec, "buf.read$1L()", byteBuffCall);
} else if (paramTypeMirror.getKind() == TypeKind.DECLARED
&& ((TypeElement) ((DeclaredType) paramTypeMirror).asElement()).getKind() == ElementKind.ENUM) {
b.addWriterStatement("buf.writeInt($1T.put($2N))", ENUM_READER, parameterSpec);
b.addReaderStatement(typeName, parameterSpec, "$1T.get($2T.class, buf.readInt())", ENUM_READER, typeName);
} else if (typeName.equals(STRING)) {
b.addWriterStatement("$T.writeUTF8String(buf, $N)", BYTE_BUF_UTILS, parameterSpec);
b.addReaderStatement(typeName, parameterSpec, "$1T.readUTF8String(buf)", BYTE_BUF_UTILS);
} else if (typeName.equals(ITEM_STACK)) {
b.addWriterStatement("$T.writeItemStack(buf, $N)", BYTE_BUF_UTILS, parameterSpec);
b.addReaderStatement(typeName, parameterSpec, "$1T.readItemStack(buf)", BYTE_BUF_UTILS);
} else if (typeName.equals(NBT_TAG_COMPOUND)) {
b.addWriterStatement("$T.writeTag(buf, $N)", BYTE_BUF_UTILS, parameterSpec);
b.addReaderStatement(typeName, parameterSpec, "$1T.readTag(buf)", BYTE_BUF_UTILS);
} else if (typeName.equals(BLOCKPOS)) {
b.addWriterStatement("buf.writeLong($1N.toLong())", parameterSpec);
b.addReaderStatement(typeName, parameterSpec, "$1T.fromLong(buf.readLong())", BLOCKPOS);
} else {
// TODO: []/List<>/NNList<> of supported types.
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Cannot serialize '" + typeName + "' into a byte stream", parameter);
return;
}
b.endNullable();
}
}
b.build();
writerBuilder.endControlFlow(""/* "" to add a ; */);
MethodSpec makeWriterMethod = writerBuilder.build();
methodProxyClassBuilder.addMethod(makeWriterMethod);
runnerBuilder.beginControlFlow("return player ->")
.beginControlFlow("if (player.openContainer instanceof $T && player.openContainer.windowId == _windowId)", ClassName.get(typeElement))
.addCode("(($T) player.openContainer).$L(", ClassName.get(typeElement), methodName);
if (parameterListCode != null) {
runnerBuilder.addCode(parameterListCode.build());
}
runnerBuilder.addStatement(")").endControlFlow().endControlFlow(""/* "" to add a ; */);
methodProxyClassBuilder.addMethod(runnerBuilder.build());
TypeSpec methodProxyClass = methodProxyClassBuilder.build();
JavaFile.builder(packageName, methodProxyClass).build().writeTo(filer);
proxyMethodBuilder.addCode("$1T.send($3N.$2N, $3N.$4N(", EXEC_PACKET, instanceField, methodProxyClass, makeWriterMethod);
if (parameterListCode != null) {
proxyMethodBuilder.addCode(parameterListCode.build());
}
proxyMethodBuilder.addCode("));");
proxyInterfaceBuilder.addMethod(proxyMethodBuilder.build());
}
JavaFile.builder(packageName, proxyInterfaceBuilder.build()).build().writeTo(filer);
}
private static String ucfirst(String str) {
return (str == null || str.isEmpty()) ? str : str.substring(0, 1).toUpperCase() + str.substring(1);
}
private static boolean isNonnull(Element el) {
for (AnnotationMirror annotation : el.getAnnotationMirrors()) {
Element element = annotation.getAnnotationType().asElement();
// assert element.getKind().equals(ElementKind.ANNOTATION_TYPE);
if (((TypeElement) element).getQualifiedName().contentEquals("javax.annotation.Nonnull")) {
return true;
}
}
return false;
}
private static ParameterSpec ParameterSpec_get(VariableElement element) {
return ParameterSpec.builder(TypeName.get(element.asType()), element.getSimpleName().toString()).addModifiers(element.getModifiers())
.addAnnotations(element.getAnnotationMirrors().stream().map((mirror) -> AnnotationSpec.get(mirror)).collect(Collectors.toList())).build();
}
/**
* {@link #findModid(Element)} would find these on its own in a full compile but Eclipse's partial compile of single changed class files hides the mod class
* from us. So we keep this precompiled list here to avoid having to do a complete project build every single time we change one of the remote call classes...
*/
private static final Map<String, String> PREMAPPED = new HashMap<>();
static {
PREMAPPED.put("crazypants.enderio.base.", "enderio");
PREMAPPED.put("crazypants.enderio.conduits.", "enderiomconduits");
PREMAPPED.put("crazypants.enderio.machines.", "enderiomachines");
}
}
|
package org.atlasapi.application.auth;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.servlet.http.HttpServletRequest;
import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher {
public static final String API_KEY_QUERY_PARAMETER = "key";
private final ApplicationStore reader;
public ApiKeySourcesFetcher(ApplicationStore reader) {
this.reader = checkNotNull(reader);
}
@Override
public ImmutableSet<String> getParameterNames() {
return ImmutableSet.of();
}
@Override
public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException {
String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER);
if (apiKey == null) {
apiKey = request.getHeader(API_KEY_QUERY_PARAMETER);
}
if (apiKey != null) {
Optional<Application> app = reader.applicationForKey(apiKey);
if (!app.isPresent() || app.get().isRevoked()) {
throw new InvalidApiKeyException(apiKey);
}
return Optional.of(app.get().getSources());
}
return Optional.absent();
}
}
|
package org.sourcepit.b2.internal.cleaner;
import java.io.File;
import javax.inject.Named;
@Named
public class PomCleaner implements IModuleGarbageCollector
{
public boolean isGarbage(File file)
{
final File parentDir = file.getParentFile();
if (isInModule(file) && isMavenProject(parentDir))
{
if (file.isFile() && "pom.xml".equals(file.getName()))
{
return true;
}
}
return false;
}
private boolean isMavenProject(File parentDir)
{
return new File(parentDir, "pom.xml").exists();
}
private boolean isInModule(File file)
{
final File parentDir = file.getParentFile();
if (parentDir == null)
{
return false;
}
if (isModuleDir(parentDir))
{
return true;
}
return isInModule(parentDir);
}
private boolean isModuleDir(File parentDir)
{
return new File(parentDir, "module.xml").exists();
}
}
|
package com.wang.baseadapter.model;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* RecyclerView
*/
public class RecyclerViewItemArray extends ArrayList<ItemData> {
/**
* type
*
* @param type
* @return position-1
*/
public int findFirstTypePosition(int type) {
for (int i = 0; i < size(); i++) {
if (type == get(i).getDataType()) {
return i;
}
}
return -1;
}
/**
* type
*
* @param type
* @return position-1
*/
public int findLastTypePosition(int type) {
for (int i = size() - 1; i >= 0; i
if (type == get(i).getDataType()) {
return i;
}
}
return -1;
}
/**
* type
*
* @param type
* @return position-1
*/
public int findFirstNotTypePosition(int type) {
for (int i = 0; i < size(); i++) {
if (type != get(i).getDataType()) {
return i;
}
}
return -1;
}
/**
* type
*
* @param type
* @return position-1
*/
public int findLastNotTypePosition(int type) {
for (int i = size() - 1; i >= 0; i
if (type != get(i).getDataType()) {
return i;
}
}
return -1;
}
/**
* type
*
* @param type
* @param data
* @return
*/
public int addAfterLast(int type, ItemData data) {
int position = findLastTypePosition(type);
add(position++, data);
return position;
}
/**
* type
*
* @param type
* @param data
* @return
*/
public int addBeforFirst(int type, ItemData data) {
int position = findFirstTypePosition(type);
add(position, data);
return position;
}
/**
* type
*
* @param type
* @return -1
*/
public int removeFirstType(int type) {
int position = findFirstTypePosition(type);
if (position != -1) {
remove(position);
return position;
}
return -1;
}
/**
* type
*
* @param type
* @return
*/
public int removeAllType(int type) {
int count = 0;
Iterator<ItemData> iterator = iterator();
while (iterator.hasNext()){
ItemData item = iterator.next();
if (item.getDataType() == type) {
iterator.remove();
count++;
}
}
return count;
}
/**
* type
* @param type
* @param datas
* @param <E>
* @return
*/
public <E> int addAllType(int type, List<E> datas) {
int count = 0;
for (E e : datas) {
addAfterLast(type, new ItemData<>(type, e));
count++;
}
return count;
}
/**
*
* @param type
* @param datas
* @param <E>
* @return
*/
public <E> int addAllAtLast(int type, List<E> datas) {
int count = 0;
for (E e : datas) {
add(new ItemData<>(type, e));
count++;
}
return count;
}
/**
*
* @param position
* @param type
* @param datas
* @param <E>
* @return
*/
public <E> int addAllAtPosition(int position, int type, List<E> datas) {
int count = 0;
for (E e : datas) {
add(position + count, new ItemData<>(type, e));
count++;
}
return count;
}
/**
* type
*
* @param type type
* @return truefalse
*/
public boolean isEmptyOfType(int type) {
return findFirstTypePosition(type) == -1;
}
}
|
package com.box.androidsdk.content.auth;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Handler;
import android.os.Looper;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.box.androidsdk.content.BoxConfig;
import com.box.sdk.android.R;
import com.box.androidsdk.content.utils.SdkUtils;
import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.Formatter;
/**
* A WebView used for OAuth flow.
*/
public class OAuthWebView extends WebView {
private static final String STATE = "state";
private static final String URL_QUERY_LOGIN = "box_login";
/**
* A state string query param set when loading the OAuth url. This will be validated in the redirect url.
*/
private String state;
/**
* An optional account email that should be prefilled in for the user if available.
*/
private String mBoxAccountEmail;
/**
* Constructor.
*
* @param context
* context
* @param attrs
* attrs
*/
public OAuthWebView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
/**
* State string. This string is optionally appended to the OAuth url query param. If appended, it will be returned as query param in the redirect url too.
* You can then verify that the two strings are the same as a security check.
*/
public String getStateString() {
return state;
}
public void setBoxAccountEmail(final String boxAccountEmail){
mBoxAccountEmail = boxAccountEmail;
}
/**
* Start authentication.
*/
public void authenticate(final String clientId, final String redirectUrl) {
authenticate(buildUrl(clientId, redirectUrl));
}
/**
*
* @param authenticationUriBuilder A builder that is used to construct the url for authentication. This method is only necessary in advanced scenarios,
* otherwise the default authetnicate(clientId, redirectUrl) method should be used.
*/
public void authenticate(final Uri.Builder authenticationUriBuilder){
state = SdkUtils.generateStateToken();
authenticationUriBuilder.appendQueryParameter(STATE, state);
loadUrl(authenticationUriBuilder.build().toString());
}
protected Uri.Builder buildUrl(String clientId, final String redirectUrl) {
Uri.Builder builder = new Uri.Builder();
builder.scheme("https");
builder.authority("app.box.com");
builder.appendPath("api");
builder.appendPath("oauth2");
builder.appendPath("authorize");
builder.appendQueryParameter("response_type", BoxApiAuthentication.RESPONSE_TYPE_CODE);
builder.appendQueryParameter("client_id", clientId);
builder.appendQueryParameter("redirect_uri", redirectUrl);
if (mBoxAccountEmail != null){
builder.appendQueryParameter(URL_QUERY_LOGIN, mBoxAccountEmail);
}
return builder;
}
/**
* WebViewClient for the OAuth WebView.
*/
public static class OAuthWebViewClient extends WebViewClient {
private boolean sslErrorDialogContinueButtonClicked;
private WebEventListener mWebEventListener;
private String mRedirectUrl;
private OnPageFinishedListener mOnPageFinishedListener;
private static final int WEB_VIEW_TIMEOUT = 30000;
private WebViewTimeOutRunnable mTimeOutRunnable;
private Handler mHandler = new Handler(Looper.getMainLooper());
/**
* a state string query param set when loading the OAuth url. This will be validated in the redirect url.
*/
private String state;
/**
* Constructor.
*
* @param eventListener
* listener to be notified when events happen on this webview
* @param redirectUrl
* (optional) redirect url, for validation only.
* @param stateString
* a state string query param set when loading the OAuth url. This will be validated in the redirect url.
*/
public OAuthWebViewClient(WebEventListener eventListener, String redirectUrl, String stateString) {
super();
this.mWebEventListener = eventListener;
this.mRedirectUrl = redirectUrl;
this.state = stateString;
}
@Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
try {
Uri uri = getURIfromURL(url);
String code = getValueFromURI(uri, BoxApiAuthentication.RESPONSE_TYPE_CODE);
String error = getValueFromURI(uri, BoxApiAuthentication.RESPONSE_TYPE_ERROR);
if (!SdkUtils.isEmptyString(error)) {
mWebEventListener.onAuthFailure(new AuthFailure(AuthFailure.TYPE_USER_INTERACTION, null));
} else if (!SdkUtils.isEmptyString(code)) {
String baseDomain = getValueFromURI(uri, BoxApiAuthentication.RESPONSE_TYPE_BASE_DOMAIN);
if (baseDomain != null){
mWebEventListener.onReceivedAuthCode(code, baseDomain);
} else {
mWebEventListener.onReceivedAuthCode(code);
}
}
} catch (InvalidUrlException e) {
mWebEventListener.onAuthFailure(new AuthFailure(AuthFailure.TYPE_URL_MISMATCH, null));
}
if (mTimeOutRunnable != null){
mHandler.removeCallbacks(mTimeOutRunnable);
}
mTimeOutRunnable = new WebViewTimeOutRunnable(view,url);
mHandler.postDelayed(mTimeOutRunnable, WEB_VIEW_TIMEOUT);
}
@Override
public void onPageFinished(final WebView view, final String url) {
if (mTimeOutRunnable != null){
mHandler.removeCallbacks(mTimeOutRunnable);
}
super.onPageFinished(view, url);
if (mOnPageFinishedListener != null) {
mOnPageFinishedListener.onPageFinished(view, url);
}
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (mTimeOutRunnable != null){
mHandler.removeCallbacks(mTimeOutRunnable);
}
if (mWebEventListener.onAuthFailure(new AuthFailure(new WebViewException(errorCode,description,failingUrl)))){
return;
}
switch(errorCode){
case ERROR_CONNECT:
case ERROR_HOST_LOOKUP:
if (!SdkUtils.isInternetAvailable(view.getContext())){
String html = SdkUtils.getAssetFile(view.getContext(), "offline.html");
Formatter formatter = new Formatter();
formatter.format(html, view.getContext().getString(R.string.boxsdk_no_offline_access), view.getContext().getString(R.string.boxsdk_no_offline_access_detail),
view.getContext().getString(R.string.boxsdk_no_offline_access_todo));
view.loadData(formatter.toString(), "text/html", "UTF-8");
formatter.close();
break;
}
case ERROR_TIMEOUT:
String html = SdkUtils.getAssetFile(view.getContext(), "offline.html");
Formatter formatter = new Formatter();
formatter.format(html, view.getContext().getString(R.string.boxsdk_unable_to_connect), view.getContext().getString(R.string.boxsdk_unable_to_connect_detail),
view.getContext().getString(R.string.boxsdk_unable_to_connect_todo));
view.loadData(formatter.toString(), "text/html", "UTF-8");
formatter.close();
break;
}
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public void onReceivedHttpAuthRequest(final WebView view, final HttpAuthHandler handler, final String host, final String realm) {
LayoutInflater factory = LayoutInflater.from(view.getContext());
final View textEntryView = factory.inflate(R.layout.boxsdk_alert_dialog_text_entry, null);
AlertDialog loginAlert = new AlertDialog.Builder(view.getContext()).setTitle(R.string.boxsdk_alert_dialog_text_entry).setView(textEntryView)
.setPositiveButton(R.string.boxsdk_alert_dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int whichButton) {
String userName = ((EditText) textEntryView.findViewById(R.id.username_edit)).getText().toString();
String password = ((EditText) textEntryView.findViewById(R.id.password_edit)).getText().toString();
handler.proceed(userName, password);
}
}).setNegativeButton(R.string.boxsdk_alert_dialog_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int whichButton) {
handler.cancel();
mWebEventListener.onAuthFailure(new AuthFailure(AuthFailure.TYPE_USER_INTERACTION, null));
}
}).create();
loginAlert.show();
}
@Override
public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
if (mTimeOutRunnable != null){
mHandler.removeCallbacks(mTimeOutRunnable);
}
Resources resources = view.getContext().getResources();
StringBuilder sslErrorMessage = new StringBuilder(
resources.getString(R.string.boxsdk_There_are_problems_with_the_security_certificate_for_this_site));
sslErrorMessage.append(" ");
String sslErrorType;
switch (error.getPrimaryError()) {
case SslError.SSL_DATE_INVALID:
sslErrorType = view.getResources().getString(R.string.boxsdk_ssl_error_warning_DATE_INVALID);
break;
case SslError.SSL_EXPIRED:
sslErrorType = resources.getString(R.string.boxsdk_ssl_error_warning_EXPIRED);
break;
case SslError.SSL_IDMISMATCH:
sslErrorType = resources.getString(R.string.boxsdk_ssl_error_warning_ID_MISMATCH);
break;
case SslError.SSL_NOTYETVALID:
sslErrorType = resources.getString(R.string.boxsdk_ssl_error_warning_NOT_YET_VALID);
break;
case SslError.SSL_UNTRUSTED:
sslErrorType = resources.getString(R.string.boxsdk_ssl_error_warning_UNTRUSTED);
break;
case SslError.SSL_INVALID:
sslErrorType = resources.getString(R.string.boxsdk_ssl_error_warning_INVALID);
break;
default:
sslErrorType = resources.getString(R.string.boxsdk_ssl_error_warning_INVALID);
break;
}
sslErrorMessage.append(sslErrorType);
sslErrorMessage.append(" ");
sslErrorMessage.append(resources.getString(R.string.boxsdk_ssl_should_not_proceed));
// Show the user a dialog to force them to accept or decline the SSL problem before continuing.
sslErrorDialogContinueButtonClicked = false;
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(view.getContext()).setTitle(R.string.boxsdk_Security_Warning)
.setMessage(sslErrorMessage.toString()).setIcon(R.drawable.boxsdk_dialog_warning)
.setNegativeButton(R.string.boxsdk_Go_back, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int whichButton) {
sslErrorDialogContinueButtonClicked = true;
handler.cancel();
mWebEventListener.onAuthFailure(new AuthFailure(AuthFailure.TYPE_USER_INTERACTION, null));
}
});
// Only allow user to continue if explicitly granted in config
if (BoxConfig.ALLOW_SSL_ERROR) {
alertBuilder.setNeutralButton(R.string.boxsdk_ssl_error_details, null);
alertBuilder.setPositiveButton(R.string.boxsdk_Continue, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int whichButton) {
sslErrorDialogContinueButtonClicked = true;
handler.proceed();
}
});
}
final AlertDialog loginAlert = alertBuilder.create();
loginAlert.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (!sslErrorDialogContinueButtonClicked) {
mWebEventListener.onAuthFailure(new AuthFailure(AuthFailure.TYPE_USER_INTERACTION, null));
}
}
});
loginAlert.show();
if (BoxConfig.ALLOW_SSL_ERROR) {
// this is to show more information on the exception.
Button neutralButton = loginAlert.getButton(AlertDialog.BUTTON_NEUTRAL);
if (neutralButton != null) {
neutralButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showCertDialog(view.getContext(), error);
}
});
}
}
}
protected void showCertDialog(final Context context, final SslError error){
AlertDialog.Builder detailsBuilder = new AlertDialog.Builder(context).setTitle(R.string.boxsdk_Security_Warning).
setView(getCertErrorView(context, error.getCertificate()));
detailsBuilder.create().show();
}
private View getCertErrorView(final Context context, final SslCertificate certificate){
LayoutInflater factory = LayoutInflater.from(context);
View certificateView = factory.inflate(
R.layout.ssl_certificate, null);
// issued to:
SslCertificate.DName issuedTo = certificate.getIssuedTo();
if (issuedTo != null) {
((TextView) certificateView.findViewById(R.id.to_common))
.setText(issuedTo.getCName());
((TextView) certificateView.findViewById(R.id.to_org))
.setText(issuedTo.getOName());
((TextView) certificateView.findViewById(R.id.to_org_unit))
.setText(issuedTo.getUName());
}
// issued by:
SslCertificate.DName issuedBy = certificate.getIssuedBy();
if (issuedBy != null) {
((TextView) certificateView.findViewById(R.id.by_common))
.setText(issuedBy.getCName());
((TextView) certificateView.findViewById(R.id.by_org))
.setText(issuedBy.getOName());
((TextView) certificateView.findViewById(R.id.by_org_unit))
.setText(issuedBy.getUName());
}
// issued on:
String issuedOn = formatCertificateDate(context, certificate.getValidNotBeforeDate());
((TextView) certificateView.findViewById(R.id.issued_on))
.setText(issuedOn);
// expires on:
String expiresOn = formatCertificateDate(context, certificate.getValidNotAfterDate());
((TextView) certificateView.findViewById(R.id.expires_on))
.setText(expiresOn);
return certificateView;
}
private String formatCertificateDate(Context context, Date certificateDate) {
if (certificateDate == null) {
return "";
}
return DateFormat.getDateFormat(context).format(certificateDate);
}
/**
* Destroy.
*/
public void destroy() {
mWebEventListener = null;
}
private Uri getURIfromURL(final String url) {
Uri uri = Uri.parse(url);
// In case redirect url is set. We only keep processing if current url matches redirect url.
if (!SdkUtils.isEmptyString(mRedirectUrl)) {
Uri redirectUri = Uri.parse(mRedirectUrl);
if (redirectUri.getScheme() == null || !redirectUri.getScheme().equals(uri.getScheme()) || !redirectUri.getAuthority().equals(uri.getAuthority())) {
return null;
}
}
return uri;
}
/**
* Get response value.
*
* @param uri uri from url
* @param key key
* @return response value
* @throws InvalidUrlException
*/
private String getValueFromURI(final Uri uri, final String key) throws InvalidUrlException {
if (uri == null) {
return null;
}
String value = null;
try {
value = uri.getQueryParameter(key);
} catch (Exception e) {
// uri cannot be parsed for query param.
}
if (!SdkUtils.isEmptyString(value)) {
// Check state token
if (!SdkUtils.isEmptyString(state)) {
String stateQ = uri.getQueryParameter(STATE);
if (!state.equals(stateQ)) {
throw new InvalidUrlException();
}
}
}
return value;
}
public void setOnPageFinishedListener(OnPageFinishedListener listener) {
this.mOnPageFinishedListener = listener;
}
public interface WebEventListener {
/**
* The failure that caused authentication to fail.
* @param failure the failure that caused authentication to fail.
* @return true if this is handled by the client and should not be handled by webview.
*/
public boolean onAuthFailure(final AuthFailure failure);
public void onReceivedAuthCode(final String code, final String baseDomain);
public void onReceivedAuthCode(final String code);
}
class WebViewTimeOutRunnable implements Runnable {
final String mFailingUrl;
final WeakReference<WebView> mViewHolder;
public WebViewTimeOutRunnable(final WebView view, final String failingUrl) {
mFailingUrl = failingUrl;
mViewHolder = new WeakReference<WebView>(view);
}
@Override
public void run() {
onReceivedError(mViewHolder.get(), WebViewClient.ERROR_TIMEOUT, "loading timed out", mFailingUrl);
}
}
}
/**
* Listener to listen to the event of a page load finishing.
*/
public static interface OnPageFinishedListener {
void onPageFinished(final WebView view, final String url);
}
/**
* Exception indicating url validation failed.
*/
private static class InvalidUrlException extends Exception {
private static final long serialVersionUID = 1L;
}
/**
* Class containing information of an authentication failure.
*/
public static class AuthFailure {
public static final int TYPE_USER_INTERACTION = 0;
public static final int TYPE_URL_MISMATCH = 1;
public static final int TYPE_WEB_ERROR = 2;
public int type;
public String message;
public WebViewException mWebException;
public AuthFailure(int failType, String failMessage) {
this.type = failType;
this.message = failMessage;
}
public AuthFailure(WebViewException exception){
this(TYPE_WEB_ERROR, null);
mWebException = exception;
}
}
public static class WebViewException extends Exception {
private final int mErrorCode;
private final String mDescription;
private final String mFailingUrl;
public WebViewException(int errorCode, String description, String failingUrl){
mErrorCode = errorCode;
mDescription = description;
mFailingUrl = failingUrl;
}
public int getErrorCode(){
return mErrorCode;
}
public String getDescription(){
return mDescription;
}
public String getFailingUrl(){
return mFailingUrl;
}
}
}
|
package servidor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServidorTransmision extends Thread {
private Socket conexionClienteTCP;
private String videoSolicitado;
private BufferedReader entradaDatos;
private PrintWriter salidaDatos;
private int puertoUDPCliente;
private TrasmisionVideo broadcaster;
public static final int FRAMESVIDEO1 = 100;
public static final int FRAMESVIDEO2 = 100;
public ServidorTransmision(Socket conexionClienteTCP){
this.conexionClienteTCP = conexionClienteTCP;
crearIOStream();
}
@Override
public void run(){
atender();
}
public void atender(){
try {
obtenerNombreVideo();
obtenerPuertoUDPCLiente();
crearBroadcaster();
this.broadcaster.transmitir();
}
catch (IOException e){
System.err.println(e.toString());
}
}
private void obtenerNombreVideo()throws IOException{
String solicitud = entradaDatos.readLine();
if(solicitud.contains("GET")){
if (solicitud.contains("video_1")){
this.videoSolicitado = "video1";
salidaDatos.println("OK "+FRAMESVIDEO1);
}
else if (solicitud.contains("video_2")){
this.videoSolicitado = "video2";
salidaDatos.println("OK "+FRAMESVIDEO2);
}
else {
salidaDatos.println("ERR");
}
}
else {
salidaDatos.println("ERR");
}
}
private void obtenerPuertoUDPCLiente() throws IOException{
String mensaje = entradaDatos.readLine();
if (mensaje.contains("PORT"))
{
this.puertoUDPCliente = Integer.parseInt(mensaje.substring(5));
salidaDatos.println("OK");
}
else {
salidaDatos.println("ERR");
}
}
private void crearBroadcaster(){
this.broadcaster = new TrasmisionVideo(puertoUDPCliente,videoSolicitado,conexionClienteTCP.getInetAddress()
,(videoSolicitado.equals("video_1")?FRAMESVIDEO1:FRAMESVIDEO2));
}
private void crearIOStream(){
try {
this.entradaDatos = new BufferedReader(new InputStreamReader(this.conexionClienteTCP.getInputStream()));
this.salidaDatos = new PrintWriter(this.conexionClienteTCP.getOutputStream(),true);
}
catch (IOException e){
//TerminalLogger.TLog("Error al crear buffers."+e.toString(),TerminalLogger.ERR);
}
}
}
|
package com.dianping.cat.consumer.matrix;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import com.dianping.cat.Cat;
import com.dianping.cat.configuration.NetworkInterfaceManager;
import com.dianping.cat.consumer.matrix.model.entity.Matrix;
import com.dianping.cat.consumer.matrix.model.entity.MatrixReport;
import com.dianping.cat.consumer.matrix.model.entity.Ratio;
import com.dianping.cat.consumer.matrix.model.transform.DefaultSaxParser;
import com.dianping.cat.consumer.matrix.model.transform.DefaultXmlBuilder;
import com.dianping.cat.hadoop.dal.Report;
import com.dianping.cat.hadoop.dal.ReportDao;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.spi.AbstractMessageAnalyzer;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.storage.Bucket;
import com.dianping.cat.storage.BucketManager;
import com.site.lookup.annotation.Inject;
public class MatrixAnalyzer extends AbstractMessageAnalyzer<MatrixReport> implements LogEnabled {
@Inject
private BucketManager m_bucketManager;
@Inject
private ReportDao m_reportDao;
// @Inject
// private TaskDao m_taskDao;
private Map<String, MatrixReport> m_reports = new HashMap<String, MatrixReport>();
private long m_extraTime;
private long m_startTime;
private long m_duration;
private Logger m_logger;
@Override
public void doCheckpoint(boolean atEnd) {
storeReports(atEnd);
}
@Override
public void enableLogging(Logger logger) {
m_logger = logger;
}
@Override
public Set<String> getDomains() {
return m_reports.keySet();
}
public MatrixReport getReport(String domain) {
MatrixReport report = m_reports.get(domain);
if (report == null) {
report = new MatrixReport(domain);
}
report.getDomainNames().addAll(m_reports.keySet());
return report;
}
@Override
protected boolean isTimeout() {
long currentTime = System.currentTimeMillis();
long endTime = m_startTime + m_duration + m_extraTime;
return currentTime > endTime;
}
private void loadReports() {
Bucket<String> reportBucket = null;
try {
reportBucket = m_bucketManager.getReportBucket(m_startTime, "matrix");
for (String id : reportBucket.getIds()) {
String xml = reportBucket.findById(id);
MatrixReport report = DefaultSaxParser.parse(xml);
m_reports.put(report.getDomain(), report);
}
} catch (Exception e) {
m_logger.error(String.format("Error when loading matrix reports of %s!", new Date(m_startTime)), e);
} finally {
if (reportBucket != null) {
m_bucketManager.closeBucket(reportBucket);
}
}
}
@Override
protected void process(MessageTree tree) {
String domain = tree.getDomain();
MatrixReport report = m_reports.get(domain);
if (report == null) {
report = new MatrixReport(domain);
report.setStartTime(new Date(m_startTime));
report.setEndTime(new Date(m_startTime + MINUTE * 60 - 1));
m_reports.put(domain, report);
}
Message message = tree.getMessage();
if (message instanceof Transaction) {
String messageType = message.getType();
if (messageType.equals("URL") || messageType.equals("Service")) {
Matrix matrix = report.findOrCreateMatrix(message.getName());
matrix.setType(message.getType());
matrix.setName(message.getName());
long duration = ((Transaction) message).getDurationInMicros();
matrix.incCount();
matrix.setTotalTime(matrix.getTotalTime() + duration);
Map<String, Ratio> ratios = new HashMap<String, Ratio>();
ratios.put("Call", new Ratio());
ratios.put("SQL", new Ratio());
ratios.put("Cache", new Ratio());
processTransaction(tree, (Transaction) message, ratios);
for (Entry<String, Ratio> entry : ratios.entrySet()) {
String type = entry.getKey();
Ratio ratio = entry.getValue();
int count = ratio.getTotalCount();
long time = ratio.getTotalTime();
Ratio real = matrix.findOrCreateRatio(type);
if (real.getMin() > count || real.getMin() == 0) {
real.setMin(count);
}
if (real.getMax() < count) {
real.setMax(count);
}
real.setTotalCount(real.getTotalCount() + count);
real.setTotalTime(real.getTotalTime() + time);
}
// the message is required by some matrixs
if (matrix.getUrl() == null) {
matrix.setUrl(tree.getMessageId());
storeMessage(tree);
}
}
}
}
private void processTransaction(MessageTree tree, Transaction t, Map<String, Ratio> ratios) {
List<Message> children = t.getChildren();
String type = t.getType();
Ratio ratio = null;
if (type.equals("Call")) {
ratio = ratios.get("Call");
} else if (type.equals("SQL")) {
ratio = ratios.get("SQL");
} else if (type.startsWith("Cache.")) {
ratio = ratios.get("Cache");
}
if (ratio != null) {
ratio.incTotalCount();
ratio.setTotalTime(ratio.getTotalTime() + t.getDurationInMicros());
}
for (Message child : children) {
if (child instanceof Transaction) {
processTransaction(tree, (Transaction) child, ratios);
}
}
}
public void setAnalyzerInfo(long startTime, long duration, long extraTime) {
m_extraTime = extraTime;
m_startTime = startTime;
m_duration = duration;
loadReports();
}
private void storeMessage(MessageTree tree) {
String messageId = tree.getMessageId();
String domain = tree.getDomain();
try {
Bucket<MessageTree> logviewBucket = m_bucketManager.getLogviewBucket(m_startTime, domain);
logviewBucket.storeById(messageId, tree);
} catch (IOException e) {
m_logger.error("Error when storing logview for matrix analyzer!", e);
}
}
private void storeReports(boolean atEnd) {
DefaultXmlBuilder builder = new DefaultXmlBuilder(true);
Bucket<String> reportBucket = null;
Transaction t = Cat.getProducer().newTransaction("Checkpoint", getClass().getSimpleName());
try {
reportBucket = m_bucketManager.getReportBucket(m_startTime, "matrix");
for (MatrixReport report : m_reports.values()) {
Set<String> domainNames = report.getDomainNames();
domainNames.clear();
domainNames.addAll(getDomains());
String xml = builder.buildXml(report);
String domain = report.getDomain();
reportBucket.storeById(domain, xml);
}
if (atEnd && !isLocalMode()) {
Date period = new Date(m_startTime);
String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress();
for (MatrixReport report : m_reports.values()) {
try {
Report r = m_reportDao.createLocal();
String xml = builder.buildXml(report);
String domain = report.getDomain();
r.setName("matrix");
r.setDomain(domain);
r.setPeriod(period);
r.setIp(ip);
r.setType(1);
r.setContent(xml);
m_reportDao.insert(r);
// Task task = m_taskDao.createLocal();
// task.setCreationDate(new Date());
// task.setProducer(ip);
// task.setReportDomain(domain);
// task.setReportName("matrix");
// task.setReportPeriod(period);
// task.setStatus(1); // status todo
// m_taskDao.insert(task);
// m_logger.info("insert matrix task:" + task.toString());
} catch (Throwable e) {
Cat.getProducer().logError(e);
}
}
}
t.setStatus(Message.SUCCESS);
} catch (Exception e) {
Cat.getProducer().logError(e);
t.setStatus(e);
m_logger.error(String.format("Error when storing matrix reports of %s!", new Date(m_startTime)), e);
} finally {
t.complete();
if (reportBucket != null) {
m_bucketManager.closeBucket(reportBucket);
}
}
}
}
|
package de.hdodenhof.circleimageview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CircleImageView extends ImageView {
private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;
private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
private static final int COLORDRAWABLE_DIMENSION = 2;
private static final int DEFAULT_BORDER_WIDTH = 0;
private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
private final RectF mDrawableRect = new RectF();
private final RectF mBorderRect = new RectF();
private final Matrix mShaderMatrix = new Matrix();
private final Paint mBitmapPaint = new Paint();
private final Paint mBorderPaint = new Paint();
private int mBorderColor = DEFAULT_BORDER_COLOR;
private int mBorderWidth = DEFAULT_BORDER_WIDTH;
private Bitmap mBitmap;
private BitmapShader mBitmapShader;
private int mBitmapWidth;
private int mBitmapHeight;
private float mDrawableRadius;
private float mBorderRadius;
private ColorFilter mColorFilter;
private boolean mReady;
private boolean mSetupPending;
public CircleImageView(Context context) {
super(context);
init();
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);
mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR);
a.recycle();
init();
}
private void init() {
super.setScaleType(SCALE_TYPE);
mReady = true;
if (mSetupPending) {
setup();
mSetupPending = false;
}
}
@Override
public ScaleType getScaleType() {
return SCALE_TYPE;
}
@Override
public void setScaleType(ScaleType scaleType) {
if (scaleType != SCALE_TYPE) {
throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
}
}
@Override
public void setAdjustViewBounds(boolean adjustViewBounds) {
if (adjustViewBounds) {
throw new IllegalArgumentException("adjustViewBounds not supported.");
}
}
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null) {
return;
}
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
if (mBorderWidth != 0) {
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setup();
}
public int getBorderColor() {
return mBorderColor;
}
public void setBorderColor(int borderColor) {
if (borderColor == mBorderColor) {
return;
}
mBorderColor = borderColor;
mBorderPaint.setColor(mBorderColor);
invalidate();
}
public int getBorderWidth() {
return mBorderWidth;
}
public void setBorderWidth(int borderWidth) {
if (borderWidth == mBorderWidth) {
return;
}
mBorderWidth = borderWidth;
setup();
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
mBitmap = bm;
setup();
}
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
mBitmap = getBitmapFromDrawable(drawable);
setup();
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
}
@Override
public void setColorFilter(ColorFilter cf) {
if (cf == mColorFilter) {
return;
}
mColorFilter = cf;
setup();
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (OutOfMemoryError e) {
return null;
}
}
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (mBitmap == null) {
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
if (mColorFilter != null) {
mBitmapPaint.setColorFilter(mColorFilter);
}
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);
updateShaderMatrix();
invalidate();
}
private void updateShaderMatrix() {
float scale;
float dx = 0;
float dy = 0;
mShaderMatrix.set(null);
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth);
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
}
|
package com.codenvy.plugin.yeoman.client.builder;
import com.codenvy.api.builder.BuildStatus;
import com.codenvy.api.builder.dto.BuildOptions;
import com.codenvy.api.builder.dto.BuildTaskDescriptor;
import com.codenvy.api.builder.gwt.client.BuilderServiceClient;
import com.codenvy.api.core.rest.shared.dto.Link;
import com.codenvy.api.project.gwt.client.ProjectServiceClient;
import com.codenvy.api.project.shared.dto.ImportProject;
import com.codenvy.api.project.shared.dto.ImportResponse;
import com.codenvy.api.project.shared.dto.ImportSourceDescriptor;
import com.codenvy.api.project.shared.dto.Source;
import com.codenvy.ide.api.app.AppContext;
import com.codenvy.ide.api.notification.Notification;
import com.codenvy.ide.api.notification.NotificationManager;
import com.codenvy.ide.commons.exception.ExceptionThrownEvent;
import com.codenvy.ide.commons.exception.UnmarshallerException;
import com.codenvy.ide.dto.DtoFactory;
import com.codenvy.ide.extension.builder.client.BuilderExtension;
import com.codenvy.ide.extension.builder.client.console.BuilderConsolePresenter;
import com.codenvy.ide.rest.AsyncRequestCallback;
import com.codenvy.ide.rest.DtoUnmarshallerFactory;
import com.codenvy.ide.util.loging.Log;
import com.codenvy.ide.websocket.Message;
import com.codenvy.ide.websocket.MessageBus;
import com.codenvy.ide.websocket.WebSocketException;
import com.codenvy.ide.websocket.rest.StringUnmarshallerWS;
import com.codenvy.ide.websocket.rest.SubscriptionHandler;
import com.codenvy.ide.websocket.rest.Unmarshallable;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.web.bindery.event.shared.EventBus;
import javax.inject.Inject;
import java.util.List;
import static com.codenvy.ide.api.notification.Notification.Status.FINISHED;
import static com.codenvy.ide.api.notification.Notification.Status.PROGRESS;
import static com.codenvy.ide.api.notification.Notification.Type.ERROR;
import static com.codenvy.ide.api.notification.Notification.Type.INFO;
/**
* @author Florent Benoit
*/
public class BuilderAgent {
@Inject
private DtoFactory dtoFactory;
@Inject
private BuilderServiceClient builderServiceClient;
@Inject
private AppContext appContext;
@Inject
private NotificationManager notificationManager;
@Inject
private DtoUnmarshallerFactory dtoUnmarshallerFactory;
@Inject
private MessageBus messageBus;
@Inject
private EventBus eventBus;
@Inject
private BuilderConsolePresenter console;
@Inject
private ProjectServiceClient projectServiceClient;
/**
* A build has been successful, change notification message.
* @param notification
* @param successMessage
*/
protected void buildSuccessful(Notification notification, String successMessage, String prefixConsole) {
notification.setMessage(successMessage);
notification.setStatus(FINISHED);
console.print(prefixConsole + "::" + successMessage);
}
/**
* Launch a build with all these options
* @param buildOptions the options to build
* @param waitMessage the message to display on the notification while waiting
* @param successMessage the message to display on the notification while it has been successful
* @param errorMessage the message to display on the notification if there was an error
* @param prefixConsole the prefix to show in the console
* @param buildFinishedCallback an optional callback to call when the build has finished
*/
public void build(final BuildOptions buildOptions, final String waitMessage, final String successMessage, final String errorMessage, final String prefixConsole,
final BuildFinishedCallback buildFinishedCallback) {
// Start a build so print a new notification message
final Notification notification = new Notification(waitMessage, INFO);
notificationManager.showNotification(notification);
// Ask the build service to perform the build
builderServiceClient.build(appContext.getCurrentProject().getProjectDescription().getPath(),
buildOptions,
new AsyncRequestCallback<BuildTaskDescriptor>(
dtoUnmarshallerFactory.newUnmarshaller(BuildTaskDescriptor.class)) {
@Override
protected void onSuccess(BuildTaskDescriptor result) {
// Notify the callback if already finished
if (result.getStatus() == BuildStatus.SUCCESSFUL) {
if (buildFinishedCallback != null) {
buildFinishedCallback.onFinished(result.getStatus());
}
buildSuccessful(notification, successMessage, prefixConsole);
} else {
// Check the status by registering a callback
startChecking(notification, result, successMessage, errorMessage, prefixConsole,
buildFinishedCallback);
notification.setStatus(PROGRESS);
}
}
@Override
protected void onFailure(Throwable exception) {
if (buildFinishedCallback != null) {
buildFinishedCallback.onFinished(BuildStatus.FAILED);
}
notification.setMessage(errorMessage);
notification.setStatus(FINISHED);
notification.setType(ERROR);
notification.setMessage(exception.getMessage());
console.print(prefixConsole + "::" + errorMessage);
}
});
}
/**
* Check the task in order to see if it is being executed and track the result
* @param notification
* @param buildTaskDescriptor
* @param successMessage
* @param errorMessage
* @param buildFinishedCallback
*/
protected void startChecking(final Notification notification, final BuildTaskDescriptor buildTaskDescriptor,
final String successMessage, final String errorMessage, final String prefixConsole,
final BuildFinishedCallback buildFinishedCallback) {
final SubscriptionHandler<String> buildOutputHandler = new SubscriptionHandler<String>(new LineUnmarshaller()) {
@Override
protected void onMessageReceived(String result) {
console.print(prefixConsole + "::" + result);
}
@Override
protected void onErrorReceived(Throwable throwable) {
try {
messageBus.unsubscribe(BuilderExtension.BUILD_OUTPUT_CHANNEL + buildTaskDescriptor.getTaskId(), this);
Log.error(BuilderAgent.class, throwable);
} catch (WebSocketException e) {
Log.error(BuilderAgent.class, e);
}
}
};
final SubscriptionHandler<String> buildStatusHandler = new SubscriptionHandler<String>(new StringUnmarshallerWS()) {
@Override
protected void onMessageReceived(String result) {
updateBuildStatus(notification, dtoFactory.createDtoFromJson(result, BuildTaskDescriptor.class), this, buildOutputHandler, successMessage,
errorMessage, prefixConsole, buildFinishedCallback);
}
@Override
protected void onErrorReceived(Throwable exception) {
try {
messageBus.unsubscribe(BuilderExtension.BUILD_STATUS_CHANNEL + buildTaskDescriptor.getTaskId(), this);
} catch (WebSocketException e) {
Log.error(BuilderAgent.class, e);
}
notification.setType(ERROR);
notification.setStatus(FINISHED);
notification.setMessage(exception.getMessage());
eventBus.fireEvent(new ExceptionThrownEvent(exception));
if (buildFinishedCallback != null) {
buildFinishedCallback.onFinished(BuildStatus.FAILED);
}
}
};
try {
messageBus.subscribe(BuilderExtension.BUILD_STATUS_CHANNEL + buildTaskDescriptor.getTaskId(), buildStatusHandler);
} catch (WebSocketException e) {
Log.error(BuilderAgent.class, e);
}
try {
messageBus.subscribe(BuilderExtension.BUILD_OUTPUT_CHANNEL + buildTaskDescriptor.getTaskId(), buildOutputHandler);
} catch (WebSocketException e) {
Log.error(BuilderAgent.class, e);
}
}
/**
* Check for status and display necessary messages.
*
* @param descriptor
* status of build
*/
protected void updateBuildStatus(Notification notification, BuildTaskDescriptor descriptor,
SubscriptionHandler<String> buildStatusHandler, SubscriptionHandler<String> buildOutputHandler, final String successMessage, final String errorMessage, final String prefixConsole,
final BuildFinishedCallback buildFinishedCallback) {
BuildStatus status = descriptor.getStatus();
if (status == BuildStatus.IN_PROGRESS || status == BuildStatus.IN_QUEUE) {
return;
}
if (status == BuildStatus.CANCELLED || status == BuildStatus.FAILED || status == BuildStatus.SUCCESSFUL) {
afterBuildFinished(notification, descriptor, buildStatusHandler, buildOutputHandler, successMessage, errorMessage, prefixConsole, buildFinishedCallback);
}
}
/**
* Perform actions after build is finished.
*
* @param descriptor
* status of build job
*/
protected void afterBuildFinished(Notification notification, BuildTaskDescriptor descriptor,
SubscriptionHandler<String> buildStatusHandler, SubscriptionHandler<String> buildOutputHandler, final String successMessage, final String errorMessage, final String prefixConsole,
BuildFinishedCallback buildFinishedCallback) {
try {
messageBus.unsubscribe(BuilderExtension.BUILD_STATUS_CHANNEL + descriptor.getTaskId(), buildStatusHandler);
} catch (Exception e) {
Log.error(BuilderAgent.class, e);
}
try {
messageBus.unsubscribe(BuilderExtension.BUILD_OUTPUT_CHANNEL + descriptor.getTaskId(), buildOutputHandler);
} catch (Exception e) {
Log.error(BuilderAgent.class, e);
}
if (descriptor.getStatus() == BuildStatus.SUCCESSFUL) {
buildSuccessful(notification, successMessage, prefixConsole);
} else if (descriptor.getStatus() == BuildStatus.FAILED) {
notification.setMessage(errorMessage);
notification.setStatus(FINISHED);
notification.setType(ERROR);
console.print(prefixConsole + "::" + errorMessage);
}
// import zip
importZipResult(descriptor, buildFinishedCallback, notification, errorMessage);
}
/**
* If there is a result zip, import it.
* @param descriptor the build descriptor
* @param buildFinishedCallback the callback to call
*/
protected void importZipResult(final BuildTaskDescriptor descriptor, final BuildFinishedCallback buildFinishedCallback, final Notification notification, final String errorMessage) {
Link downloadLink = null;
List<Link> links = descriptor.getLinks();
for (Link link : links) {
if (link.getRel().equalsIgnoreCase("download result")) {
downloadLink = link;
}
}
if (downloadLink != null) {
ImportProject importProject = dtoFactory.createDto(ImportProject.class).withSource(dtoFactory.createDto(Source.class).withProject(
dtoFactory.createDto(ImportSourceDescriptor.class).withLocation(downloadLink.getHref()).withType("zip")));
projectServiceClient.importProject(appContext.getCurrentProject().getProjectDescription().getPath(), true, importProject,
new AsyncRequestCallback<ImportResponse>() {
@Override
protected void onSuccess(ImportResponse projectDescriptor) {
// notify callback
if (buildFinishedCallback != null) {
buildFinishedCallback.onFinished(descriptor.getStatus());
}
}
@Override
protected void onFailure(Throwable throwable) {
notification.setMessage(errorMessage + ":" + throwable.getMessage());
notification.setStatus(FINISHED);
notification.setType(ERROR);
if (buildFinishedCallback != null) {
buildFinishedCallback.onFinished(descriptor.getStatus());
}
}
});
} else {
// notify callback
if (buildFinishedCallback != null) {
buildFinishedCallback.onFinished(descriptor.getStatus());
}
}
}
static class LineUnmarshaller implements Unmarshallable<String> {
private String line;
@Override
public void unmarshal(Message response) throws UnmarshallerException {
JSONObject jsonObject = JSONParser.parseStrict(response.getBody()).isObject();
if (jsonObject == null) {
return;
}
if (jsonObject.containsKey("line")) {
line = jsonObject.get("line").isString().stringValue();
}
}
@Override
public String getPayload() {
return line;
}
}
}
|
package io.cloudslang.lang.systemtests;
import com.google.common.collect.Sets;
import io.cloudslang.lang.api.Slang;
import io.cloudslang.lang.entities.CompilationArtifact;
import io.cloudslang.lang.entities.ScoreLangConstants;
import io.cloudslang.lang.entities.SystemProperty;
import io.cloudslang.lang.entities.bindings.values.Value;
import io.cloudslang.lang.runtime.events.LanguageEventData;
import io.cloudslang.score.events.ScoreEvent;
import io.cloudslang.score.events.ScoreEventListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.springframework.beans.factory.annotation.Autowired;
public class TriggerFlows {
private static final HashSet<String> FINISHED_EVENTS =
Sets.newHashSet(ScoreLangConstants.EVENT_EXECUTION_FINISHED, ScoreLangConstants.SLANG_EXECUTION_EXCEPTION);
private static final HashSet<String> STEP_EVENTS =
Sets.newHashSet(
ScoreLangConstants.EVENT_INPUT_END,
ScoreLangConstants.EVENT_OUTPUT_END,
ScoreLangConstants.EVENT_ARGUMENT_START,
ScoreLangConstants.EVENT_ARGUMENT_END
);
private static final HashSet<String> BRANCH_EVENTS = Sets.newHashSet(ScoreLangConstants.EVENT_BRANCH_END);
private static final HashSet<String> PARALLEL_LOOP_EVENTS =
Sets.newHashSet(ScoreLangConstants.EVENT_JOIN_BRANCHES_END);
private static final HashSet<String> ALL_CLOUDSLANG_EVENTS =
Sets.newHashSet(
ScoreLangConstants.SLANG_EXECUTION_EXCEPTION,
ScoreLangConstants.EVENT_ACTION_START,
ScoreLangConstants.EVENT_ACTION_END,
ScoreLangConstants.EVENT_ACTION_ERROR,
ScoreLangConstants.EVENT_INPUT_START,
ScoreLangConstants.EVENT_INPUT_END,
ScoreLangConstants.EVENT_STEP_START,
ScoreLangConstants.EVENT_ARGUMENT_START,
ScoreLangConstants.EVENT_ARGUMENT_END,
ScoreLangConstants.EVENT_OUTPUT_START,
ScoreLangConstants.EVENT_OUTPUT_END,
ScoreLangConstants.EVENT_EXECUTION_FINISHED,
ScoreLangConstants.EVENT_BRANCH_START,
ScoreLangConstants.EVENT_BRANCH_END,
ScoreLangConstants.EVENT_SPLIT_BRANCHES,
ScoreLangConstants.EVENT_JOIN_BRANCHES_START,
ScoreLangConstants.EVENT_JOIN_BRANCHES_END
);
@Autowired
private Slang slang;
public ScoreEvent runSync(
CompilationArtifact compilationArtifact,
Map<String, Value> userInputs,
Set<SystemProperty> systemProperties) {
return runSync(compilationArtifact, userInputs, systemProperties, true);
}
public ScoreEvent runSync(
CompilationArtifact compilationArtifact,
Map<String, Value> userInputs,
Set<SystemProperty> systemProperties,
boolean shouldFail) {
final BlockingQueue<ScoreEvent> finishEvent = new LinkedBlockingQueue<>();
ScoreEventListener finishListener = new ScoreEventListener() {
@Override
public synchronized void onEvent(ScoreEvent event) throws InterruptedException {
finishEvent.add(event);
}
};
slang.subscribeOnEvents(finishListener, FINISHED_EVENTS);
long executionId = slang.run(compilationArtifact, userInputs, systemProperties);
try {
ScoreEvent event = null;
boolean finishEventReceived = false;
while (!finishEventReceived) {
event = finishEvent.take();
long executionIdFromEvent = (long) ((Map) event.getData()).get(LanguageEventData.EXECUTION_ID);
finishEventReceived = executionId == executionIdFromEvent;
}
if (event.getEventType().equals(ScoreLangConstants.SLANG_EXECUTION_EXCEPTION) && shouldFail) {
LanguageEventData languageEvent = (LanguageEventData) event.getData();
throw new RuntimeException(languageEvent.getException());
}
slang.unSubscribeOnEvents(finishListener);
return event;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public RuntimeInformation runWithData(
CompilationArtifact compilationArtifact,
Map<String, Value> userInputs,
Set<SystemProperty> systemProperties) {
RunDataAggregatorListener runDataAggregatorListener = new RunDataAggregatorListener();
slang.subscribeOnEvents(runDataAggregatorListener, STEP_EVENTS);
BranchAggregatorListener branchAggregatorListener = new BranchAggregatorListener();
slang.subscribeOnEvents(branchAggregatorListener, BRANCH_EVENTS);
JoinAggregatorListener joinAggregatorListener = new JoinAggregatorListener();
slang.subscribeOnEvents(joinAggregatorListener, PARALLEL_LOOP_EVENTS);
runSync(compilationArtifact, userInputs, systemProperties);
Map<String, StepData> steps = runDataAggregatorListener.aggregate();
Map<String, List<StepData>> branchesByPath = branchAggregatorListener.aggregate();
Map<String, StepData> parallelSteps = joinAggregatorListener.aggregate();
final RuntimeInformation runtimeInformation = new RuntimeInformation(steps, branchesByPath, parallelSteps);
slang.unSubscribeOnEvents(joinAggregatorListener);
slang.unSubscribeOnEvents(branchAggregatorListener);
slang.unSubscribeOnEvents(runDataAggregatorListener);
return runtimeInformation;
}
public List<ScoreEvent> runAndCollectAllEvents(
CompilationArtifact compilationArtifact,
Map<String, Value> userInputs,
Set<SystemProperty> systemProperties) {
final List<ScoreEvent> events = Collections.synchronizedList(new ArrayList<ScoreEvent>());
ScoreEventListener allEventsListener = new ScoreEventListener() {
@Override
public synchronized void onEvent(ScoreEvent event) throws InterruptedException {
events.add(event);
}
};
slang.subscribeOnEvents(allEventsListener, ALL_CLOUDSLANG_EVENTS);
ScoreEvent finishEvent = runSync(compilationArtifact, userInputs, systemProperties, false);
slang.unSubscribeOnEvents(allEventsListener);
// make sure finish event is saved
for (ScoreEvent scoreEvent : events) {
String eventType = scoreEvent.getEventType();
if (ScoreLangConstants.SLANG_EXECUTION_EXCEPTION.equals(eventType) ||
ScoreLangConstants.EVENT_EXECUTION_FINISHED.equals(eventType)) {
return events;
}
}
events.add(finishEvent);
return events;
}
}
|
package org.jetel.util.protocols.sandbox;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import org.jetel.graph.TransformationGraph;
import org.jetel.util.file.SandboxUrlUtils;
/**
*
* @author mvarecha
*
*/
public class SandboxStreamHandler extends URLStreamHandler {
public static final String SANDBOX_PROTOCOL = "sandbox";
public static final String SANDBOX_PROTOCOL_URL_PREFIX = SANDBOX_PROTOCOL+":
private final TransformationGraph graph;
public SandboxStreamHandler(TransformationGraph graph) {
super();
this.graph = graph;
}
/*
* (non-Javadoc)
* @see java.net.URLStreamHandler#openConnection(java.net.URL)
*/
@Override
public URLConnection openConnection(URL url) throws IOException {
return new SandboxConnection(graph, url);
}
/*
* (non-Javadoc)
* @see java.net.URLStreamHandler#parseURL(java.net.URL, java.lang.String, int, int)
*/
protected void parseURL(URL url, String spec, int start, int limit) {
super.parseURL(url, spec, start, limit);
if (!SandboxUrlUtils.isSandboxUrl(url)) {
throw new RuntimeException("Parse error: The URL protocol name must be sandbox!");
}
}
}
|
package com.github.neunkasulle.chronocommand.model;
public class TimeSheetDAO {
public TimeSheet getTimeSheet(int month, int year, Proletarier proletarier) {
throw new UnsupportedOperationException();
}
public TimeRecord[] getTimeRecords(TimeSheet timeSheet) {
throw new UnsupportedOperationException();
}
public TimeRecord[] getTimeRecordsByDay(TimeSheet timeSheet, int dayOfMonth) {
throw new UnsupportedOperationException();
}
public TimeSheetHandler getTimeSheetHandler() {
throw new UnsupportedOperationException();
}
public TimeSheet[] getAllUnlockedTimeSheets() {
throw new UnsupportedOperationException();
}
public boolean addTimeSheet(TimeSheet timeSheet) {
throw new UnsupportedOperationException();
}
}
|
package com.example.android.rssfeed;
import android.app.Activity;
import android.app.Application;
import android.content.res.Configuration;
import android.os.Bundle;
public class DetailActivity extends Activity {
public static final String EXTRA_URL = "url";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Need to check if Activity has been switched to landscape mode
// If yes, finished and go back to the start Activity
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
setContentView(R.layout.activity_detail);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String url = extras.getString(EXTRA_URL);
DetailFragment detailFragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detailFragment);
detailFragment.setText(url);
}
}
}
|
package com.github.sormuras.bach;
import com.github.sormuras.bach.internal.Paths;
import com.github.sormuras.bach.module.ModuleDirectory;
import com.github.sormuras.bach.module.ModuleSearcher;
import com.github.sormuras.bach.project.MainSpace;
import com.github.sormuras.bach.project.TestSpace;
import com.github.sormuras.bach.tool.Command;
import com.github.sormuras.bach.tool.ToolCall;
import com.github.sormuras.bach.tool.ToolRunner;
import java.io.File;
import java.lang.System.Logger.Level;
import java.lang.module.ModuleFinder;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/** Builds a modular Java project. */
public class ProjectBuilder {
private final Bach bach;
private final Project project;
private final ModuleDirectory moduleDirectory;
private final ToolRunner runner;
/**
* Initialize this project builder with the given components.
*
* @param bach the {@code Bach} instance
* @param project the project to build
*/
public ProjectBuilder(Bach bach, Project project) {
this.bach = bach;
this.project = project;
this.moduleDirectory = ModuleDirectory.of(Project.LIBRARIES, project.library().links());
this.runner = new ToolRunner(moduleDirectory.finder());
}
void info(String format, Object... args) {
bach.logbook().log(Level.INFO, format, args);
}
void run(ToolCall call) {
info(call.toCommand().toString());
var response = runner.run(call);
bach.logbook().log(response);
response.checkSuccessful();
}
/** Builds a modular Java project. */
public void build() {
var start = Instant.now();
var logbook = bach.logbook();
info("Build project %s %s", project.name(), project.version());
try {
if (project.findAllModuleNames().count() == 0) throw new RuntimeException("No module found!");
loadRequiredAndMissingModules();
build(project.main());
build(project.test());
} catch (Exception exception) {
logbook.log(Level.ERROR, exception.toString());
throw new BuildException("Build failed: " + exception);
} finally {
info("Build took %s", Logbook.toString(Duration.between(start, Instant.now())));
var file = logbook.write(project);
logbook.accept("Logbook written to " + file.toUri());
}
}
/** Load required and missing modules in a best-effort manner. */
public void loadRequiredAndMissingModules() {
var searcher = ModuleSearcher.ofBestEffort(bach);
var requires = project.library().requires();
requires.forEach(module -> bach.loadModule(moduleDirectory, searcher, module));
bach.loadMissingModules(moduleDirectory, searcher);
}
/**
* Builds the main space.
*
* <ul>
* <li>javac + jar
* <li>javadoc
* <li>jlink
* <li>jpackage
* </ul>
*
* @param main the main space to build
*/
public void build(MainSpace main) {
if (main.modules().isEmpty()) return;
Paths.deleteDirectories(main.workspace("modules"));
info("Compile main modules");
if (main.release() >= 9) run(computeMainJavacCall());
else buildSingleRelease78Modules();
Paths.createDirectories(main.workspace("modules"));
for (var module : project.main().modules()) {
for (var release : project.main().supplements().get(module).releases()) {
run(computeMainJavacCall(module, release));
}
run(computeMainJarCall(module));
}
if (isGenerateApiDocumentation()) {
info("Generate API documentation");
run(computeMainDocumentationJavadocCall());
run(computeMainDocumentationJarCall());
}
if (isGenerateCustomRuntimeImage()) {
info("Generate custom runtime image");
Paths.deleteDirectories(main.workspace("image"));
run(computeMainJLinkCall());
}
if (isGenerateApplicationPackage()) {
info("Generate self-contained Java application");
run(computeMainJPackageCall());
}
}
/** Builds all main modules in a single */
public void buildSingleRelease78Modules() {
var main = project.main();
if (main.release() > 8) throw new IllegalStateException("release too high: " + main.release());
for (var module : project.main().modules()) {
var moduleInfoJavaFiles = new ArrayList<Path>();
Paths.find(Path.of(module, "main/java-module"), "module-info.java", moduleInfoJavaFiles::add);
var compileModuleOnly =
Command.builder("javac")
.with("--release", 9)
.with("--module-version", project.version())
.with("--module-source-path", String.join(File.pathSeparator, main.moduleSourcePaths()))
.with("--module-path", String.join(File.pathSeparator, main.modulePaths()))
.with("-implicit:none") // generate classes for explicitly referenced source files
.withEach(main.tweaks().getOrDefault("javac", List.of()))
.with("-d", main.classes())
.withEach(moduleInfoJavaFiles)
.build();
run(compileModuleOnly);
var javaSourceFiles = new ArrayList<Path>();
Paths.find(Path.of(module, "main/java"), "**.java", javaSourceFiles::add);
var javac =
Command.builder("javac")
.with("--release", main.release()) // 7 or 8
.withEach(main.tweaks().getOrDefault("javac", List.of()))
.with("-d", main.classes().resolve(module))
.withEach(javaSourceFiles);
run(javac.build());
}
}
/**
* Builds the test space.
*
* <ul>
* <li>javac + jar
* <li>junit
* </ul>
*
* @param test the test space to build
*/
public void build(TestSpace test) {
if (test.modules().isEmpty()) return;
Paths.deleteDirectories(test.workspace("modules-test"));
info("Compile test modules");
run(computeTestJavacCall());
Paths.createDirectories(test.workspace("modules-test"));
for (var module : project.test().modules()) {
run(computeTestJarCall(module));
}
if (moduleDirectory.finder().find("org.junit.platform.console").isPresent()) {
for (var module : project.test().modules()) {
var archive = module + "@" + project.version() + "+test.jar";
var finder =
ModuleFinder.of(
test.workspace("modules-test", archive), // module under test
test.workspace("modules"), // main modules
test.workspace("modules-test"), // (more) test modules
Project.LIBRARIES // external modules
);
info("Launch JUnit Platform for test module: %s", module);
var junit = computeTestJUnitCall(module);
info(junit.toCommand().toString());
runner.run(junit, finder, module).checkSuccessful();
}
}
}
/** @return {@code true} if an API documenation should be generated, else {@code false} */
public boolean isGenerateApiDocumentation() {
return project.main().generateApiDocumentation();
}
/** @return {@code true} if a custom runtime image should be generated, else {@code false} */
public boolean isGenerateCustomRuntimeImage() {
return project.main().generateCustomRuntimeImage();
}
/** @return {@code true} if a self-contained package should be generated, else {@code false} */
public boolean isGenerateApplicationPackage() {
return project.main().generateApplicationPackage();
}
/** @return the {@code javac} call to compile all modules of the main space. */
public ToolCall computeMainJavacCall() {
var main = project.main();
return Command.builder("javac")
.with("--release", main.release())
.with("--module", String.join(",", main.modules()))
.with("--module-version", project.version())
.with("--module-source-path", String.join(File.pathSeparator, main.moduleSourcePaths()))
.with("--module-path", String.join(File.pathSeparator, main.modulePaths()))
.withEach(main.tweaks().getOrDefault("javac", List.of()))
.with("-d", main.classes())
.build();
}
/**
* @param module the module to compile
* @param release the release to compile
* @return the {@code javac} call to compile a version of a multi-release module
*/
public ToolCall computeMainJavacCall(String module, int release) {
var main = project.main();
var classes = main.workspace("classes-mr", release + "/" + module);
var javaSourceFiles = new ArrayList<Path>();
Paths.find(Path.of(module, "main/java-" + release), "**.java", javaSourceFiles::add);
return Command.builder("javac")
.with("--release", release)
.with("--module-version", project.version())
.with("--module-path", main.classes())
.with("-implicit:none") // generate classes for explicitly referenced source files
.withEach(main.tweaks().getOrDefault("javac", List.of()))
.with("-d", classes)
.withEach(javaSourceFiles)
.build();
}
/**
* @param module the name of module to create an archive for
* @return the {@code jar} call to archive all assets for the given module
*/
public ToolCall computeMainJarCall(String module) {
var main = project.main();
var archive = computeMainJarFileName(module);
var jar =
Command.builder("jar")
.with("--create")
.with("--file", main.workspace("modules", archive))
.withEach(main.tweaks().getOrDefault("jar", List.of()))
.withEach(main.tweaks().getOrDefault("jar(" + module + ')', List.of()))
.with("-C", main.classes().resolve(module), ".");
for (var release : main.supplements().get(module).releases()) {
var classes = main.workspace("classes-mr", release + "/" + module);
jar.with("--release", release).with("-C", classes, ".");
}
return jar.build();
}
/**
* @param module the name of the module
* @return the name of the JAR file for the given module
*/
public String computeMainJarFileName(String module) {
var slug = project.main().jarslug();
var builder = new StringBuilder(module);
if (!slug.isEmpty()) builder.append('@').append(slug);
return builder.append(".jar").toString();
}
/** @return the javadoc call generating the API documentation for all main modules */
public ToolCall computeMainDocumentationJavadocCall() {
var main = project.main();
var api = main.documentation("api");
return Command.builder("javadoc")
.with("--module", String.join(",", main.modules()))
.with("--module-source-path", String.join(File.pathSeparator, main.moduleSourcePaths()))
.with("--module-path", String.join(File.pathSeparator, main.modulePaths()))
.withEach(main.tweaks().getOrDefault("javadoc", List.of()))
.with("-d", api)
.build();
}
/** @return the jar call generating the API documentation archive */
public ToolCall computeMainDocumentationJarCall() {
var main = project.main();
var api = main.documentation("api");
var file = project.name() + "-api-" + project.version() + ".zip";
return Command.builder("jar")
.with("--create")
.with("--file", api.getParent().resolve(file))
.with("--no-manifest")
.with("-C", api, ".")
.build();
}
/** @return the jllink call */
public ToolCall computeMainJLinkCall() {
var main = project.main();
var test = project.test();
return Command.builder("jlink")
.with("--add-modules", String.join(",", main.modules()))
.with("--module-path", String.join(File.pathSeparator, test.modulePaths()))
.withEach(main.tweaks().getOrDefault("jlink", List.of()))
.with("--output", main.workspace("image"))
.build();
}
/** @return the jpackage call */
public ToolCall computeMainJPackageCall() {
return Command.builder("jpackage").build();
}
/** @return the {@code javac} call to compile all modules of the test space. */
public ToolCall computeTestJavacCall() {
var test = project.test();
return Command.builder("javac")
.with("--module", String.join(",", test.modules()))
.with("--module-source-path", String.join(File.pathSeparator, test.moduleSourcePaths()))
.with("--module-path", String.join(File.pathSeparator, test.modulePaths()))
.withEach(test.tweaks().getOrDefault("javac", List.of()))
.with("-d", test.classes())
.build();
}
/**
* @param module the name of the module to create an archive for
* @return the {@code jar} call to archive all assets for the given module
*/
public ToolCall computeTestJarCall(String module) {
var test = project.test();
var archive = module + "@" + project.version() + "+test.jar";
return Command.builder("jar")
.with("--create")
.with("--file", test.workspace("modules-test", archive))
.withEach(test.tweaks().getOrDefault("jar", List.of()))
.withEach(test.tweaks().getOrDefault("jar(" + module + ')', List.of()))
.with("-C", test.classes().resolve(module), ".")
.build();
}
/**
* @param module the name of the module to scan for tests
* @return the {@code junit} call to launch the JUnit Platform for
*/
public ToolCall computeTestJUnitCall(String module) {
var test = project.test();
return Command.builder("junit")
.with("--select-module", module)
.with("--reports-dir", test.workspace("reports", "junit-test", module))
.withEach(test.tweaks().getOrDefault("junit", List.of()))
.withEach(test.tweaks().getOrDefault("junit(" + module + ')', List.of()))
.build();
}
}
|
package com.williamfiset.algorithms.graphtheory.networkflow;
import static java.lang.Math.min;
import static java.lang.Math.max;
import java.util.*;
public class MinCostMaxFlowJohnsons extends NetworkFlowSolverBase {
/**
* Creates an instance of a flow network solver. Use the
* {@link NetworkFlowSolverBase#addEdge} method to add edges to the graph.
*
* @param n - The number of nodes in the graph including source and sink nodes.
* @param s - The index of the source node, 0 <= s < n
* @param t - The index of the sink node, 0 <= t < n, t != s
*/
public MinCostMaxFlowJohnsons(int n, int s, int t) {
super(n, s, t);
}
private void init() {
long[] dist = new long[n];
Arrays.fill(dist, INF);
dist[s] = 0;
// Run Bellman-Ford algorithm to get the optimal distance to each node, O(VE)
for (int i = 0; i < n-1; i++)
for(List<Edge> edges : graph)
for (Edge edge : edges)
if (edge.remainingCapacity() > 0 && dist[edge.from] + edge.cost < dist[edge.to])
dist[edge.to] = dist[edge.from] + edge.cost;
adjustEdgeCosts(dist);
}
// Adjust edge costs to be non-negative for Dijkstra's algorithm, O(E)
private void adjustEdgeCosts(long[] dist) {
for (int from = 0; from < n; from++) {
for (Edge edge : graph[from]) {
if (edge.remainingCapacity() > 0) {
edge.cost += dist[from] - dist[edge.to];
} else {
edge.cost = 0;
}
}
}
}
@Override
public void solve() {
init();
// Sum up the bottlenecks on each augmenting path to find the max flow and min cost.
List<Edge> path;
while((path = getAugmentingPath()).size() != 0) {
// Find bottle neck edge value along path.
long bottleNeck = Long.MAX_VALUE;
for(Edge edge : path)
bottleNeck = min(bottleNeck, edge.remainingCapacity());
// Retrace path while augmenting the flow
for(Edge edge : path) {
edge.augment(bottleNeck);
minCost += bottleNeck * edge.originalCost;
}
maxFlow += bottleNeck;
}
}
// Finds an augmenting path from the source node to the sink using Johnson's
// shortest path algorithm. First, Bellman-Ford was ran to get the shortest
// path from the source to every node, and then the graph was cost adjusted
// to remove negative edge weights so that Dijkstra's can be used in
// subsequent runs for improved time complexity.
private List<Edge> getAugmentingPath() {
class Node implements Comparable<Node> {
int id;
long value;
public Node(int id, long value) {
this.id = id;
this.value = value;
}
@Override
public int compareTo(Node other) {
return (int)(value - other.value);
}
}
long[] dist = new long[n];
Arrays.fill(dist, INF);
dist[s] = 0;
markAllNodesAsUnvisited();
Edge[] prev = new Edge[n];
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.offer(new Node(s, 0));
// Run Dijkstra's to find augmenting path.
while(!pq.isEmpty()) {
Node node = pq.poll();
visit(node.id);
if (dist[node.id] < node.value) continue;
List<Edge> edges = graph[node.id];
for(int i = 0; i < edges.size(); i++) {
Edge edge = edges.get(i);
if (visited(edge.to)) continue;
long newDist = dist[edge.from] + edge.cost;
if (edge.remainingCapacity() > 0 && newDist < dist[edge.to]) {
prev[edge.to] = edge;
dist[edge.to] = newDist;
pq.offer(new Node(edge.to, dist[edge.to]));
}
}
}
LinkedList<Edge> path = new LinkedList<>();
if (dist[t] == INF) return path;
adjustEdgeCosts(dist);
for(Edge edge = prev[t]; edge != null; edge = prev[edge.from])
path.addFirst(edge);
return path;
}
}
|
package com.ptsmods.morecommands.mixin.client;
import com.mojang.blaze3d.platform.ClipboardManager;
import com.ptsmods.morecommands.MoreCommands;
import com.ptsmods.morecommands.MoreCommandsClient;
import com.ptsmods.morecommands.api.IMoreCommands;
import com.ptsmods.morecommands.api.MessageHistory;
import com.ptsmods.morecommands.api.ReflectionHelper;
import com.ptsmods.morecommands.api.addons.ChatComponentAddon;
import com.ptsmods.morecommands.api.addons.GuiMessageAddon;
import com.ptsmods.morecommands.api.util.compat.client.ClientCompat;
import com.ptsmods.morecommands.clientoption.ClientOptions;
import com.ptsmods.morecommands.commands.client.SearchCommand;
import com.ptsmods.morecommands.mixin.client.accessor.MixinChatComponentAccessor;
import net.minecraft.client.GuiMessage;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.ChatComponent;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screens.ChatScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.player.ChatVisiblity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.List;
@Mixin(ChatScreen.class)
public class MixinChatScreen {
private static final ClipboardManager clipboard = new ClipboardManager();
@Unique private static boolean colourPickerOpen = false;
@Shadow protected EditBox input;
@Inject(at = @At("TAIL"), method = "init()V")
private void init(CallbackInfo cbi) {
Screen thiz = ReflectionHelper.cast(this);
MoreCommandsClient.addColourPicker(thiz, thiz.width - 117, 5, false, colourPickerOpen, input::insertText, b -> colourPickerOpen = b);
}
@Inject(at = @At("TAIL"), method = "mouseClicked(DDI)Z", cancellable = true)
public void mouseClicked(double mouseX, double mouseY, int button, CallbackInfoReturnable<Boolean> cbi) {
boolean b = cbi.getReturnValueZ();
if (b) return;
ChatComponent chatHud = Minecraft.getInstance().gui.getChat();
GuiMessageAddon line = getLine(chatHud, mouseX, mouseY);
if (line == null) return;
if (button == 0 && ClientOptions.Chat.chatMsgCopy.getValue()) {
// Copies a message's content when you click on it in the chat.
Component t = line.mc$getRichContent();
if (t != null) {
String s = IMoreCommands.get().textToString(t, null, Screen.hasControlDown());
clipboard.setClipboard(Minecraft.getInstance().getWindow().getWindow(), Screen.hasControlDown() ? s.replaceAll("\u00a7", "&") : MoreCommands.stripFormattings(s));
Minecraft.getInstance().getSoundManager().play(ClientCompat.get().newCopySound());
b = true;
}
} else if (button == 1 && ClientOptions.Chat.chatMsgRemove.getValue()) {
MessageHistory.removeMessage(line.mc$getId());
((ChatComponentAddon) chatHud).mc$removeById(line.mc$getId());
b = true;
}
cbi.setReturnValue(b);
}
@Unique
public GuiMessageAddon getLine(ChatComponent hud, double x, double y) {
Minecraft client = Minecraft.getInstance();
List<GuiMessage> visibleMessages = ((MixinChatComponentAccessor) hud).getTrimmedMessages();
List<GuiMessage> messages = ((MixinChatComponentAccessor) hud).getAllMessages();
int scrolledLines = ((MixinChatComponentAccessor) hud).getChatScrollbarPos();
if (visibleMessages == null || !(client.screen instanceof ChatScreen) || client.options.hideGui ||
ClientCompat.get().getChatVisibility(client.options) == ChatVisiblity.HIDDEN) return null;
double d = x - 2.0D;
double e = (double) client.getWindow().getGuiScaledHeight() - y - 40.0D;
d = Mth.floor(d / hud.getScale());
e = Mth.floor(e / (hud.getScale() * (ClientCompat.get().getChatLineSpacing(client.options) + 1.0D)));
if (!(d >= 0.0D) || !(e >= 0.0D)) return null;
int i = Math.min(hud.getLinesPerPage(), visibleMessages.size());
if (!(d <= (double) Mth.floor((double) hud.getWidth() / hud.getScale())) ||
!(e < (double) (9 * i + i))) return null;
int j = (int)(e / 9.0D + (double) scrolledLines);
if (j < 0 || j >= visibleMessages.size()) return null;
GuiMessage chatHudLine = visibleMessages.get(j);
for (GuiMessage line : messages)
if (((GuiMessageAddon) (Object) line).mc$getId() == ((GuiMessageAddon) (Object) chatHudLine).mc$getId() )
return (GuiMessageAddon) (Object) line;
return null;
}
@Redirect(at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screens/ChatScreen;handleComponentClicked(Lnet/minecraft/network/chat/Style;)Z"), method = "mouseClicked(DDI)Z")
private boolean mouseClicked_handleTextClick(ChatScreen thiz, Style style, double mouseX, double mouseY, int button) {
if (style != null && style.getClickEvent() != null && style.getClickEvent().getAction() == SearchCommand.SCROLL_ACTION) {
ChatComponent chat = Minecraft.getInstance().gui.getChat();
int scrolled = ((MixinChatComponentAccessor) chat).getChatScrollbarPos();
int id = Integer.parseInt(style.getClickEvent().getValue());
List<GuiMessage> messages = ((MixinChatComponentAccessor) chat).getTrimmedMessages();
int index = -1;
for (int i = 0; i < messages.size(); i++)
if (((GuiMessageAddon) (Object) messages.get(i)).mc$getId() == id) {
index = i;
break;
}
if (index >= 0) chat.scrollChat(index - scrolled - chat.getLinesPerPage() + (MessageHistory.contains(id) ?
Minecraft.getInstance().font.getSplitter().splitLines(MessageHistory.getMessage(id).mc$getRichContent(), chat.getWidth(), Style.EMPTY).size() : 0));
return true;
}
return thiz.handleComponentClicked(style);
}
}
|
package com.yahoo.searchdefinition;
import com.yahoo.document.ArrayDataType;
import com.yahoo.document.CollectionDataType;
import com.yahoo.document.DataType;
import com.yahoo.document.DocumentType;
import com.yahoo.document.Field;
import com.yahoo.document.MapDataType;
import com.yahoo.document.ReferenceDataType;
import com.yahoo.document.StructDataType;
import com.yahoo.document.StructuredDataType;
import com.yahoo.document.TemporaryStructuredDataType;
import com.yahoo.document.WeightedSetDataType;
import com.yahoo.document.annotation.AnnotationReferenceDataType;
import com.yahoo.document.annotation.AnnotationType;
import com.yahoo.documentmodel.DataTypeCollection;
import com.yahoo.documentmodel.NewDocumentType;
import com.yahoo.documentmodel.VespaDocumentType;
import com.yahoo.searchdefinition.document.Attribute;
import com.yahoo.searchdefinition.document.SDDocumentType;
import com.yahoo.searchdefinition.document.SDField;
import com.yahoo.searchdefinition.document.TemporaryImportedFields;
import com.yahoo.searchdefinition.document.annotation.SDAnnotationType;
import com.yahoo.searchdefinition.document.annotation.TemporaryAnnotationReferenceDataType;
import com.yahoo.vespa.documentmodel.DocumentModel;
import com.yahoo.vespa.documentmodel.FieldView;
import com.yahoo.vespa.documentmodel.SearchDef;
import com.yahoo.vespa.documentmodel.SearchField;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author baldersheim
*/
public class DocumentModelBuilder {
private final DocumentModel model;
public DocumentModelBuilder() {
this.model = new DocumentModel();
this.model.getDocumentManager().add(VespaDocumentType.INSTANCE);
}
public DocumentModel build(Collection<Schema> schemaList) {
List<SDDocumentType> docList = new LinkedList<>();
for (Schema schema : schemaList) {
docList.add(schema.getDocument());
}
docList = sortDocumentTypes(docList);
addDocumentTypes(docList);
for (Collection<Schema> toAdd = tryAdd(schemaList);
! toAdd.isEmpty() && (toAdd.size() < schemaList.size());
toAdd = tryAdd(schemaList)) {
schemaList = toAdd;
}
return model;
}
private List<SDDocumentType> sortDocumentTypes(List<SDDocumentType> docList) {
Set<String> doneNames = new HashSet<>();
doneNames.add(SDDocumentType.VESPA_DOCUMENT.getName());
List<SDDocumentType> doneList = new LinkedList<>();
List<SDDocumentType> prevList = null;
List<SDDocumentType> nextList = docList;
while (prevList == null || nextList.size() < prevList.size()) {
prevList = nextList;
nextList = new LinkedList<>();
for (SDDocumentType doc : prevList) {
boolean isDone = true;
for (SDDocumentType inherited : doc.getInheritedTypes()) {
if (!doneNames.contains(inherited.getName())) {
isDone = false;
break;
}
}
if (isDone) {
doneNames.add(doc.getName());
doneList.add(doc);
} else {
nextList.add(doc);
}
}
}
if (!nextList.isEmpty()) {
throw new IllegalArgumentException("Could not resolve inheritance of document types " +
toString(prevList) + ".");
}
return doneList;
}
private static String toString(List<SDDocumentType> lst) {
StringBuilder out = new StringBuilder();
for (int i = 0, len = lst.size(); i < len; ++i) {
out.append("'").append(lst.get(i).getName()).append("'");
if (i < len - 2) {
out.append(", ");
} else if (i < len - 1) {
out.append(" and ");
}
}
return out.toString();
}
private Collection<Schema> tryAdd(Collection<Schema> schemaList) {
Collection<Schema> left = new ArrayList<>();
for (Schema schema : schemaList) {
try {
addToModel(schema);
} catch (RetryLaterException e) {
left.add(schema);
}
}
return left;
}
private void addToModel(Schema schema) {
// Then we add the search specific stuff
SearchDef searchDef = new SearchDef(schema.getName());
addSearchFields(schema.extraFieldList(), searchDef);
for (Field f : schema.getDocument().fieldSet()) {
addSearchField((SDField) f, searchDef);
}
for (SDField field : schema.allConcreteFields()) {
for (Attribute attribute : field.getAttributes().values()) {
if ( ! searchDef.getFields().containsKey(attribute.getName())) {
searchDef.add(new SearchField(new Field(attribute.getName(), field), !field.getIndices().isEmpty(), true));
}
}
}
for (Field f : schema.getDocument().fieldSet()) {
addAlias((SDField) f, searchDef);
}
model.getSearchManager().add(searchDef);
}
private static void addSearchFields(Collection<SDField> fields, SearchDef searchDef) {
for (SDField field : fields) {
addSearchField(field, searchDef);
}
}
private static void addSearchField(SDField field, SearchDef searchDef) {
SearchField searchField =
new SearchField(field,
field.getIndices().containsKey(field.getName()) && field.getIndices().get(field.getName()).getType().equals(Index.Type.VESPA),
field.getAttributes().containsKey(field.getName()));
searchDef.add(searchField);
// Add field to views
addToView(field.getIndices().keySet(), searchField, searchDef);
}
private static void addAlias(SDField field, SearchDef searchDef) {
for (Map.Entry<String, String> entry : field.getAliasToName().entrySet()) {
searchDef.addAlias(entry.getKey(), entry.getValue());
}
}
private static void addToView(Collection<String> views, Field field, SearchDef searchDef) {
for (String viewName : views) {
addToView(viewName, field, searchDef);
}
}
private static void addToView(String viewName, Field field, SearchDef searchDef) {
if (searchDef.getViews().containsKey(viewName)) {
searchDef.getViews().get(viewName).add(field);
} else {
if (!searchDef.getFields().containsKey(viewName)) {
FieldView view = new FieldView(viewName);
view.add(field);
searchDef.add(view);
}
}
}
// This is how you make a "Pair" class in java....
private static class TypeReplacement extends AbstractMap.SimpleEntry<DataType,DataType> {
DataType oldType() { return getKey(); }
DataType newType() { return getValue(); }
public TypeReplacement(DataType oldType, DataType newType) {
super(oldType, newType);
}
}
private static String descT(DataType type) {
if (type == null) { return "<null>"; }
return "'" + type.getName() + "' [" + type.getId() + "] {"+type.getClass() + "}";
}
private void addDocumentTypes(List<SDDocumentType> docList) {
LinkedList<NewDocumentType> lst = new LinkedList<>();
for (SDDocumentType doc : docList) {
lst.add(convert(doc));
model.getDocumentManager().add(lst.getLast());
}
Set<TypeReplacement> replacements = new HashSet<>();
for(NewDocumentType doc : lst) {
resolveTemporaries(doc.getAllTypes(), lst, replacements);
}
for(NewDocumentType doc : lst) {
for (var entry : replacements) {
var old = entry.oldType();
if (doc.getDataType(old.getId()) == old) {
doc.replace(entry.newType());
}
}
}
}
private static void resolveTemporaries(DataTypeCollection dtc,
Collection<NewDocumentType> docs,
Set<TypeReplacement> replacements)
{
for (DataType type : dtc.getTypes()) {
resolveTemporariesRecurse(type, dtc, docs, replacements);
}
}
@SuppressWarnings("deprecation")
private static DataType resolveTemporariesRecurse(DataType type, DataTypeCollection repo,
Collection<NewDocumentType> docs,
Set<TypeReplacement> replacements) {
DataType original = type;
if (type instanceof TemporaryStructuredDataType) {
DataType other = repo.getDataType(type.getId());
if (other == null || other == type) {
other = getDocumentType(docs, type.getId());
}
if (other != null) {
type = other;
}
} else if (type instanceof DocumentType) {
DataType other = getDocumentType(docs, type.getId());
if (other != null) {
type = other;
} else if (! type.getName().equals("document")) {
throw new IllegalArgumentException
("Can not handle nested document definitions. Undefined document type: " + type.toString());
}
} else if (type instanceof NewDocumentType) {
DataType other = getDocumentType(docs, type.getId());
if (other != null) {
type = other;
}
} else if (type instanceof StructDataType) {
StructDataType dt = (StructDataType) type;
for (com.yahoo.document.Field field : dt.getFields()) {
var ft = field.getDataType();
if (ft != type) {
var newft = resolveTemporariesRecurse(ft, repo, docs, replacements);
if (ft != newft) {
// XXX deprecated:
field.setDataType(newft);
}
}
}
}
else if (type instanceof MapDataType) {
MapDataType t = (MapDataType) type;
var kt = resolveTemporariesRecurse(t.getKeyType(), repo, docs, replacements);
var vt = resolveTemporariesRecurse(t.getValueType(), repo, docs, replacements);
type = new MapDataType(kt, vt, t.getId());
}
else if (type instanceof ArrayDataType) {
ArrayDataType t = (ArrayDataType) type;
var nt = resolveTemporariesRecurse(t.getNestedType(), repo, docs, replacements);
type = new ArrayDataType(nt, t.getId());
}
else if (type instanceof WeightedSetDataType) {
WeightedSetDataType t = (WeightedSetDataType) type;
var nt = resolveTemporariesRecurse(t.getNestedType(), repo, docs, replacements);
boolean c = t.createIfNonExistent();
boolean r = t.removeIfZero();
type = new WeightedSetDataType(nt, c, r, t.getId());
}
else if (type instanceof ReferenceDataType) {
ReferenceDataType t = (ReferenceDataType) type;
if (t.getTargetType() instanceof TemporaryStructuredDataType) {
DataType targetType = resolveTemporariesRecurse(t.getTargetType(), repo, docs, replacements);
t.setTargetType((StructuredDataType) targetType);
}
}
if (type != original) {
replacements.add(new TypeReplacement(original, type));
}
return type;
}
private static NewDocumentType getDocumentType(Collection<NewDocumentType> docs, int id) {
for (NewDocumentType doc : docs) {
if (doc.getId() == id) {
return doc;
}
}
return null;
}
private static boolean anyParentsHavePayLoad(SDAnnotationType sa, SDDocumentType sdoc) {
if (sa.getInherits() != null) {
AnnotationType tmp = sdoc.findAnnotation(sa.getInherits());
SDAnnotationType inherited = (SDAnnotationType) tmp;
return ((inherited.getSdDocType() != null) || anyParentsHavePayLoad(inherited, sdoc));
}
return false;
}
private NewDocumentType convert(SDDocumentType sdoc) {
NewDocumentType dt = new NewDocumentType(new NewDocumentType.Name(sdoc.getName()),
sdoc.getDocumentType().contentStruct(),
sdoc.getFieldSets(),
convertDocumentReferencesToNames(sdoc.getDocumentReferences()),
convertTemporaryImportedFieldsToNames(sdoc.getTemporaryImportedFields()));
for (SDDocumentType n : sdoc.getInheritedTypes()) {
NewDocumentType.Name name = new NewDocumentType.Name(n.getName());
NewDocumentType inherited = model.getDocumentManager().getDocumentType(name);
if (inherited != null) {
dt.inherit(inherited);
}
}
var extractor = new TypeExtractor(dt);
extractor.extract(sdoc);
return dt;
}
static class TypeExtractor {
private final NewDocumentType targetDt;
Map<AnnotationType, String> annotationInheritance = new HashMap<>();
Map<StructDataType, String> structInheritance = new HashMap<>();
private final Map<Object, Object> inProgress = new IdentityHashMap<>();
TypeExtractor(NewDocumentType target) {
this.targetDt = target;
}
void extract(SDDocumentType sdoc) {
for (SDDocumentType type : sdoc.getTypes()) {
if (type.isStruct()) {
handleStruct(type);
} else {
throw new IllegalArgumentException("Data type '" + type.getName() + "' is not a struct => tostring='" + type.toString() + "'.");
}
}
for (SDDocumentType type : sdoc.getTypes()) {
for (SDDocumentType proxy : type.getInheritedTypes()) {
var inherited = (StructDataType) targetDt.getDataTypeRecursive(proxy.getName());
var converted = (StructDataType) targetDt.getDataType(type.getName());
if (! converted.inherits(inherited)) {
converted.inherit(inherited);
}
}
}
for (AnnotationType annotation : sdoc.getAnnotations().values()) {
targetDt.add(annotation);
}
for (AnnotationType annotation : sdoc.getAnnotations().values()) {
SDAnnotationType sa = (SDAnnotationType) annotation;
if (annotation.getInheritedTypes().isEmpty() && (sa.getInherits() != null) ) {
annotationInheritance.put(annotation, sa.getInherits());
}
if (annotation.getDataType() == null) {
if (sa.getSdDocType() != null) {
StructDataType s = handleStruct(sa.getSdDocType());
annotation.setDataType(s);
if ((sa.getInherits() != null)) {
structInheritance.put(s, "annotation."+sa.getInherits());
}
} else if (sa.getInherits() != null) {
StructDataType s = new StructDataType("annotation."+annotation.getName());
if (anyParentsHavePayLoad(sa, sdoc)) {
annotation.setDataType(s);
addType(s);
}
structInheritance.put(s, "annotation."+sa.getInherits());
}
}
}
for (Map.Entry<AnnotationType, String> e : annotationInheritance.entrySet()) {
e.getKey().inherit(targetDt.getAnnotationType(e.getValue()));
}
for (Map.Entry<StructDataType, String> e : structInheritance.entrySet()) {
StructDataType s = (StructDataType)targetDt.getDataType(e.getValue());
if (s != null) {
e.getKey().inherit(s);
}
}
handleStruct(sdoc.getDocumentType().contentStruct());
extractDataTypesFromFields(sdoc.fieldSet());
}
private void extractDataTypesFromFields(Collection<Field> fields) {
for (Field f : fields) {
DataType type = f.getDataType();
if (testAddType(type)) {
extractNestedTypes(type);
addType(type);
}
}
}
private void extractNestedTypes(DataType type) {
if (inProgress.containsKey(type)) {
return;
}
inProgress.put(type, this);
if (type instanceof StructDataType) {
StructDataType tmp = (StructDataType) type;
extractDataTypesFromFields(tmp.getFieldsThisTypeOnly());
} else if (type instanceof CollectionDataType) {
CollectionDataType tmp = (CollectionDataType) type;
extractNestedTypes(tmp.getNestedType());
addType(tmp.getNestedType());
} else if (type instanceof MapDataType) {
MapDataType tmp = (MapDataType) type;
extractNestedTypes(tmp.getKeyType());
extractNestedTypes(tmp.getValueType());
addType(tmp.getKeyType());
addType(tmp.getValueType());
} else if (type instanceof TemporaryAnnotationReferenceDataType) {
throw new IllegalArgumentException(type.toString());
}
}
private boolean testAddType(DataType type) { return internalAddType(type, true); }
private boolean addType(DataType type) { return internalAddType(type, false); }
private boolean internalAddType(DataType type, boolean dryRun) {
DataType oldType = targetDt.getDataTypeRecursive(type.getId());
if (oldType == null) {
if ( ! dryRun) {
targetDt.add(type);
}
return true;
} else if ((type instanceof StructDataType) && (oldType instanceof StructDataType)) {
StructDataType s = (StructDataType) type;
StructDataType os = (StructDataType) oldType;
if ((os.getFieldCount() == 0) && (s.getFieldCount() > os.getFieldCount())) {
if ( ! dryRun) {
targetDt.replace(type);
}
return true;
}
}
return false;
}
@SuppressWarnings("deprecation")
private void specialHandleAnnotationReference(Field field) {
DataType fieldType = specialHandleAnnotationReferenceRecurse(field.getName(), field.getDataType());
if (fieldType == null) {
return;
}
field.setDataType(fieldType); // XXX deprecated
}
private DataType specialHandleAnnotationReferenceRecurse(String fieldName,
DataType dataType) {
if (dataType instanceof TemporaryAnnotationReferenceDataType) {
TemporaryAnnotationReferenceDataType refType = (TemporaryAnnotationReferenceDataType)dataType;
if (refType.getId() != 0) {
return null;
}
AnnotationType target = targetDt.getAnnotationType(refType.getTarget());
if (target == null) {
throw new RetryLaterException("Annotation '" + refType.getTarget() + "' in reference '" + fieldName +
"' does not exist.");
}
dataType = new AnnotationReferenceDataType(target);
addType(dataType);
return dataType;
}
else if (dataType instanceof MapDataType) {
MapDataType t = (MapDataType)dataType;
DataType valueType = specialHandleAnnotationReferenceRecurse(fieldName, t.getValueType());
if (valueType == null) {
return null;
}
var mapType = new MapDataType(t.getKeyType(), valueType, t.getId());
addType(mapType);
return mapType;
}
else if (dataType instanceof ArrayDataType) {
ArrayDataType t = (ArrayDataType) dataType;
DataType nestedType = specialHandleAnnotationReferenceRecurse(fieldName, t.getNestedType());
if (nestedType == null) {
return null;
}
var lstType = new ArrayDataType(nestedType, t.getId());
addType(lstType);
return lstType;
}
else if (dataType instanceof WeightedSetDataType) {
WeightedSetDataType t = (WeightedSetDataType) dataType;
DataType nestedType = specialHandleAnnotationReferenceRecurse(fieldName, t.getNestedType());
if (nestedType == null) {
return null;
}
boolean c = t.createIfNonExistent();
boolean r = t.removeIfZero();
var lstType = new WeightedSetDataType(nestedType, c, r, t.getId());
addType(lstType);
return lstType;
}
return null;
}
private StructDataType handleStruct(SDDocumentType type) {
StructDataType s = new StructDataType(type.getName());
for (Field f : type.getDocumentType().contentStruct().getFieldsThisTypeOnly()) {
specialHandleAnnotationReference(f);
s.addField(f);
}
for (StructDataType inherited : type.getDocumentType().contentStruct().getInheritedTypes()) {
s.inherit(inherited);
}
extractNestedTypes(s);
addType(s);
return s;
}
private StructDataType handleStruct(StructDataType s) {
for (Field f : s.getFieldsThisTypeOnly()) {
specialHandleAnnotationReference(f);
}
extractNestedTypes(s);
addType(s);
return s;
}
}
private static Set<NewDocumentType.Name> convertDocumentReferencesToNames(Optional<DocumentReferences> documentReferences) {
if (!documentReferences.isPresent()) {
return Set.of();
}
return documentReferences.get().referenceMap().values().stream()
.map(documentReference -> documentReference.targetSearch().getDocument())
.map(documentType -> new NewDocumentType.Name(documentType.getName()))
.collect(Collectors.toCollection(() -> new LinkedHashSet<>()));
}
private static Set<String> convertTemporaryImportedFieldsToNames(TemporaryImportedFields importedFields) {
if (importedFields == null) {
return Set.of();
}
return Collections.unmodifiableSet(importedFields.fields().keySet());
}
public static class RetryLaterException extends IllegalArgumentException {
public RetryLaterException(String message) {
super(message);
}
}
}
|
package com.yahoo.search.dispatch;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.yahoo.search.dispatch.searchcluster.Group;
import com.yahoo.search.dispatch.searchcluster.Node;
import com.yahoo.search.dispatch.searchcluster.SearchCluster;
import com.yahoo.vespa.config.search.DispatchConfig;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* @author ollivir
*/
public class MockSearchCluster extends SearchCluster {
private final int numGroups;
private final int numNodesPerGroup;
private final ImmutableList<Group> orderedGroups;
private final ImmutableMap<Integer, Group> groups;
public MockSearchCluster(String clusterId, int groups, int nodesPerGroup) {
this(clusterId, createDispatchConfig(), groups, nodesPerGroup);
}
public MockSearchCluster(String clusterId, DispatchConfig dispatchConfig, int groups, int nodesPerGroup) {
super(clusterId, dispatchConfig, null, null);
ImmutableList.Builder<Group> orderedGroupBuilder = ImmutableList.builder();
ImmutableMap.Builder<Integer, Group> groupBuilder = ImmutableMap.builder();
ImmutableMultimap.Builder<String, Node> hostBuilder = ImmutableMultimap.builder();
int distributionKey = 0;
for (int group = 0; group < groups; group++) {
List<Node> nodes = new ArrayList<>();
for (int node = 0; node < nodesPerGroup; node++) {
Node n = new Node(distributionKey, "host" + distributionKey, group);
nodes.add(n);
hostBuilder.put(n.hostname(), n);
distributionKey++;
}
Group g = new Group(group, nodes);
groupBuilder.put(group, g);
orderedGroupBuilder.add(g);
}
this.orderedGroups = orderedGroupBuilder.build();
this.groups = groupBuilder.build();
this.numGroups = groups;
this.numNodesPerGroup = nodesPerGroup;
}
@Override
public ImmutableList<Group> orderedGroups() {
return orderedGroups;
}
@Override
public int size() {
return numGroups * numNodesPerGroup;
}
@Override
public ImmutableMap<Integer, Group> groups() {
return groups;
}
@Override
public boolean allGroupsHaveSize1() { return numNodesPerGroup == 1;}
@Override
public int groupsWithSufficientCoverage() {
return numGroups;
}
@Override
public Optional<Group> group(int n) {
if (n < numGroups) {
return Optional.of(groups.get(n));
} else {
return Optional.empty();
}
}
@Override
public Optional<Node> localCorpusDispatchTarget() {
return Optional.empty();
}
@Override
public void working(Node node) {
node.setWorking(true);
}
@Override
public void failed(Node node) {
node.setWorking(false);
}
public static DispatchConfig createDispatchConfig(Node... nodes) {
return createDispatchConfig(100.0, nodes);
}
public static DispatchConfig createDispatchConfig(List<Node> nodes) {
return createDispatchConfig(100.0, nodes);
}
public static DispatchConfig createDispatchConfig(double minSearchCoverage, Node... nodes) {
return createDispatchConfig(minSearchCoverage, Arrays.asList(nodes));
}
public static DispatchConfig createDispatchConfig(double minSearchCoverage, List<Node> nodes) {
DispatchConfig.Builder builder = new DispatchConfig.Builder();
builder.minActivedocsPercentage(88.0);
builder.minGroupCoverage(99.0);
builder.minSearchCoverage(minSearchCoverage);
builder.distributionPolicy(DispatchConfig.DistributionPolicy.Enum.ROUNDROBIN)
.mergeGroupingResultInSearchInvokerEnabled(true);
if (minSearchCoverage < 100.0) {
builder.minWaitAfterCoverageFactor(0);
builder.maxWaitAfterCoverageFactor(0.5);
}
int port = 10000;
for (Node n : nodes) {
builder.node(new DispatchConfig.Node.Builder().key(n.key()).host(n.hostname()).port(port++).group(n.group()));
}
return new DispatchConfig(builder);
}
}
|
package org.kuali.rice.core.api.uif;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
import org.kuali.rice.core.api.mo.ModelBuilder;
import org.w3c.dom.Element;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @see AttributeField for more info.
*/
@XmlRootElement(name = RemotableAttributeField.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = RemotableAttributeField.Constants.TYPE_NAME, propOrder = {
RemotableAttributeField.Elements.NAME,
RemotableAttributeField.Elements.DATA_TYPE,
RemotableAttributeField.Elements.SHORT_LABEL,
RemotableAttributeField.Elements.LONG_LABEL,
RemotableAttributeField.Elements.HELP_SUMMARY,
RemotableAttributeField.Elements.HELP_CONSTRAINT,
RemotableAttributeField.Elements.HELP_DESCRIPTION,
RemotableAttributeField.Elements.FORCE_UPPERCASE,
RemotableAttributeField.Elements.MIN_LENGTH,
RemotableAttributeField.Elements.MAX_LENGTH,
RemotableAttributeField.Elements.MIN_VALUE,
RemotableAttributeField.Elements.MAX_VALUE,
RemotableAttributeField.Elements.REGEX_CONSTRAINT,
RemotableAttributeField.Elements.REGEX_CONSTRAINT_MSG,
RemotableAttributeField.Elements.REQUIRED,
RemotableAttributeField.Elements.DEFAULT_VALUES,
RemotableAttributeField.Elements.LOOKUP_CASE_SENSITIVE,
RemotableAttributeField.Elements.ATTRIBUTE_LOOKUP_SETTINGS,
RemotableAttributeField.Elements.CONTROL,
RemotableAttributeField.Elements.WIDGETS,
CoreConstants.CommonElements.FUTURE_ELEMENTS })
public final class RemotableAttributeField extends AbstractDataTransferObject implements AttributeField {
@XmlElement(name = Elements.NAME, required = true)
private final String name;
@XmlJavaTypeAdapter(DataType.Adapter.class)
@XmlElement(name = Elements.DATA_TYPE, required = false)
private final String dataType;
@XmlElement(name = Elements.SHORT_LABEL, required = false)
private final String shortLabel;
@XmlElement(name = Elements.LONG_LABEL, required = false)
private final String longLabel;
@XmlElement(name = Elements.HELP_SUMMARY, required = false)
private final String helpSummary;
@XmlElement(name = Elements.HELP_CONSTRAINT, required = false)
private final String helpConstraint;
@XmlElement(name = Elements.HELP_DESCRIPTION, required = false)
private final String helpDescription;
@XmlElement(name = Elements.FORCE_UPPERCASE, required = false)
private final boolean forceUpperCase;
@XmlElement(name = Elements.MIN_LENGTH, required = false)
private final Integer minLength;
@XmlElement(name = Elements.MAX_LENGTH, required = false)
private final Integer maxLength;
@XmlElement(name = Elements.MIN_VALUE, required = false)
private final Double minValue;
@XmlElement(name = Elements.MAX_VALUE, required = false)
private final Double maxValue;
@XmlElement(name = Elements.REGEX_CONSTRAINT, required = false)
private final String regexConstraint;
@XmlElement(name = Elements.REGEX_CONSTRAINT_MSG, required = false)
private final String regexContraintMsg;
@XmlElement(name = Elements.REQUIRED, required = false)
private final boolean required;
@XmlElementWrapper(name = Elements.DEFAULT_VALUES, required = false)
@XmlElement(name = Elements.DEFAULT_VALUE, required = false)
private final Collection<String> defaultValues;
@XmlElement(name = Elements.LOOKUP_CASE_SENSITIVE, required = false)
private final Boolean lookupCaseSensitive;
@XmlElement(name = Elements.ATTRIBUTE_LOOKUP_SETTINGS, required = false)
private final RemotableAttributeLookupSettings attributeLookupSettings;
@XmlElements(value = {
@XmlElement(name = RemotableCheckboxGroup.Constants.ROOT_ELEMENT_NAME, type = RemotableCheckboxGroup.class, required = false),
@XmlElement(name = RemotableHiddenInput.Constants.ROOT_ELEMENT_NAME, type = RemotableHiddenInput.class, required = false),
@XmlElement(name = RemotablePasswordInput.Constants.ROOT_ELEMENT_NAME, type = RemotablePasswordInput.class, required = false),
@XmlElement(name = RemotableRadioButtonGroup.Constants.ROOT_ELEMENT_NAME, type = RemotableRadioButtonGroup.class, required = false),
@XmlElement(name = RemotableSelect.Constants.ROOT_ELEMENT_NAME, type = RemotableSelect.class, required = false),
@XmlElement(name = RemotableTextarea.Constants.ROOT_ELEMENT_NAME, type = RemotableTextarea.class, required = false),
@XmlElement(name = RemotableTextInput.Constants.ROOT_ELEMENT_NAME, type = RemotableTextInput.class, required = false)
})
private final RemotableAbstractControl control;
@XmlElementWrapper(name = Elements.WIDGETS, required = false)
@XmlElements(value = {
@XmlElement(name = RemotableDatepicker.Constants.ROOT_ELEMENT_NAME, type = RemotableDatepicker.class, required = false),
@XmlElement(name = RemotableQuickFinder.Constants.ROOT_ELEMENT_NAME, type = RemotableQuickFinder.class, required = false),
@XmlElement(name = RemotableTextExpand.Constants.ROOT_ELEMENT_NAME, type = RemotableTextExpand.class, required = false)
})
private final Collection<? extends RemotableAbstractWidget> widgets;
@SuppressWarnings("unused")
@XmlAnyElement
private final Collection<Element> _futureElements = null;
/**
* Should only be invoked by JAXB.
*/
@SuppressWarnings("unused")
private RemotableAttributeField() {
this.name = null;
this.dataType = null;
this.shortLabel = null;
this.longLabel = null;
this.helpSummary = null;
this.helpConstraint = null;
this.helpDescription = null;
this.forceUpperCase = false;
this.minLength = null;
this.maxLength = null;
this.minValue = null;
this.maxValue = null;
this.regexConstraint = null;
this.regexContraintMsg = null;
this.required = false;
this.defaultValues = null;
this.lookupCaseSensitive = null;
this.attributeLookupSettings = null;
this.control = null;
this.widgets = null;
}
private RemotableAttributeField(Builder b) {
this.name = b.name;
if (b.dataType == null) {
this.dataType = null;
} else {
this.dataType = b.dataType.name();
}
this.shortLabel = b.shortLabel;
this.longLabel = b.longLabel;
this.helpSummary = b.helpSummary;
this.helpConstraint = b.helpConstraint;
this.helpDescription = b.helpDescription;
this.forceUpperCase = b.forceUpperCase;
this.minLength = b.minLength;
this.maxLength = b.maxLength;
this.minValue = b.minValue;
this.maxValue = b.maxValue;
this.regexConstraint = b.regexConstraint;
this.regexContraintMsg = b.regexContraintMsg;
this.required = b.required;
if (b.defaultValues == null) {
this.defaultValues = Collections.emptyList();
} else {
List<String> defaultValuesCopy = new ArrayList<String>(b.defaultValues);
this.defaultValues = Collections.unmodifiableList(defaultValuesCopy);
}
this.lookupCaseSensitive = b.lookupCaseSensitive;
if (b.attributeLookupSettings == null) {
this.attributeLookupSettings = null;
} else {
this.attributeLookupSettings = b.attributeLookupSettings.build();
}
if (b.control == null) {
this.control = null;
} else {
this.control = b.control.build();
}
final List<RemotableAbstractWidget> temp = new ArrayList<RemotableAbstractWidget>();
if (b.widgets != null) {
for (RemotableAbstractWidget.Builder attr : b.widgets) {
temp.add(attr.build());
}
}
this.widgets = Collections.unmodifiableList(temp);
}
@Override
public String getName() {
return name;
}
@Override
public DataType getDataType() {
if (dataType == null) {
return null;
}
return DataType.valueOf(dataType);
}
@Override
public String getShortLabel() {
return shortLabel;
}
@Override
public String getLongLabel() {
return longLabel;
}
@Override
public String getHelpSummary() {
return helpSummary;
}
@Override
public String getHelpConstraint() {
return helpConstraint;
}
@Override
public String getHelpDescription() {
return helpDescription;
}
@Override
public boolean isForceUpperCase() {
return forceUpperCase;
}
@Override
public Integer getMinLength() {
return minLength;
}
@Override
public Integer getMaxLength() {
return maxLength;
}
@Override
public Double getMinValue() {
return minValue;
}
@Override
public Double getMaxValue() {
return maxValue;
}
@Override
public String getRegexConstraint() {
return regexConstraint;
}
@Override
public String getRegexContraintMsg() {
return regexContraintMsg;
}
@Override
public boolean isRequired() {
return required;
}
@Override
public Collection<String> getDefaultValues() {
return defaultValues;
}
@Override
public RemotableAbstractControl getControl() {
return control;
}
@Override
public Collection<? extends RemotableAbstractWidget> getWidgets() {
return widgets;
}
@Override
public Boolean isLookupCaseSensitive() {
return lookupCaseSensitive;
}
@Override
public RemotableAttributeLookupSettings getAttributeLookupSettings() {
return attributeLookupSettings;
}
/**
* Utility method to search a collection of attribute fields and returns
* a field for a give attribute name.
*
* @param attributeName the name of the attribute to search for. Cannot be blank or null.
* @param fields cannot be null.
*
* @return the attribute field or null if not found.
*/
public static RemotableAttributeField findAttribute(String attributeName, Collection<RemotableAttributeField> fields) {
if (StringUtils.isBlank(attributeName)) {
throw new IllegalArgumentException("attributeName is blank");
}
if (fields == null) {
throw new IllegalArgumentException("errors is null");
}
for (RemotableAttributeField field : fields) {
if (attributeName.equals(field.getName())) {
return field;
}
}
return null;
}
public static final class Builder implements AttributeField, ModelBuilder {
private String name;
private DataType dataType;
private String shortLabel;
private String longLabel;
private String helpSummary;
private String helpConstraint;
private String helpDescription;
private boolean forceUpperCase;
private Integer minLength;
private Integer maxLength;
private Double minValue;
private Double maxValue;
private String regexConstraint;
private String regexContraintMsg;
private boolean required;
private Collection<String> defaultValues = new ArrayList<String>();
private Boolean lookupCaseSensitive;
private RemotableAttributeLookupSettings.Builder attributeLookupSettings;
private RemotableAbstractControl.Builder control;
private Collection<RemotableAbstractWidget.Builder> widgets = new ArrayList<RemotableAbstractWidget.Builder>();
private Builder(String name) {
setName(name);
}
public static Builder create(String name) {
return new Builder(name);
}
public static Builder create(AttributeField field) {
if (field == null) {
throw new IllegalArgumentException("field was null");
}
Builder b = new Builder(field.getName());
b.setDataType(field.getDataType());
b.setShortLabel(field.getShortLabel());
b.setLongLabel(field.getLongLabel());
b.setHelpSummary(field.getHelpSummary());
b.setHelpConstraint(field.getHelpConstraint());
b.setHelpDescription(field.getHelpDescription());
b.setForceUpperCase(field.isForceUpperCase());
b.setMinLength(field.getMinLength());
b.setMaxLength(field.getMaxLength());
b.setMinValue(field.getMinValue());
b.setMaxValue(field.getMaxValue());
b.setRegexConstraint(field.getRegexConstraint());
b.setRegexContraintMsg(field.getRegexContraintMsg());
b.setRequired(field.isRequired());
b.setDefaultValues(field.getDefaultValues());
b.setLookupCaseSensitive(field.isLookupCaseSensitive());
if (field.getAttributeLookupSettings() != null) {
b.setAttributeLookupSettings(RemotableAttributeLookupSettings.Builder.create(
field.getAttributeLookupSettings()));
}
if (field.getControl() != null) {
b.setControl(ControlCopy.toBuilder(field.getControl()));
}
final List<RemotableAbstractWidget.Builder> temp = new ArrayList<RemotableAbstractWidget.Builder>();
if (field.getWidgets() != null) {
for (Widget w : field.getWidgets()) {
temp.add(WidgetCopy.toBuilder(w));
}
}
b.setWidgets(temp);
return b;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("name is blank");
}
this.name = name;
}
@Override
public DataType getDataType() {
return dataType;
}
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
@Override
public String getShortLabel() {
return shortLabel;
}
public void setShortLabel(String shortLabel) {
this.shortLabel = shortLabel;
}
@Override
public String getLongLabel() {
return longLabel;
}
public void setLongLabel(String longLabel) {
this.longLabel = longLabel;
}
@Override
public String getHelpSummary() {
return helpSummary;
}
public void setHelpSummary(String helpSummary) {
this.helpSummary = helpSummary;
}
@Override
public String getHelpConstraint() {
return helpConstraint;
}
public void setHelpConstraint(String helpConstraint) {
this.helpConstraint = helpConstraint;
}
@Override
public String getHelpDescription() {
return helpDescription;
}
public void setHelpDescription(String helpDescription) {
this.helpDescription = helpDescription;
}
@Override
public boolean isForceUpperCase() {
return forceUpperCase;
}
public void setForceUpperCase(boolean forceUpperCase) {
this.forceUpperCase = forceUpperCase;
}
@Override
public Integer getMinLength() {
return minLength;
}
public void setMinLength(Integer minLength) {
if (minLength != null && minLength < 1) {
throw new IllegalArgumentException("minLength was < 1");
}
this.minLength = minLength;
}
@Override
public Integer getMaxLength() {
return maxLength;
}
public void setMaxLength(Integer maxLength) {
if (maxLength != null && maxLength < 1) {
throw new IllegalArgumentException("maxLength was < 1");
}
this.maxLength = maxLength;
}
@Override
public Double getMinValue() {
return minValue;
}
public void setMinValue(Double minValue) {
this.minValue = minValue;
}
@Override
public Double getMaxValue() {
return maxValue;
}
public void setMaxValue(Double maxValue) {
this.maxValue = maxValue;
}
@Override
public String getRegexConstraint() {
return regexConstraint;
}
public void setRegexConstraint(String regexConstraint) {
this.regexConstraint = regexConstraint;
}
@Override
public String getRegexContraintMsg() {
return regexContraintMsg;
}
public void setRegexContraintMsg(String regexContraintMsg) {
this.regexContraintMsg = regexContraintMsg;
}
@Override
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
@Override
public Collection<String> getDefaultValues() {
return defaultValues;
}
public void setDefaultValues(Collection<String> defaultValues) {
this.defaultValues = defaultValues;
}
@Override
public Boolean isLookupCaseSensitive() {
return lookupCaseSensitive;
}
public void setLookupCaseSensitive(Boolean lookupCaseSensitive) {
this.lookupCaseSensitive = lookupCaseSensitive;
}
@Override
public RemotableAttributeLookupSettings.Builder getAttributeLookupSettings() {
return attributeLookupSettings;
}
public void setAttributeLookupSettings(RemotableAttributeLookupSettings.Builder attributeLookupSettings) {
this.attributeLookupSettings = attributeLookupSettings;
}
@Override
public RemotableAbstractControl.Builder getControl() {
return control;
}
public void setControl(RemotableAbstractControl.Builder control) {
this.control = control;
}
@Override
public Collection<RemotableAbstractWidget.Builder> getWidgets() {
return widgets;
}
public void setWidgets(Collection<RemotableAbstractWidget.Builder> widgets) {
this.widgets = widgets;
}
@Override
public RemotableAttributeField build() {
return new RemotableAttributeField(this);
}
}
/**
* Defines some internal constants used on this class.
*/
static final class Constants {
static final String TYPE_NAME = "AttributeFieldType";
final static String ROOT_ELEMENT_NAME = "attributeField";
}
static final class Elements {
static final String NAME = "name";
static final String DATA_TYPE = "dataType";
static final String SHORT_LABEL = "shortLabel";
static final String LONG_LABEL = "longLabel";
static final String HELP_SUMMARY = "helpSummary";
static final String HELP_CONSTRAINT = "helpConstraint";
static final String HELP_DESCRIPTION = "helpDescription";
static final String FORCE_UPPERCASE = "forceUpperCase";
static final String MIN_LENGTH = "minLength";
static final String MAX_LENGTH = "maxLength";
static final String MIN_VALUE = "minValue";
static final String MAX_VALUE = "maxValue";
static final String REGEX_CONSTRAINT = "regexConstraint";
static final String REGEX_CONSTRAINT_MSG = "regexContraintMsg";
static final String REQUIRED = "required";
static final String DEFAULT_VALUES = "defaultValues";
static final String DEFAULT_VALUE = "defaultValue";
static final String LOOKUP_CASE_SENSITIVE = "lookupCaseSensitive";
static final String ATTRIBUTE_LOOKUP_SETTINGS = "attributeLookupSettings";
static final String CONTROL = "control";
static final String WIDGETS = "widgets";
}
}
|
package imagej.core.plugins.typechange;
import imagej.data.Dataset;
import imagej.ext.menu.MenuService;
import imagej.ext.module.ItemIO;
import imagej.ext.plugin.RunnablePlugin;
import imagej.ext.plugin.Parameter;
import net.imglib2.Cursor;
import net.imglib2.RandomAccess;
import net.imglib2.img.Img;
import net.imglib2.img.ImgFactory;
import net.imglib2.img.ImgPlus;
import net.imglib2.meta.Axes;
import net.imglib2.meta.AxisType;
import net.imglib2.ops.Function;
import net.imglib2.ops.InputIterator;
import net.imglib2.ops.PointSet;
import net.imglib2.ops.function.real.RealArithmeticMeanFunction;
import net.imglib2.ops.function.real.RealImageFunction;
import net.imglib2.ops.input.PointSetInputIteratorFactory;
import net.imglib2.ops.pointset.HyperVolumePointSet;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.real.DoubleType;
/**
* Transforms a {@link Dataset} (and linked {@link ImgPlus}) between types.
* <p>
* Although ImgLib does not do any range clamping of values we will do so here.
* </p>
*
* @author Barry DeZonia
* @author Curtis Rueden
*/
public abstract class TypeChanger implements RunnablePlugin {
@Parameter
protected MenuService menuService;
@Parameter(type = ItemIO.BOTH)
protected Dataset input;
protected <T extends RealType<T>> void changeType(
final T newType)
{
changeType(input, newType);
menuService.setSelected(this, true);
}
/**
* Changes the given {@link Dataset}'s underlying {@link Img} data to the
* specified type.
*/
public static <T extends RealType<T>> void changeType(
final Dataset dataset, final T newType)
{
final ImgPlus<? extends RealType<?>> inputImg = dataset.getImgPlus();
final Class<?> currTypeClass = dataset.getType().getClass();
final Class<?> newTypeClass = newType.getClass();
int chanIndex = dataset.getAxisIndex(Axes.CHANNEL);
long numChannels = (chanIndex < 0) ? 1 : dataset.dimension(chanIndex);
final boolean isColor = dataset.getCompositeChannelCount() == numChannels;
if ((currTypeClass != newTypeClass) || isColor) {
ImgPlus<? extends RealType<?>> imgPlus;
if (isColor)
imgPlus = colorToGrayscale(inputImg, newType);
else
imgPlus = copyToType(inputImg, newType);
dataset.setImgPlus(imgPlus);
dataset.setRGBMerged(false);
dataset.setCompositeChannelCount(1);
}
}
/**
* Creates a planar ImgLib {@link Img} of the given type. It populates the
* output {@link Img}'s data from the input {@link Img} (which is likely of a
* different data type). Output data is range clamped.
*/
public static <T extends RealType<T>>
ImgPlus<? extends RealType<?>> copyToType(
final ImgPlus<? extends RealType<?>> inputImg, final T newType)
{
final ImgFactory<? extends RealType<?>> factory = inputImg.factory();
@SuppressWarnings("unchecked")
final ImgFactory<T> typedFactory = (ImgFactory<T>) factory;
return copyToType(inputImg, newType, typedFactory);
}
/**
* Creates an ImgLib {@link Img} of the given type using the specified
* {@link ImgFactory}. It populates the output {@link Img}'s data from the
* input {@link Img} (which is likely of a different data type). Output data
* is range clamped.
*/
public static <T extends RealType<T>> ImgPlus<T> copyToType(
final ImgPlus<? extends RealType<?>> inputImg, final T newType,
final ImgFactory<T> imgFactory)
{
final long[] dims = new long[inputImg.numDimensions()];
inputImg.dimensions(dims);
final Img<T> outputImg = imgFactory.create(dims, newType);
final Cursor<? extends RealType<?>> in = inputImg.localizingCursor();
final RandomAccess<T> out = outputImg.randomAccess();
final double outTypeMin = out.get().getMinValue();
final double outTypeMax = out.get().getMaxValue();
final boolean inputIs1Bit = in.get().getBitsPerPixel() == 1;
final long[] pos = new long[dims.length];
while (in.hasNext()) {
in.fwd();
in.localize(pos);
out.setPosition(pos);
double value = in.get().getRealDouble();
if (value < outTypeMin) value = outTypeMin;
if (value > outTypeMax) value = outTypeMax;
if (inputIs1Bit && value > 0) value = outTypeMax;
out.get().setReal(value);
}
return new ImgPlus<T>(outputImg, inputImg);
}
// TODO - make public?
/** Creates an output ImgPlus of specified type by averaging the channel
* values of an input ImgPlus */
private static
<I extends RealType<I>, O extends RealType<O>>
ImgPlus<O> colorToGrayscale(
ImgPlus<? extends RealType<?>> inputImg, final O newType)
{
// determine the attributes of the output image
String name = inputImg.getName();
long[] dims = outputDims(inputImg);
AxisType[] axes = outputAxes(inputImg);
double[] cal = outputCalibration(inputImg);
// create the output image
ImgFactory<? extends RealType<?>> factory = inputImg.factory();
@SuppressWarnings("unchecked")
ImgFactory<O> typedFactory = (ImgFactory<O>) factory;
Img<O> outputImg = typedFactory.create(dims, newType);
// for each set of channels in the image
// figure out what color it is
// turn that into an intensity value from 0 to 255
// set the output pixel to that value
// problems though: we don't have color table info except for view
// so instead of color just average the channel intensities
// and could do a special case for rgb that uses formula
// determine channel space
int chIndex = inputImg.getAxisIndex(Axes.CHANNEL);
int numInputDims = inputImg.numDimensions();
long[] minChanPt = new long[numInputDims];
long[] maxChanPt = new long[numInputDims];
if (chIndex >= 0) maxChanPt[chIndex] = inputImg.dimension(chIndex) - 1;
PointSet channelColumn = new HyperVolumePointSet(minChanPt, maxChanPt);
// determine data space without channels
long[] minDimPt = new long[numInputDims];
long[] maxDimPt = new long[numInputDims];
for (int i = 0; i < numInputDims; i++) {
if (i != chIndex) maxDimPt[i] = inputImg.dimension(i)-1;
}
PointSet allOtherDims = new HyperVolumePointSet(minDimPt, maxDimPt);
// setup neighborhood iterator
PointSetInputIteratorFactory inputFactory =
new PointSetInputIteratorFactory(channelColumn);
InputIterator<PointSet> iter =
inputFactory.createInputIterator(allOtherDims);
// build averaging function
@SuppressWarnings("unchecked")
Function<long[], DoubleType> valFunc =
new RealImageFunction<I, DoubleType>(
(ImgPlus<I>)inputImg, new DoubleType());
Function<PointSet, DoubleType> avgFunc =
new RealArithmeticMeanFunction<DoubleType>(valFunc);
// do the iteration and copy the data
RandomAccess<? extends RealType<?>> outputAccessor =
outputImg.randomAccess();
PointSet inputPointset = null;
long[] outputPt = new long[outputImg.numDimensions()];
DoubleType avg = new DoubleType();
while (iter.hasNext()) {
inputPointset = iter.next(inputPointset);
avgFunc.compute(inputPointset, avg);
computeOutputPoint(chIndex, inputPointset.getAnchor(), outputPt);
outputAccessor.setPosition(outputPt);
outputAccessor.get().setReal(avg.getRealDouble());
}
// return the result
return new ImgPlus<O>(outputImg, name, axes, cal);
}
/** determines the axes of the output image ignoring channels if necessary */
private static AxisType[] outputAxes(ImgPlus<?> inputImg) {
int inputAxisCount = inputImg.numDimensions();
int chanIndex = inputImg.getAxisIndex(Axes.CHANNEL);
int outputAxisCount = (chanIndex < 0) ? inputAxisCount : inputAxisCount - 1;
AxisType[] inputAxes = new AxisType[inputAxisCount];
inputImg.axes(inputAxes);
AxisType[] outputAxes = new AxisType[outputAxisCount];
int o = 0;
for (int i = 0; i < inputAxisCount; i++) {
if (i != chanIndex) outputAxes[o++] = inputAxes[i];
}
return outputAxes;
}
/** determines the dims of the output image ignoring channels if necessary */
private static long[] outputDims(ImgPlus<?> inputImg) {
int inputDimCount = inputImg.numDimensions();
int chanIndex = inputImg.getAxisIndex(Axes.CHANNEL);
int outputDimCount = (chanIndex < 0) ? inputDimCount : inputDimCount - 1;
long[] inputDims = new long[inputDimCount];
inputImg.dimensions(inputDims);
long[] outputDims = new long[outputDimCount];
int o = 0;
for (int i = 0; i < inputDimCount; i++) {
if (i != chanIndex) outputDims[o++] = inputDims[i];
}
return outputDims;
}
/** determines the calibration of the output image ignoring channels if
* necessary */
private static double[] outputCalibration(ImgPlus<?> inputImg) {
int inputDimCount = inputImg.numDimensions();
int chanIndex = inputImg.getAxisIndex(Axes.CHANNEL);
int outputDimCount = (chanIndex < 0) ? inputDimCount : inputDimCount - 1;
double[] inputCal = new double[inputDimCount];
inputImg.calibration(inputCal);
double[] outputCal = new double[outputDimCount];
int o = 0;
for (int i = 0; i < inputDimCount; i++) {
if (i != chanIndex) outputCal[o++] = inputCal[i];
}
return outputCal;
}
/** computes an output point from an input point ignoring the channel axis
* if necessary. */
private static void computeOutputPoint(
int chIndex, long[] inputPt, long[] outputPt)
{
int p = 0;
for (int i = 0; i < inputPt.length; i++) {
if (i != chIndex) outputPt[p++] = inputPt[i];
}
}
}
|
package io.bisq.core.payment.payload;
import com.google.protobuf.Message;
import io.bisq.common.locale.BankUtil;
import io.bisq.common.locale.CountryUtil;
import io.bisq.common.locale.Res;
import io.bisq.generated.protobuffer.PB;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import javax.annotation.Nullable;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@EqualsAndHashCode(callSuper = true)
@ToString
@Setter
@Getter
@Slf4j
public class WesternUnionAccountPayload extends CountryBasedPaymentAccountPayload {
private String holderName="";
@Nullable
private String requirements;
public WesternUnionAccountPayload(String paymentMethod, String id) {
super(paymentMethod, id);
}
// PROTO BUFFER
private WesternUnionAccountPayload(String paymentMethodName,
String id,
String countryCode,
String holderName,
@Nullable String requirements,
long maxTradePeriod,
@Nullable Map<String, String> excludeFromJsonDataMap) {
super(paymentMethodName,
id,
countryCode,
maxTradePeriod,
excludeFromJsonDataMap);
this.holderName = holderName;
this.requirements = requirements;
}
@Override
public Message toProtoMessage() {
PB.WesternUnionAccountPayload.Builder builder =
PB.WesternUnionAccountPayload.newBuilder()
.setHolderName(holderName);
Optional.ofNullable(requirements).ifPresent(builder::setRequirements);
final PB.CountryBasedPaymentAccountPayload.Builder countryBasedPaymentAccountPayload = getPaymentAccountPayloadBuilder()
.getCountryBasedPaymentAccountPayloadBuilder()
.setWesternUnionAccountPayload(builder);
return getPaymentAccountPayloadBuilder()
.setCountryBasedPaymentAccountPayload(countryBasedPaymentAccountPayload)
.build();
}
public static PaymentAccountPayload fromProto(PB.PaymentAccountPayload proto) {
PB.CountryBasedPaymentAccountPayload countryBasedPaymentAccountPayload = proto.getCountryBasedPaymentAccountPayload();
PB.WesternUnionAccountPayload westernUnionAccountPayload = countryBasedPaymentAccountPayload.getWesternUnionAccountPayload();
return new WesternUnionAccountPayload(proto.getPaymentMethodId(),
proto.getId(),
countryBasedPaymentAccountPayload.getCountryCode(),
westernUnionAccountPayload.getHolderName(),
westernUnionAccountPayload.getRequirements().isEmpty() ? null : westernUnionAccountPayload.getRequirements(),
proto.getMaxTradePeriod(),
CollectionUtils.isEmpty(proto.getExcludeFromJsonDataMap()) ? null : new HashMap<>(proto.getExcludeFromJsonDataMap()));
}
// API
@Override
public String getPaymentDetails() {
return "WU deposit - " + getPaymentDetailsForTradePopup().replace("\n", ", ");
}
@Override
public String getPaymentDetailsForTradePopup() {
String requirementsString = requirements != null && !requirements.isEmpty() ?
("Extra requirements: " + requirements + "\n") : "";
return "Holder name: " + holderName + "\n" +
requirementsString +
CountryUtil.getNameByCode(countryCode);
}
@Override
public byte[] getAgeWitnessInputData() {
// We don't add holderName and holderEmail because we don't want to break age validation if the user recreates an account with
// slight changes in holder name (e.g. add or remove middle name)
String all = this.countryCode +
this.holderName +
this.requirements;
return super.getAgeWitnessInputData(all.getBytes(Charset.forName("UTF-8")));
}
}
|
package fi.henu.gdxextras;
public class IVector2
{
public int x, y;
public IVector2()
{
x = 0;
y = 0;
}
public IVector2(int x, int y)
{
this.x = x;
this.y = y;
}
public IVector2(IVector2 v)
{
x = v.x;
y = v.y;
}
public void set(IVector2 pos)
{
x = pos.x;
y = pos.y;
}
public String toString()
{
return "(" + x + ", " + y + ")";
}
@Override
public final boolean equals(Object o)
{
if (o instanceof IVector2) {
IVector2 v = (IVector2)o;
return equals(v.x, v.y);
}
return false;
}
public boolean equals(int x, int y)
{
return x == this.x && y == this.y;
}
public float distanceTo(IVector2 pos)
{
return (float)Math.sqrt(distanceTo2(pos));
}
public long distanceTo2(IVector2 pos)
{
long xdiff = pos.x - x;
long ydiff = pos.y - y;
return xdiff * xdiff + ydiff * ydiff;
}
public int chebyshevDistanceTo(IVector2 pos)
{
return Math.max(Math.abs(pos.x - x), Math.abs(pos.y - y));
}
public IVector2 cpy()
{
return new IVector2(x, y);
}
public void scl(int i) {
x *= i;
y *= i;
}
public void sub(IVector2 pos)
{
sub(pos.x, pos.y);
}
private void sub(int x, int y) {
this.x -= x;
this.y -= y;
}
@Override
public int hashCode()
{
return x * 991 + y * 997;
}
}
|
package io.viper.core.server.file;
import io.viper.core.server.Util;
import java.io.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.jar.JarFile;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.json.JSONException;
import org.json.JSONObject;
public class StaticFileContentInfoProvider implements FileContentInfoProvider
{
private String _rootPath;
private final boolean _fromClasspath;
String _metaFilePath;
private Class _clazz;
final String[] defaultFiles = new String[]{"index.html", "index.htm"};
public static StaticFileContentInfoProvider create(Class clazz, String rootPath)
{
return new StaticFileContentInfoProvider(clazz, rootPath);
}
public StaticFileContentInfoProvider(Class clazz, String rootPath)
{
_clazz = clazz;
_fromClasspath = rootPath.startsWith("res:
if (_fromClasspath)
{
rootPath = rootPath.replace("res:
}
_rootPath = rootPath.endsWith("/") ? rootPath : rootPath + "/";
_rootPath = _rootPath.replace(File.separatorChar, '/');
_metaFilePath = _rootPath + ".meta" + File.separatorChar;
}
@Override
public FileContentInfo getFileContent(String path)
{
if (path == null) return null;
FileChannel fc = null;
FileContentInfo result = null;
try
{
path = path.startsWith("/") ? path.substring(1) : path;
final String fullPath = _rootPath + path;
if (fullPath.endsWith("/"))
{
for (String defaultFileName : defaultFiles)
{
result = getFileContent(path + defaultFileName);
if (result != null) break;
}
}
else
{
Map<String, String> meta = new HashMap<String, String>();
File file;
if (_fromClasspath)
{
URL url = _clazz.getResource(fullPath);
if (url == null)
{
return null;
}
if (url.toString().startsWith("jar:")) {
// TODO: this is a hack to deal with the fact that jarFile seems to be non-thread safe
byte[] bytes;
synchronized (StaticFileContentInfoProvider.class) {
JarURLConnection conn = (JarURLConnection)url.openConnection();
JarFile jarFile = conn.getJarFile();
InputStream input = jarFile.getInputStream(conn.getJarEntry());
bytes = Util.copyStream(input);
jarFile.close();
}
meta.put(HttpHeaders.Names.CONTENT_TYPE, Util.getContentType(path));
meta.put(HttpHeaders.Names.CONTENT_LENGTH, Long.toString(bytes.length));
result = FileContentInfo.create(bytes, meta);
file = null;
}
else
{
file = new File(url.getFile());
}
}
else
{
file = new File(fullPath);
File metaFile = new File(_metaFilePath + path);
if (metaFile.exists())
{
RandomAccessFile metaRaf = new RandomAccessFile(metaFile, "r");
String rawJSON = metaRaf.readUTF();
JSONObject jsonObject = new JSONObject(rawJSON);
metaRaf.close();
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext())
{
String key = keys.next();
meta.put(key, jsonObject.getString(key));
}
}
}
if (file != null && file.exists())
{
if (!meta.containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
meta.put(HttpHeaders.Names.CONTENT_TYPE, Util.getContentType(path));
}
if (!meta.containsKey(HttpHeaders.Names.CONTENT_LENGTH)) {
meta.put(HttpHeaders.Names.CONTENT_LENGTH, Long.toString(file.length()));
}
result = FileContentInfo.create(file, meta);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
finally
{
if (result == null)
{
if (fc != null)
{
try
{
fc.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
return result;
}
@Override
public void dispose(FileContentInfo info)
{
info.dispose();
}
}
|
package org.tigris.subversion.subclipse.core.commands;
import java.util.HashSet;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.ResourceAttributes;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.team.core.TeamException;
import org.tigris.subversion.subclipse.core.ISVNLocalResource;
import org.tigris.subversion.subclipse.core.Policy;
import org.tigris.subversion.subclipse.core.SVNException;
import org.tigris.subversion.subclipse.core.SVNProviderPlugin;
import org.tigris.subversion.subclipse.core.client.OperationManager;
import org.tigris.subversion.subclipse.core.resources.SVNWorkspaceRoot;
import org.tigris.subversion.svnclientadapter.ISVNClientAdapter;
import org.tigris.subversion.svnclientadapter.SVNClientException;
/**
* Add the given resources to the project.
* <p>
* The sematics follow that of SVN in the sense that any folders and files
* are created remotely on the next commit.
* </p>
*
* @author Cedric Chabanois (cchab at tigris.org)
*/
public class AddResourcesCommand implements ISVNCommand {
// resources to add
private IResource[] resources;
private int depth;
private SVNWorkspaceRoot root;
public AddResourcesCommand(SVNWorkspaceRoot root, IResource[] resources, int depth) {
this.resources = resources;
this.depth = depth;
this.root = root;
}
/* (non-Javadoc)
* @see org.tigris.subversion.subclipse.core.commands.ISVNCommand#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public void run(IProgressMonitor monitor) throws SVNException {
monitor = Policy.monitorFor(monitor);
// Visit the children of the resources using the depth in order to
// determine which folders, text files and binary files need to be added
// A TreeSet is needed for the folders so they are in the right order (i.e. parents created before children)
final SortedSet folders = new TreeSet();
// Sets are required for the files to ensure that files will not appear twice if there parent was added as well
// and the depth isn't zero
final HashSet files = new HashSet();
for (int i=0; i<resources.length; i++) {
final IResource currentResource = resources[i];
try {
// Auto-add parents if they are not already managed
IContainer parent = currentResource.getParent();
ISVNLocalResource svnParentResource = SVNWorkspaceRoot.getSVNResourceFor(parent);
while (parent.getType() != IResource.ROOT && parent.getType() != IResource.PROJECT && ! svnParentResource.isManaged()) {
folders.add(svnParentResource);
parent = parent.getParent();
svnParentResource = svnParentResource.getParent();
}
// Auto-add children accordingly to depth
final SVNException[] exception = new SVNException[] { null };
currentResource.accept(new IResourceVisitor() {
public boolean visit(IResource resource) {
try {
ISVNLocalResource mResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
// Add the resource is its not already managed and it was either
// added explicitly (is equal currentResource) or is not ignored
if ((! mResource.isManaged()) && (currentResource.equals(resource) || ! mResource.isIgnored())) {
if (resource.getType() == IResource.FILE) {
files.add(mResource);
} else {
folders.add(mResource);
}
}
// Always return true and let the depth determine if children are visited
return true;
} catch (SVNException e) {
exception[0] = e;
return false;
}
}
}, depth, false);
if (exception[0] != null) {
throw exception[0];
}
} catch (CoreException e) {
throw new SVNException(new Status(IStatus.ERROR, SVNProviderPlugin.ID, TeamException.UNABLE, Policy.bind("SVNTeamProvider.visitError", new Object[] {resources[i].getFullPath()}), e)); //$NON-NLS-1$
}
} // for
// If an exception occured during the visit, throw it here
// Add the folders, followed by files!
ISVNClientAdapter svnClient = root.getRepository().getSVNClient();
monitor.beginTask(null, files.size() * 10 + (folders.isEmpty() ? 0 : 10));
OperationManager.getInstance().beginOperation(svnClient);
try {
for(Iterator it=folders.iterator(); it.hasNext();) {
final ISVNLocalResource localResource = (ISVNLocalResource)it.next();
try {
svnClient.addDirectory(localResource.getIResource().getLocation().toFile(),false);
} catch (SVNClientException e) {
throw SVNException.wrapException(e);
}
}
for(Iterator it=files.iterator(); it.hasNext();) {
final ISVNLocalResource localResource = (ISVNLocalResource)it.next();
try {
svnClient.addFile(localResource.getIResource().getLocation().toFile());
// If file has read-only attribute set, remove it
ResourceAttributes attrs = localResource.getIResource().getResourceAttributes();
if (localResource.getIResource().getType() == IResource.FILE && attrs.isReadOnly()) {
attrs.setReadOnly(false);
try {
localResource.getIResource().setResourceAttributes(attrs);
} catch (CoreException swallow) {
}
}
} catch (SVNClientException e) {
throw SVNException.wrapException(e);
}
}
} finally {
OperationManager.getInstance().endOperation();
monitor.done();
}
}
}
|
package simulator.simbot;
import java.io.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import basestation.bot.commands.FourWheelMovement;
import basestation.bot.connection.Connection;
import com.google.gson.JsonObject;
import simulator.Simulator;
import simulator.baseinterface.SimulatorVisionSystem;
import org.jbox2d.dynamics.Body;
import org.jbox2d.common.Vec2;
public class SimBotCommandCenter implements FourWheelMovement {
private SimBot bot;
private Simulator simulator;
public final float topspeed = 0.655f; //top speed of minibot in meters/second
public final float turningspeed = (float) Math.PI;
public transient boolean record = false;
Map<String,String> commandsLog = new ConcurrentHashMap<>();
public SimBotCommandCenter(SimBot myBot, Body obj_body, Simulator
mySimulator) {
bot = myBot;
simulator = mySimulator;
}
/**
* Does not record data until start is called
*/
public void toggleLogging() {
this.record = !this.record;
}
public boolean isLogging() {
return this.record;
}
public void setData(String name, String value) {
this.commandsLog.put(name,value);
}
public void setWheelsData(String fl, String v1, String fr, String v2, String bl, String v3, String br, String v4) {
this.commandsLog.put(fl,v1);
this.commandsLog.put(fr,v2);
this.commandsLog.put(bl,v3);
this.commandsLog.put(br,v4);
}
public JsonObject getData(String name) {
JsonObject data = new JsonObject();
for (Map.Entry<String, String> entry : this.commandsLog.entrySet()) {
String n = entry.getKey();
if (name.equals(n)) {
String value = entry.getValue();
data.addProperty(name, value);
return data;
}
}
data.addProperty(name,"");
return data;
}
public JsonObject getAllData() {
JsonObject allData = new JsonObject();
for (Map.Entry<String, String> entry : this.commandsLog.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
allData.addProperty(name, value);
}
return allData;
}
@Override
public boolean setWheelPower(double fl, double fr, double bl, double br) {
Body b = bot.getMyPhysicalObject().getBody();
//forwards
if(fl > 0 && fr > 0 && bl >0 && br>0) {
float angle = b.getAngle();
float newX = (float) (topspeed*fl/100*Math.cos(angle));
float newY = (float) (topspeed*fl/100*Math.sin(angle));
b.setLinearVelocity(new Vec2(newX, newY));
b.setAngularVelocity(0.0f);
}
//backwards
else if(fl < 0 && fr < 0 && bl < 0 && br < 0) {
float angle = b.getAngle();
float newX = (float) (topspeed*fl/100*Math.cos(angle));
float newY = (float) (topspeed*fl/100*Math.sin(angle));
b.setLinearVelocity(new Vec2(newX, newY));
b.setAngularVelocity(0.0f);
}
//no motor power
else if(fl == 0 && fr == 0 && bl == 0 && br == 0) {
b.setLinearVelocity(new Vec2(0.0f, 0.0f));
b.setAngularVelocity(0.0f);
}
//turning right
else if(fl > 0 && fr < 0 && bl > 0 && br < 0) {
b.setLinearVelocity(new Vec2(0.0f, 0.0f));
b.setAngularVelocity((float)(-turningspeed*fl/100));
}
//turning left
else if(fl < 0 && fr > 0 && bl < 0 && br > 0) {
b.setLinearVelocity(new Vec2(0.0f, 0.0f));
b.setAngularVelocity((float)(-turningspeed*fl/100));
}
else {
float angle = b.getAngle();
float floatL = (float) fl;
float floatR = (float) fr;
float linearMagnitude = topspeed * (floatL + floatR) / (float)Math
.sqrt
(floatL*floatL + floatR*floatR);
if (linearMagnitude < 1f) {
b.setLinearVelocity(new Vec2(0.0f, 0.0f));
b.setAngularVelocity(0.0f);
}
float angularSpeed = turningspeed * ((floatR-floatL) / (float)Math
.sqrt(100*100 +
100*100));
b.setLinearVelocity(new Vec2(linearMagnitude*(float)Math.cos(angle),
linearMagnitude*(float)Math.sin(angle)));
b.setAngularVelocity(angularSpeed);
}
return true;
}
@Override
public boolean sendKV(String key, String value) {
if (key == "WHEELS") {
String[] wheelCommands = value.split(",");
double fl = Double.parseDouble(wheelCommands[0]);
double fr = Double.parseDouble(wheelCommands[1]);
double bl = Double.parseDouble(wheelCommands[2]);
double br = Double.parseDouble(wheelCommands[3]);
Body b = bot.getMyPhysicalObject().getBody();
//forwards
if(fl > 0 && fr > 0 && bl >0 && br>0) {
float angle = b.getAngle();
float newX = (float) (topspeed*fl/100*Math.cos(angle));
float newY = (float) (topspeed*fl/100*Math.sin(angle));
b.setLinearVelocity(new Vec2(newX, newY));
b.setAngularVelocity(0.0f);
}
//backwards
else if(fl < 0 && fr < 0 && bl < 0 && br < 0) {
float angle = b.getAngle();
float newX = (float) (topspeed*fl/100*Math.cos(angle));
float newY = (float) (topspeed*fl/100*Math.sin(angle));
b.setLinearVelocity(new Vec2(newX, newY));
b.setAngularVelocity(0.0f);
}
//no motor power
else if(fl == 0 && fr == 0 && bl == 0 && br == 0) {
b.setLinearVelocity(new Vec2(0.0f, 0.0f));
b.setAngularVelocity(0.0f);
}
//turning right
else if(fl > 0 && fr < 0 && bl > 0 && br < 0) {
b.setLinearVelocity(new Vec2(0.0f, 0.0f));
b.setAngularVelocity((float)(-turningspeed*fl/100));
}
//turning left
else if(fl < 0 && fr > 0 && bl < 0 && br > 0) {
b.setLinearVelocity(new Vec2(0.0f, 0.0f));
b.setAngularVelocity((float)(-turningspeed*fl/100));
}
else {
System.out.println("Invalid wheel power command!");
}
this.setWheelsData("fl", wheelCommands[0], "fr", wheelCommands[1],
"bl", wheelCommands[2], "br", wheelCommands[3]);
return true;
} else {
try{
BufferedReader reader =
new BufferedReader(new FileReader("cs-minibot-platform-src/src/main/java/simulator/simbot/ScriptHeader.py"));
String header = "";
String sCurrentLine;
while ((sCurrentLine = reader.readLine()) != null) {
header = header + sCurrentLine + "\n";
}
String prg = value;
BufferedWriter out = new BufferedWriter(new FileWriter("script.py"));
out.write(header);
out.write(prg);
out.close();
ProcessBuilder pb = new ProcessBuilder("python","script.py");
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret;
String line;
while ((line = in.readLine()) != null) {
ret = new String(line);
System.out.println(ret);
}
}catch(Exception e){
System.out.println(e);
}
}
return false;
}
@Override
public Connection getConnection() {
return null;
}
}
|
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.lang.reflect.*;
/*
javac -Xlint TestReflection.java
*/
public class TestReflection
{
public static void main( String[] args )
{
try
{
/* test Class class */
Class calClass = Class.forName( "java.util.Calendar" );
Class gCalClass = Class.forName( "java.util.GregorianCalendar" );
/* retrieve constructors */
Constructor[] calConstructors = calClass.getConstructors();
Constructor[] gCalConstructors = gCalClass.getConstructors();
System.out.println(
"Class name: " + calClass.getName() + "\n" +
"Number of constructors: " + calConstructors.length + "\n" +
"Class name: " + gCalClass.getName() + "\n" +
"Number of constructors: " + gCalConstructors.length
);
/* test constructor */
for( Constructor c : gCalConstructors )
{
Class[] paramTypes = c.getParameterTypes();
// find the default constructor
if( paramTypes.length == 0 )
{
System.out.println( "Default constructor found." );
// construct an object
GregorianCalendar gCal = ( GregorianCalendar ) c.newInstance();
// output some information
System.out.println( gCal.get( Calendar.YEAR ) ); // 2017
}
// find the constructor taking 3 params
if( paramTypes.length == 3 )
{
GregorianCalendar gCalWithParams =
( GregorianCalendar ) c.newInstance( 2018, 0, 1 );
System.out.println( gCalWithParams.get( Calendar.YEAR ) ); // 2018
}
}
/* test fields */
Field april = calClass.getField( "APRIL" );
System.out.println( april.getType().getName() ); // int
/* test method */
Method calMethod = calClass.getMethod( "getInstance" );
System.out.println( calMethod.getName() ); // getInstance
GregorianCalendar c = ( GregorianCalendar ) calMethod.invoke( null );
System.out.println( c.get( Calendar.YEAR ) ); // 2017
}
catch( ClassNotFoundException e )
{
System.out.println( e.getMessage() );
}
catch( Exception e )
{
System.out.println( e.getMessage() );
}
}
}
|
package org.datavec.dataframe.store;
import org.datavec.dataframe.api.BooleanColumn;
import org.datavec.dataframe.api.CategoryColumn;
import org.datavec.dataframe.api.DateColumn;
import org.datavec.dataframe.api.DateTimeColumn;
import org.datavec.dataframe.api.FloatColumn;
import org.datavec.dataframe.api.IntColumn;
import org.datavec.dataframe.api.LongColumn;
import org.datavec.dataframe.api.ShortColumn;
import org.datavec.dataframe.api.Table;
import org.datavec.dataframe.api.TimeColumn;
import org.datavec.dataframe.columns.Column;
import org.datavec.dataframe.table.Relation;
import org.iq80.snappy.SnappyFramedInputStream;
import org.iq80.snappy.SnappyFramedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
/**
* A controller for reading and writing data in Tablesaw's own compressed, column-oriented file format
*/
public class StorageManager {
private static final int FLUSH_AFTER_ITERATIONS = 10_000;
private static final String FILE_EXTENSION = "saw";
private static final Pattern WHITE_SPACE_PATTERN = Pattern.compile("\\s+");
private static final Pattern SEPARATOR_PATTERN = Pattern.compile(separator());
private static final int READER_POOL_SIZE = 4;
private static final String WINDOWS_PATH_SEPARATOR = "\\";
static String separator() {
FileSystem fileSystem = FileSystems.getDefault();
String separator = fileSystem.getSeparator();
if(WINDOWS_PATH_SEPARATOR.equals(separator)){
return "\\\\"; //Regex: "\\" is a single '\', and need 2 of them to be a valid regex
}
return separator;
}
/**
* Reads a tablesaw table into memory
*
* @param path The location of the table. It is interpreted as relative to the working directory if not fully
* specified. The path will typically end in ".saw", as in "mytables/nasdaq-2015.saw"
* @throws IOException if the file cannot be read
*/
public static Table readTable(String path) throws IOException {
ExecutorService executorService = Executors.newFixedThreadPool(READER_POOL_SIZE);
CompletionService readerCompletionService = new ExecutorCompletionService<>(executorService);
TableMetadata tableMetadata = readTableMetadata(path + separator() + "Metadata.json");
List<ColumnMetadata> columnMetadata = tableMetadata.getColumnMetadataList();
Table table = Table.create(tableMetadata);
// NB: We do some extra work with the hash map to ensure that the columns are added to the table in original order
// TODO(lwhite): Not using CPU efficiently. Need to prevent waiting for other threads until all columns are read
// TODO - continued : Problem seems to be mostly with category columns rebuilding the encoding dictionary
ConcurrentLinkedQueue<Column> columnList = new ConcurrentLinkedQueue<>();
Map<String, Column> columns = new HashMap<>();
try {
for (ColumnMetadata column : columnMetadata) {
readerCompletionService.submit(() -> {
columnList.add(readColumn(path + separator() + column.getId(), column));
return null;
});
}
for (int i = 0; i < columnMetadata.size(); i++) {
Future future = readerCompletionService.take();
future.get();
}
for (Column c : columnList) {
columns.put(c.id(), c);
}
for (ColumnMetadata metadata : columnMetadata) {
String id = metadata.getId();
table.addColumn(columns.get(id));
}
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
executorService.shutdown();
return table;
}
private static Column readColumn(String fileName, ColumnMetadata columnMetadata)
throws IOException {
switch (columnMetadata.getType()) {
case FLOAT:
return readFloatColumn(fileName, columnMetadata);
case INTEGER:
return readIntColumn(fileName, columnMetadata);
case BOOLEAN:
return readBooleanColumn(fileName, columnMetadata);
case LOCAL_DATE:
return readLocalDateColumn(fileName, columnMetadata);
case LOCAL_TIME:
return readLocalTimeColumn(fileName, columnMetadata);
case LOCAL_DATE_TIME:
return readLocalDateTimeColumn(fileName, columnMetadata);
case CATEGORY:
return readCategoryColumn(fileName, columnMetadata);
case SHORT_INT:
return readShortColumn(fileName, columnMetadata);
case LONG_INT:
return readLongColumn(fileName, columnMetadata);
default:
throw new RuntimeException("Unhandled column type writing columns");
}
}
public static FloatColumn readFloatColumn(String fileName, ColumnMetadata metadata) throws IOException {
FloatColumn floats = new FloatColumn(metadata);
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
boolean EOF = false;
while (!EOF) {
try {
float cell = dis.readFloat();
floats.add(cell);
} catch (EOFException e) {
EOF = true;
}
}
}
return floats;
}
public static IntColumn readIntColumn(String fileName, ColumnMetadata metadata) throws IOException {
IntColumn ints = new IntColumn(metadata);
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
boolean EOF = false;
while (!EOF) {
try {
ints.add(dis.readInt());
} catch (EOFException e) {
EOF = true;
}
}
}
return ints;
}
public static ShortColumn readShortColumn(String fileName, ColumnMetadata metadata) throws IOException {
ShortColumn ints = new ShortColumn(metadata);
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
boolean EOF = false;
while (!EOF) {
try {
ints.add(dis.readShort());
} catch (EOFException e) {
EOF = true;
}
}
}
return ints;
}
public static LongColumn readLongColumn(String fileName, ColumnMetadata metadata) throws IOException {
LongColumn ints = new LongColumn(metadata);
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
boolean EOF = false;
while (!EOF) {
try {
ints.add(dis.readLong());
} catch (EOFException e) {
EOF = true;
}
}
}
return ints;
}
public static DateColumn readLocalDateColumn(String fileName, ColumnMetadata metadata) throws IOException {
DateColumn dates = new DateColumn(metadata);
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
boolean EOF = false;
while (!EOF) {
try {
int cell = dis.readInt();
dates.add(cell);
} catch (EOFException e) {
EOF = true;
}
}
}
return dates;
}
public static DateTimeColumn readLocalDateTimeColumn(String fileName, ColumnMetadata metadata) throws
IOException {
DateTimeColumn dates = new DateTimeColumn(metadata);
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
boolean EOF = false;
while (!EOF) {
try {
long cell = dis.readLong();
dates.add(cell);
} catch (EOFException e) {
EOF = true;
}
}
}
return dates;
}
public static TimeColumn readLocalTimeColumn(String fileName, ColumnMetadata metadata) throws IOException {
TimeColumn times = new TimeColumn(metadata);
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
boolean EOF = false;
while (!EOF) {
try {
int cell = dis.readInt();
times.add(cell);
} catch (EOFException e) {
EOF = true;
}
}
}
return times;
}
public static CategoryColumn readCategoryColumn(String fileName, ColumnMetadata metadata) throws IOException {
CategoryColumn stringColumn = new CategoryColumn(metadata);
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
int stringCount = dis.readInt();
int j = 0;
while (j < stringCount) {
stringColumn.dictionaryMap().put(j, dis.readUTF());
j++;
}
int size = metadata.getSize();
for (int i = 0; i < size; i++) {
stringColumn.data().add(dis.readInt());
}
}
return stringColumn;
}
public static BooleanColumn readBooleanColumn(String fileName, ColumnMetadata metadata) throws IOException {
BooleanColumn bools = new BooleanColumn(metadata);
try (FileInputStream fis = new FileInputStream(fileName);
SnappyFramedInputStream sis = new SnappyFramedInputStream(fis, true);
DataInputStream dis = new DataInputStream(sis)) {
boolean EOF = false;
while (!EOF) {
try {
boolean cell = dis.readBoolean();
bools.add(cell);
} catch (EOFException e) {
EOF = true;
}
}
}
return bools;
}
/**
* Saves the data from the given table in the location specified by folderName. Within that folder each table has
* its own sub-folder, whose name is based on the name of the table.
* <p>
* NOTE: If you store a table with the same name in the same folder. The data in that folder will be over-written.
* <p>
* The storage format is the tablesaw compressed column-oriented format, which consists of a set of file in a folder.
* The name of the folder is based on the name of the table.
*
* @param folderName The location of the table (for example: "mytables")
* @param table The table to be saved
* @return The path and name of the table
* @throws IOException
*/
public static String saveTable(String folderName, Relation table) throws IOException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
CompletionService writerCompletionService = new ExecutorCompletionService<>(executorService);
String name = table.name();
name = WHITE_SPACE_PATTERN.matcher(name).replaceAll(""); // remove whitespace from the table name
name = SEPARATOR_PATTERN.matcher(name).replaceAll("_"); // remove path separators from the table name
String storageFolder = folderName + separator() + name + '.' + FILE_EXTENSION;
Path path = Paths.get(storageFolder);
if (!Files.exists(path)) {
try {
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
}
}
writeTableMetadata(path.toString() + separator() + "Metadata.json", table);
try {
for (Column column : table.columns()) {
writerCompletionService.submit(() -> {
Path columnPath = path.resolve(column.id());
writeColumn(columnPath.toString(), column);
return null;
});
}
for (int i = 0; i < table.columnCount(); i++) {
Future future = writerCompletionService.take();
future.get();
}
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
executorService.shutdown();
return storageFolder;
}
private static void writeColumn(String fileName, Column column) {
try {
switch (column.type()) {
case FLOAT:
writeColumn(fileName, (FloatColumn) column);
break;
case INTEGER:
writeColumn(fileName, (IntColumn) column);
break;
case BOOLEAN:
writeColumn(fileName, (BooleanColumn) column);
break;
case LOCAL_DATE:
writeColumn(fileName, (DateColumn) column);
break;
case LOCAL_TIME:
writeColumn(fileName, (TimeColumn) column);
break;
case LOCAL_DATE_TIME:
writeColumn(fileName, (DateTimeColumn) column);
break;
case CATEGORY:
writeColumn(fileName, (CategoryColumn) column);
break;
case SHORT_INT:
writeColumn(fileName, (ShortColumn) column);
break;
case LONG_INT:
writeColumn(fileName, (LongColumn) column);
break;
default:
throw new RuntimeException("Unhandled column type writing columns");
}
} catch (IOException ex) {
throw new RuntimeException("IOException writing to file");
}
}
public static void writeColumn(String fileName, FloatColumn column) throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileName);
SnappyFramedOutputStream sos = new SnappyFramedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(sos)) {
int i = 0;
for (float d : column) {
dos.writeFloat(d);
if (i % FLUSH_AFTER_ITERATIONS == 0) {
dos.flush();
}
i++;
}
dos.flush();
}
}
/**
* Writes out the values of the category column encoded as ints to minimize the time required for subsequent reads
* <p>
* The files are written Strings first, then the ints that encode them so they can be read in the opposite order
*
* @throws IOException
*/
public static void writeColumn(String fileName, CategoryColumn column) throws IOException {
int categoryCount = column.dictionaryMap().size();
try (FileOutputStream fos = new FileOutputStream(fileName);
SnappyFramedOutputStream sos = new SnappyFramedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(sos)) {
dos.writeInt(categoryCount);
// write the strings
SortedSet<Integer> keys = new TreeSet<>(column.dictionaryMap().keyToValueMap().keySet());
for (int key : keys) {
dos.writeUTF(column.dictionaryMap().get(key));
}
dos.flush();
// write the integer values that represent the strings
int i = 0;
for (int d : column.data()) {
dos.writeInt(d);
if (i % FLUSH_AFTER_ITERATIONS == 0) {
dos.flush();
}
i++;
}
}
}
//TODO(lwhite): saveTable the column using integer compression
public static void writeColumn(String fileName, IntColumn column) throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileName);
SnappyFramedOutputStream sos = new SnappyFramedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(sos)) {
int i = 0;
for (int d : column.data()) {
dos.writeInt(d);
if (i % FLUSH_AFTER_ITERATIONS == 0) {
dos.flush();
}
i++;
}
dos.flush();
}
}
public static void writeColumn(String fileName, ShortColumn column) throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileName);
SnappyFramedOutputStream sos = new SnappyFramedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(sos)) {
int i = 0;
for (short d : column) {
dos.writeShort(d);
if (i % FLUSH_AFTER_ITERATIONS == 0) {
dos.flush();
}
i++;
}
dos.flush();
}
}
public static void writeColumn(String fileName, LongColumn column) throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileName);
SnappyFramedOutputStream sos = new SnappyFramedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(sos)) {
int i = 0;
for (long d : column) {
dos.writeLong(d);
if (i % FLUSH_AFTER_ITERATIONS == 0) {
dos.flush();
}
i++;
}
dos.flush();
}
}
//TODO(lwhite): saveTable the column using integer compression
public static void writeColumn(String fileName, DateColumn column) throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileName);
SnappyFramedOutputStream sos = new SnappyFramedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(sos)) {
int i = 0;
for (int d : column.data()) {
dos.writeInt(d);
if (i % FLUSH_AFTER_ITERATIONS == 0) {
dos.flush();
}
i++;
}
dos.flush();
}
}
public static void writeColumn(String fileName, DateTimeColumn column) throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileName);
SnappyFramedOutputStream sos = new SnappyFramedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(sos)) {
int i = 0;
for (long d : column.data()) {
dos.writeLong(d);
if (i % FLUSH_AFTER_ITERATIONS == 0) {
dos.flush();
}
i++;
}
dos.flush();
}
}
//TODO(lwhite): saveTable the column using integer compression
public static void writeColumn(String fileName, TimeColumn column) throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileName);
SnappyFramedOutputStream sos = new SnappyFramedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(sos)) {
int i = 0;
for (int d : column.data()) {
dos.writeInt(d);
if (i % FLUSH_AFTER_ITERATIONS == 0) {
dos.flush();
}
i++;
}
dos.flush();
}
}
//TODO(lwhite): saveTable the column using compressed bitmap
public static void writeColumn(String fileName, BooleanColumn column) throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileName);
SnappyFramedOutputStream sos = new SnappyFramedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(sos)) {
for (int i = 0; i < column.size(); i++) {
boolean value = column.get(i);
dos.writeBoolean(value);
if (i % FLUSH_AFTER_ITERATIONS == 0) {
dos.flush();
}
}
dos.flush();
}
}
/**
* Writes out a json-formatted representation of the given {@code table}'s metadata to the given {@code file}
*
* @param fileName Expected to be fully specified
* @throws IOException if the file can not be read
*/
public static void writeTableMetadata(String fileName, Relation table) throws IOException {
File myFile = Paths.get(fileName).toFile();
myFile.createNewFile();
try (FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut)) {
myOutWriter.append(new TableMetadata(table).toJson());
}
}
/**
* Reads in a json-formatted file and creates a TableMetadata instance from it. Files are expected to be in
* the format provided by TableMetadata}
*
* @param fileName Expected to be fully specified
* @throws IOException if the file can not be read
*/
public static TableMetadata readTableMetadata(String fileName) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(fileName));
return TableMetadata.fromJson(new String(encoded, StandardCharsets.UTF_8));
}
}
|
package dogtooth.tree.internal;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import dogtooth.tree.Selector;
import dogtooth.tree.Tree;
import dogtooth.tree.TreeAlreadySealedException;
import dogtooth.tree.TreeBuilder;
import dogtooth.tree.TreeException;
import dogtooth.tree.annotated.Tag;
/**
* Default implementation not really suitable for very large trees but fast and simple.
*
* @author Toni Menzel <toni.menzel@rebaze.com>
*
*/
public class InMemoryTreeBuilderImpl implements TreeBuilder {
private final static Logger LOG = LoggerFactory.getLogger(InMemoryTreeBuilderImpl.class);
private MessageDigest m_digest;
private Tree m_hash;
private boolean m_sealed = false;
final private List<TreeBuilder> m_sub;
private Selector m_selector;
private Tag m_tag;
public InMemoryTreeBuilderImpl( ) {
try {
m_digest = MessageDigest.getInstance("SHA-1");
m_sub = new ArrayList<TreeBuilder>();
}catch (Exception e) {
throw new TreeException("Problem creating collector",e);
}
}
public InMemoryTreeBuilderImpl( final Selector selector ) {
this();
m_selector = selector;
}
public InMemoryTreeBuilderImpl( final String selector ) {
this( Selector.selector( (selector)));
}
/* (non-Javadoc)
* @see dogtooth.tree.internal.TreeBuilder#add(byte[])
*/
@Override
synchronized public TreeBuilder add(byte[] bytes) {
verifyTreeNotSealed();
m_digest.update(bytes);
return this;
}
/* (non-Javadoc)
* @see dogtooth.tree.internal.TreeBuilder#seal()
*/
@Override
synchronized public Tree seal() {
if (!m_sealed) {
if (m_selector == null) throw new TreeException("Sealing not possible due to missing selector.");
List<Tree> subHashes = new ArrayList<Tree>(m_sub.size());
for (TreeBuilder c : m_sub) {
Tree subHash = c.seal();
subHashes.add(subHash);
add(subHash.fingerprint().getBytes());
}
m_hash = new InMemoryTreeImpl(m_selector,convertToHex(m_digest.digest()),subHashes.toArray(new Tree[subHashes.size()]),m_tag);
m_sealed = true;
resetMembers();
}
return m_hash;
}
private void resetMembers() {
m_sub.clear();
m_digest = null;
m_selector = null;
}
/* (non-Javadoc)
* @see dogtooth.tree.internal.TreeBuilder#childCollector(java.lang.String)
*/
@Override
synchronized public TreeBuilder branch( Selector selector) {
verifyTreeNotSealed();
TreeBuilder c = new InMemoryTreeBuilderImpl(selector);
m_sub.add(c);
return c;
}
private void verifyTreeNotSealed() {
if (m_sealed) throw new TreeAlreadySealedException("No modification on a sealed tree!");
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9)) {
buf.append((char) ('0' + halfbyte));
} else {
buf.append((char) ('a' + (halfbyte - 10)));
}
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
/* (non-Javadoc)
* @see dogtooth.tree.internal.TreeBuilder#setSelector(java.lang.String)
*/
@Override
synchronized public TreeBuilder selector(Selector selector) {
verifyTreeNotSealed();
m_selector = selector;
return this;
}
@Override
public TreeBuilder tag( Tag tag ) {
m_tag = tag;
return this;
}
}
|
package org.dspace.curate;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.ItemIterator;
import org.dspace.content.crosswalk.StreamIngestionCrosswalk;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.doi.CDLDataCiteService;
import org.dspace.embargo.EmbargoManager;
import org.dspace.identifier.DOIIdentifierProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Curation task to report embargoed items without publication date
*
* @author pmidford
* created Dec 9, 2011
*
*/
@Suspendable
public class EmbargoedWithoutPubDate extends AbstractCurationTask {
private int total;
private int unpublishedCount;
private List<DatedEmbargo> embargoes;
private DatedEmbargo[] dummy = new DatedEmbargo[1];
private static Logger LOGGER = LoggerFactory.getLogger(EmbargoedWithoutPubDate.class);
@Override
public void init(Curator curator, String taskID) throws IOException{
super.init(curator, taskID);
}
@Override
public int perform(DSpaceObject dso) throws IOException{
throw new RuntimeException("Didn't want to call this");
}
@Override
public int perform(Context ctx, String id) throws IOException {
DSpaceObject dso = dereference(ctx,id);
if (dso instanceof Collection){
total = 0;
unpublishedCount = 0;
embargoes = new ArrayList<DatedEmbargo>();
distribute(dso);
if (!embargoes.isEmpty()){
DatedEmbargo[] s = embargoes.toArray(dummy);
Arrays.sort(s);
this.report("Collection: " + dso.getName() + "; Total items = " + total + "; unpublished items = " + unpublishedCount);
for(DatedEmbargo d : s)
this.report(d.toString());
}
else if (total > 0)
this.report("Collection: " + dso.getName() + "; Total items = " + total + "; no unpublished items");
}
return Curator.CURATE_SUCCESS;
}
@Override
protected void performItem(Item item){
String handle = item.getHandle();
DCValue partof[] = item.getMetadata("dc.relation.ispartof");
if (handle != null){ //ignore items in workflow
total++;
boolean unpublished = false;
DCDate itemPubDate;
DCValue values[] = item.getMetadata("dc", "date", "available", Item.ANY);
if (values== null || values.length==0){ //no available date - save and report
unpublished = true;
}
DCDate itemEmbargoDate = null;
if (unpublished){
unpublishedCount++;
try { //want to continue if a problem comes up
itemEmbargoDate = EmbargoManager.getEmbargoDate(null, item);
if (itemEmbargoDate != null){
DatedEmbargo de = new DatedEmbargo(itemEmbargoDate.toDate(),item);
embargoes.add(de);
}
} catch (Exception e) {
this.report("Exception " + e + " encountered while processing " + item);
}
}
}
}
private static class DatedEmbargo implements Comparable<DatedEmbargo>{
private Date embargoDate;
private Item embargoedItem;
public DatedEmbargo(Date date, Item item) {
embargoDate = date;
embargoedItem = item;
}
@Override
public int compareTo(DatedEmbargo o) {
return embargoDate.compareTo(o.embargoDate);
}
@Override
public String toString(){
return embargoedItem.getName() + " " + embargoDate.toString();
}
}
}
|
package io.coati.eSourcetrail.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.texteditor.ITextEditor;
import io.coati.eSourcetrail.core.preferences.PreferenceConstants;
public class TCPServerWorker extends Thread {
private Display display;
private void logError(String msg, Exception e) {
Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Status.OK, msg, e));
}
private void logWarning(String msg, Exception e ) {
Activator.getDefault().getLog().log(new Status(IStatus.WARNING, Activator.PLUGIN_ID, Status.OK, msg, e));
}
private void sendPing() {
String ip = "localhost";
Integer port = 0;
try {
IPreferenceStore store = io.coati.eSourcetrail.core.Activator.getDefault().getPreferenceStore();
port = store.getInt(PreferenceConstants.P_ECLIPSE_TO_SOURCETRAIL_PORT);
Socket socket = new Socket(ip, port);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("ping>>Eclipse<EOM>");
writer.flush();
socket.close();
} catch (Exception e) {
logWarning(
"Unable to establish connection to Sourcetrail instance.\n\nMake sure Sourcetrail is running and the " +
"right address is used (" + ip + ":" + port + ").",
e
);
}
}
public TCPServerWorker(Display display) {
if (display == null) {
logError("display null", null);
}
this.display = display;
}
@Override
public void run() {
ServerSocket server = null;
try {
IPreferenceStore store = io.coati.eSourcetrail.core.Activator.getDefault().getPreferenceStore();
String ip = "localhost";
int port = store.getInt(PreferenceConstants.P_SOURCETRAIL_TO_ECLIPSE_PORT);
server = new ServerSocket(port, 5, InetAddress.getByName(ip));
sendPing();
while (true) {
final Socket client = server.accept();
if (client == null) {
logWarning("client is null", null);
continue;
}
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(client.getInputStream()));
String message = inFromClient.readLine();
if (message == null) {
logWarning("message is null", null);
continue;
}
if (message.contains("<EOM>")) {
message = message.replace("<EOM>", "");
String [] split = message.split("\\>\\>");
if (split[0].equals("moveCursor")) {
display.asyncExec(new Runnable() {
@Override
public void run() {
try {
File fileToOpen = new File(split[1]);
IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
if (fileStore == null) {
throw new PartInitException("filestorage is null");
}
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (page == null) {
throw new PartInitException("page is null");
}
IEditorPart part = IDE.openEditorOnFileStore(page, fileStore);
if(part == null) {
throw new PartInitException("part is null");
}
ITextEditor editor = (ITextEditor) part;
Object control = part.getAdapter(Control.class);
if(control == null) {
throw new PartInitException("control is null");
}
// For a text editor the control will be StyledText
if (control instanceof StyledText) {
StyledText text = (StyledText)control;
int row = Integer.parseInt(split[2]) - 1;
int col = Integer.parseInt(split[3]);
int offset = text.getOffsetAtLine(row) + col;
editor.selectAndReveal(offset, 1);
text.setCaretOffset(offset);
}
}
catch(PartInitException e) {
logWarning("Failed to open file", e);
}
}
});
}
if (split[0].equals("ping")) {
sendPing();
}
}
else {
logWarning("No EOM in the message", null);
}
client.close();
}
} catch(final Exception e) {
logError("Tcp server crashed", e);
} finally {
if (server != null) {
try {
server.close();
}
catch(IOException e) {
logError("Could not close server", e);
}
}
}
}
}
|
// ClassUtils.java
package imagej.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* Useful methods for working with {@link Class} objects and primitive types.
*
* @author Curtis Rueden
*/
public final class ClassUtils {
private ClassUtils() {
// prevent instantiation of utility class
}
// -- Type conversion and casting --
/**
* Converts the given object to an object of the specified type. The object is
* casted directly if possible, or else a new object is created using the
* destination type's public constructor that takes the original object as
* input (except when converting to {@link String}, which uses the
* {@link Object#toString()} method instead). In the case of primitive types,
* returns an object of the corresponding wrapped type. If the destination
* type does not have an appropriate constructor, returns null.
*
* @param <T> Type to which the object should be converted.
* @param value The object to convert.
* @param type Type to which the object should be converted.
*/
public static <T> T convert(final Object value, final Class<T> type) {
if (value == null) return getNullValue(type);
// ensure type is well-behaved, rather than a primitive type
final Class<T> saneType = getNonprimitiveType(type);
// cast the existing object, if possible
if (canCast(value, saneType)) return cast(value, saneType);
// special cases for strings
if (value instanceof String) {
// source type is String
final String s = (String) value;
if (s.isEmpty()) {
// return null for empty strings
return getNullValue(type);
}
// use first character when converting to Character
if (saneType == Character.class) {
final Character c = new Character(s.charAt(0));
@SuppressWarnings("unchecked")
final T result = (T) c;
return result;
}
}
if (saneType == String.class) {
// destination type is String; use Object.toString() method
final String sValue = value.toString();
@SuppressWarnings("unchecked")
final T result = (T) sValue;
return result;
}
// wrap the original object with one of the new type, using a constructor
try {
final Constructor<T> ctor = saneType.getConstructor(value.getClass());
return ctor.newInstance(value);
}
catch (final Exception e) {
// NB: Many types of exceptions; simpler to handle them all the same.
Log.warn("Cannot convert '" + value + "' to " + type.getName(), e);
}
return null;
}
/**
* Casts the given object to the specified type, or null if the types are
* incompatible.
*/
public static <T> T cast(final Object obj, final Class<T> type) {
if (!canCast(obj, type)) return null;
@SuppressWarnings("unchecked")
final T result = (T) obj;
return result;
}
/** Checks whether the given object can be cast to the specified type. */
public static boolean canCast(final Object obj, final Class<?> type) {
return (type.isAssignableFrom(obj.getClass()));
}
/**
* Returns the non-primitive {@link Class} closest to the given type.
* <p>
* Specifically, the following type conversions are done:
* <ul>
* <li>boolean.class becomes Boolean.class</li>
* <li>byte.class becomes Byte.class</li>
* <li>char.class becomes Character.class</li>
* <li>double.class becomes Double.class</li>
* <li>float.class becomes Float.class</li>
* <li>int.class becomes Integer.class</li>
* <li>long.class becomes Long.class</li>
* <li>short.class becomes Short.class</li>
* </ul>
* All other types are unchanged.
* </p>
*/
public static <T> Class<T> getNonprimitiveType(final Class<T> type) {
final Class<?> destType;
if (type == boolean.class) destType = Boolean.class;
else if (type == byte.class) destType = Byte.class;
else if (type == char.class) destType = Character.class;
else if (type == double.class) destType = Double.class;
else if (type == float.class) destType = Float.class;
else if (type == int.class) destType = Integer.class;
else if (type == long.class) destType = Long.class;
else if (type == short.class) destType = Short.class;
else destType = type;
@SuppressWarnings("unchecked")
final Class<T> result = (Class<T>) destType;
return result;
}
/**
* Gets the "null" value for the given type. For non-primitives, this will
* actually be null. For primitives, it will be zero for numeric types, false
* for boolean, and the null character for char.
*/
public static <T> T getNullValue(final Class<T> type) {
final Object defaultValue;
if (type == boolean.class) defaultValue = false;
else if (type == byte.class) defaultValue = (byte) 0;
else if (type == char.class) defaultValue = '\0';
else if (type == double.class) defaultValue = 0.0;
else if (type == float.class) defaultValue = 0f;
else if (type == int.class) defaultValue = 0;
else if (type == long.class) defaultValue = 0L;
else if (type == short.class) defaultValue = (short) 0;
else defaultValue = null;
@SuppressWarnings("unchecked")
final T result = (T) defaultValue;
return result;
}
// -- Class loading and reflection --
/** Loads the class with the given name, or null if it cannot be loaded. */
public static Class<?> loadClass(final String className) {
try {
return Class.forName(className);
}
catch (final ClassNotFoundException e) {
Log.error("Could not load class: " + className, e);
return null;
}
}
/** Checks whether a class with the given name exists. */
public static boolean hasClass(final String className) {
try {
Class.forName(className);
return true;
}
catch (final ClassNotFoundException e) {
return false;
}
}
/**
* Gets the specified field of the given class, or null if it does not exist.
*/
public static Field getField(final String className, final String fieldName) {
final Class<?> c = loadClass(className);
if (c == null) return null;
try {
return c.getDeclaredField(fieldName);
}
catch (final NoSuchFieldException e) {
Log.error("No such field: " + fieldName, e);
return null;
}
}
/**
* Gets the given field's value of the specified object instance, or null if
* the value cannot be obtained.
*/
public static Object getValue(final Field field, final Object instance) {
if ((instance == null) && (!Modifier.isStatic(field.getModifiers())))
return null;
try {
field.setAccessible(true);
return field.get(instance);
}
catch (final IllegalArgumentException e) {
Log.error(e);
return null;
}
catch (final IllegalAccessException e) {
Log.error(e);
return null;
}
}
/**
* Sets the given field's value of the specified object instance. Does nothing
* if the value cannot be set.
*/
public static void setValue(final Field field, final Object instance,
final Object value)
{
if (instance == null) return;
try {
field.setAccessible(true);
field.set(instance, convert(value, field.getType()));
}
catch (final IllegalArgumentException e) {
Log.error(e);
assert false;
}
catch (final IllegalAccessException e) {
Log.error(e);
assert false;
}
}
// -- Type querying --
public static boolean isBoolean(final Class<?> type) {
return type == boolean.class || Boolean.class.isAssignableFrom(type);
}
public static boolean isByte(final Class<?> type) {
return type == byte.class || Byte.class.isAssignableFrom(type);
}
public static boolean isCharacter(final Class<?> type) {
return type == char.class || Character.class.isAssignableFrom(type);
}
public static boolean isDouble(final Class<?> type) {
return type == double.class || Double.class.isAssignableFrom(type);
}
public static boolean isFloat(final Class<?> type) {
return type == float.class || Float.class.isAssignableFrom(type);
}
public static boolean isInteger(final Class<?> type) {
return type == int.class || Integer.class.isAssignableFrom(type);
}
public static boolean isLong(final Class<?> type) {
return type == long.class || Long.class.isAssignableFrom(type);
}
public static boolean isShort(final Class<?> type) {
return type == short.class || Short.class.isAssignableFrom(type);
}
public static boolean isNumber(final Class<?> type) {
return Number.class.isAssignableFrom(type) || type == byte.class ||
type == double.class || type == float.class || type == int.class ||
type == long.class || type == short.class;
}
public static boolean isText(final Class<?> type) {
return String.class.isAssignableFrom(type) || isCharacter(type);
}
}
|
package brooklyn.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Throwables;
import com.google.common.io.Closeables;
public class ResourceUtils {
private static final Logger log = LoggerFactory.getLogger(ResourceUtils.class);
ClassLoader loader = null;
String context = null;
/** context string used for errors */
public ResourceUtils(ClassLoader loader, String context) {
this.loader = loader;
this.context = context;
}
/** uses the classloader of the given object, and the phrase object's toString (preceded by the word 'for') as the context string used in errors */
public ResourceUtils(Object context) {
this(context==null ? null : context instanceof Class ? ((Class)context).getClassLoader() : context.getClass().getClassLoader(), context==null ? null : ""+context);
}
public ClassLoader getLoader() {
//TODO allow a sequence of loaders?
return (loader!=null ? loader : getClass().getClassLoader());
}
public InputStream getResourceFromUrl(String url) {
try {
if (url==null) throw new NullPointerException("Cannot read from null");
if (url=="") throw new NullPointerException("Cannot read from empty string");
String orig = url;
if (url.startsWith("classpath:")) {
url = url.substring(10);
while (url.startsWith("/")) url = url.substring(1);
URL u = getLoader().getResource(url);
try {
if (u!=null) return u.openStream();
else throw new IOException(url+" not found on classpath");
} catch (IOException e) {
//catch the above because both orig and modified url may be interesting
throw new IOException("Error accessing "+orig+": "+e, e);
}
}
if (url.matches("[A-Za-z]+:.*")) {
//looks like a URL
return new URL(url).openStream();
}
try {
//try as classpath reference, then as file
URL u = getLoader().getResource(url);
if (u!=null) return u.openStream();
if (url.startsWith("/")) {
//some getResource calls fail if argument starts with /
String urlNoSlash = url;
while (urlNoSlash.startsWith("/")) urlNoSlash = urlNoSlash.substring(1);
u = getLoader().getResource(urlNoSlash);
if (u!=null) return u.openStream();
// //Class.getResource can require a / (else it attempts to be relative) but Class.getClassLoader doesn't
// u = getLoader().getResource("/"+urlNoSlash);
// if (u!=null) return u.openStream();
}
File f = new File(url);
if (f.exists()) return new FileInputStream(f);
} catch (IOException e) {
//catch the above because both u and modified url will be interesting
throw new IOException("Error accessing "+orig+": "+e, e);
}
throw new IOException("'"+orig+"' not found on classpath or filesystem");
} catch (Exception e) {
if (context!=null)
throw new RuntimeException("Error getting resource for "+context+": "+e, e);
else throw new RuntimeException(e);
}
}
/** takes {@link #getResourceFromUrl(String)} and reads fully, into a string */
public String getResourceAsString(String url) {
try {
return readFullyString(getResourceFromUrl(url));
} catch (Exception e) {
log.warn("error reading "+url+(context==null?"":" "+context)+" (rethrowing): "+e);
throw Throwables.propagate(e);
}
}
public static String readFullyString(InputStream is) throws IOException {
return new String(readFullyBytes(is));
}
public static byte[] readFullyBytes(InputStream is) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(is, out);
return out.getBytes();
}
public static void copy(InputStream input, OutputStream output) throws IOException {
byte[] buf = new byte[1024];
int bytesRead = input.read(buf);
while (bytesRead != -1) {
output.write(buf, 0, bytesRead);
bytesRead = input.read(buf);
}
output.flush();
}
}
|
package cloud.swiftnode.kspam;
import cloud.swiftnode.kspam.abstraction.MockPlayer;
import cloud.swiftnode.kspam.abstraction.MockPlugin;
import cloud.swiftnode.kspam.abstraction.MockServer;
import cloud.swiftnode.kspam.listener.PlayerListener;
import cloud.swiftnode.kspam.listener.ServerListener;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.server.ServerListPingEvent;
import org.junit.Test;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class KSpamTest {
@Test
public void prcsTest() throws UnknownHostException, IllegalAccessException, NoSuchFieldException {
// Injection
Field serverField = Bukkit.class.getDeclaredField("server");
Field instField = KSpam.class.getDeclaredField("INSTANCE");
serverField.setAccessible(true);
instField.setAccessible(true);
serverField.set(null, new MockServer());
instField.set(null, new MockPlugin());
// Element
Player player = new MockPlayer();
InetAddress addr = InetAddress.getByAddress(new byte[]{12, 32, 12, 32});
// PlayerEvent
PlayerLoginEvent loginEvent = new PlayerLoginEvent(player, "12.32.12.32", addr);
PlayerJoinEvent joinEvent = new PlayerJoinEvent(player, "Test join");
PlayerQuitEvent quitEvent = new PlayerQuitEvent(player, "Test quit");
// ServerEvent
ServerListPingEvent pingEvent = new ServerListPingEvent(addr, "test motd", 1, 10);
// PlayerListener
PlayerListener playerListener = new PlayerListener();
playerListener.onLogin(loginEvent);
playerListener.onJoin(joinEvent);
playerListener.onQuit(quitEvent);
// ServerListener
ServerListener serverListener = new ServerListener();
serverListener.onPing(pingEvent);
}
}
|
package hudson.scm.browsers;
import hudson.model.Descriptor;
import hudson.scm.CVSChangeLogSet.CVSChangeLog;
import hudson.scm.CVSChangeLogSet.File;
import hudson.scm.CVSChangeLogSet.Revision;
import hudson.scm.CVSRepositoryBrowser;
import hudson.scm.RepositoryBrowser;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* {@link RepositoryBrowser} for CVS.
* @author Kohsuke Kawaguchi
*/
// See http://viewvc.tigris.org/source/browse/*checkout*/viewvc/trunk/docs/url-reference.html
public final class ViewCVS extends CVSRepositoryBrowser {
public final URL url;
/**
* @stapler-constructor
*/
public ViewCVS(URL url) throws MalformedURLException {
this.url = normalizeToEndWithSlash(url);
}
public URL getFileLink(File file) throws IOException {
return new URL(url,trimHeadSlash(file.getFullName())+param());
}
public URL getDiffLink(File file) throws IOException {
Revision r = new Revision(file.getRevision());
Revision p = r.getPrevious();
if(p==null) return null;
return new URL(getFileLink(file), file.getSimpleName()+".diff"+param().add("r1="+p).add("r2="+r));
}
/**
* No changeset support in ViewCVS.
*/
public URL getChangeSetLink(CVSChangeLog changeSet) throws IOException {
return null;
}
private QueryBuilder param() {
return new QueryBuilder(url.getQuery());
}
public Descriptor<RepositoryBrowser<?>> getDescriptor() {
return DESCRIPTOR;
}
public static final Descriptor<RepositoryBrowser<?>> DESCRIPTOR = new Descriptor<RepositoryBrowser<?>>(ViewCVS.class) {
public String getDisplayName() {
return "ViewCVS";
}
public ViewCVS newInstance(StaplerRequest req) throws FormException {
return req.bindParameters(ViewCVS.class,"viewcvs.");
}
};
private static final long serialVersionUID = 1L;
}
|
package com.intellij.execution.application;
import com.intellij.coverage.CoverageDataManager;
import com.intellij.coverage.CoverageSuite;
import com.intellij.coverage.DefaultCoverageFileProvider;
import com.intellij.diagnostic.logging.LogConfigurationPanel;
import com.intellij.execution.*;
import com.intellij.execution.configuration.EnvironmentVariablesComponent;
import com.intellij.execution.configurations.*;
import com.intellij.execution.configurations.coverage.CoverageEnabledConfiguration;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.junit.RefactoringListeners;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.util.JavaParametersUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.options.SettingsEditorGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.DefaultJDOMExternalizer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiMethodUtil;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
public class ApplicationConfiguration extends CoverageEnabledConfiguration implements RunJavaConfiguration, SingleClassConfiguration, RefactoringListenerProvider {
private static final Logger LOG = Logger.getInstance("com.intellij.execution.application.ApplicationConfiguration");
public String MAIN_CLASS_NAME;
public String VM_PARAMETERS;
public String PROGRAM_PARAMETERS;
public String WORKING_DIRECTORY;
public boolean ALTERNATIVE_JRE_PATH_ENABLED;
public String ALTERNATIVE_JRE_PATH;
public boolean ENABLE_SWING_INSPECTOR;
public String ENV_VARIABLES;
private Map<String,String> myEnvs = new LinkedHashMap<String, String>();
public boolean PASS_PARENT_ENVS = true;
public ApplicationConfiguration(final String name, final Project project, ApplicationConfigurationType applicationConfigurationType) {
super(name, new JavaRunConfigurationModule(project, true), applicationConfigurationType.getConfigurationFactories()[0]);
}
public void setMainClass(final PsiClass psiClass) {
setMainClassName(JavaExecutionUtil.getRuntimeQualifiedName(psiClass));
setModule(JavaExecutionUtil.findModule(psiClass));
}
public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException {
final JavaCommandLineState state = new MyJavaCommandLineState(env);
state.setConsoleBuilder(TextConsoleBuilderFactory.getInstance().createBuilder(getProject()));
return state;
}
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
SettingsEditorGroup<ApplicationConfiguration> group = new SettingsEditorGroup<ApplicationConfiguration>();
group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), new ApplicationConfigurable2(getProject()));
group.addEditor(ExecutionBundle.message("coverage.tab.title"), new ApplicationCoverageConfigurable(getProject()));
group.addEditor(ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel());
return group;
}
@Nullable
public String getGeneratedName() {
if (MAIN_CLASS_NAME == null) {
return null;
}
return JavaExecutionUtil.getPresentableClassName(MAIN_CLASS_NAME, getConfigurationModule());
}
public void setGeneratedName() {
setName(getGeneratedName());
}
public RefactoringElementListener getRefactoringElementListener(final PsiElement element) {
return RefactoringListeners.
getClassOrPackageListener(element, new RefactoringListeners.SingleClassConfigurationAccessor(this));
}
@Nullable
public PsiClass getMainClass() {
return getConfigurationModule().findClass(MAIN_CLASS_NAME);
}
public boolean isGeneratedName() {
if (MAIN_CLASS_NAME == null || MAIN_CLASS_NAME.length() == 0) {
return JavaExecutionUtil.isNewName(getName());
}
return Comparing.equal(getName(), getGeneratedName());
}
public String suggestedName() {
return ExecutionUtil.shortenName(JavaExecutionUtil.getShortClassName(MAIN_CLASS_NAME), 6) + ".main()";
}
public void setMainClassName(final String qualifiedName) {
final boolean generatedName = isGeneratedName();
MAIN_CLASS_NAME = qualifiedName;
if (generatedName) setGeneratedName();
}
public void checkConfiguration() throws RuntimeConfigurationException {
if (ALTERNATIVE_JRE_PATH_ENABLED){
if (ALTERNATIVE_JRE_PATH == null ||
ALTERNATIVE_JRE_PATH.length() == 0 ||
!JavaSdkImpl.checkForJre(ALTERNATIVE_JRE_PATH)){
throw new RuntimeConfigurationWarning(ExecutionBundle.message("jre.path.is.not.valid.jre.home.error.mesage", ALTERNATIVE_JRE_PATH));
}
}
final JavaRunConfigurationModule configurationModule = getConfigurationModule();
final PsiClass psiClass = configurationModule.checkModuleAndClassName(MAIN_CLASS_NAME, ExecutionBundle.message("no.main.class.specified.error.text"));
if (!PsiMethodUtil.hasMainMethod(psiClass)) {
throw new RuntimeConfigurationWarning(ExecutionBundle.message("main.method.not.found.in.class.error.message", MAIN_CLASS_NAME));
}
}
public void setProperty(final int property, final String value) {
switch (property) {
case PROGRAM_PARAMETERS_PROPERTY:
PROGRAM_PARAMETERS = value;
break;
case VM_PARAMETERS_PROPERTY:
VM_PARAMETERS = value;
break;
case WORKING_DIRECTORY_PROPERTY:
WORKING_DIRECTORY = ExternalizablePath.urlValue(value);
break;
default:
throw new RuntimeException("Unknown property: " + property);
}
}
public String getProperty(final int property) {
switch (property) {
case PROGRAM_PARAMETERS_PROPERTY:
return PROGRAM_PARAMETERS;
case VM_PARAMETERS_PROPERTY:
return VM_PARAMETERS;
case WORKING_DIRECTORY_PROPERTY:
return getWorkingDirectory();
default:
throw new RuntimeException("Unknown property: " + property);
}
}
@Override
public boolean canHavePerTestCoverage() {
return false;
}
private String getWorkingDirectory() {
return ExternalizablePath.localPathValue(WORKING_DIRECTORY);
}
public Collection<Module> getValidModules() {
return JavaRunConfigurationModule.getModulesForClass(getProject(), MAIN_CLASS_NAME);
}
protected ModuleBasedConfiguration createInstance() {
return new ApplicationConfiguration(getName(), getProject(), ApplicationConfigurationType.getInstance());
}
protected boolean isMergeDataByDefault() {
return true;
}
public void readExternal(final Element element) throws InvalidDataException {
super.readExternal(element);
DefaultJDOMExternalizer.readExternal(this, element);
readModule(element);
EnvironmentVariablesComponent.readExternal(element, getEnvs());
}
public void writeExternal(final Element element) throws WriteExternalException {
super.writeExternal(element);
DefaultJDOMExternalizer.writeExternal(this, element);
writeModule(element);
EnvironmentVariablesComponent.writeExternal(element, getEnvs());
}
public Map<String, String> getEnvs() {
return myEnvs;
}
public void setEnvs(final Map<String, String> envs) {
this.myEnvs = envs;
}
private class MyJavaCommandLineState extends JavaCommandLineState {
private CoverageSuite myCurrentCoverageSuite;
public MyJavaCommandLineState(final ExecutionEnvironment environment) {
super(environment);
}
protected JavaParameters createJavaParameters() throws ExecutionException {
final JavaParameters params = new JavaParameters();
params.setupEnvs(getEnvs(), PASS_PARENT_ENVS);
final int classPathType = JavaParametersUtil.getClasspathType(getConfigurationModule(), MAIN_CLASS_NAME, false);
JavaParametersUtil.configureModule(getConfigurationModule(), params, classPathType, ALTERNATIVE_JRE_PATH_ENABLED ? ALTERNATIVE_JRE_PATH : null);
JavaParametersUtil.configureConfiguration(params, ApplicationConfiguration.this);
params.setMainClass(MAIN_CLASS_NAME);
for(RunConfigurationExtension ext: Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
if (ext instanceof JavaRunConfigurationExtension) {
((JavaRunConfigurationExtension)ext).updateJavaParameters(ApplicationConfiguration.this, params);
}
}
if (!(getRunnerSettings().getData() instanceof DebuggingRunnerData) && isCoverageEnabled()) {
final String coverageFileName = getCoverageFilePath();
final long lastCoverageTime = System.currentTimeMillis();
String name = getName();
if (name == null) name = getGeneratedName();
final CoverageDataManager coverageDataManager = CoverageDataManager.getInstance(getProject());
myCurrentCoverageSuite = coverageDataManager.addCoverageSuite(
name,
new DefaultCoverageFileProvider(coverageFileName),
getPatterns(),
lastCoverageTime,
getSuiteToMergeWith(), getCoverageRunner(), isTrackPerTestCoverage() && !isSampling(), !isSampling());
appendCoverageArgument(params);
}
return params;
}
@Override
protected OSProcessHandler startProcess() throws ExecutionException {
final OSProcessHandler handler = super.startProcess();
for(RunConfigurationExtension ext: Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
ext.handleStartProcess(ApplicationConfiguration.this, handler);
}
handler.addProcessListener(new ProcessAdapter() {
public void processTerminated(final ProcessEvent event) {
final CoverageDataManager coverageDataManager = CoverageDataManager.getInstance(getProject());
if (myCurrentCoverageSuite != null) {
coverageDataManager.coverageGathered(myCurrentCoverageSuite);
}
}
});
return handler;
}
}
}
|
package com.github.jsonj;
import static com.github.jsonj.tools.JsonBuilder.array;
import static com.github.jsonj.tools.JsonBuilder.field;
import static com.github.jsonj.tools.JsonBuilder.fromObject;
import static com.github.jsonj.tools.JsonBuilder.nullValue;
import static com.github.jsonj.tools.JsonBuilder.object;
import static com.github.jsonj.tools.JsonBuilder.primitive;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertTrue;
import com.github.jsonj.exceptions.JsonTypeMismatchException;
import com.github.jsonj.tools.JsonBuilder;
import com.jillesvangurp.efficientstring.EfficientString;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test
public class JsonObjectTest {
@DataProvider
public Object[][] equalPairs() {
return new Object[][] {
{ object().put("a", object().put("b", object().put("c", "d").get()).get()).get(),
object().put("a", object().put("b", object().put("c", "d").get()).get()).get() },
{ object().get(), object().get() },
{ object().put("a", "a").put("b", 42).put("c", true).put("d", array("foo", "bar")).put("e", primitive((String) null)).get(),
object().put("b", 42).put("a", "a").put("c", true).put("d", array("foo", "bar")).put("e", primitive((String) null)).get() } };
}
@Test(dataProvider = "equalPairs")
public void shouldBeEqualToSelf(final JsonObject left, final JsonObject right) {
Assert.assertTrue(left.equals(left)); // reflexive
Assert.assertTrue(right.equals(right)); // reflexive
Assert.assertTrue(left.equals(right)); // symmetric
Assert.assertTrue(right.equals(left)); // symmetric
}
@Test(dataProvider="equalPairs")
public void shouldHaveSameHashCode(final JsonObject left, final JsonObject right) {
Assert.assertEquals(left.hashCode(), right.hashCode());
}
@DataProvider
public Object[][] unEqualPairs() {
return new Object[][] {
{ object().put("a", "b").get(),
object().put("a", "b").put("b", 42).get() },
{ object().put("a", "b").get(), null },
{ object().put("a", "b").get(), primitive(42) },
{ object().put("a", 42).get(), object().put("a", 41).get() } };
}
@Test(dataProvider = "unEqualPairs")
public void shouldNotBeEqual(final JsonObject o, final JsonElement e) {
Assert.assertNotSame(o, e);
}
public void shouldExtractValue() {
JsonObject o = object().put("a",
object().put("b", object().put("c", "d").get()).get()).get();
Assert.assertEquals("d", o.get("a", "b", "c").asPrimitive().asString());
assertThat(o.maybeGet("a", "b", "c").isPresent()).isTrue();
assertThat(o.maybeGetString("a", "b", "c").get()).isEqualTo("d");
}
public void shouldCreateArray() {
JsonObject object = new JsonObject();
JsonArray createdArray = object.getOrCreateArray("a","b","c");
createdArray.add("1");
Assert.assertTrue(object.getArray("a","b","c").contains("1"), "array should have been added to the object");
}
public void shouldReturnExistingArray() {
JsonObject object = object().put("a", object().put("b", array("foo")).get()).get();
Assert.assertTrue(object.getOrCreateArray("a","b").contains("foo"));
}
@Test(expectedExceptions=JsonTypeMismatchException.class)
public void shouldThrowExceptionOnElementThatIsNotAnArray() {
JsonObject object = object().put("a", object().put("b", 42).get()).get();
object.getOrCreateArray("a","b");
}
public void shouldCreateObject() {
JsonObject object = new JsonObject();
JsonObject createdObject = object.getOrCreateObject("a","b","c");
createdObject.put("foo", "bar");
Assert.assertTrue(object.getString("a","b","c", "foo").equals("bar"), "object should have been added");
}
public void shouldReturnExistingObject() {
JsonObject object = object().put("a", object().put("b", object().put("foo","bar").get()).get()).get();
JsonObject orCreateObject = object.getOrCreateObject("a","b");
Assert.assertTrue(orCreateObject.getString("foo").equals("bar"), "return the object with foo=bar");
}
@Test(expectedExceptions=JsonTypeMismatchException.class)
public void shouldThrowExceptionOnElementThatIsNotAnObject() {
JsonObject object = object().put("a", object().put("b", 42).get()).get();
object.getOrCreateObject("a","b");
}
public void shouldDoDeepClone() {
JsonObject o = object().put("1", 42).put("2", "Hello world").get();
JsonObject cloneOfO = o.deepClone();
Assert.assertTrue(o.equals(cloneOfO));
o.remove("1");
Assert.assertFalse(o.equals(cloneOfO));
o.put("1", cloneOfO);
Object clone = o.clone();
Assert.assertTrue(o.equals(clone));
cloneOfO.remove("2");
Assert.assertFalse(o.equals(clone));
}
public void shouldRemoveEmptyElements() {
JsonObject jsonObject = object().put("empty", object().get()).put("empty2", nullValue()).put("empty3", new JsonArray()).get();
jsonObject.removeEmpty();
assertThat("should leave empty objects",jsonObject.getObject("empty"), is(object().get()));
Assert.assertEquals(jsonObject.get("empty2"), null);
Assert.assertEquals(jsonObject.get("empty3"), null);
}
public void shouldReturn2ndEntry() {
assertThat(object().put("1", 1).put("2", 2).put("3", 3).get().get(1).getValue(), is((JsonElement)primitive(2)));
}
public void shouldReturnFirstEntry() {
assertThat(object().put("1", 1).put("2", 2).put("3", 3).get().first().getValue(), is((JsonElement)primitive(1)));
}
public void shouldSupportJavaSerialization() throws IOException, ClassNotFoundException {
JsonObject object = object().put("42",42).get();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.close();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
Object object2 = ois.readObject();
assertTrue(object.equals(object2));
}
public void shouldPutBuilder() {
JsonBuilder builder = object().put("foo", "bar");
JsonObject object1 = object().put("foobar",builder).get();
JsonObject object2 = new JsonObject();
object2.put("foobar", builder);
JsonObject object3 = new JsonObject();
object3.put("foobar", fromObject(builder));
assertThat(object1, is(object2));
assertThat(object1, is(object3));
assertThat(object1.toString(), is("{\"foobar\":{\"foo\":\"bar\"}}"));
}
public void shouldHandleJsonNullsOnGet() {
JsonObject o = object().put("x", JsonPrimitive.JSON_NULL).get();
// should return the json null
assertThat((JsonPrimitive)o.get("x"), CoreMatchers.notNullValue());
// these should all return a java null
assertThat(o.getInt("x"), CoreMatchers.nullValue());
assertThat(o.getLong("x"), CoreMatchers.nullValue());
assertThat(o.getFloat("x"), CoreMatchers.nullValue());
assertThat(o.getDouble("x"), CoreMatchers.nullValue());
assertThat(o.getBoolean("x"), CoreMatchers.nullValue());
assertThat(o.getString("x"), CoreMatchers.nullValue());
assertThat(o.getArray("x"), CoreMatchers.nullValue());
assertThat(o.getObject("x"), CoreMatchers.nullValue());
}
public void shouldAllowPutOfNullValue() {
JsonElement x=null;
JsonObject o = object().put("x", x).get();
assertThat(o.getInt("x"), CoreMatchers.nullValue());
}
public void shouldAddFields() {
JsonObject object = object(field("meaningoflife", 42), field("foo", primitive("bar")), field("list",array("stuff")));
assertThat(object.getInt("meaningoflife"), is(42));
assertThat(object.getString("foo"), is("bar"));
assertThat(object.getArray("list").get(0).asString(), is("stuff"));
}
// public void shouldAddFieldsShortNotation() {
// JsonObject object = $(
// _("meaningoflife", 42),
// _("foo", primitive("bar")),
// _("list",$("stuff"))
// assertThat(object.getInt("meaningoflife"), is(42));
// assertThat(object.getString("foo"), is("bar"));
// assertThat(object.getArray("list").get(0).asString(), is("stuff"));
public void shouldSupportConcurrentlyCreatingNewKeys() throws InterruptedException {
// note. this test did never actually trigger the race condition so only limited confidence here.
// this is the best I've come up with so far for actually triggering the conditions this breaks
int factor = 666;
int startIndex = EfficientString.nextIndex();
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(20);
final JsonObject o = new JsonObject();
// this should create some potential for the race condition to trigger since it rapidly creates the same keys
int total = 100000;
for(int i=0;i<total;i++) {
// make sure we are actually creating new Strings with no overlap with the other tests
final String str="shouldSupportConcurrentlyCreatingNewKeys-"+ i/factor;
executorService.execute(() -> {
o.put(str, str); // this should never fail with null key because of the (hopefully) now fixed EfficientString
EfficientString e = EfficientString.fromString(str);
assertThat(EfficientString.fromString(str), is(e));
});
}
executorService.shutdown();
executorService.awaitTermination(2, TimeUnit.SECONDS);
// check greater than so that it won't clash with concurrent executions of other tests in surefire
assertThat(EfficientString.nextIndex()-startIndex, Matchers.greaterThan(total/factor));
}
public void shouldGetPrimitiveDefaultValues() {
JsonObject object = object().get();
assertThat(object.get("field", 42), is(42));
assertThat(object.get("field", 42l), is(42l));
assertThat(object.get("field", 42.0), is(42.0));
assertThat(object.get("field", 42.0f), is(42.0f));
assertThat(object.get("field", true), is(true));
}
public void shouldGetPrimitiveNumber() {
JsonObject object = object(field("field",42));
assertThat(object.get("field", 1), is(42));
assertThat(object.get("field", 1l), is(42l));
assertThat(object.get("field", 1.0), is(42.0));
assertThat(object.get("field", 1.0f), is(42.0f));
assertThat(object.get("field", false), is(true));
}
public void shouldConvertFieldToSet() {
JsonObject object = object(field("f", array(1,1,1,1,1)));
assertThat(object.getOrCreateArray("f").size(), is(5));
assertThat(object.getOrCreateSet("f").size(), is(1));
assertThat(object.getArray("f").size(), is(1));
object.getArray("f").add(1);
assertThat(object.getArray("f").size(), is(1));
}
@Test(expectedExceptions=IllegalStateException.class)
public void shouldNotAllowMutations() {
JsonObject object = object(field("f", array(1,1,1,1,1)));
JsonObject clone = object.immutableClone();
assertThat(clone).isEqualTo(object);
clone.put("x", "y");
}
@Test(expectedExceptions=IllegalStateException.class)
public void shouldNotAllowMutationsOnArrayInObject() {
JsonObject object = object(field("f", array(1,1,1,1,1)));
JsonObject clone = object.immutableClone();
assertThat(clone).isEqualTo(object);
clone.getArray("f").add(1);
}
@Test(expectedExceptions=IllegalStateException.class)
public void shouldNotAllowMutationsOnObjectInObject() {
JsonObject object = object(field("f", object(field("1",1))));
JsonObject clone = object.immutableClone();
assertThat(clone).isEqualTo(object);
clone.getObject("f").put("2",2);
}
public void shouldPutJsonDataObject() {
JsonDataObject jdo = new JsonDataObject() {
private static final long serialVersionUID = 1L;
@Override
public JsonObject getJsonObject() {
return object(field("foo","bar"));
}
};
JsonObject o = object(field("x",42));
o.put("jdo", jdo);
assertThat(o.getString("jdo","foo")).isEqualTo("bar");
}
public void shouldConvertSimpleHashMapToJsonObject() {
Map<String,String> simpleMap=new HashMap<>();
simpleMap.put("one", "xxxxx");
simpleMap.put("two", "xxxxx");
simpleMap.put("three", "xxxxx");
JsonObject object = new JsonObject(simpleMap);
assertThat(object.getString("one")).isEqualTo("xxxxx");
}
public void shouldSupportOptional() {
JsonObject o = object(
field("o1", Optional.of(1)),
field("o2", Optional.empty())
);
o.put("o3", Optional.of(array(1,2,3)));
System.err.println(o.prettyPrint());
assertThat(o.get("o1").isNumber()).isTrue();
assertThat(o.get("o2").isNull()).isTrue();
assertThat(o.get("o3").isArray()).isTrue();
}
public void shouldFlatten() {
JsonObject obj = object(field("x", object(field("y", array(primitive(1),primitive(2),object(field("foo","bar")))))));
JsonObject flattened = obj.flatten(":");
assertThat(flattened.getInt("x:y:0")).isEqualTo(1);
assertThat(flattened.getInt("x:y:1")).isEqualTo(2);
assertThat(flattened.getString("x:y:2:foo")).isEqualTo("bar");
}
public void shouldHandleBooleanOnLongField() {
JsonObject o = object(field("deleted",1l));
assertThat(o.get("deleted",false)).isTrue();
o.put("deleted", 0);
assertThat(o.get("deleted",false)).isFalse();
o.put("deleted", true);
assertThat(o.get("deleted",false)).isTrue();
}
}
|
package com.google.sps.image;
import java.util.List;
import java.util.Set;
/** Similar to ImageScorer, but for testing purposes. */
public final class LocalImageScorer {
private static final float LANDMARK_SCORE = 0.8f;
private static final float LOGO_SCORE = 0.5f;
private static final float OCR_SCORE = 0.1f;
private static final float LABEL_SCORE = 0.2f;
private static final double EPS = 1e-5;
private String[] keywords;
private Analyser label;
private Analyser landmark;
private Analyser ocr;
private Analyser logo;
public LocalImageScorer(String[] keywords) {
label = new LabelAnalyser();
landmark = new LandmarkAnalyser();
ocr = new OcrAnalyser();
logo = new LogoAnalyser();
this.keywords = keywords;
}
private float landmarkScore(String imagePath) {
List<String> landmarkElements = landmark.analyseStoredImage(imagePath);
if (!landmarkElements.isEmpty()) {
return LANDMARK_SCORE;
}
return 0;
}
private float logoScore(String imagePath) {
List<String> logoElements = logo.analyseStoredImage(imagePath);
if (!logoElements.isEmpty()) {
for (String keyword : keywords) {
if (logoElements.contains(keyword)) {
return LOGO_SCORE;
}
}
}
return 0;
}
private float ocrScore(String imagePath) {
List<String> ocrElements = ocr.analyseStoredImage(imagePath);
if (ocrElements.size() > 0) {
return -OCR_SCORE;
}
return 0;
}
private float labelScore(String imagePath) {
float score = 0;
List<String> labelElements = label.analyseStoredImage(imagePath);
if (!labelElements.isEmpty()) {
for (String keyword : keywords) {
if (labelElements.contains(keyword)) {
score += LABEL_SCORE;
}
}
}
return score;
}
/**
* The algorithm that scores images.
* @param imagePath link of image that needs to be scored.
*/
public float score(String imagePath) {
float imageScore = landmarkScore(imagePath);
float logo = logoScore(imagePath);
if (logo < EPS) {
imageScore += ocrScore(imagePath);
if (imageScore < 0) {
return imageScore;
}
} else {
imageScore += logo;
}
imageScore += labelScore(imagePath);
return imageScore;
}
}
|
package de.charite.compbio.exomiser.core.model;
import java.util.ArrayList;
import java.util.List;
import org.thymeleaf.util.StringUtils;
import com.google.common.base.Joiner;
import de.charite.compbio.jannovar.annotation.Annotation;
import de.charite.compbio.jannovar.annotation.AnnotationList;
import de.charite.compbio.jannovar.annotation.AnnotationLocation;
import de.charite.compbio.jannovar.annotation.VariantEffect;
import de.charite.compbio.jannovar.reference.GenomeChange;
import de.charite.compbio.jannovar.reference.GenomePosition;
import de.charite.compbio.jannovar.reference.Strand;
import htsjdk.variant.variantcontext.Allele;
import htsjdk.variant.variantcontext.Genotype;
import htsjdk.variant.variantcontext.VariantContext;
/**
* Collects information about one allele in a VCF variant, together with its
* Jannovar Annotation.
*
* @author Manuel Holtgrewe <manuel.holtgrewe@charite.de>
*/
public class Variant {
// HTSJDK {@link VariantContext} instance of this allele
private final VariantContext variantContext;
// numeric index of the alternative allele in {@link
private final int altAlleleID;
/**
* list of {@link Annotation}s for this variant context, one for each
* affected transcript, and sorted by predicted impact, highest first.
*/
private final AnnotationList annotationList;
/**
* shortcut to the {@link GenomeChange} in the first element of
* {@link #annotationList}, or null.
*/
private final GenomeChange genomeChange;
public Variant(VariantContext variantContext, int altAlleleID, GenomeChange genomeChange, AnnotationList annotationList) {
this.variantContext = variantContext;
this.altAlleleID = altAlleleID;
this.annotationList = annotationList;
this.genomeChange = genomeChange;
}
public VariantContext getVariantContext() {
return variantContext;
}
public int getAltAlleleID() {
return altAlleleID;
}
public GenomeChange getGenomeChange() {
return genomeChange;
}
public AnnotationList getAnnotationList() {
return annotationList;
}
/**
* @return forward strand {@link GenomePosition}
*/
public GenomePosition getGenomePosition() {
return genomeChange.pos.withStrand(Strand.FWD);
}
/**
* Shortcut to <code>change.pos.chr</code>
*
* @return <code>int</code> representation of chromosome
*/
public int getChromosome() {
return genomeChange.getChr();
}
/**
* @return String representation of {@link #genomeChange}/
*/
public String getChromosomalVariant() {
// Change can be null for unknown references. In this case, we hack together something from the Variant Context.
//TODO: change should never be null - it should be constructed from the VariantContext
if (genomeChange != null) {
return genomeChange.toString();
} else {
return StringUtils.concat(variantContext.getChr(), ":g.", variantContext.getStart(), variantContext.getReference(), ">",
variantContext.getAlternateAllele(altAlleleID));
}
}
/**
* Shortcut to <code>change.pos.pos + 1</code>.
*
* Returns a 1-based coordinate (as used in the Exomiser) instead of the
* 0-based coordinates from Jannovar.
*
* @return one-based position
*/
public int getPosition() {
if (genomeChange.getRef().equals("")) {
// return change.pos.withStrand(Strand.FWD).pos;
return genomeChange.getPos();
} else {
return genomeChange.getPos() + 1;
}
}
/**
* Shortcut to {@link #change.ref}, returning "-" in case of insertions.
*/
public String getRef() {
// if (change.ref.equals("")) {
if (genomeChange.getRef().equals("")) {
return "-";
} else {
// return change.withStrand('+').ref;
return genomeChange.getRef();
}
}
/**
* Shortcut to {@link #change.alt}, returning "-" in case of deletions.
*/
public String getAlt() {
if (genomeChange.getAlt().equals("")) {
return "-";
} else {
return genomeChange.getAlt();
}
}
/**
* @return most pathogenic {@link VariantEffect}
*/
public VariantEffect getVariantEffect() {
return annotationList.getHighestImpactEffect();
}
/**
* @return <code>true</code> if the variant is neither exonic nor splicing
*/
public boolean isOffExome() {
return annotationList.getHighestImpactEffect().isOffExome();
}
public int getReadDepth() {
// FIXME: alleleID != sample ID!
return variantContext.getGenotype(altAlleleID).getDP();
}
/**
* @return annotation of the most pathogenic annotation
*/
public String getRepresentativeAnnotation() {
Annotation anno = annotationList.getHighestImpactAnnotation();
if (anno == null) {
return "?";
}
String exonIntron = null;
if (anno.annoLoc != null && anno.annoLoc.rankType == AnnotationLocation.RankType.EXON) {
exonIntron = StringUtils.concat("exon", anno.annoLoc.rank + 1);
} else if (anno.annoLoc != null && anno.annoLoc.rankType == AnnotationLocation.RankType.INTRON) {
exonIntron = StringUtils.concat("intron", anno.annoLoc.rank + 1);
}
final Joiner joiner = Joiner.on(":").skipNulls();
return joiner.join(anno.getGeneSymbol(), anno.transcript.accession, exonIntron, anno.ntHGVSDescription,
anno.aaHGVSDescription);
}
/**
* @return list of all annotation strings
*/
public List<String> getAnnotations() {
ArrayList<String> result = new ArrayList<>();
for (Annotation anno : annotationList) {
String annoS = anno.getSymbolAndAnnotation();
if (annoS != null) {
result.add(annoS);
}
}
return result;
}
/**
* @return list of all annotation strings with type prepended
*/
public List<String> getAnnotationsWithAnnotationClass() {
List<String> result = new ArrayList<>();
for (Annotation anno : annotationList) {
result.add(anno.getMostPathogenicVarType() + "|" + anno.getSymbolAndAnnotation());
}
return result;
}
public boolean isXChromosomal() {
return getChromosome() == genomeChange.pos.refDict.contigID.get("X").intValue();
}
public boolean isYChromosomal() {
return getChromosome() == genomeChange.pos.refDict.contigID.get("Y").intValue();
}
public double getPhredScore() {
return variantContext.getPhredScaledQual();
}
public String getGeneSymbol() {
final Annotation anno = annotationList.getHighestImpactAnnotation();
return anno.getGeneSymbol();
}
public String getGenotypeAsString() {
// collect genotype string list
ArrayList<String> gtStrings = new ArrayList<String>();
for (Genotype gt : variantContext.getGenotypes()) {
boolean firstAllele = true;
StringBuilder builder = new StringBuilder();
for (Allele allele : gt.getAlleles()) {
if (firstAllele) {
firstAllele = false;
} else {
builder.append('/');
}
if (allele.isNoCall()) {
builder.append('.');
} else if (allele.equals(variantContext.getAlternateAllele(altAlleleID))) {
builder.append('1');
} else {
builder.append('0');
}
}
gtStrings.add(builder.toString());
}
// normalize 1/0 to 0/1 and join genotype strings with colon
for (int i = 0; i < gtStrings.size(); ++i) {
if (gtStrings.get(i).equals("1/0")) {
gtStrings.set(i, "0/1");
}
}
return Joiner.on(":").join(gtStrings);
}
public int getEntrezGeneID() {
final Annotation anno = annotationList.getHighestImpactAnnotation();
if (anno == null || anno.transcript == null || anno.transcript.geneID == null) {
return -1;
}
// The gene ID is of the form "${NAMESPACE}${NUMERIC_ID}" where "NAMESPACE" is "ENTREZ"
// for UCSC. At this point, there is a hard dependency on using the UCSC database.
return Integer.parseInt(anno.transcript.geneID.substring("ENTREZ".length()));
}
public Genotype getGenotype() {
return variantContext.getGenotype(0);
}
@Override
public String toString() {
return "Variant [vc=" + variantContext + ", altAlleleID=" + altAlleleID + ", annotations=" + annotationList + ", change="
+ genomeChange + "]";
}
}
|
package tech.tablesaw.io;
import static tech.tablesaw.api.ColumnType.SKIP;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.univocity.parsers.common.AbstractParser;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.tablesaw.api.ColumnType;
import tech.tablesaw.api.Table;
import tech.tablesaw.columns.AbstractColumnParser;
import tech.tablesaw.columns.Column;
public abstract class FileReader {
private static Logger logger = LoggerFactory.getLogger(FileReader.class);
public FileReader() {}
/**
* Returns an array containing the inferred columnTypes for the file being read, as calculated by
* the ColumnType inference logic. These types may not be correct.
*/
public ColumnType[] getColumnTypes(
Reader reader, ReadOptions options, int linesToSkip, AbstractParser<?> parser) {
parser.beginParsing(reader);
for (int i = 0; i < linesToSkip; i++) {
parser.parseNext();
}
ColumnTypeDetector detector = new ColumnTypeDetector(options.columnTypesToDetect());
return detector.detectColumnTypes(
new Iterator<String[]>() {
String[] nextRow = parser.parseNext();
@Override
public boolean hasNext() {
return nextRow != null;
}
@Override
public String[] next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
String[] tmp = nextRow;
nextRow = parser.parseNext();
return tmp;
}
},
options);
}
private String cleanName(String name) {
return name.trim();
}
/** Returns the column names for each column in the source. */
public String[] getColumnNames(
ReadOptions options, ColumnType[] types, AbstractParser<?> parser) {
if (options.header()) {
String[] headerNames = parser.parseNext();
// work around issue where Univocity returns null if a column has no header.
for (int i = 0; i < headerNames.length; i++) {
if (headerNames[i] == null) {
headerNames[i] = "C" + i;
} else {
headerNames[i] = headerNames[i].trim();
}
}
return headerNames;
} else {
// Placeholder column names for when the file read has no header
String[] headerNames = new String[types.length];
for (int i = 0; i < types.length; i++) {
headerNames[i] = "C" + i;
}
return headerNames;
}
}
protected Table parseRows(
ReadOptions options,
boolean headerOnly,
Reader reader,
ColumnType[] types,
AbstractParser<?> parser) {
parser.beginParsing(reader);
Table table = Table.create(options.tableName());
List<String> headerRow = Lists.newArrayList(getColumnNames(options, types, parser));
for (int x = 0; x < types.length; x++) {
if (types[x] != SKIP) {
String columnName = cleanName(headerRow.get(x));
if (Strings.isNullOrEmpty(columnName)) {
columnName = "Column " + table.columnCount();
}
Column<?> newColumn = types[x].create(columnName);
table.addColumns(newColumn);
}
}
if (!headerOnly) {
String[] columnNames = selectColumnNames(headerRow, types);
int[] columnIndexes = new int[columnNames.length];
for (int i = 0; i < columnIndexes.length; i++) {
// get the index in the original table, which includes skipped fields
columnIndexes[i] = headerRow.indexOf(columnNames[i]);
}
addRows(options, types, parser, table, columnIndexes);
}
return table;
}
private void addRows(
ReadOptions options,
ColumnType[] types,
AbstractParser<?> reader,
Table table,
int[] columnIndexes) {
String[] nextLine;
Map<String, AbstractColumnParser<?>> parserMap = getParserMap(options, table);
// Add the rows
for (long rowNumber = options.header() ? 1L : 0L;
(nextLine = reader.parseNext()) != null;
rowNumber++) {
// validation
if (nextLine.length < types.length) {
if (nextLine.length == 1 && Strings.isNullOrEmpty(nextLine[0])) {
logger.error("Warning: Invalid file. Row " + rowNumber + " is empty. Continuing.");
continue;
} else {
Exception e =
new IndexOutOfBoundsException(
"Row number "
+ rowNumber
+ " contains "
+ nextLine.length
+ " columns. "
+ types.length
+ " expected.");
throw new AddCellToColumnException(e, 0, rowNumber, table.columnNames(), nextLine);
}
} else if (nextLine.length > types.length) {
throw new IllegalArgumentException(
"Row number "
+ rowNumber
+ " contains "
+ nextLine.length
+ " columns. "
+ types.length
+ " expected.");
}
// append each column that we're including (not skipping)
int cellIndex = 0;
for (int columnIndex : columnIndexes) {
Column<?> column = table.column(cellIndex);
AbstractColumnParser<?> parser = parserMap.get(column.name());
try {
String value = nextLine[columnIndex];
column.appendCell(value, parser);
} catch (Exception e) {
throw new AddCellToColumnException(
e, columnIndex, rowNumber, table.columnNames(), nextLine);
}
cellIndex++;
}
}
}
private Map<String, AbstractColumnParser<?>> getParserMap(ReadOptions options, Table table) {
Map<String, AbstractColumnParser<?>> parserMap = new HashMap<>();
for (Column<?> column : table.columns()) {
AbstractColumnParser<?> parser = column.type().customParser(options);
parserMap.put(column.name(), parser);
}
return parserMap;
}
/** Reads column names from header, skipping any for which the type == SKIP */
private String[] selectColumnNames(List<String> names, ColumnType[] types) {
List<String> header = new ArrayList<>();
for (int i = 0; i < types.length; i++) {
if (types[i] != SKIP) {
String name = names.get(i);
name = name.trim();
header.add(name);
}
}
String[] result = new String[header.size()];
return header.toArray(result);
}
protected String getTypeString(Table structure) {
StringBuilder buf = new StringBuilder();
buf.append("ColumnType[] columnTypes = {");
buf.append(System.lineSeparator());
Column<?> typeCol = structure.column("Column Type");
Column<?> indxCol = structure.column("Index");
Column<?> nameCol = structure.column("Column Name");
// add the column headers
int typeColIndex = structure.columnIndex(typeCol);
int indxColIndex = structure.columnIndex(indxCol);
int nameColIndex = structure.columnIndex(nameCol);
int typeColWidth = typeCol.columnWidth();
int indxColWidth = indxCol.columnWidth();
int nameColWidth = nameCol.columnWidth();
final char padChar = ' ';
for (int r = 0; r < structure.rowCount(); r++) {
String cell = Strings.padEnd(structure.get(r, typeColIndex) + ",", typeColWidth, padChar);
buf.append(cell);
buf.append("
cell = Strings.padEnd(structure.getUnformatted(r, indxColIndex), indxColWidth, padChar);
buf.append(cell);
buf.append(' ');
cell = Strings.padEnd(structure.getUnformatted(r, nameColIndex), nameColWidth, padChar);
buf.append(cell);
buf.append(' ');
buf.append(System.lineSeparator());
}
buf.append("}");
buf.append(System.lineSeparator());
return buf.toString();
}
}
|
package com.jcabi.github;
import com.jcabi.aspects.Tv;
import java.util.Iterator;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assume;
import org.junit.Test;
/**
* Test case for {@link RtSearch}.
*
* @author Carlos Miranda (miranda.cma@gmail.com)
* @version $Id$
* @checkstyle MultipleStringLiterals (41 lines)
*/
public final class RtSearchITCase {
/**
* RtSearch can search for repos.
*
* @throws Exception if a problem occurs
*/
@Test
public void canSearchForRepos() throws Exception {
MatcherAssert.assertThat(
RtSearchITCase.github().search().repos("repo", "stars", "desc"),
Matchers.not(Matchers.emptyIterableOf(Repo.class))
);
}
/**
* RtSearch can fetch multiple pages of a large result (more than 25 items).
*
* @throws Exception if a problem occurs
*/
@Test
public void canFetchMultiplePages() throws Exception {
final Iterator<Repo> iter = RtSearchITCase.github().search().repos(
"java", "", ""
).iterator();
int count = 0;
while (iter.hasNext() && count < Tv.HUNDRED) {
iter.next();
count += 1;
}
MatcherAssert.assertThat(
count,
Matchers.greaterThanOrEqualTo(Tv.HUNDRED)
);
}
/**
* RtSearch can search for issues.
*
* @throws Exception if a problem occurs
*/
@Test
public void canSearchForIssues() throws Exception {
MatcherAssert.assertThat(
RtSearchITCase.github().search().issues("issue", "updated", "desc"),
Matchers.not(Matchers.emptyIterableOf(Issue.class))
);
}
/**
* RtSearch can search for users.
*
* @throws Exception if a problem occurs
*/
@Test
public void canSearchForUsers() throws Exception {
MatcherAssert.assertThat(
RtSearchITCase.github().search().users("jcabi", "joined", "desc"),
Matchers.not(Matchers.emptyIterableOf(User.class))
);
}
/**
* Return github for test.
* @return Github
*/
private static Github github() {
final String key = System.getProperty("failsafe.github.key");
Assume.assumeThat(key, Matchers.notNullValue());
return new RtGithub(key);
}
}
|
package org.fedorahosted.flies.core.action;
import org.fedorahosted.flies.core.model.HCommunity;
import org.fedorahosted.flies.core.model.HIterationProject;
import org.fedorahosted.flies.repository.model.HDocument;
import org.fedorahosted.flies.repository.model.HParentResource;
import org.fedorahosted.flies.repository.model.HTextFlow;
import org.hibernate.CacheMode;
import org.hibernate.FlushMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Transaction;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
@Name("adminAction")
@Scope(ScopeType.APPLICATION)
public class AdminActionBean {
private static final int BATCH_SIZE = 500;
@Logger
private Log log;
@In
FullTextSession session;
/*
* TODO make it an @Asynchronous call and have some boolean
* isRunning method to disable the button if the job is already running
*/
public void reindexDatabase() {
log.info("Re-indexing started");
reindex(HCommunity.class);
reindex(HIterationProject.class);
// reindex(HDocument.class);
reindex(HTextFlow.class);
// reindex(HTextFlowTarget.class);
log.info("Re-indexing finished");
// TODO: this is a global action - not for a specific user
// should have some sort of global status on this one
FacesMessages.instance().add("Re-indexing finished");
}
private void reindex (Class<?> clazz) {
log.info("Re-indexing {0}", clazz);
try {
session.setFlushMode(FlushMode.MANUAL);
session.setCacheMode(CacheMode.IGNORE);
Transaction transaction = session.beginTransaction();
//Scrollable results will avoid loading too many objects in memory
ScrollableResults results = session.createCriteria( clazz )
.setFetchSize(BATCH_SIZE)
.scroll( ScrollMode.FORWARD_ONLY );
int index = 0;
while( results.next() ) {
index++;
session.index( results.get(0) ); //index each element
if (index % BATCH_SIZE == 0) {
session.flushToIndexes(); //apply changes to indexes
session.clear(); //clear since the queue is processed
}
}
results.close();
transaction.commit();
} catch (Exception e) {
log.warn("Unable to index object of {0}", e, clazz);
}
}
}
|
package dk.itu.kelvin.math;
// JUnit annotations
import org.junit.Test;
// JUnit assertions
import static org.junit.Assert.assertTrue;
/**
* {@link Mercator} test suite.
*
* <p>
* Test convert a x- and y-coordinate into a spherical latitude and longitude.
*
* We take into account that we compare doubles and set a deviation at 0,1 %.
* <p>
*
*/
public class MercatorTest {
/**
* Test convert an x-coordinate into a spherical longitude
*/
@Test
public void testXToLon() {
Mercator m = new Mercator();
double lon = m.xToLon(20.03);
assertTrue(20.03 == m.lonToX(lon));
}
/**
* Test convert an y-coordinate into a spherical latitude
*/
@Test
public void testYToLon() {
Mercator m = new Mercator();
double lat = m.yToLat(200.03);
// deviation of 0,1 %.
double devLat1 = m.latToY(lat) * 1.001;
double devLat2 = m.latToY(lat) * 0.099;
double yCoord = 200.03;
assertTrue( yCoord < devLat1);
assertTrue( yCoord > devLat2);
}
}
|
package freemarker.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import freemarker.template.Configuration;
import freemarker.template.Version;
import freemarker.template.utility.DateUtil;
public class SQLTimeZoneTest extends TemplateOutputTest {
private TimeZone lastDefaultTimeZone;
private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
{
df.setTimeZone(DateUtil.UTC);
}
// Values that JDBC in GMT+02:00 would produce
private final java.sql.Date sqlDate = new java.sql.Date(utcToLong("2014-07-11T22:00:00")); // 2014-07-12
private final Time sqlTime = new Time(utcToLong("1970-01-01T10:30:05")); // 12:30:05
private final Timestamp sqlTimestamp = new Timestamp(utcToLong("2014-07-12T10:30:05")); // 2014-07-12T12:30:05
private final Date javaDate = new Date(utcToLong("2014-07-12T10:30:05")); // 2014-07-12T12:30:05
private final Date javaDayErrorDate = new Date(utcToLong("2014-07-11T22:00:00")); // 2014-07-12T12:30:05
public TimeZone getLastDefaultTimeZone() {
return lastDefaultTimeZone;
}
public void setLastDefaultTimeZone(TimeZone lastDefaultTimeZone) {
this.lastDefaultTimeZone = lastDefaultTimeZone;
}
public java.sql.Date getSqlDate() {
return sqlDate;
}
public Time getSqlTime() {
return sqlTime;
}
public Timestamp getSqlTimestamp() {
return sqlTimestamp;
}
public Date getJavaDate() {
return javaDate;
}
public Date getJavaDayErrorDate() {
return javaDayErrorDate;
}
@Before
public void setup() {
lastDefaultTimeZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("GMT+02:00"));
}
private static final String FTL =
"${sqlDate} ${sqlTime} ${sqlTimestamp} ${javaDate?datetime}\n"
+ "${sqlDate?iso_local_z} ${sqlTime?iso_local_z} "
+ "${sqlTimestamp?iso_local_z} ${javaDate?datetime?iso_local_z}\n"
+ "${sqlDate?string.xs_z} ${sqlTime?string.xs_z} "
+ "${sqlTimestamp?string.xs_z} ${javaDate?datetime?string.xs_z}\n"
+ "${sqlDate?string.xs} ${sqlTime?string.xs} "
+ "${sqlTimestamp?string.xs} ${javaDate?datetime?string.xs}\n"
+ "<#setting time_zone='GMT'>\n"
+ "${sqlDate} ${sqlTime} ${sqlTimestamp} ${javaDate?datetime}\n"
+ "${sqlDate?iso_local_z} ${sqlTime?iso_local_z} "
+ "${sqlTimestamp?iso_local_z} ${javaDate?datetime?iso_local_z}\n"
+ "${sqlDate?string.xs_z} ${sqlTime?string.xs_z} "
+ "${sqlTimestamp?string.xs_z} ${javaDate?datetime?string.xs_z}\n"
+ "${sqlDate?string.xs} ${sqlTime?string.xs} "
+ "${sqlTimestamp?string.xs} ${javaDate?datetime?string.xs}\n";
private static final String OUTPUT_BEFORE_SETTZ_GMT2
= "2014-07-12 12:30:05 2014-07-12T12:30:05 2014-07-12T12:30:05\n"
+ "2014-07-12 12:30:05+02:00 2014-07-12T12:30:05+02:00 2014-07-12T12:30:05+02:00\n"
+ "2014-07-12+02:00 12:30:05+02:00 2014-07-12T12:30:05+02:00 2014-07-12T12:30:05+02:00\n"
+ "2014-07-12 12:30:05 2014-07-12T12:30:05+02:00 2014-07-12T12:30:05+02:00\n";
private static final String OUTPUT_BEFORE_SETTZ_GMT1_SQL_DIFFERENT
= "2014-07-12 12:30:05 2014-07-12T11:30:05 2014-07-12T11:30:05\n"
+ "2014-07-12 12:30:05+02:00 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n"
+ "2014-07-12+02:00 12:30:05+02:00 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n"
+ "2014-07-12 12:30:05 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n";
private static final String OUTPUT_BEFORE_SETTZ_GMT1_SQL_SAME
= "2014-07-11 11:30:05 2014-07-12T11:30:05 2014-07-12T11:30:05\n"
+ "2014-07-11 11:30:05+01:00 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n"
+ "2014-07-11+01:00 11:30:05+01:00 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n"
+ "2014-07-11 11:30:05 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n";
private static final String OUTPUT_AFTER_SETTZ_SQL_SAME
= "2014-07-11 10:30:05 2014-07-12T10:30:05 2014-07-12T10:30:05\n"
+ "2014-07-11 10:30:05Z 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n"
+ "2014-07-11Z 10:30:05Z 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n"
+ "2014-07-11 10:30:05 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n";
private static final String OUTPUT_AFTER_SETTZ_SQL_DIFFERENT
= "2014-07-12 12:30:05 2014-07-12T10:30:05 2014-07-12T10:30:05\n"
+ "2014-07-12 12:30:05+02:00 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n"
+ "2014-07-12+02:00 12:30:05+02:00 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n"
+ "2014-07-12 12:30:05 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n";
@Test
public void testWithDefaultTZAndNoUseDefSysForSQL() throws Exception {
Configuration cfg = createConfiguration();
assertFalse(cfg.getUseSystemDefaultTimeZoneForSQLDateAndTime());
assertEquals(TimeZone.getDefault(), cfg.getTimeZone());
assertOutput(FTL, OUTPUT_BEFORE_SETTZ_GMT2 + OUTPUT_AFTER_SETTZ_SQL_SAME, cfg);
}
@Test
public void testWithDefaultTZAndUseDefSysForSQL() throws Exception {
Configuration cfg = createConfiguration();
cfg.setUseSystemDefaultTimeZoneForSQLDateAndTime(true);
assertOutput(FTL, OUTPUT_BEFORE_SETTZ_GMT2 + OUTPUT_AFTER_SETTZ_SQL_DIFFERENT, cfg);
}
@Test
public void testWithGMT1AndNoUseDefSysForSQL() throws Exception {
Configuration cfg = createConfiguration();
assertFalse(cfg.getUseSystemDefaultTimeZoneForSQLDateAndTime());
cfg.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));
assertOutput(FTL, OUTPUT_BEFORE_SETTZ_GMT1_SQL_SAME + OUTPUT_AFTER_SETTZ_SQL_SAME, cfg);
}
@Test
public void testWithGMT1AndUseDefSysForSQL() throws Exception {
Configuration cfg = createConfiguration();
cfg.setUseSystemDefaultTimeZoneForSQLDateAndTime(true);
cfg.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));
assertOutput(FTL, OUTPUT_BEFORE_SETTZ_GMT1_SQL_DIFFERENT + OUTPUT_AFTER_SETTZ_SQL_DIFFERENT, cfg);
}
@Test
public void testWithGMT2AndNoUseDefSysForSQL() throws Exception {
Configuration cfg = createConfiguration();
assertFalse(cfg.getUseSystemDefaultTimeZoneForSQLDateAndTime());
cfg.setTimeZone(TimeZone.getTimeZone("GMT+02:00"));
assertOutput(FTL, OUTPUT_BEFORE_SETTZ_GMT2 + OUTPUT_AFTER_SETTZ_SQL_SAME, cfg);
}
@Test
public void testWithGMT2AndUseDefSysForSQL() throws Exception {
Configuration cfg = createConfiguration();
cfg.setUseSystemDefaultTimeZoneForSQLDateAndTime(true);
cfg.setTimeZone(TimeZone.getTimeZone("GMT+02:00"));
assertOutput(FTL, OUTPUT_BEFORE_SETTZ_GMT2 + OUTPUT_AFTER_SETTZ_SQL_DIFFERENT, cfg);
}
@Test
public void testCacheFlushings() throws Exception {
Configuration cfg = createConfiguration();
cfg.setTimeZone(DateUtil.UTC);
cfg.setDateFormat("yyyy-MM-dd E");
cfg.setTimeFormat("HH:mm:ss E");
cfg.setDateTimeFormat("yyyy-MM-dd'T'HH:mm:ss E");
assertOutput(
"${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n"
+ "<#setting locale='de'>\n"
+ "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n",
"2014-07-11 Fri, 10:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n"
+ "2014-07-11 Fr, 10:30:05 Do, 2014-07-12T10:30:05 Sa, 2014-07-12T10:30:05 Sa, 2014-07-12 Sa, 10:30:05 Sa\n",
cfg);
assertOutput(
"${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n"
+ "<#setting date_format='yyyy-MM-dd'>\n"
+ "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n",
"2014-07-11 Fri, 10:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n"
+ "2014-07-11, 10:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12, 10:30:05 Sat\n",
cfg);
assertOutput(
"${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n"
+ "<#setting time_format='HH:mm:ss'>\n"
+ "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n",
"2014-07-11 Fri, 10:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n"
+ "2014-07-11 Fri, 10:30:05, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05\n",
cfg);
assertOutput(
"${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n"
+ "<#setting datetime_format='yyyy-MM-dd\\'T\\'HH:mm:ss'>\n"
+ "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n",
"2014-07-11 Fri, 10:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n"
+ "2014-07-11 Fri, 10:30:05 Thu, 2014-07-12T10:30:05, 2014-07-12T10:30:05, 2014-07-12 Sat, 10:30:05 Sat\n",
cfg);
cfg.setUseSystemDefaultTimeZoneForSQLDateAndTime(true);
assertOutput(
"${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n"
+ "<#setting locale='de'>\n"
+ "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n",
"2014-07-12 Sat, 12:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n"
+ "2014-07-12 Sa, 12:30:05 Do, 2014-07-12T10:30:05 Sa, 2014-07-12T10:30:05 Sa, 2014-07-12 Sa, 10:30:05 Sa\n",
cfg);
assertOutput(
"${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n"
+ "<#setting date_format='yyyy-MM-dd'>\n"
+ "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n",
"2014-07-12 Sat, 12:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n"
+ "2014-07-12, 12:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12, 10:30:05 Sat\n",
cfg);
assertOutput(
"${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n"
+ "<#setting time_format='HH:mm:ss'>\n"
+ "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n",
"2014-07-12 Sat, 12:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n"
+ "2014-07-12 Sat, 12:30:05, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05\n",
cfg);
assertOutput(
"${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n"
+ "<#setting datetime_format='yyyy-MM-dd\\'T\\'HH:mm:ss'>\n"
+ "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n",
"2014-07-12 Sat, 12:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n"
+ "2014-07-12 Sat, 12:30:05 Thu, 2014-07-12T10:30:05, 2014-07-12T10:30:05, 2014-07-12 Sat, 10:30:05 Sat\n",
cfg);
}
@Test
public void testDateAndTimeBuiltInsHasNoEffect() throws Exception {
Configuration cfg = createConfiguration();
cfg.setTimeZone(DateUtil.UTC);
cfg.setUseSystemDefaultTimeZoneForSQLDateAndTime(true);
assertOutput(
"${javaDayErrorDate?date} ${javaDayErrorDate?time} ${sqlTimestamp?date} ${sqlTimestamp?time} "
+ "${sqlDate?date} ${sqlTime?time}\n"
+ "<#setting time_zone='GMT+02'>\n"
+ "${javaDayErrorDate?date} ${javaDayErrorDate?time} ${sqlTimestamp?date} ${sqlTimestamp?time} "
+ "${sqlDate?date} ${sqlTime?time}\n"
+ "<#setting time_zone='GMT-11'>\n"
+ "${javaDayErrorDate?date} ${javaDayErrorDate?time} ${sqlTimestamp?date} ${sqlTimestamp?time} "
+ "${sqlDate?date} ${sqlTime?time}\n",
"2014-07-11 22:00:00 2014-07-12 10:30:05 2014-07-12 12:30:05\n"
+ "2014-07-12 00:00:00 2014-07-12 12:30:05 2014-07-12 12:30:05\n"
+ "2014-07-11 11:00:00 2014-07-11 23:30:05 2014-07-12 12:30:05\n",
cfg);
}
@Test
public void testChangeSettingInTemplate() throws Exception {
Configuration cfg = createConfiguration();
cfg.setTimeZone(DateUtil.UTC);
assertOutput(
"${sqlDate}, ${sqlTime}\n"
+ "<#setting use_system_default_time_zone_for_sql_date_and_time=true>\n"
+ "${sqlDate}, ${sqlTime}\n"
+ "<#setting use_system_default_time_zone_for_sql_date_and_time=false>\n"
+ "${sqlDate}, ${sqlTime}\n"
+ "<#setting time_zone='GMT+03'>\n"
+ "${sqlDate}, ${sqlTime}\n"
+ "<#setting use_system_default_time_zone_for_sql_date_and_time=true>\n"
+ "${sqlDate}, ${sqlTime}\n",
"2014-07-11, 10:30:05\n"
+ "2014-07-12, 12:30:05\n"
+ "2014-07-11, 10:30:05\n"
+ "2014-07-12, 13:30:05\n"
+ "2014-07-12, 12:30:05\n",
cfg);
}
private Configuration createConfiguration() {
Configuration cfg = new Configuration(new Version(2, 3, 21));
cfg.setLocale(Locale.US);
cfg.setDateFormat("yyyy-MM-dd");
cfg.setTimeFormat("HH:mm:ss");
cfg.setDateTimeFormat("yyyy-MM-dd'T'HH:mm:ss");
return cfg;
}
@After
public void teardown() {
TimeZone.setDefault(lastDefaultTimeZone);
}
@Override
protected Object createDataModel() {
return this;
}
private long utcToLong(String isoDateTime) {
try {
return df.parse(isoDateTime).getTime();
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
|
//@@author A0139961U
package guitests;
import static org.junit.Assert.assertTrue;
import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_DIRECTORY;
import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_FILE;
import org.junit.Test;
import seedu.tache.logic.commands.LoadCommand;
import seedu.tache.logic.commands.SaveCommand;
import seedu.tache.testutil.TestTask;
import seedu.tache.testutil.TestUtil;
public class SaveAndLoadCommandTest extends TaskManagerGuiTest {
public final String saveFolder1 = TestUtil.SANDBOX_FOLDER + "saveTest1";
public final String saveFolder2 = TestUtil.SANDBOX_FOLDER + "saveTest2";
public final String fileName = "\\taskmanager.xml";
@Test
public void saveAndLoadDataFile() {
TestTask[] tasks = td.getTypicalTasks();
commandBox.runCommand(td.getFit.getAddCommand());
tasks = TestUtil.addTasksToList(tasks, td.getFit);
commandBox.runCommand(SaveCommand.COMMAND_WORD + " " + saveFolder1);
commandBox.runCommand(SaveCommand.COMMAND_WORD + " " + saveFolder2);
//Delete the newly added task and add findGirlfriend
commandBox.runCommand("delete 3"); //delete getFit
tasks = TestUtil.removeTasksFromList(tasks, td.getFit);
commandBox.runCommand(td.findGirlfriend.getAddCommand());
tasks = TestUtil.addTasksToList(tasks, td.findGirlfriend);
assertTrue(taskListPanel.isListMatching(tasks));
//Load saveTest1
//saveTest1 : payDavid, visitSarah, eggsAndBread, visitGrandma, readBook, getFit
//saveTest2 : payDavid, visitSarah, eggsAndBread, visitGrandma, readBook, findGirlfriend
commandBox.runCommand(LoadCommand.COMMAND_WORD + " " + saveFolder1 + fileName);
tasks = TestUtil.removeTasksFromList(tasks, td.findGirlfriend);
//Check if saveTest1 still has getFit
tasks = TestUtil.addTasksToList(td.getTypicalTasks(), td.getFit);
assertTrue(taskListPanel.isListMatching(tasks));
tasks = TestUtil.removeTasksFromList(tasks, td.getFit);
tasks = TestUtil.removeTasksFromList(tasks, td.visitSarah);
commandBox.runCommand("delete 3"); //getFit
commandBox.runCommand("delete 2"); //visitSarah
commandBox.runCommand(td.findGirlfriend.getAddCommand());
tasks = TestUtil.addTasksToList(tasks, td.findGirlfriend);
assertTrue(taskListPanel.isListMatching(tasks));
//saveTest1 : payDavid, eggsAndBread, visitGrandma, readBook, findGirlfriend
//saveTest2 : payDavid, visitSarah, eggsAndBread, visitGrandma, readBook, findGirlfriend)
//Load back the new file and check if getFit is deleted
tasks = TestUtil.addTasksToList(td.getTypicalTasks(), td.findGirlfriend);
commandBox.runCommand(LoadCommand.COMMAND_WORD + " " + saveFolder2 + fileName);
assertTrue(taskListPanel.isListMatching(tasks));
}
@Test
public void saveInvalidDirectoryFailure() {
commandBox.runCommand(SaveCommand.COMMAND_WORD + " \\");
assertResultMessage(MESSAGE_INVALID_DIRECTORY);
commandBox.runCommand(SaveCommand.COMMAND_WORD + " /");
assertResultMessage(MESSAGE_INVALID_DIRECTORY);
}
@Test
public void saveDirectoryNotExistSuccess() {
commandBox.runCommand(SaveCommand.COMMAND_WORD + " " + saveFolder1 + "\\NotExistFolder");
assertResultMessage(String.format(SaveCommand.MESSAGE_SUCCESS, saveFolder1 + "\\NotExistFolder"));
}
@Test
public void saveDirectoryExistSuccess() {
commandBox.runCommand(SaveCommand.COMMAND_WORD + " " + saveFolder1);
assertResultMessage(String.format(SaveCommand.MESSAGE_SUCCESS, saveFolder1));
}
@Test
public void loadInvalidFilePathFailure() {
commandBox.runCommand(LoadCommand.COMMAND_WORD + " " + saveFolder1);
assertResultMessage(MESSAGE_INVALID_FILE);
commandBox.runCommand(LoadCommand.COMMAND_WORD + " " + saveFolder1 + "\\someInvalidFolder" + fileName);
assertResultMessage(MESSAGE_INVALID_FILE);
}
}
|
package mousio.etcd4j;
import mousio.client.retry.RetryWithExponentialBackOff;
import mousio.etcd4j.promises.EtcdResponsePromise;
import mousio.etcd4j.responses.EtcdException;
import mousio.etcd4j.responses.EtcdKeyAction;
import mousio.etcd4j.responses.EtcdKeysResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.*;
/**
* Performs tests on a real server at local address. All actions are performed in "etcd4j_test" dir
*/
public class TestFunctionality {
private EtcdClient etcd;
@Before
public void setUp() throws Exception {
System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "DEBUG");
this.etcd = new EtcdClient();
this.etcd.setRetryHandler(new RetryWithExponentialBackOff(20, 4, -1));
}
/**
* Test version
*
* @throws Exception
*/
@Test
public void testVersion() {
assertTrue(etcd.getVersion().startsWith("etcd "));
}
@Test
public void testTimeout() throws IOException, EtcdException {
try {
etcd.put("etcd4j_test/fooTO", "bar").timeout(1, TimeUnit.MILLISECONDS).send().get();
fail();
} catch (TimeoutException e) {
// Should time out
}
}
/**
* Simple value tests
*/
@Test
public void testKey() throws IOException, EtcdException, TimeoutException {
EtcdKeysResponse response = etcd.put("etcd4j_test/foo", "bar").send().get();
assertEquals(EtcdKeyAction.set, response.action);
response = etcd.put("etcd4j_test/foo2", "bar").prevExist(false).send().get();
assertEquals(EtcdKeyAction.create, response.action);
response = etcd.put("etcd4j_test/foo", "bar1").ttl(40).prevExist(true).send().get();
assertEquals(EtcdKeyAction.update, response.action);
assertNotNull(response.node.expiration);
response = etcd.put("etcd4j_test/foo", "bar2").prevValue("bar1").send().get();
assertEquals(EtcdKeyAction.compareAndSwap, response.action);
response = etcd.put("etcd4j_test/foo", "bar3").prevIndex(response.node.modifiedIndex).send().get();
assertEquals(EtcdKeyAction.compareAndSwap, response.action);
response = etcd.get("etcd4j_test/foo").consistent().send().get();
assertEquals("bar3", response.node.value);
// Test slash before key
response = etcd.get("/etcd4j_test/foo").consistent().send().get();
assertEquals("bar3", response.node.value);
response = etcd.delete("etcd4j_test/foo").send().get();
assertEquals(EtcdKeyAction.delete, response.action);
}
/**
* Simple value tests
*/
@Test
public void testError() throws IOException, TimeoutException {
try {
etcd.get("etcd4j_test/barf").send().get();
} catch (EtcdException e) {
assertEquals(100, e.errorCode);
}
try {
etcd.put("etcd4j_test/barf", "huh").prevExist(true).send().get();
} catch (EtcdException e) {
assertEquals(100, e.errorCode);
}
}
/**
* Tests redirect by sending a key with too many slashes.
*/
@Test
public void testRedirect() throws IOException, EtcdException, TimeoutException {
etcd.put("etcd4j_test/redirect", "bar").send().get();
// Test redirect with a double slash
EtcdKeysResponse response = etcd.get("//etcd4j_test/redirect").consistent().send().get();
assertEquals("bar", response.node.value);
}
/**
* Directory tests
*/
@Test
public void testDir() throws IOException, EtcdException, TimeoutException {
EtcdKeysResponse r = etcd.putDir("etcd4j_test/foo_dir").send().get();
assertEquals(r.action, EtcdKeyAction.set);
r = etcd.getDir("etcd4j_test/foo_dir").consistent().send().get();
assertEquals(r.action, EtcdKeyAction.get);
// Test slash before key
r = etcd.getDir("/etcd4j_test/foo_dir").send().get();
assertEquals(r.action, EtcdKeyAction.get);
r = etcd.put("etcd4j_test/foo_dir/foo", "bar").send().get();
assertEquals(r.node.value, "bar");
r = etcd.putDir("etcd4j_test/foo_dir/foo_subdir").ttl(20).send().get();
assertEquals(r.action, EtcdKeyAction.set);
assertNotNull(r.node.expiration);
r = etcd.deleteDir("etcd4j_test/foo_dir").recursive().send().get();
assertEquals(r.action, EtcdKeyAction.delete);
}
/**
* In order key tests
*/
@Test
public void testInOrderKeys() throws IOException, EtcdException, TimeoutException {
EtcdKeysResponse r = etcd.post("etcd4j_test/queue", "Job1").send().get();
assertEquals(r.action, EtcdKeyAction.create);
r = etcd.post("etcd4j_test/queue", "Job2").ttl(20).send().get();
assertEquals(r.action, EtcdKeyAction.create);
r = etcd.get("etcd4j_test/queue/" + r.node.createdIndex).consistent().send().get();
assertEquals(r.node.value, "Job2");
r = etcd.get("etcd4j_test/queue").consistent().recursive().sorted().send().get();
assertEquals(2, r.node.nodes.size());
assertEquals("Job2", r.node.nodes.get(1).value);
r = etcd.deleteDir("etcd4j_test/queue").recursive().send().get();
assertEquals(r.action, EtcdKeyAction.delete);
}
/**
* In order key tests
*/
@Test
public void testWait() throws IOException, EtcdException, InterruptedException, TimeoutException {
EtcdResponsePromise<EtcdKeysResponse> p = etcd.get("etcd4j_test/test").waitForChange().send();
// Ensure the change is received after the listen command is received.
new Timer().schedule(new TimerTask() {
@Override
public void run() {
try {
etcd.put("etcd4j_test/test", "changed").send().get();
} catch (IOException | EtcdException | TimeoutException e) {
fail();
}
}
}, 20);
EtcdKeysResponse r = p.get();
assertEquals("changed", r.node.value);
}
@Test(timeout = 1000)
public void testChunkedData() throws IOException, EtcdException, TimeoutException {
//creating very long key to force content to be chunked
StringBuilder stringBuilder = new StringBuilder(15000);
for (int i = 0; i < 15000; i++) {
stringBuilder.append("a");
}
EtcdKeysResponse response = etcd.put("etcd4j_test/foo", stringBuilder.toString()).send().get();
assertEquals(EtcdKeyAction.set, response.action);
}
@After
public void tearDown() throws Exception {
try {
etcd.deleteDir("etcd4j_test").recursive().send().get();
} catch (EtcdException | IOException e) {
// ignore since not all tests create the directory
}
this.etcd.close();
}
}
|
package net.edralzar.wargolem;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import org.junit.Before;
import net.edralzar.wargolem.model.Gw2Class;
import net.edralzar.wargolem.model.MapResource;
import net.edralzar.wargolem.model.Player;
import net.edralzar.wargolem.model.Role;
import net.edralzar.wargolem.model.WarRoom;
public class GolemTest {
private Golem golem;
private Player soldier1;
private Player scout1;
private Player scout2;
@Before
public void setUp() throws Exception {
Player owner = new Player("testLead", Gw2Class.GUARDIAN);
WarRoom room = new WarRoom("test", "testTopic", "someServer", owner);
soldier1 = new Player("soldier1", Gw2Class.ELEMENTALIST);
scout1 = new Player("scout1", Gw2Class.THIEF);
scout2 = new Player("scout2", Gw2Class.ENGINEER);
golem = new Golem(room);
golem.addPlayer(soldier1);
golem.addPlayer(scout1);
golem.addPlayer(scout2);
}
@org.junit.Test
public void testAddPlayer() throws Exception {
Player p = new Player("toto", Gw2Class.THIEF);
assertThat(p.getRole()).isEqualTo(Role.SOLDIER);
assertThat(p.getRoleSince()).isEqualTo(Instant.EPOCH);
assertThat(golem.getWarRoom().getSquad().size()).isEqualTo(3);
golem.addPlayer(p);
assertThat(golem.getWarRoom().getSquad().size()).isEqualTo(4);
assertThat(golem.getWarRoom().getSquad()).contains(p);
}
@org.junit.Test
public void testSetScout() throws Exception {
MapResource tower = new MapResource("blueLakeTower", "Blue Lake Tower");
Instant beforeScout = scout1.getRoleSince();
assertThat(scout1.getRole()).isEqualTo(Role.SOLDIER);
golem.setScout(scout1, tower);
assertThat(golem.getWarRoom().getScouts().get(tower)).isEqualTo(scout1);
assertThat(scout1.getRole()).isEqualTo(Role.SCOUT);
assertThat(scout1.getRoleSince().isAfter(beforeScout)).isTrue();
}
@org.junit.Test
public void testScoutReplaces() throws Exception {
MapResource tower = new MapResource("redLakeTower", "Red Lake Tower");
golem.setScout(scout1, tower);
golem.setScout(scout2, tower);
assertThat(golem.getWarRoom().getScouts().get(tower)).isEqualTo(scout2);
assertThat(scout1.getRole()).isEqualTo(Role.SOLDIER);
assertThat(golem.getWarRoom().getScouts().inverse().get(scout1)).isNull();
}
}
|
package net.lightbody.bmp.proxy;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
public class SslTest extends ProxyServerTest {
@Test
public void testFidelity() throws Exception {
get("https:
}
@Test
public void testSalesforce() throws Exception {
get("https://login.salesforce.com/");
}
@Test
public void testNewRelic() throws Exception {
proxy.remapHost("foo.newrelic.com", "rpm.newrelic.com");
proxy.remapHost("bar.newrelic.com", "rpm.newrelic.com");
get("https://foo.newrelic.com/");
get("https://bar.newrelic.com/");
get("https://rpm.newrelic.com/");
}
private void get(String url) throws IOException {
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
Assert.assertEquals("Expected 200 when fetching " + url, 200, response.getStatusLine().getStatusCode());
}
}
|
package studentcapture.user;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.WebApplicationContext;
import studentcapture.config.H2DB;
import studentcapture.config.StudentCaptureApplicationTests;
import studentcapture.login.ErrorFlags;
import java.sql.SQLException;
import java.sql.Types;
import static org.junit.Assert.*;
public class UserDAOTest extends StudentCaptureApplicationTests {
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private UserDAO userDAO;
@Autowired
private JdbcTemplate jdbcMock;
private User userSetup;
@Before
public void setup() {
//Add one user
String sql = "INSERT INTO users"
+" (username, firstname, lastname, email, pswd)"
+" VALUES (?, ?, ?, ?, ?)";
userSetup = new User("testUser","testFName","testLName",
"testEmail@example.com","testPassword123", false);
Object[] args = new Object[] {userSetup.getUserName(), userSetup.getFirstName(),
userSetup.getLastName(),userSetup.getEmail(),
userSetup.getPswd()};
int[] types = new int[]{Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,
Types.VARCHAR,Types.VARCHAR};
try {
jdbcMock.update(sql,args,types);
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* Remove all content from the database
*/
@After
public void tearDown() {
try {
H2DB.TearDownDB(jdbcMock);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void testGetUserByID() {
User userRes = userDAO.getUser("1",1);
assertEquals(userSetup,userRes);
}
@Test
public void testAddUser() {
User user = new User("userPelle", "Pelle", "Jönsson", "pelle@gmail.com",
"mypassword123", false);
ErrorFlags res = userDAO.addUser(user);
User userRes = userDAO.getUser("userPelle", UserDAO.GET_USER_BY_USERNAME);
assertEquals(ErrorFlags.NOERROR, res);
assertEquals(user, userRes);
}
@Test
public void testAddingUserTwice() {
H2DB.printTable(jdbcMock,"users");
ErrorFlags errorFlags = userDAO.addUser(userSetup);
H2DB.printTable(jdbcMock,"users");
assertEquals(ErrorFlags.USEREXISTS,errorFlags);
}
@Test
public void testAddingNullUser() {
User user = new User("userPelle","Pelle","Jönsson",null,
"mypassword123", false);
ErrorFlags errorFlag = userDAO.addUser(user);
assertEquals(ErrorFlags.USERCONTAINNULL, errorFlag);
}
@Test
public void testGetNonExistingUser() {
User userRes = userDAO.getUser("notExist",0);
assertEquals(null,userRes);
}
@Test
public void testUpdateUser() {
userSetup.setFirstName("new username");
userSetup.setPswd("new password");
boolean res = userDAO.updateUser(userSetup);
User userRes = userDAO.getUser("testUser",0);
assertTrue(res);
assertEquals(userSetup,userRes);
}
@Test
public void testUpdateNonExistingUser() {
User user = new User("testUserNotExists","newFirstName","newLname",
"newemai@gmail.com","new_pswd_1fdsgasda213fC", false);
boolean res = userDAO.updateUser(user);
assertFalse(res);
}
@Test
public void testAddingEmailTwice() {
User user = new User("testNewUser","newFirstName","newLname",
userSetup.getEmail(),"newpswd", false);
ErrorFlags res = userDAO.addUser(user);
assertEquals(ErrorFlags.EMAILEXISTS,res);
}
@Test
public void testAddToken() {
userSetup.setToken("new token");
boolean res = userDAO.updateUser(userSetup);
User user = userDAO.getUser(userSetup.getUserName(),0);
assertEquals(userSetup,user);
assertTrue(res);
}
@Test
public void testRemoveToken() {
userSetup.setToken(null);
boolean res = userDAO.updateUser(userSetup);
User user = userDAO.getUser(userSetup.getUserName(),0);
assertEquals(userSetup,user);
assertTrue(res);
}
@Test
public void testIsTeacher() {
User user = new User("userPelle", "Pelle", "Jönsson", "pelle@gmail.com",
"mypassword123", true);
ErrorFlags result = userDAO.addUser(user);
user = userDAO.getUser(user.getUserName(), UserDAO.GET_USER_BY_USERNAME);
assertTrue(user.isTeacher());
}
}
|
package de.tu.darmstadt.lt.ner.preprocessing;
import static org.uimafit.factory.AnalysisEngineFactory.createPrimitiveDescription;
import static org.uimafit.pipeline.SimplePipeline.runPipeline;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.uima.UIMAException;
import org.apache.uima.UIMAFramework;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.util.Level;
import org.cleartk.classifier.CleartkSequenceAnnotator;
import org.cleartk.classifier.crfsuite.CRFSuiteStringOutcomeDataWriter;
import org.cleartk.classifier.jar.DefaultSequenceDataWriterFactory;
import org.cleartk.classifier.jar.DirectoryDataWriterFactory;
import org.cleartk.classifier.jar.GenericJarClassifierFactory;
import org.cleartk.util.cr.FilesCollectionReader;
import de.tu.darmstadt.lt.ner.annotator.NERAnnotator;
import de.tu.darmstadt.lt.ner.reader.NERReader;
import de.tu.darmstadt.lt.ner.writer.EvaluatedNERWriter;
import de.tudarmstadt.ukp.dkpro.core.snowball.SnowballStemmer;
public class TrainNERModel {
private static final Logger LOG = Logger.getLogger(TrainNERModel.class
.getName());
public static void writeModel(File NER_TagFile, String modelDirectory,
String language) throws ResourceInitializationException,
UIMAException, IOException {
runPipeline(
FilesCollectionReader.getCollectionReaderWithSuffixes(
NER_TagFile.getAbsolutePath(), NERReader.CONLL_VIEW,
NER_TagFile.getName()),
createPrimitiveDescription(NERReader.class),
createPrimitiveDescription(
NERAnnotator.class,
NERAnnotator.PARAM_FEATURE_EXTRACTION_FILE,
modelDirectory + "feature.xml",
CleartkSequenceAnnotator.PARAM_IS_TRAINING,
true,
DirectoryDataWriterFactory.PARAM_OUTPUT_DIRECTORY,
modelDirectory,
DefaultSequenceDataWriterFactory.PARAM_DATA_WRITER_CLASS_NAME,
CRFSuiteStringOutcomeDataWriter.class));
}
public static void trainModel(String modelDirectory) throws Exception {
org.cleartk.classifier.jar.Train.main(modelDirectory);
}
public static String classifyTestFile(String aClassifierJarPath,
File testPosFile,
String language, File outputFile)
throws ResourceInitializationException, UIMAException, IOException {
runPipeline(
FilesCollectionReader.getCollectionReaderWithSuffixes(
testPosFile.getAbsolutePath(), NERReader.CONLL_VIEW,
testPosFile.getName()),
createPrimitiveDescription(NERReader.class),
createPrimitiveDescription(SnowballStemmer.class,
SnowballStemmer.PARAM_LANGUAGE, language),
createPrimitiveDescription(NERAnnotator.class,
NERAnnotator.PARAM_FEATURE_EXTRACTION_FILE,
aClassifierJarPath + "feature.xml",
GenericJarClassifierFactory.PARAM_CLASSIFIER_JAR_PATH,
aClassifierJarPath + "model.jar"),
createPrimitiveDescription(EvaluatedNERWriter.class,
EvaluatedNERWriter.OUTPUT_FILE, outputFile));
return FileUtils.readFileToString(outputFile, "UTF-8");
}
public static void main(String[] args) throws Exception {
String usage = "USAGE: java -jar germanner.jar (f OR ft OR t) modelDir (trainFile OR testFile) "
+ "where f means training mode, t means testing mode, modelDir is model directory, trainFile is a training file, and "
+ "testFile is a Test file";
long start = System.currentTimeMillis();
ChangeColon c = new ChangeColon();
String language = "de";
try {
if (!(args[0].equals("f") || args[0].equals("t") || args[0]
.equals("ft"))
|| !new File(args[1]).exists()
|| !new File(args[2]).exists()) {
LOG.error(usage);
System.exit(1);
}
if (args[0].equals("ft") && !new File(args[3]).exists()) {
LOG.error(usage);
System.exit(1);
}
String modelDirectory = args[1] + "/";
new File(modelDirectory).mkdirs();
File outputFile = new File(modelDirectory, "res.txt");
if (args[0].equals("f")) {
c.run(args[2], args[2] + ".c");
writeModel(new File(args[2] + ".c"),
modelDirectory, language);
trainModel(modelDirectory);
} else if (args[0].equals("ft")) {
c.run(args[2], args[2] + ".c");
c.run(args[3], args[3] + ".c");
writeModel(new File(args[2] + ".c"),
modelDirectory, language);
trainModel(modelDirectory);
classifyTestFile( modelDirectory,
new File(args[3] + ".c"), language, outputFile);
} else {
c.run(args[2], args[2] + ".c");
classifyTestFile( modelDirectory,
new File(args[2] + ".c"), language, outputFile);
}
long now = System.currentTimeMillis();
UIMAFramework.getLogger().log(Level.INFO,
"Time: " + (now - start) + "ms");
} catch (Exception e) {
LOG.error(usage);
e.printStackTrace();
}
}
}
|
package org.xins.tests.server;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.xins.server.IPFilter;
import org.xins.util.text.ParseException;
/**
* Tests for class <code>IPFilter</code>.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*/
public class IPFilterTests extends TestCase {
// Class functions
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(IPFilterTests.class);
}
// Class fields
// Constructor
/**
* Constructs a new <code>IPFilterTests</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public IPFilterTests(String name) {
super(name);
}
// Fields
// Methods
/**
* Performs setup for the tests.
*/
protected void setUp() {
// empty
}
public void testGetExpression() throws Throwable {
doTestGetExpression("1.2.3.4/1");
doTestGetExpression("0.0.0.0/0");
doTestGetExpression("194.134.168.213/32");
doTestGetExpression("194.13.1.213/20");
}
private void doTestGetExpression(String expression)
throws Throwable {
IPFilter filter = IPFilter.parseFilter(expression);
assertNotNull(filter);
assertEquals(expression, filter.getExpression());
assertEquals(expression, filter.getExpression());
}
public void testParseFilter() throws Throwable {
try {
IPFilter.parseFilter(null);
fail("IPFilter.parseFilter(null) should throw an IllegalArgumentException.");
} catch (IllegalArgumentException exception) {
// as expected
}
doTestParseFilter("abcd", false);
doTestParseFilter("abcd/24", false);
doTestParseFilter("a.b.c.d/12", false);
doTestParseFilter("1.", false);
doTestParseFilter("1.2.", false);
doTestParseFilter("1.2.3", false);
doTestParseFilter("1.2.3.", false);
doTestParseFilter("1.2.3.4", false);
doTestParseFilter("1./", false);
doTestParseFilter("1.2./", false);
doTestParseFilter("1.2.3/", false);
doTestParseFilter("1.2.3./", false);
doTestParseFilter("1.2.3.4/", false);
doTestParseFilter("1./0", false);
doTestParseFilter("1.2./0", false);
doTestParseFilter("1.2.3/0", false);
doTestParseFilter("1.2.3./0", false);
doTestParseFilter("1.2.3.4/a", false);
doTestParseFilter("1.2.3.4/-1", false);
doTestParseFilter(" 1.2.3.4/0", false);
doTestParseFilter("1.2.3.4/0 ", false);
doTestParseFilter(" 1.2.3.4/0 ", false);
doTestParseFilter("1.2.3.4/0", true);
doTestParseFilter("1.2.3.4/5", true);
doTestParseFilter("1.2.3.4/5a", false);
doTestParseFilter("1.2.3.4a/5", false);
doTestParseFilter("1.2.3.4//5", false);
doTestParseFilter("1.2.3.4/32", true);
doTestParseFilter("1.2.3.4/33", false);
doTestParseFilter("1.2.3.4/1234567890123456", false);
}
private void doTestParseFilter(String expression, boolean okay)
throws Throwable {
if (! okay) {
try {
IPFilter.parseFilter(expression);
fail("IPFilter.parse(\"" + expression + "\") should throw a ParseException.");
} catch (ParseException exception) {
// as expected
}
} else {
IPFilter filter = IPFilter.parseFilter(expression);
assertNotNull(filter);
}
}
public void testIsAuthorized() throws Throwable {
IPFilter filter = IPFilter.parseFilter("194.134.168.213/32");
assertNotNull(filter);
try {
filter.isAuthorized(null);
fail("IPFilter.isAuthorized(null) should throw an IllegalArgumentException.");
return;
} catch (IllegalArgumentException exception) {
// as expected
}
doTestIsAuthorized(filter, "abcd", false, false);
doTestIsAuthorized(filter, "abcd", false, false);
doTestIsAuthorized(filter, "abcd/24", false, false);
doTestIsAuthorized(filter, "a.b.c.d", false, false);
doTestIsAuthorized(filter, "a.b.c.d/12", false, false);
doTestIsAuthorized(filter, "1.2.3.4/", false, false);
doTestIsAuthorized(filter, "1.2.3.4/a", false, false);
doTestIsAuthorized(filter, "1.2.3.4/-1", false, false);
doTestIsAuthorized(filter, "1.2.3.4/0", false, false);
doTestIsAuthorized(filter, "1.2.3.4/5", false, false);
doTestIsAuthorized(filter, "1.2.3.4/5a", false, false);
doTestIsAuthorized(filter, "1.2.3.4a/5", false, false);
doTestIsAuthorized(filter, "1.2.3.4//5", false, false);
doTestIsAuthorized(filter, "1.2.3.4/32", false, false);
doTestIsAuthorized(filter, "1.2.3.4/33", false, false);
doTestIsAuthorized(filter, "1.2.3.4/1234567890123456", false, false);
doTestIsAuthorized(filter, "1.", false, false);
doTestIsAuthorized(filter, "1.2", false, false);
doTestIsAuthorized(filter, "1.2.", false, false);
doTestIsAuthorized(filter, "1.2.3", false, false);
doTestIsAuthorized(filter, "1.2.3.", false, false);
doTestIsAuthorized(filter, "1.2.34.", false, false);
doTestIsAuthorized(filter, "1.2.3.4", true, false);
doTestIsAuthorized(filter, "194.134.168.213", true, true);
doTestIsAuthorized(filter, "194.134.168.212", true, false);
doTestIsAuthorized(filter, "194.134.168.214", true, false);
}
private void doTestIsAuthorized(IPFilter filter,
String ip,
boolean validIP,
boolean shouldBeAuth)
throws Throwable {
if (validIP) {
boolean auth = filter.isAuthorized(ip);
if (shouldBeAuth && !auth) {
fail("IPFilter.isAuthorized(\"" + ip + "\") should return true for \"" + filter + "\".");
} else if (!shouldBeAuth && auth) {
fail("IPFilter.isAuthorized(\"" + ip + "\") should return false for \"" + filter + "\".");
}
} else {
try {
filter.isAuthorized(ip);
fail("IPFilter.isAuthorized(\"" + ip + "\") should throw a ParseException.");
return;
} catch (ParseException exception) {
// as expected
}
}
}
}
|
package timeBench.data.relational;
import java.util.Iterator;
import prefuse.data.Graph;
import prefuse.data.Schema;
import prefuse.data.Table;
import prefuse.data.Tuple;
import prefuse.data.column.Column;
import prefuse.data.expression.AbstractPredicate;
import prefuse.data.tuple.TableEdge;
import prefuse.data.tuple.TupleManager;
import prefuse.util.collections.IntIterator;
import timeBench.data.TemporalDataException;
import timeBench.data.util.IntervalComparator;
import timeBench.data.util.IntervalIndex;
import timeBench.data.util.IntervalTreeIndex;
/**
* This class maintains data structures that encompass a temporal dataset. It
* consists of a {@link Table} of DataElements and a {@link Graph} of temporal
* elements. Temporal occurrences of data elements are saved in an additional
* {@link Table}. Furthermore, the class provides utility methods to index and
* query the dataset.
*
* <p>
* <b>Warning:</b> If a pre-existing temporal elements table is used, it needs
* to provide four columns for inf, sup, kind, and granularity id. Furthermore,
* the temporal elements table should yield tuples of class
* {@link GenericTemporalElement}.
*
* @author BA, AR, TL
*
*/
public class TemporalDataset {
private BipartiteGraph graph;
private Graph temporalElements;
private Graph occurrences;
private Table dataElements;
private TemporalElementManager temporalPrimitives;
// predefined column names for temporal elements
public static final String INF = "inf";
public static final String SUP = "sup";
public static final String GRANULARITY_ID = "granularityID";
public static final String KIND = "kind";
/**
* Constructs an empty {@link TemporalDataset}
*/
public TemporalDataset() {
this(new Table(), new Table());
// define temporal element columns for nodes of the temporal e. graph
this.getTemporalElements().addColumns(this.getTemporalElementSchema());
this.setTemporalElementManager(new TemporalElementManager(this, true));
}
/**
* Constructs a {@link TemporalDataset} with the given data- and temporal-elements
* @param dataElements a {@link Table} containing the data elements
* @param temporalElements a {@link Table} containing the temporal elements
*/
public TemporalDataset(Table dataElements, Table temporalElements) {
// here we cannot call the other constructor, because that would throw
// an exception that is impossible to catch
this.dataElements = dataElements;
this.temporalElements = new Graph(temporalElements, true);
graph = new BipartiteGraph(dataElements, getTemporalElements());
occurrences = new Graph(graph.getEdgeTable(), true);
// set a tuple manager for the edge table of the bipartite graph
// so that its tuples are instances of TemporalObject
graph.getEdgeTable().setTupleManager(
new BipartiteEdgeManager(graph.getEdgeTable(), graph,
TemporalObject.class));
this.temporalPrimitives = new TemporalElementManager(this, false);
this.temporalPrimitives.invalidateAutomatically();
}
/**
* Constructs a {@link TemporalDataset} with the given data- and temporal-elements
* @param dataElements a {@link Table} containing the data elements
* @param temporalElements a directed {@link Graph} containing the temporal elements
* and how they are related
* @throws TemporalDataException if the temporal element Graph is not directed
*/
public TemporalDataset(Table dataElements, Graph temporalElements) throws TemporalDataException {
if (!temporalElements.isDirected()) {
throw new TemporalDataException("The graph of the temporal elements must be directed");
}
this.dataElements = dataElements;
this.temporalElements = temporalElements;
graph = new BipartiteGraph(dataElements, getTemporalElements());
occurrences = new Graph(graph.getEdgeTable(), true);
// set a tuple manager for the edge table of the bipartite graph
// so that its tuples are instances of TemporalObject
graph.getEdgeTable().setTupleManager(
new BipartiteEdgeManager(graph.getEdgeTable(), graph,
TemporalObject.class));
this.temporalPrimitives = new TemporalElementManager(this, false);
this.temporalPrimitives.invalidateAutomatically();
}
/**
* Gets the data elements in the dataset
* @return a {@link Table} containing the data elements
*/
public Table getDataElements() {
return dataElements;
}
/**
* Gets the temporal elements in the dataset
* @return a {@link Table} containing the temporal elements.
*/
public Table getTemporalElements() {
return temporalElements.getNodeTable();
}
/**
* Gets the temporal elements in the dataset
* @return a {@link Graph} containing the temporal elements and how they are related.
*/
public Graph getTemporalElementsGraph() {
return temporalElements;
}
/**
* Get the TemporalElement instance corresponding to its id.
* @param n element id (temporal element table row number)
* @return the TemporalElement instance corresponding to the element id
*/
public GenericTemporalElement getTemporalElement(int n) {
return (GenericTemporalElement) temporalElements.getNode(n);
}
/**
* Get the temporal primitive corresponding to its id.
* @param n element id (temporal element table row number)
* @return the temporal primitive corresponding to the element id
*/
public TemporalElement getTemporalPrimitive(int n) {
return (TemporalElement) this.temporalPrimitives.getTuple(n);
}
/**
* Get an iterator over all temporal elements in the temporal dataset.
* @return an iterator over TemporalElement instances
*/
@SuppressWarnings("unchecked")
public Iterator<GenericTemporalElement> temporalElements() {
return temporalElements.nodes();
}
/**
* allows iteration over all temporal elements.
* @return an object, which provides an iterator
*/
public Iterable<TemporalElement> temporalElementsIterable() {
return new Iterable<TemporalElement>() {
@SuppressWarnings("unchecked")
@Override
public Iterator<TemporalElement> iterator() {
return temporalElements.nodes();
}
};
}
/**
* Get an iterator over all temporal primitives in the temporal dataset.
* @return an iterator over TemporalElement instances
*/
@SuppressWarnings("unchecked")
public Iterator<TemporalElement> temporalPrimitives() {
return this.temporalPrimitives.iterator(temporalElements.nodeRows());
}
/**
* Get an iterator over all temporal objects in the temporal dataset.
* The temporal object is a proxy tuple for a row in the occurrences table.
* @return an iterator over TemporalObject instances
*/
@SuppressWarnings("unchecked")
public Iterator<TemporalObject> temporalObjects() {
return graph.getEdgeTable().tuples();
}
/**
* Get the TemporalObject instance corresponding to its id.
* @param n object id (occurrences table row number)
* @return the TemporalObject instance corresponding to the object id
*/
public TemporalObject getTemporalObject(int n) {
return (TemporalObject) graph.getEdgeTable().getTuple(n);
}
/**
* Gets all (temporal) occurrences of data elements
* @return a {@link Table} containing all temporal occurrences
*
* TL 2011-11-07: not deprecated because needed to generate VisualTable
*/
public Table getOccurrences() {
return occurrences.getNodeTable();
}
/**
* Gets the graph that contains all (temporal) occurrences of data elements,
* and the relations between these occurrences.
* @return a {@link Graph} containing all occurrences and relations between them
*/
public Graph getOccurrencesGraph() {
return occurrences;
}
/**
* Adds an occurrence of a data element at a given temporal element
* @param dataElementInd the index of the data element in the {@link Table} of data elements
* @param temporalElementInd the index of the temporal element in the {@link Table} of temporal elements
* @return the index of the added occurrence in the {@link Table} of occurrences
*/
public int addOccurrence(int dataElementInd, int temporalElementInd) {
return graph.addEdge(dataElementInd, temporalElementInd);
}
/**
* Creates an {@link IntervalIndex} for the temporal elements. It helps in querying
* the elements based on intervals.
* @param comparator an {@link IntervalComparator} to compare intervals for indexing any querying purposes.
*/
// XXX this method does not yet exclude spans
public IntervalIndex createTemporalIndex(IntervalComparator comparator) {
Table elements = getTemporalElements();
Column colLo = elements.getColumn(INF);
Column colHi = elements.getColumn(SUP);
IntIterator rows = elements.rows(new AbstractPredicate() {
@Override
public boolean getBoolean(Tuple t) {
return t.getInt(KIND) != PRIMITIVE_SPAN;
}
});
return new IntervalTreeIndex(elements, rows, colLo, colHi, comparator);
}
/**
* Adds a new temporal element to the dataset
* @param inf the lower end of the temporal element
* @param sup the upper end of the temporal element
* @param granularityId the granularityID of the temporal element
* @param kind the kind of the temporal element
* @return the index of the created element in the table of temporal elements
*/
public int addTemporalElement(long inf, long sup, int granularityId, int kind) {
Table nodeTable = temporalElements.getNodeTable();
int row = nodeTable.addRow();
nodeTable.set(row, INF, inf);
nodeTable.set(row, SUP, sup);
nodeTable.set(row, GRANULARITY_ID, granularityId);
nodeTable.set(row, KIND, kind);
// enforce that class of proxy tuple is reconsidered
// this is safe because the object is not known outside of this method
// (exception are tuple listeners)
// this.temporalTuples.invalidate(row);
return row;
}
// TODO do we want/need methods like this
/**
* Add a new instant to the dataset. This method returns a proxy tuple of
* this instant, which is of class {@link Instant}.
*
* @param inf
* the lower end of the temporal element
* @param sup
* the upper end of the temporal element
* @param granularityId
* the granularityID of the temporal element
* @return a proxy tuple of the created temporal element
*/
public Instant addInstant(long inf, long sup, int granularityId) {
int row = this.addTemporalElement(inf, sup, granularityId,
TemporalDataset.PRIMITIVE_INSTANT);
Instant result = (Instant) this.temporalPrimitives.getTuple(row);
return result;
}
/**
* Set a tuple manager for temporal elements and use it in the underlying
* data structures.
*
* <p>
* Use this method carefully, as it will cause all existing Tuples retrieved
* from this dataset to be invalidated.
*
* @param manager
* tuple manager for temporal elements
*/
private void setTemporalElementManager(TemporalElementManager manager) {
// TupleManager temporalTuples = new TupleManager(
// temporalElements.getNodeTable(), temporalElements,
// GenericTemporalElement.class);
TupleManager temporalTuples = manager;
// we also need to set a manager for edge tuples
TupleManager edgeTuples = new TupleManager(
temporalElements.getEdgeTable(), temporalElements,
TableEdge.class);
temporalElements.setTupleManagers(temporalTuples, edgeTuples);
temporalElements.getNodeTable().setTupleManager(temporalTuples);
temporalElements.getEdgeTable().setTupleManager(edgeTuples);
}
/**
* Get an instance of the default {@link Schema} used for
* {@link TemporalElement} instances. Contains the data members internally
* used to model a temporal element, i.e. inf, sup, granularity, and kind.
*
* @return the TemporalElement data Schema
*/
public Schema getTemporalElementSchema() {
Schema s = new Schema();
s.addColumn(INF, long.class, Long.MIN_VALUE);
s.addColumn(SUP, long.class, Long.MAX_VALUE);
s.addColumn(GRANULARITY_ID, int.class, -1);
s.addColumn(KIND, int.class, -1);
return s;
}
// predefined kinds of temporal elements
public static final int PRIMITIVE_SPAN = 0;
public static final int PRIMITIVE_SET = 1;
public static final int PRIMITIVE_INSTANT = 2;
public static final int PRIMITIVE_INTERVAL = 3;
// TODO move this enumeration to a separate file???
// TODO use constants instead of enumeration?
@Deprecated
public enum Primitives {
SPAN(0),
SET(1),
INSTANT(2),
INTERVAL(3);
public final int kind;
private Primitives(int kind) {
this.kind = kind;
}
}
/**
* creates a human-readable string from a {@link TemporalDataset}.
* <p>
* Example:TemporalDataset [7 temporal elements, 6 data elements, 6 temporal
* objects]
*
* @return a string representation
*/
@Override
public String toString() {
return "TemporalDataset [" + this.getTemporalElements().getRowCount()
+ " temporal elements, " + this.getDataElements().getRowCount()
+ " data elements, " + this.graph.getEdgeCount()
+ " temporal objects]";
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.controls.scrolling;
import com.jme3.input.event.MouseButtonEvent;
import com.jme3.input.event.MouseMotionEvent;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector4f;
import java.util.Set;
import tonegod.gui.core.Element;
import tonegod.gui.core.Screen;
import tonegod.gui.listeners.MouseWheelListener;
/**
*
* @author t0neg0d
*/
public class ScrollArea extends Element implements MouseWheelListener {
protected Element scrollableArea;
private boolean isTextOnly = true;
private boolean isScrollable = true;
private VScrollBar vScrollBar;
private float scrollSize;
/**
* Creates a new instance of the ScrollArea control
*
* @param screen The screen control the Element is to be added to
* @param UID A unique String identifier for the Element
* @param position A Vector2f containing the x/y position of the Element
* @param isTextOnly Boolean defining if the scroll area will contain other Elements or use formatted text
*/
public ScrollArea(Screen screen, String UID, Vector2f position, boolean isTextOnly) {
this(screen, UID, position,
screen.getStyle("ScrollArea").getVector2f("defaultSize"),
screen.getStyle("ScrollArea").getVector4f("resizeBorders"),
screen.getStyle("ScrollArea").getString("defaultImg"),
isTextOnly
);
}
/**
* Creates a new instance of the ScrollArea control
*
* @param screen The screen control the Element is to be added to
* @param UID A unique String identifier for the Element
* @param position A Vector2f containing the x/y position of the Element
* @param dimensions A Vector2f containing the width/height dimensions of the Element
* @param isTextOnly Boolean defining if the scroll area will contain other Elements or use formatted text
*/
public ScrollArea(Screen screen, String UID, Vector2f position, Vector2f dimensions, boolean isTextOnly) {
this(screen, UID, position, dimensions,
screen.getStyle("ScrollArea").getVector4f("resizeBorders"),
screen.getStyle("ScrollArea").getString("defaultImg"),
isTextOnly
);
}
/**
* Creates a new instance of the ScrollArea control
*
* @param screen The screen control the Element is to be added to
* @param UID A unique String identifier for the Element
* @param position A Vector2f containing the x/y position of the Element
* @param dimensions A Vector2f containing the width/height dimensions of the Element
* @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S)
* @param defaultImg The default image to use for the Slider's track
* @param isTextOnly Boolean defining if the scroll area will contain other Elements or use formatted text
*/
public ScrollArea (Screen screen, String UID, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg, boolean isTextOnly) {
super (screen, UID, position, dimensions, resizeBorders, defaultImg);
this.isTextOnly = isTextOnly;
scrollSize = screen.getStyle("ScrollArea#VScrollBar").getFloat("defaultControlSize");
if (!isTextOnly) {
createScrollableArea();
} else {
setTextPadding(0);
}
vScrollBar = new VScrollBar(screen, UID + ":vScroll",
new Vector2f(getWidth(), 0),
new Vector2f(scrollSize, getHeight())
);
addChild(vScrollBar);
setVScrollBar(vScrollBar);
}
private void createScrollableArea() {
scrollableArea = new Element(screen, getUID() + ":scrollable", new Vector2f(0, 0), new Vector2f(getWidth(), getHeight()), new Vector4f(14,14,14,14), null);
// scrollableArea.setTextPadding(0);
scrollableArea.setIsResizable(false);
scrollableArea.setIsMovable(false);
scrollableArea.setScaleEW(true);
scrollableArea.setScaleNS(false);
scrollableArea.setDockN(true);
scrollableArea.setDockW(true);
scrollableArea.setClippingLayer(this);
scrollableArea.setTextClipPadding(4);
this.addChild(scrollableArea);
}
public boolean getIsTextOnly() {
return isTextOnly;
}
private void setVScrollBar(VScrollBar vScrollBar) {
this.vScrollBar = vScrollBar;
vScrollBar.setScrollableArea(this);
}
public VScrollBar getVScrollBar() {
return this.vScrollBar;
}
public void addScrollableChild(Element child) {
scrollableArea.addChild(child);
}
public void setPadding(float padding) {
if (isTextOnly) {
setTextPadding(padding);
setTextClipPadding(padding);
} else {
scrollableArea.setTextPadding(padding);
scrollableArea.setTextClipPadding(padding);
}
}
public float getPadding() {
if (isTextOnly) {
return getTextPadding();
} else {
return scrollableArea.getTextPadding();
}
}
public float getScrollableHeight() {
if (isTextOnly) {
return textElement.getHeight()+(getTextPadding()*2);
} else {
return scrollableArea.getHeight()+(scrollableArea.getTextPadding()*2);
}
}
@Override
public void controlResizeHook() {
if (vScrollBar != null) {
vScrollBar.setThumbScale();
}
}
@Override
public void setControlClippingLayer(Element clippingLayer) {
// setClippingLayer(clippingLayer);
Set<String> keys = elementChildren.keySet();
for (String key : keys) {
elementChildren.get(key).setControlClippingLayer(clippingLayer);
}
}
public void scrollYTo(float y) {
if (scrollableArea == null) {
textElement.setLocalTranslation(textElement.getLocalTranslation().setY(y));
} else {
scrollableArea.setY(0);
scrollableArea.setY(y);
}
}
public void scrollYBy(float yInc) {
if (scrollableArea == null) {
float nextY = textElement.getLocalTranslation().getY() + yInc;
textElement.setLocalTranslation(textElement.getLocalTranslation().setY(yInc));
} else {
scrollableArea.setY(scrollableArea.getY()+yInc);
}
}
public void scrollToBottom() {
vScrollBar.scrollToBottom();
/*
if (scrollableArea == null) {
if (textElement.getHeight() > getHeight()) {
textElement.setLocalTranslation(textElement.getLocalTranslation().setY(0));
}
} else {
if (scrollableArea.getHeight() > getHeight()) {
scrollableArea.setY(0+scrollableArea.getTextPadding());
}
}
*/
}
public void scrollToTop() {
if (scrollableArea == null) {
if (textElement.getHeight() > getHeight()) {
textElement.setLocalTranslation(textElement.getLocalTranslation().setY(0+this.getTextPadding()));
}
} else {
if (scrollableArea.getHeight() > getHeight()) {
scrollableArea.setY(0+scrollableArea.getTextPadding());
}
}
}
@Override
public void onMouseWheelPressed(MouseButtonEvent evt) { }
@Override
public void onMouseWheelReleased(MouseButtonEvent evt) { }
@Override
public void onMouseWheelUp(MouseMotionEvent evt) {
if (vScrollBar != null) {
vScrollBar.scrollByYInc(-vScrollBar.getTrackInc());
}
}
@Override
public void onMouseWheelDown(MouseMotionEvent evt) {
if (vScrollBar != null) {
vScrollBar.scrollByYInc(vScrollBar.getTrackInc());
}
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TSP {
private static final int TIME_LIMIT = 1500;
private double[][] coordinates;
private int[][] distances;
private List<Short> route;
private long deadline;
private static boolean benchmark;
public TSP() {
deadline = System.currentTimeMillis() + TIME_LIMIT;
try {
coordinates = readCoordinates();
} catch (IOException e) {
e.printStackTrace();
}
distances = calculateEuclideanDistance();
route = twoOptSearch(nearestNeighbourRoute());
if (benchmark) {
System.out.println(calculateTotalDistance(route));
} else {
for (int i = 0; i < route.size(); i++) {
System.out.println(route.get(i));
}
}
}
private List<Short> twoOptSearch(List<Short> existingRoute) {
int bestDistance = calculateTotalDistance(existingRoute);
search: while (true) {
for (int i = 0; i < existingRoute.size() - 1; i++) {
for (int k = i + 1; k < existingRoute.size(); k++) {
if (System.currentTimeMillis() >= deadline)
break search;
int newDistance = bestDistance - gainAfterSwap(existingRoute, i, k);
if (newDistance < bestDistance) {
twoOptSwap(existingRoute, i, k);
bestDistance = newDistance;
continue search;
}
}
}
break;
}
return existingRoute;
}
private int gainAfterSwap(List<Short> existingRoute, int i, int k) {
short first, last;
if (i == 0)
first = existingRoute.get(existingRoute.size() - 1);
else
first = existingRoute.get(i - 1);
if (k == existingRoute.size() - 1)
last = existingRoute.get(0);
else
last = existingRoute.get(k + 1);
int previousCost = getDistance(first, existingRoute.get(i)) + getDistance(existingRoute.get(k), last);
int newCost = getDistance(first, existingRoute.get(k)) + getDistance(existingRoute.get(i), last);
return previousCost - newCost;
}
private void twoOptSwap(List<Short> route, int i, int k) {
Collections.reverse(route.subList(i, k));
}
private List<Short> nearestNeighbourRoute() {
List<Short> newRoute = new ArrayList<Short>();
boolean[] visited = new boolean[distances.length];
short firstVertex = 0;
newRoute.add(firstVertex);
visited[firstVertex] = true;
for (int i = 0; i < distances.length - 1; i++) {
newRoute.add(findNearestNeighbour(newRoute.get(i), visited));
}
return newRoute;
}
private short findNearestNeighbour(int from, boolean[] visited) {
int minCost = Integer.MAX_VALUE;
short nearest = 0;
for (short to = 0; to < distances.length; to++) {
int cost = getDistance(from, to);
if (!visited[to] && cost < minCost) {
minCost = cost;
nearest = to;
}
}
visited[nearest] = true;
return nearest;
}
private int calculateTotalDistance(List<Short> route) {
int sum = getDistance(route.get(route.size() - 1), route.get(0));
for (int i = 0; i < route.size() - 1; i++) {
sum += getDistance(route.get(i), route.get(i + 1));
}
return sum;
}
private int[][] calculateEuclideanDistance() {
int[][] euclideanDistances = new int[coordinates.length][];
for (int i = 0; i < coordinates.length; i++) {
euclideanDistances[i] = new int[i + 1];
for (int j = 0; j < i; j++) {
euclideanDistances[i][j] = euclidianDistance(coordinates[i], coordinates[j]);
}
}
return euclideanDistances;
}
private int euclidianDistance(double[] i, double[] j) {
return (int) Math.round(Math.sqrt(Math.pow(i[0] - j[0], 2) + Math.pow(i[1] - j[1], 2)));
}
private int getDistance(int i, int j) {
if (j > i) {
return distances[j][i];
} else {
return distances[i][j];
}
}
private double[][] readCoordinates() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double[][] data;
int n = Integer.parseInt(br.readLine());
data = new double[n][2];
for (int i = 0; i < n; i++) {
String[] input = br.readLine().split(" ");
data[i][0] = Double.parseDouble(input[0]);
data[i][1] = Double.parseDouble(input[1]);
}
return data;
}
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("benchmark")) {
benchmark = true;
}
new TSP();
}
}
|
package etomica.models.water;
import java.util.ArrayList;
import etomica.action.BoxImposePbc;
import etomica.action.activity.ActivityIntegrate;
import etomica.api.IAtomType;
import etomica.api.IBox;
import etomica.api.IPotentialMaster;
import etomica.atom.AtomLeafAgentManager;
import etomica.atom.DiameterHashByType;
import etomica.box.Box;
import etomica.config.ConfigurationLattice;
import etomica.data.DataPump;
import etomica.data.meter.MeterPotentialEnergy;
import etomica.graphics.ColorSchemeByType;
import etomica.graphics.DisplayBox;
import etomica.graphics.DisplayTextBox;
import etomica.graphics.SimulationGraphic;
import etomica.integrator.IntegratorMC;
import etomica.integrator.mcmove.MCMoveMolecule;
import etomica.integrator.mcmove.MCMoveRotateMolecule3D;
import etomica.integrator.mcmove.MCMoveStepTracker;
import etomica.integrator.mcmove.MCMoveVolume;
import etomica.lattice.LatticeCubicFcc;
import etomica.listener.IntegratorListenerAction;
import etomica.nbr.CriterionAll;
import etomica.potential.EwaldSummation;
import etomica.potential.EwaldSummation.MyCharge;
import etomica.potential.P2LennardJones;
import etomica.potential.PotentialMaster;
import etomica.simulation.Simulation;
import etomica.space.BoundaryRectangularPeriodic;
import etomica.space.Space;
import etomica.space3d.Space3D;
import etomica.units.Bar;
import etomica.units.Kelvin;
import etomica.units.Pixel;
public class TestEwaldTIP4PWater extends Simulation {
TestEwaldTIP4PWater(Space space){
super(space);
potentialMaster = new PotentialMaster();
LatticeCubicFcc lattice = new LatticeCubicFcc(space);
ConfigurationLattice configuration = new ConfigurationLattice(lattice, space);
ConformationWaterTIP4P config = new ConformationWaterTIP4P(space);
species = new SpeciesWater4P(space);
species.setConformation(config);
addSpecies(species);
integrator = new IntegratorMC(this, potentialMaster);
integrator.setTemperature(Kelvin.UNIT.toSim(298));
MCMoveMolecule mcMoveMolecule = new MCMoveMolecule(this, potentialMaster, space);
MCMoveRotateMolecule3D mcMoveRotateMolecule = new MCMoveRotateMolecule3D(potentialMaster, random, space);
MCMoveVolume mcMoveVolume = new MCMoveVolume(potentialMaster, random, space, Bar.UNIT.toSim(1.0132501));
((MCMoveStepTracker)mcMoveVolume.getTracker()).setNoisyAdjustment(true);
integrator.getMoveManager().addMCMove(mcMoveMolecule);
integrator.getMoveManager().addMCMove(mcMoveRotateMolecule);
integrator.getMoveManager().addMCMove(mcMoveVolume);
ActivityIntegrate activityIntegrate = new ActivityIntegrate(integrator);
activityIntegrate.setMaxSteps(6000);
getController().addAction(activityIntegrate);
box = new Box(space);
addBox(box);
box.getBoundary().setBoxSize(space.makeVector(new double[] {25, 25, 25}));
box.setNMolecules(species, 125);
//Potential
P2LennardJones potentialLJ = new P2LennardJones(space, 3.154,Kelvin.UNIT.toSim(78.02));
potentialMaster.addPotential(potentialLJ, new IAtomType[]{species.getOxygenType(), species.getOxygenType()} );
CriterionAll criterionAll = new CriterionAll();
//Ewald Summation
ChargeAgentSourceTIP4PWater agentSource = new ChargeAgentSourceTIP4PWater();
AtomLeafAgentManager<MyCharge> atomAgentManager = new AtomLeafAgentManager<MyCharge>(agentSource, box, MyCharge.class);
EwaldSummation ewaldSummation = new EwaldSummation(box, atomAgentManager, space, 4, 9);
// ewaldSummation.setCriterion(criterionAll);
// ewaldSummation.setBondedIterator(new ApiIntragroup());
potentialMaster.addPotential(ewaldSummation, new IAtomType[0]);
BoxImposePbc imposePBC = new BoxImposePbc(box, space);
boundary = new BoundaryRectangularPeriodic(space, 20);
boundary.setBoxSize(space.makeVector(new double[] {20, 20, 20}));
box.setBoundary(boundary);
configuration.initializeCoordinates(box);
integrator.setBox(box);
integrator.getEventManager().addListener(new IntegratorListenerAction(imposePBC));
}
public static void main (String[] args){
Space sp = Space3D.getInstance();
TestEwaldTIP4PWater sim = new TestEwaldTIP4PWater(sp);
SimulationGraphic simGraphic = new SimulationGraphic(sim, APP_NAME, 1, sp, sim.getController());
Pixel pixel = new Pixel(10);
simGraphic.getDisplayBox(sim.box).setPixelUnit(pixel);
ArrayList dataStreamPumps = simGraphic.getController().getDataStreamPumps();
MeterPotentialEnergy meterPE = new MeterPotentialEnergy(sim.potentialMaster);
meterPE.setBox(sim.box);
DisplayTextBox PEbox = new DisplayTextBox();
DataPump PEpump = new DataPump(meterPE, PEbox);
dataStreamPumps.add(PEpump);
IntegratorListenerAction pumpListener = new IntegratorListenerAction(PEpump);
pumpListener.setInterval(1);
sim.integrator.getEventManager().addListener(pumpListener);
simGraphic.add(PEbox);
simGraphic.getDisplayBox(sim.box).setPixelUnit(new Pixel(PIXEL_SIZE));
simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box));
ColorSchemeByType colorScheme = ((ColorSchemeByType)((DisplayBox)simGraphic.displayList().getFirst()).getColorScheme());
colorScheme.setColor(sim.species.getHydrogenType(), java.awt.Color.WHITE);
colorScheme.setColor(sim.species.getOxygenType(), java.awt.Color.RED);
((DiameterHashByType)simGraphic.getDisplayBox(sim.box).getDiameterHash()).setDiameter(sim.species.getMType(), 0);
simGraphic.makeAndDisplayFrame(APP_NAME);
simGraphic.getDisplayBox(sim.box).repaint();
}
protected final IPotentialMaster potentialMaster;
protected final IBox box;
protected final SpeciesWater4P species;
protected final IntegratorMC integrator;
protected final BoundaryRectangularPeriodic boundary;
private final static String APP_NAME = "Test Ewald Sum TIP4P Water";
private static final int PIXEL_SIZE = 15;
private static final long serialVersionUID = 1L;
}
|
package org.dukecon.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
/**
* @author Gerd Aschemann <gerd@aschemann.net>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserPreference {
@NonNull private String talkId;
private int version;
}
|
package io.mockk.junit;
import io.mockk.agent.MockKClassLoader;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.JUnit4;
import java.lang.reflect.Constructor;
/**
* Do class translation for JUnit4 tests.
* <p>
* Delegates actual running responsibility to one of runners:
* <ul>
* <li>runner annotated with @ChainedRunWith (first found in class hierarchy)</li>
* <li>annotated with @RunWith for superclasses</li>
* <li>JUnit4 default runner</li>
* </ul>
*/
public class MockKJUnit4Runner extends Runner {
private final Runner runner;
public MockKJUnit4Runner(Class<?> cls) throws Exception {
ClassLoader loader = MockKClassLoader.newClassLoader(cls.getClassLoader());
Thread.currentThread().setContextClassLoader(loader);
cls = loader.loadClass(cls.getName());
Class<?> runnerClass = findChainedRunner(cls);
if (runnerClass == null) {
runnerClass = findRunnerInSuperclass(cls);
}
if (runnerClass == null) {
runnerClass = JUnit4.class;
}
Constructor<?> constructor = runnerClass.getConstructor(Class.class);
this.runner = (Runner) constructor.newInstance(cls);
}
private Class<?> findChainedRunner(Class<?> cls) {
while (cls != null) {
ChainedRunWith chainedRunWith = cls.getAnnotation(ChainedRunWith.class);
if (chainedRunWith != null) {
return chainedRunWith.value();
}
cls = cls.getSuperclass();
}
return null;
}
private Class<?> findRunnerInSuperclass(Class<?> cls) {
cls = cls.getSuperclass();
while (cls != null) {
RunWith runWith = cls.getAnnotation(RunWith.class);
if (runWith != null) {
return runWith.value();
}
cls = cls.getSuperclass();
}
return null;
}
@Override
public Description getDescription() {
return runner.getDescription();
}
@Override
public void run(RunNotifier notifier) {
runner.run(notifier);
}
}
|
package com.microsoft.hostedwebapp;
import android.app.Activity;
import android.content.res.AssetManager;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
/**
* This class manipulates the Web App W3C manifest.
*/
public class HostedWebApp extends CordovaPlugin {
private static final String OFFLINE_PAGE = "offline.html";
private static final String OFFLINE_PAGE_TEMPLATE = "<html><body><div style=\"top:50%%;text-align:center;position:absolute\">%s</div></body></html>";
private JSONObject manifestObject;
private Activity activity;
private WebView offlineWebView;
private LinearLayout rootLayout;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.activity = cordova.getActivity();
this.activity.runOnUiThread(new Runnable() {
@Override
public void run() {
HostedWebApp me = HostedWebApp.this;
if (me.rootLayout == null) {
me.rootLayout = me.createOfflineRootLayout();
me.activity.addContentView(me.rootLayout, me.rootLayout.getLayoutParams());
}
if (me.offlineWebView == null) {
me.offlineWebView = me.createOfflineWebView();
me.rootLayout.addView(me.offlineWebView);
}
if (me.assetExists(HostedWebApp.OFFLINE_PAGE)) {
me.offlineWebView.loadUrl("file:///android_asset/www/" + HostedWebApp.OFFLINE_PAGE);
} else {
me.offlineWebView.loadData(
String.format(HostedWebApp.OFFLINE_PAGE_TEMPLATE, "It looks like you are offline. Please reconnect to use this application."),
"text/html",
null);
}
}
});
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("load")) {
AssetManager assetManager = cordova.getActivity().getResources().getAssets();
try {
String configFilename = args.getString(0);
InputStream inputStream = assetManager.open("www/" + configFilename);
int size = inputStream.available();
byte[] bytes = new byte[size];
inputStream.read(bytes);
inputStream.close();
String jsonString = new String(bytes, "UTF-8");
callbackContext.success(jsonString);
} catch (IOException e) {
callbackContext.error(e.getMessage());
}
} else if (action.equals("initialize")) {
this.manifestObject = args.getJSONObject(0);
} else if (action.equals("showOfflineOverlay")) {
this.showOfflineOverlay();
} else if (action.equals("hideOfflineOverlay")) {
this.hideOfflineOverlay();
} else {
return false;
}
return true;
}
@Override
public Object onMessage(String id, Object data) {
if (id.equals("networkconnection") && data != null) {
handleNetworkConnectionChange(data.toString());
}
return null;
}
private boolean assetExists(String asset) {
final AssetManager assetManager = this.activity.getResources().getAssets();
try {
return Arrays.asList(assetManager.list("www")).contains(asset);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private WebView createOfflineWebView() {
WebView webView = new WebView(activity);
webView.getSettings().setJavaScriptEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
1.0F));
return webView;
}
private LinearLayout createOfflineRootLayout() {
LinearLayout root = new LinearLayout(activity.getBaseContext());
root.setOrientation(LinearLayout.VERTICAL);
root.setVisibility(View.INVISIBLE);
root.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
0.0F));
return root;
}
private void handleNetworkConnectionChange(String info) {
if (info.equals("none")) {
this.showOfflineOverlay();
} else {
this.hideOfflineOverlay();
}
}
private void showOfflineOverlay() {
this.activity.runOnUiThread(new Runnable() {
@Override
public void run() {
rootLayout.setVisibility(View.VISIBLE);
}
});
}
private void hideOfflineOverlay() {
this.activity.runOnUiThread(new Runnable() {
@Override
public void run() {
rootLayout.setVisibility(View.INVISIBLE);
}
});
}
}
|
package org.cache2k;
/**
* @author Jens Wilke; created: 2014-03-21
*
* @deprecated
*/
public class EntryRefreshController<T> implements RefreshController<T> {
public static final EntryRefreshController INSTANCE = new EntryRefreshController();
public long calculateNextRefreshTime(
T _oldObject,
T _newObject,
long _timeOfLastRefresh, long now) {
return ((ValueWithNextRefreshTime) _newObject).getNextRefreshTime();
}
}
|
package com.data.models;
public class PlanedEvent {
private String title;
private String description;
private String start;
private String end;
private String id;
private SimpleDate date;
private Boolean isUserIn;
public PlanedEvent(){
}
public PlanedEvent(String end, String start, String description, String title, SimpleDate date) {
this.setEnd(end);
this.setStart(start);
this.setDescription(description);
this.setTitle(title);
this.setDate(date);
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public SimpleDate getDate() {
return date;
}
public void setDate(SimpleDate date) {
this.date = date;
}
public Boolean getUserIn() {
return isUserIn;
}
public void setUserIn(Boolean userIn) {
isUserIn = userIn;
}
}
|
package statzall;
import java.util.Map;
/**
* Utilities for strong typing in Map.get() and Objects, more robust than JDK
* standard Class.cast()
*
* @author mpouttuclarke
*
*/
public class Cast {
/**
* Attempt to get the key's value from the passed map, casting to the
* caller's desired type if possible.
*
* If the key does not exist or the type is not as expected, returns a null.
*
* @param map
* @param key
* @param returnType
* @return
*/
public static <T> T getAs(Map<? extends Object, ? extends Object> map, Object key, Class<T> returnType) {
if (map == null || key == null || returnType == null) {
return null;
}
return as(map.get(key), returnType);
}
/**
* Attempt to get the key's value from the passed map, casting to the
* caller's desired type if possible. Throws a ClassCastException in the
* case of a failed cast, and a NullPointerException if the map is null.
*
* @param map
* @param key
* @return
* @throws NullPointerException
* @throws ClassCastException
*/
public static <T> T getAs(Map<? extends Object, ? extends Object> map, String key)
throws NullPointerException, ClassCastException {
return as(map.get(key));
}
/**
* Attempt to get the Objects value, casting to the caller's desired type if
* possible.
*
* If the object does not exist or the type is not as expected, returns a
* null.
*
* @param obj
* @param returnType
* @return
*/
@SuppressWarnings({ "unchecked" })
public static <T> T as(Object object, Class<T> returnType) {
if (object == null) {
return null;
} else if (!returnType.isAssignableFrom(object.getClass())) {
if (returnType.isAssignableFrom(String.class)) {
return (T)String.valueOf(object);
}
return null;
} else {
return (T) object;
}
}
/**
* Attempt to cast the Object's value, casting to the caller's desired type
* if possible. Throws a ClassCastException in the case of a failed cast,
* and a NullPointerException if the object is null.
*
* @param obj
* @return
* @throws NullPointerException
* @throws ClassCastException
*/
@SuppressWarnings({ "unchecked" })
public static <T> T as(Object object) throws NullPointerException, ClassCastException {
return (T) object;
}
}
|
package com.oracle.graal.nodes.java;
import static com.oracle.graal.api.code.DeoptimizationAction.*;
import static com.oracle.graal.api.meta.DeoptimizationReason.*;
import static com.oracle.graal.nodes.extended.BranchProbabilityNode.*;
import com.oracle.graal.api.code.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.api.meta.ProfilingInfo.TriState;
import com.oracle.graal.graph.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.calc.*;
import com.oracle.graal.nodes.spi.*;
import com.oracle.graal.nodes.type.*;
/**
* Implements a type check against a compile-time known type.
*/
public final class CheckCastNode extends FixedWithNextNode implements Canonicalizable, Lowerable, Node.IterableNodeType, Virtualizable, ValueProxy {
@Input private ValueNode object;
private final ResolvedJavaType type;
private final JavaTypeProfile profile;
/**
* Determines the exception thrown by this node if the check fails: {@link ClassCastException}
* if false; {@link ArrayStoreException} if true.
*/
private final boolean forStoreCheck;
/**
* Creates a new CheckCast instruction.
*
* @param type the type being cast to
* @param object the instruction producing the object
*/
public CheckCastNode(ResolvedJavaType type, ValueNode object, JavaTypeProfile profile, boolean forStoreCheck) {
super(StampFactory.declared(type));
assert type != null;
this.type = type;
this.object = object;
this.profile = profile;
this.forStoreCheck = forStoreCheck;
}
public boolean isForStoreCheck() {
return forStoreCheck;
}
/**
* Lowers a {@link CheckCastNode} to a {@link GuardingPiNode}. That is:
*
* <pre>
* 1: A a = ...
* 2: B b = (B) a;
* </pre>
*
* is lowered to:
*
* <pre>
* 1: A a = ...
* 2: B b = guardingPi(a == null || a instanceof B, a, stamp(B))
* </pre>
*
* or if a is known to be non-null:
*
* <pre>
* 1: A a = ...
* 2: B b = guardingPi(a instanceof B, a, stamp(B, non-null))
* </pre>
*
* Note: we use {@link Graph#add} as opposed to {@link Graph#unique} for the new
* {@link InstanceOfNode} to maintain the invariant checked by
* {@code LoweringPhase.checkUsagesAreScheduled()}.
*/
@Override
public void lower(LoweringTool tool) {
InstanceOfNode typeTest = graph().add(new InstanceOfNode(type, object, profile));
Stamp stamp = StampFactory.declared(type);
if (stamp() instanceof ObjectStamp && object().stamp() instanceof ObjectStamp) {
stamp = ((ObjectStamp) object().stamp()).castTo((ObjectStamp) stamp);
}
ValueNode condition;
if (stamp instanceof IllegalStamp) {
// This is a check cast that will always fail
condition = LogicConstantNode.contradiction(graph());
stamp = StampFactory.declared(type);
} else if (ObjectStamp.isObjectNonNull(object)) {
condition = typeTest;
} else {
if (profile != null && profile.getNullSeen() == TriState.FALSE) {
FixedGuardNode nullGuard = graph().add(new FixedGuardNode(graph().unique(new IsNullNode(object)), UnreachedCode, DeoptimizationAction.InvalidateReprofile, true));
graph().addBeforeFixed(this, nullGuard);
condition = typeTest;
stamp = stamp.join(StampFactory.objectNonNull());
} else {
// TODO (ds) replace with probability of null-seen when available
double shortCircuitProbability = NOT_FREQUENT_PROBABILITY;
condition = LogicNode.or(graph().unique(new IsNullNode(object)), typeTest, shortCircuitProbability);
}
}
GuardingPiNode checkedObject = graph().add(new GuardingPiNode(object, condition, false, forStoreCheck ? ArrayStoreException : ClassCastException, InvalidateReprofile, stamp));
graph().replaceFixedWithFixed(this, checkedObject);
}
@Override
public boolean inferStamp() {
if (stamp() instanceof ObjectStamp && object().stamp() instanceof ObjectStamp) {
return updateStamp(((ObjectStamp) object().stamp()).castTo((ObjectStamp) stamp()));
}
return false;
}
@Override
public ValueNode canonical(CanonicalizerTool tool) {
assert object() != null : this;
ResolvedJavaType objectType = ObjectStamp.typeOrNull(object());
if (objectType != null && type.isAssignableFrom(objectType)) {
// we don't have to check for null types here because they will also pass the
// checkcast.
return object();
}
// if the previous node is also a checkcast, with a less precise and compatible type,
// replace both with one checkcast checking the more specific type.
if (predecessor() instanceof CheckCastNode) {
CheckCastNode ccn = (CheckCastNode) predecessor();
if (ccn != null && ccn.type != null && ccn == object && ccn.forStoreCheck == forStoreCheck && ccn.type.isAssignableFrom(type)) {
StructuredGraph graph = ccn.graph();
CheckCastNode newccn = graph.add(new CheckCastNode(type, ccn.object, ccn.profile, ccn.forStoreCheck));
graph.replaceFixedWithFixed(ccn, newccn);
return newccn;
}
}
if (ObjectStamp.isObjectAlwaysNull(object())) {
return object();
}
if (tool.assumptions() != null && tool.assumptions().useOptimisticAssumptions()) {
ResolvedJavaType exactType = type.findUniqueConcreteSubtype();
if (exactType != null && exactType != type) {
// Propagate more precise type information to usages of the checkcast.
tool.assumptions().recordConcreteSubtype(type, exactType);
return graph().add(new CheckCastNode(exactType, object, profile, forStoreCheck));
}
}
return this;
}
public ValueNode object() {
return object;
}
/**
* Gets the type being cast to.
*/
public ResolvedJavaType type() {
return type;
}
public JavaTypeProfile profile() {
return profile;
}
@Override
public void virtualize(VirtualizerTool tool) {
State state = tool.getObjectState(object);
if (state != null && state.getState() == EscapeState.Virtual) {
if (type.isAssignableFrom(state.getVirtualObject().type())) {
tool.replaceWithVirtual(state.getVirtualObject());
}
}
}
@Override
public ValueNode getOriginalValue() {
return object;
}
}
|
package charts.builder.spreadsheet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.Color;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.tika.io.IOUtils;
import play.Logger;
import charts.builder.DataSource;
import charts.builder.Value;
import charts.builder.spreadsheet.external.ResolvedRef;
import charts.builder.spreadsheet.external.SimpleCellLink;
import charts.builder.spreadsheet.external.UnresolvedRef;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public abstract class SpreadsheetDataSource implements DataSource {
private Workbook workbook;
private FormulaEvaluator evaluator;
private final int defaultSheet;
private class SpreadsheetCellValue implements Value {
private final Cell cell;
public SpreadsheetCellValue(Cell cell) {
this.cell = cell;
}
@Override
public String getValue() {
String result = "";
try {
CellValue cellValue = evaluator().evaluate(cell);
if (cellValue == null) {
return "";
}
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
result = Boolean.toString(cellValue.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
double val = cellValue.getNumberValue();
result = Double.toString(val);
break;
case Cell.CELL_TYPE_STRING:
result = cellValue.getStringValue();
break;
case Cell.CELL_TYPE_BLANK:
result = "";
break;
case Cell.CELL_TYPE_ERROR:
result = ErrorEval.getText(cellValue.getErrorValue());
break;
// CELL_TYPE_FORMULA will never happen
case Cell.CELL_TYPE_FORMULA:
result = "#FORMULAR";
break;
default:
result = "#DEFAULT";
}
} catch(RuntimeException e) {
if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
switch(cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
double val = cell.getNumericCellValue();
result = Double.toString(val);
break;
case Cell.CELL_TYPE_ERROR:
FormulaError fe = FormulaError.forInt(cell.getErrorCellValue());
result = fe.getString();
break;
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
result = Boolean.toString(cell.getBooleanCellValue());
break;
default:
result = "";
}
}
}
return result;
}
@Override
public String toString() {
String result;
DataFormatter df = new DataFormatter();
result = df.formatCellValue(cell, evaluator());
return result;
}
@Override
public String asString() {
return getValue();
}
@Override
public Double asDouble() {
String s = getValue();
try {
return new Double(s);
} catch (NumberFormatException e) {
return null;
}
}
@Override
public Integer asInteger() {
String s = getValue();
try {
return new Integer(Math.round(Float.parseFloat(s)));
} catch (NumberFormatException e) {
return null;
}
}
@Override
public java.awt.Color asColor() {
for(Color c : Lists.newArrayList(cell.getCellStyle().getFillForegroundColorColor(),
cell.getCellStyle().getFillBackgroundColorColor())) {
if (c instanceof HSSFColor && (((HSSFColor)c).getTriplet() != null)) {
final short[] rgb = ((HSSFColor)c).getTriplet();
return new java.awt.Color(rgb[0], rgb[1], rgb[2]);
}
if (c instanceof XSSFColor && (((XSSFColor)c).getRgb() != null)) {
final byte[] rgb = ((XSSFColor)c).getRgb();
// Convert bytes to unsigned integers
return new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF);
}
}
return null;
}
@Override
public Date asDate() {
return cell.getDateCellValue();
}
@Override
public Double asPercent() {
Double value = asDouble();
if(!cell.getCellStyle().getDataFormatString().contains("%") && (value!=null)) {
value = value / 100.0;
}
return value;
}
}
private static class EmptyCell implements Value {
@Override
public String getValue() {
return null;
}
@Override
public String asString() {
return null;
}
@Override
public Double asDouble() {
return null;
}
@Override
public Integer asInteger() {
return null;
}
@Override
public java.awt.Color asColor() {
return null;
}
@Override
public Date asDate() {
return null;
}
@Override
public Double asPercent() {
return null;
}
}
public SpreadsheetDataSource() {
defaultSheet = 0;
}
SpreadsheetDataSource(Workbook workbook, FormulaEvaluator evaluator, int defaultSheet) {
this.workbook = workbook;
this.evaluator = evaluator;
this.defaultSheet = defaultSheet;
}
void init(Workbook workbook, FormulaEvaluator evaluator) {
this.workbook = workbook;
this.evaluator = evaluator;
}
/**
* select value from 1st sheet
*
* @param row
* - starts with 0
* @param col
* - starts with 0
* @throws MissingDataException
*/
public Value select(int row, int col) throws MissingDataException {
return select(null, row, col);
}
public Value select(String sheetname, int row, int col)
throws MissingDataException {
String cellref = new CellReference(row, col).formatAsString();
if (StringUtils.isNotBlank(sheetname)) {
cellref = sheetname + "!" + cellref;
}
return select(cellref);
}
public Value select(String sheetname, String selector) throws MissingDataException {
return select(sheetname+"!"+selector);
}
@Override
public Value select(String selector) throws MissingDataException {
Cell cell = selectCell(selector);
return cell!=null?new SpreadsheetCellValue(cell):new EmptyCell();
}
private Cell selectCell(String selector) throws MissingDataException {
// currently only CellReference selectors are supported like
// [sheet!]<row><column>
// e.g. Coral!A1 or just B20 which will select the cell from the first
// sheet.
CellReference cr = new CellReference(selector);
Sheet sheet;
String sheetName = cr.getSheetName();
if (sheetName != null) {
sheet = getSheet(sheetName);
if (sheet == null) {
throw new MissingDataException(String.format(
"Sheet '%s' does not exist in workbook", sheetName));
}
} else {
sheet = workbook.getSheetAt(defaultSheet);
if (sheet == null) {
throw new MissingDataException(
String.format("Sheet does not exist in workbook"));
}
}
Row row = sheet.getRow(cr.getRow());
if (row == null) {
return null;
}
Cell cell = row.getCell(cr.getCol());
if (cell == null) {
return null;
}
return cell;
}
private Sheet getSheet(String name) {
Sheet sheet = workbook.getSheet(name);
String strippedName = StringUtils.strip(name);
if (sheet == null) {
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
if (strippedName.equalsIgnoreCase(StringUtils.strip(workbook
.getSheetName(i)))) {
sheet = workbook.getSheetAt(i);
break;
}
}
}
if (sheet == null) {
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
if (StringUtils.containsIgnoreCase(
StringUtils.strip(workbook.getSheetName(i)), strippedName)) {
sheet = workbook.getSheetAt(i);
break;
}
}
}
return sheet;
}
public boolean hasSheet(String name) {
return getSheet(name) != null;
}
public String getSheetname(int i) {
Sheet sheet = workbook.getSheetAt(i);
if(sheet != null) {
return sheet.getSheetName();
} else {
return null;
}
}
public int sheets() {
return workbook.getNumberOfSheets();
}
public abstract SpreadsheetDataSource toSheet(int sheet);
public SpreadsheetDataSource toSheet(String sheetname) {
Sheet s = getSheet(sheetname);
if(s!= null) {
return toSheet(workbook.getSheetIndex(s));
} else {
return null;
}
}
public String getDefaultSheet() {
return workbook.getSheetName(defaultSheet);
}
public Integer getColumnCount(int row) {
return getColumnCount(defaultSheet, row);
}
public Integer getColumnCount(int i, int row) {
Sheet sheet = workbook.getSheetAt(i);
if(sheet != null) {
Row r = sheet.getRow(row);
if(r != null) {
return Integer.valueOf(r.getLastCellNum());
}
}
return null;
}
public List<Value> selectRow(int row) throws MissingDataException {
List<Value> result = Lists.newArrayList();
Integer max = getColumnCount(row);
if(max == null) {
return result;
}
for(int col = 0;col <= max;col++) {
result.add(select(row, col));
}
return result;
}
public List<Value> selectColumn(int column) throws MissingDataException {
return selectColumn(column, 100);
}
public List<Value> selectColumn(int column, int limit) throws MissingDataException {
List<Value> result = Lists.newArrayList();
Sheet sheet = workbook.getSheetAt(defaultSheet);
int max = Math.min(sheet.getLastRowNum(), limit);
for(int row = 0; row <= max;row++) {
result.add(select(row, column));
}
return result;
}
public static boolean containsString(List<Value> values, String s) {
for(Value v : values) {
if(StringUtils.equals(v.asString(),s)) {
return true;
}
}
return false;
}
Workbook workbook() {
return workbook;
}
FormulaEvaluator evaluator() {
return evaluator;
}
public boolean hasExternalReferences() {
for (int si = 0; si < workbook.getNumberOfSheets();si++) {
Sheet sheet = workbook.getSheetAt(si);
for (Row row : sheet) {
for (Cell cell : row) {
if (externalReference(cell) != null) {
return true;
}
}
}
}
return false;
}
public Set<UnresolvedRef> externalReferences() {
Set<UnresolvedRef> urefs = Sets.newHashSet();
for(int si = 0; si < workbook.getNumberOfSheets();si++) {
Sheet sheet = workbook.getSheetAt(si);
for(Row row : sheet) {
for(Cell cell : row) {
UnresolvedRef uref = externalReference(cell);
if(uref != null) {
//Logger.debug(String.format(
// "found external reference source '%s', source cell '%s', destination cell '%s'",
// uref.source(), uref.link().source(), uref.link().destination()));
urefs.add(uref);
}
}
}
}
return urefs;
}
abstract UnresolvedRef externalReference(Cell cell);
protected UnresolvedRef uref(String sIdOrName, final String sSelector,
final String dSelector) {
return new UnresolvedRef(sIdOrName,
new SimpleCellLink(sSelector, dSelector));
}
public InputStream updateExternalReferences(Set<ResolvedRef> refs) throws IOException {
boolean dirty = false;
for (ResolvedRef ref : refs) {
try {
final Cell dCell = selectCell(ref.link().destination());
if (dCell == null)
continue;
if (ref.source().isDefined()) {
final SpreadsheetDataSource source = ref.source().get();
try {
final Cell sCell = source.selectCell(ref.link().source());
dirty |= updatePrecalculatedValue(dCell, sCell, source.evaluator());
} catch (MissingDataException e) {
dirty |= updatePrecalculatedError(dCell, FormulaError.REF);
}
} else {
dirty |= updatePrecalculatedError(dCell, FormulaError.REF);
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
evaluateAll();
} catch(RuntimeException e) {
Logger.debug("evaluateAll() failed on updateExternalReferences," +
"some cached formula results may be out of date", e);
}
return dirty ? writeToTempFile() : null;
}
// evaluate all formula cells but external references. the XSSF evaluator seem to have
// issues with external references even if setIgnoreMissingWorkbooks(...) is set to true
// this workaround will probably not fully resolve the issue as formulas that depend on
// problematic external references might still fail.
private void evaluateAll() {
for(int i=0; i<workbook.getNumberOfSheets(); i++) {
Sheet sheet = workbook.getSheetAt(i);
for(Row r : sheet) {
for (Cell c : r) {
if (c.getCellType() == Cell.CELL_TYPE_FORMULA && !isExternalReference(c)) {
try {
evaluator.evaluateFormulaCell(c);
} catch(RuntimeException e) {
CellReference cr = new CellReference(c);
Logger.debug(String.format("failed to evaluate cell %s!%s, formula %s." +
" some cached formula results may be out of date",
sheet.getSheetName(), cr.formatAsString(), c.getCellFormula()), e);
}
}
}
}
}
}
private boolean isExternalReference(Cell cell) {
return externalReference(cell) != null;
}
private boolean updatePrecalculatedValue(Cell destination,
Cell source, FormulaEvaluator sEvaluator) {
if(source != null) {
switch(source.getCellType()) {
case Cell.CELL_TYPE_BLANK:
return updatePrecalculatedBlank(destination);
case Cell.CELL_TYPE_BOOLEAN:
return updatePrecalculatedBoolean(destination, source.getBooleanCellValue());
case Cell.CELL_TYPE_ERROR:
return updatePrecalculatedError(destination,
FormulaError.forInt(source.getErrorCellValue()));
case Cell.CELL_TYPE_FORMULA:
try {
return updatePrecalculatedCellValue(destination, sEvaluator.evaluate(source));
} catch(Exception e) {
switch(source.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
return updatePrecalculatedNumeric(destination, source.getNumericCellValue());
case Cell.CELL_TYPE_STRING:
return updatePrecalculatedString(destination, source.getStringCellValue());
case Cell.CELL_TYPE_BOOLEAN:
return updatePrecalculatedBoolean(destination, source.getBooleanCellValue());
case Cell.CELL_TYPE_ERROR:
return updatePrecalculatedError(destination,
FormulaError.forInt(source.getErrorCellValue()));
}
}
case Cell.CELL_TYPE_NUMERIC:
return updatePrecalculatedNumeric(destination, source.getNumericCellValue());
case Cell.CELL_TYPE_STRING:
return updatePrecalculatedString(destination, source.getStringCellValue());
default:
return false;
}
} else {
return updatePrecalculatedError(destination, FormulaError.REF);
}
}
private boolean updatePrecalculatedCellValue(Cell destination, CellValue val) {
if(val != null) {
switch(val.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
return updatePrecalculatedBoolean(destination, val.getBooleanValue());
case Cell.CELL_TYPE_NUMERIC:
return updatePrecalculatedNumeric(destination, val.getNumberValue());
case Cell.CELL_TYPE_STRING:
return updatePrecalculatedString(destination, val.getStringValue());
case Cell.CELL_TYPE_BLANK:
return updatePrecalculatedBlank(destination);
case Cell.CELL_TYPE_ERROR:
return updatePrecalculatedError(destination,
FormulaError.forInt(val.getErrorValue()));
default: return false;
}
} else {
return updatePrecalculatedError(destination, FormulaError.REF);
}
}
private boolean updatePrecalculatedBlank(Cell destination) {
return updatePrecalculatedNumeric(destination, 0);
}
private boolean updatePrecalculatedNumeric(Cell destination, double sVal) {
if(isFormula(destination)) {
try {
double dVal = destination.getNumericCellValue();
if(dVal != sVal) {
destination.setCellValue(sVal);
return true;
}
} catch(Exception e) {
destination.setCellValue(sVal);
return true;
}
}
return false;
}
private boolean updatePrecalculatedString(Cell destination, String sVal) {
if(isFormula(destination)) {
try {
String dVal = destination.getStringCellValue();
if(!StringUtils.equals(sVal, dVal)) {
destination.setCellValue(sVal);
return true;
}
} catch(Exception e) {
destination.setCellValue(sVal);
return true;
}
}
return false;
}
private boolean updatePrecalculatedError(Cell destination, FormulaError sError) {
if(isFormula(destination)) {
try {
FormulaError dError = FormulaError.forInt(destination.getErrorCellValue());
if(sError != dError) {
destination.setCellErrorValue(sError.getCode());
return true;
}
} catch(Exception e) {
destination.setCellErrorValue(sError.getCode());
return true;
}
}
return false;
}
private boolean updatePrecalculatedBoolean(Cell destination, boolean sVal) {
if(isFormula(destination)) {
try {
boolean dVal = destination.getBooleanCellValue();
if(dVal != sVal) {
destination.setCellValue(sVal);
return true;
}
} catch(Exception e) {
destination.setCellValue(sVal);
return true;
}
}
return false;
}
private boolean isFormula(Cell cell) {
return (cell != null) && (cell.getCellType() == Cell.CELL_TYPE_FORMULA);
}
private InputStream writeToTempFile() throws IOException {
final File f = File.createTempFile("spreadsheet", "poi");
FileOutputStream out = new FileOutputStream(f);
workbook.write(out);
IOUtils.closeQuietly(out);
return new FileInputStream(f) {
@Override
public void close() throws IOException {
super.close();
FileUtils.deleteQuietly(f);
}
};
}
public int getColumns(int row) {
return workbook.getSheetAt(defaultSheet).getRow(row).getLastCellNum();
}
}
|
package complex.tdoc;
import com.sun.star.beans.XPropertiesChangeNotifier;
import com.sun.star.beans.XPropertyContainer;
import com.sun.star.beans.XPropertySetInfoChangeNotifier;
import com.sun.star.container.XChild;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lang.XTypeProvider;
import com.sun.star.text.XTextDocument;
import com.sun.star.ucb.XCommandInfoChangeNotifier;
import com.sun.star.ucb.XCommandProcessor;
import com.sun.star.ucb.XContent;
import com.sun.star.ucb.XContentIdentifier;
import com.sun.star.ucb.XContentIdentifierFactory;
import com.sun.star.ucb.XContentProvider;
import com.sun.star.uno.UnoRuntime;
import complexlib.ComplexTestCase;
import complex.tdoc.interfaces._XChild;
import complex.tdoc.interfaces._XCommandInfoChangeNotifier;
import complex.tdoc.interfaces._XComponent;
import complex.tdoc.interfaces._XServiceInfo;
import complex.tdoc.interfaces._XTypeProvider;
import complex.tdoc.interfaces._XCommandProcessor;
import complex.tdoc.interfaces._XContent;
import complex.tdoc.interfaces._XPropertiesChangeNotifier;
import complex.tdoc.interfaces._XPropertyContainer;
import complex.tdoc.interfaces._XPropertySetInfoChangeNotifier;
import lib.TestEnvironment;
import util.WriterTools;
import util.utils;
/**
* Check the TransientDocumentsContentProvider (TDOC). Three documents are
* loaded. Then every possible TDCP content type is instantiated and its
* interfaces are tested.<br>
* Important: opened documents are numbered in the order they are opened and
* numbers are not reused. This test will work only, if you start a new office
* with an accept parameter (writer is initially opened). Otherwise loaded
* documents are not found.
*/
public class CheckContentProvider extends ComplexTestCase {
private final String testDocuments[] = new String[]{"filter.sxw", "chinese.sxw", "Iterator.sxw"};
private final int countDocs = testDocuments.length;
private XMultiServiceFactory xMSF = null;
private XTextDocument[] xTextDoc = null;
private XContent xContent = null;
/**
* The test methods: the test methods have to be executed in a specified
* order. This order is:
* <ol>
* <li>"checkTDOCRoot"</li>
* <li>"checkTDOCRootInterfaces"</li>
* <li>"checkTDOCDocument"</li>
* <li>"checkTDOCDocumentInterfaces"</li>
* <li>"checkTDOCFolder"</li>
* <li>"checkTDOCFolderInterfaces"</li>
* <li>"checkTDOCStream"</li>
* <li>"checkTDOCStreamInterfaces"</li>
* </ol>
* Important is, that the test of the element comes first, then the test of
* its interfaces.
**/
public String[] getTestMethodNames() {
return new String[]{"checkTDOCRoot",
"checkTDOCRootInterfaces",
"checkTDOCDocument",
"checkTDOCDocumentInterfaces",
"checkTDOCFolder",
"checkTDOCFolderInterfaces",
"checkTDOCStream",
"checkTDOCStreamInterfaces",
};
}
/**
* Open some documents before the test
*/
public void before() {
xMSF = (XMultiServiceFactory)param.getMSF();
xTextDoc = new XTextDocument[countDocs];
log.println("Open some new documents.");
for (int i=0; i<countDocs; i++) {
String fileName = utils.getFullTestURL(testDocuments[i]);
System.out.println("Doc " + i + ": " + fileName);
xTextDoc[i] = WriterTools.loadTextDoc(xMSF, fileName);
}
}
/**
* Close the documents
*/
public void after() {
log.println("Close all documents.");
for (int i=0; i<countDocs; i++) {
xTextDoc[i].dispose();
}
}
/**
* Check the tdcp root.
*/
public void checkTDOCRoot() {
try {
// create a content provider
Object o = xMSF.createInstance("com.sun.star.comp.ucb.TransientDocumentsContentProvider");
XContentProvider xContentProvider =
(XContentProvider)UnoRuntime.queryInterface(XContentProvider.class, o);
// create the ucb
XContentIdentifierFactory xContentIdentifierFactory =
(XContentIdentifierFactory)UnoRuntime.queryInterface(
XContentIdentifierFactory.class, xMSF.createInstance(
"com.sun.star.ucb.UniversalContentBroker"));
// create a content identifier from the ucb for tdoc
XContentIdentifier xContentIdentifier =
xContentIdentifierFactory.createContentIdentifier("vnd.sun.star.tdoc:/");
// get content
xContent = xContentProvider.queryContent(xContentIdentifier);
String content = xContent.getContentType();
log.println("
// try to get some documents: should be "countDocs" at least.
XContentIdentifier[] xContentId = new XContentIdentifier[countDocs+5];
XContent[] xCont = new XContent[countDocs+5];
for (int i=0; i<countDocs+5; i++) {
xContentId[i] = xContentIdentifierFactory.createContentIdentifier("vnd.sun.star.tdoc:/" + i);
// get content
xCont[i] = xContentProvider.queryContent(xContentId[i]);
int returnVal = xContentProvider.compareContentIds(xContentId[i], xContentIdentifier);
String cont = null;
if (xCont[i] != null)
cont = xCont[i].getContentType();
log.println("Document Content " + i + ": " + cont + " compare with root: " + returnVal);
xContentId[i] = xContentIdentifierFactory.createContentIdentifier("vnd.sun.star.tdoc:/" + i + "/content.xml");
// get content
xCont[i] = xContentProvider.queryContent(xContentId[i]);
cont = null;
if (xCont[i] != null)
cont = xCont[i].getContentType();
log.println("\tContent.xml Content " + i + ": " + cont);
}
util.dbg.printInterfaces(xContent);
}
catch(Exception e) {
e.printStackTrace((java.io.PrintWriter)log);
failed("Unexpected Exception: " + e.getMessage());
}
}
/**
* Check the interfaces of the root.
*/
public void checkTDOCRootInterfaces() {
checkInterfaces(false);
}
/**
* Check the tdcp document: document 3 is used.
*/
public void checkTDOCDocument() {
try {
xContent = null;
Object o = xMSF.createInstance("com.sun.star.comp.ucb.TransientDocumentsContentProvider");
XContentProvider xContentProvider =
(XContentProvider)UnoRuntime.queryInterface(XContentProvider.class, o);
// create the ucb
XContentIdentifierFactory xContentIdentifierFactory =
(XContentIdentifierFactory)UnoRuntime.queryInterface(
XContentIdentifierFactory.class, xMSF.createInstance(
"com.sun.star.ucb.UniversalContentBroker"));
// create a content identifier from the ucb for tdoc
XContentIdentifier xContentIdentifier =
xContentIdentifierFactory.createContentIdentifier("vnd.sun.star.tdoc:/3");
// get content
xContent = xContentProvider.queryContent(xContentIdentifier);
String content = xContent.getContentType();
log.println("
}
catch(Exception e) {
e.printStackTrace((java.io.PrintWriter)log);
failed("Unexpected Exception: " + e.getMessage());
}
}
/**
* Check the interfaces on the document.
*/
public void checkTDOCDocumentInterfaces() {
checkInterfaces(true);
}
/**
* Check a folder on document 2 (document 2 contains an embedded picture and
* therefore contans a subfolder "Pictures"
*/
public void checkTDOCFolder() {
try {
xContent = null;
Object o = xMSF.createInstance("com.sun.star.comp.ucb.TransientDocumentsContentProvider");
XContentProvider xContentProvider =
(XContentProvider)UnoRuntime.queryInterface(XContentProvider.class, o);
// create the ucb
XContentIdentifierFactory xContentIdentifierFactory =
(XContentIdentifierFactory)UnoRuntime.queryInterface(
XContentIdentifierFactory.class, xMSF.createInstance(
"com.sun.star.ucb.UniversalContentBroker"));
// create a content identifier from the ucb for tdoc
XContentIdentifier xContentIdentifier =
xContentIdentifierFactory.createContentIdentifier("vnd.sun.star.tdoc:/2/Pictures");
// get content
xContent = xContentProvider.queryContent(xContentIdentifier);
String content = xContent.getContentType();
log.println("
}
catch(Exception e) {
e.printStackTrace((java.io.PrintWriter)log);
failed("Unexpected Exception: " + e.getMessage());
}
}
/**
* Check the interfaces on the folder.
*/
public void checkTDOCFolderInterfaces() {
checkInterfaces(true);
}
/**
* Open a stream to the embedded picture of document 1.
*/
public void checkTDOCStream() {
try {
xContent = null;
Object o = xMSF.createInstance("com.sun.star.comp.ucb.TransientDocumentsContentProvider");
XContentProvider xContentProvider =
(XContentProvider)UnoRuntime.queryInterface(XContentProvider.class, o);
// create the ucb
XContentIdentifierFactory xContentIdentifierFactory =
(XContentIdentifierFactory)UnoRuntime.queryInterface(
XContentIdentifierFactory.class, xMSF.createInstance(
"com.sun.star.ucb.UniversalContentBroker"));
// create a content identifier from the ucb for tdoc
XContentIdentifier xContentIdentifier =
xContentIdentifierFactory.createContentIdentifier("vnd.sun.star.tdoc:/1/Pictures/10000000000000640000004B9C743800.gif");
// get content
xContent = xContentProvider.queryContent(xContentIdentifier);
String content = xContent.getContentType();
log.println("
}
catch(Exception e) {
e.printStackTrace((java.io.PrintWriter)log);
failed("Unexpected Exception: " + e.getMessage());
}
}
/**
* Check the interfaces on the stream.
*/
public void checkTDOCStreamInterfaces() {
checkInterfaces(true);
}
/**
* Since all tdcp content types implement (nearly) the same interfaces, they
* are called here.
* Executed interface tests are (in this order):
* <ol>
* <li>XTypeProvider</li>
* <li>XServiceInfo</li>
* <li>XCommandProcessor</li>
* <li>XChild</li>
* <li>XPropertiesChangeNotifier</li>
* <li>XPropertySetInfoChangeNotifier</li>
* <li>XCommandInfoChangeNotifier</li>
* <li>XContent</li>
* <li>XPropertyContainer</li>
* <li>XComponent</li>
* </ol>
* @param hasParent True, if the tested content type does have a parent:
* only the root has not. Used in the XChild interface test.
*/
private void checkInterfaces(boolean hasParent) {
// check the XTypeProvider interface
_XTypeProvider xTypeProvider = new _XTypeProvider();
xTypeProvider.oObj = (XTypeProvider)UnoRuntime.queryInterface(XTypeProvider.class, xContent);
xTypeProvider.log = log;
assure("getImplementationId()", xTypeProvider._getImplementationId());
assure("getTypes()", xTypeProvider._getTypes());
// check the XSewrviceInfo interface
_XServiceInfo xServiceInfo = new _XServiceInfo();
xServiceInfo.oObj = (XServiceInfo)UnoRuntime.queryInterface(XServiceInfo.class, xContent);
xServiceInfo.log = log;
assure("getImplementationName()", xServiceInfo._getImplementationName());
assure("getSupportedServiceNames()", xServiceInfo._getSupportedServiceNames());
assure("supportsService()", xServiceInfo._supportsService());
// check the XCommandProcessor interface
_XCommandProcessor xCommandProcessor = new _XCommandProcessor();
xCommandProcessor.oObj = (XCommandProcessor)UnoRuntime.queryInterface(XCommandProcessor.class, xContent);
xCommandProcessor.log = log;
xCommandProcessor.before((XMultiServiceFactory)param.getMSF());
assure("createCommandIdentifier()", xCommandProcessor._createCommandIdentifier());
assure("execute()", xCommandProcessor._execute());
assure("abort()", xCommandProcessor._abort());
// check the XChild interface
_XChild xChild = new _XChild();
xChild.oObj = (XChild)UnoRuntime.queryInterface(XChild.class, xContent);
xChild.log = log;
// hasParent dermines, if this content has a parent
assure("getParent()", xChild._getParent(hasParent));
// parameter does dermine, if this funczion is supported: generally not supported with tdcp content
assure("setParent()", xChild._setParent(false));
// check the XPropertyChangeNotifier interface
_XPropertiesChangeNotifier xPropChange = new _XPropertiesChangeNotifier();
xPropChange.oObj = (XPropertiesChangeNotifier)UnoRuntime.queryInterface(XPropertiesChangeNotifier.class, xContent);
xPropChange.log = log;
assure("addPropertiesChangeListener()", xPropChange._addPropertiesChangeListener());
assure("removePropertiesChangeListener()", xPropChange._removePropertiesChangeListener());
// check the XPropertySetInfoChangeNotifier interface
_XPropertySetInfoChangeNotifier xPropSetInfo = new _XPropertySetInfoChangeNotifier();
xPropSetInfo.oObj = (XPropertySetInfoChangeNotifier)UnoRuntime.queryInterface(XPropertySetInfoChangeNotifier.class, xContent);
xPropSetInfo.log = log;
assure("addPropertiesChangeListener()", xPropSetInfo._addPropertiesChangeListener());
assure("removePropertiesChangeListener()", xPropSetInfo._removePropertiesChangeListener());
// check the XCommandInfoChangeNotifier interface
_XCommandInfoChangeNotifier xCommandChange = new _XCommandInfoChangeNotifier();
xCommandChange.oObj = (XCommandInfoChangeNotifier)UnoRuntime.queryInterface(XCommandInfoChangeNotifier.class, xContent);
xCommandChange.log = log;
assure("addCommandInfoChangeListener()", xCommandChange._addCommandInfoChangeListener());
assure("removeCommandInfoChangeListener()", xCommandChange._removeCommandInfoChangeListener());
// check the XContent interface
_XContent xCont = new _XContent();
xCont.oObj = (XContent)UnoRuntime.queryInterface(XContent.class, xContent);
xCont.log = log;
assure("addContentEventListener()", xCont._addContentEventListener());
assure("getContentType()", xCont._getContentType());
assure("getIdentifier()", xCont._getIdentifier());
assure("removeContentEventListener()", xCont._removeContentEventListener());
// check the XPropertyContainer interface
_XPropertyContainer xPropCont = new _XPropertyContainer();
xPropCont.oObj = (XPropertyContainer)UnoRuntime.queryInterface(XPropertyContainer.class, xContent);
xPropCont.log = log;
assure("addProperty()", xPropCont._addProperty());
assure("removeProperty()", xPropCont._removeProperty());
// check the XComponent interface
_XComponent xComponent = new _XComponent();
xComponent.oObj = (XComponent)UnoRuntime.queryInterface(XComponent.class, xContent);
xComponent.log = log;
assure("addEventListener()", xComponent._addEventListener());
assure("removeEventListener()", xComponent._removeEventListener());
// assure("dispose()", xComponent._dispose());
}
}
|
// Protocol Buffers - Google's data interchange format
// modification, are permitted provided that the following conditions are
// met:
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.google.protobuf;
import java.io.InputStream;
/**
* Abstract interface for parsing Protocol Messages.
*
* The implementation should be stateless and thread-safe.
*
* @author liujisi@google.com (Pherl Liu)
*/
public interface Parser<MessageType> {
/**
* Parses a message of {@code MessageType} from the input.
*
* <p>Note: The caller should call
* {@link CodedInputStream#checkLastTagWas(int)} after calling this to
* verify that the last tag seen was the appropriate end-group tag,
* or zero for EOF.
*/
public MessageType parseFrom(CodedInputStream input)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(CodedInputStream)}, but also parses extensions.
* The extensions that you want to be able to parse must be registered in
* {@code extensionRegistry}. Extensions not in the registry will be treated
* as unknown fields.
*/
public MessageType parseFrom(CodedInputStream input,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(CodedInputStream)}, but does not throw an
* exception if the message is missing required fields. Instead, a partial
* message is returned.
*/
public MessageType parsePartialFrom(CodedInputStream input)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(CodedInputStream input, ExtensionRegistryLite)},
* but does not throw an exception if the message is missing required fields.
* Instead, a partial message is returned.
*/
public MessageType parsePartialFrom(CodedInputStream input,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
// Convenience methods.
/**
* Parses {@code data} as a message of {@code MessageType}.
* This is just a small wrapper around {@link #parseFrom(CodedInputStream)}.
*/
public MessageType parseFrom(ByteString data)
throws InvalidProtocolBufferException;
/**
* Parses {@code data} as a message of {@code MessageType}.
* This is just a small wrapper around
* {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}.
*/
public MessageType parseFrom(ByteString data,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(ByteString)}, but does not throw an
* exception if the message is missing required fields. Instead, a partial
* message is returned.
*/
public MessageType parsePartialFrom(ByteString data)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(ByteString, ExtensionRegistryLite)},
* but does not throw an exception if the message is missing required fields.
* Instead, a partial message is returned.
*/
public MessageType parsePartialFrom(ByteString data,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Parses {@code data} as a message of {@code MessageType}.
* This is just a small wrapper around {@link #parseFrom(CodedInputStream)}.
*/
public MessageType parseFrom(byte[] data, int off, int len)
throws InvalidProtocolBufferException;
/**
* Parses {@code data} as a message of {@code MessageType}.
* This is just a small wrapper around
* {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}.
*/
public MessageType parseFrom(byte[] data, int off, int len,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Parses {@code data} as a message of {@code MessageType}.
* This is just a small wrapper around {@link #parseFrom(CodedInputStream)}.
*/
public MessageType parseFrom(byte[] data)
throws InvalidProtocolBufferException;
/**
* Parses {@code data} as a message of {@code MessageType}.
* This is just a small wrapper around
* {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}.
*/
public MessageType parseFrom(byte[] data,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(byte[], int, int)}, but does not throw an
* exception if the message is missing required fields. Instead, a partial
* message is returned.
*/
public MessageType parsePartialFrom(byte[] data, int off, int len)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(ByteString, ExtensionRegistryLite)},
* but does not throw an exception if the message is missing required fields.
* Instead, a partial message is returned.
*/
public MessageType parsePartialFrom(byte[] data, int off, int len,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(byte[])}, but does not throw an
* exception if the message is missing required fields. Instead, a partial
* message is returned.
*/
public MessageType parsePartialFrom(byte[] data)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(byte[], ExtensionRegistryLite)},
* but does not throw an exception if the message is missing required fields.
* Instead, a partial message is returned.
*/
public MessageType parsePartialFrom(byte[] data,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Parse a message of {@code MessageType} from {@code input}.
* This is just a small wrapper around {@link #parseFrom(CodedInputStream)}.
* Note that this method always reads the <i>entire</i> input (unless it
* throws an exception). If you want it to stop earlier, you will need to
* wrap your input in some wrapper stream that limits reading. Or, use
* {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} to write your
* message and {@link #parseDelimitedFrom(InputStream)} to read it.
* <p>
* Despite usually reading the entire input, this does not close the stream.
*/
public MessageType parseFrom(InputStream input)
throws InvalidProtocolBufferException;
/**
* Parses a message of {@code MessageType} from {@code input}.
* This is just a small wrapper around
* {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}.
*/
public MessageType parseFrom(InputStream input,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(InputStream)}, but does not throw an
* exception if the message is missing required fields. Instead, a partial
* message is returned.
*/
public MessageType parsePartialFrom(InputStream input)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(InputStream, ExtensionRegistryLite)},
* but does not throw an exception if the message is missing required fields.
* Instead, a partial message is returned.
*/
public MessageType parsePartialFrom(InputStream input,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseFrom(InputStream)}, but does not read util EOF.
* Instead, the size of message (encoded as a varint) is read first,
* then the message data. Use
* {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} to write
* messages in this format.
*
* @return Parsed message if successful, or null if the stream is at EOF when
* the method starts. Any other error (including reaching EOF during
* parsing) will cause an exception to be thrown.
*/
public MessageType parseDelimitedFrom(InputStream input)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseDelimitedFrom(InputStream)} but supporting extensions.
*/
public MessageType parseDelimitedFrom(InputStream input,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseDelimitedFrom(InputStream)}, but does not throw an
* exception if the message is missing required fields. Instead, a partial
* message is returned.
*/
public MessageType parsePartialDelimitedFrom(InputStream input)
throws InvalidProtocolBufferException;
/**
* Like {@link #parseDelimitedFrom(InputStream, ExtensionRegistryLite)},
* but does not throw an exception if the message is missing required fields.
* Instead, a partial message is returned.
*/
public MessageType parsePartialDelimitedFrom(
InputStream input,
ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
}
|
package io.bisq.gui.main.portfolio.closedtrades;
import com.googlecode.jcsv.writer.CSVEntryConverter;
import io.bisq.common.locale.Res;
import io.bisq.common.monetary.Price;
import io.bisq.common.monetary.Volume;
import io.bisq.core.alert.PrivateNotificationManager;
import io.bisq.core.offer.Offer;
import io.bisq.core.offer.OpenOffer;
import io.bisq.core.trade.Tradable;
import io.bisq.core.trade.Trade;
import io.bisq.core.user.Preferences;
import io.bisq.gui.common.view.ActivatableViewAndModel;
import io.bisq.gui.common.view.FxmlView;
import io.bisq.gui.components.AutoTooltipLabel;
import io.bisq.gui.components.HyperlinkWithIcon;
import io.bisq.gui.components.PeerInfoIcon;
import io.bisq.gui.main.overlays.windows.OfferDetailsWindow;
import io.bisq.gui.main.overlays.windows.TradeDetailsWindow;
import io.bisq.gui.util.BSFormatter;
import io.bisq.gui.util.GUIUtil;
import io.bisq.network.p2p.NodeAddress;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.bitcoinj.core.Coin;
import sun.security.krb5.internal.rcache.AuthList;
import javax.inject.Inject;
import java.util.Comparator;
@FxmlView
public class ClosedTradesView extends ActivatableViewAndModel<VBox, ClosedTradesViewModel> {
@FXML
TableView<ClosedTradableListItem> tableView;
@FXML
TableColumn<ClosedTradableListItem, ClosedTradableListItem> priceColumn, amountColumn, volumeColumn,
marketColumn, directionColumn, dateColumn, tradeIdColumn, stateColumn, avatarColumn;
@FXML
Button exportButton;
private final OfferDetailsWindow offerDetailsWindow;
private Preferences preferences;
private final BSFormatter formatter;
private final TradeDetailsWindow tradeDetailsWindow;
private final PrivateNotificationManager privateNotificationManager;
private final Stage stage;
private SortedList<ClosedTradableListItem> sortedList;
@Inject
public ClosedTradesView(ClosedTradesViewModel model,
OfferDetailsWindow offerDetailsWindow,
Preferences preferences,
TradeDetailsWindow tradeDetailsWindow,
PrivateNotificationManager privateNotificationManager,
Stage stage,
BSFormatter formatter) {
super(model);
this.offerDetailsWindow = offerDetailsWindow;
this.preferences = preferences;
this.tradeDetailsWindow = tradeDetailsWindow;
this.privateNotificationManager = privateNotificationManager;
this.stage = stage;
this.preferences = preferences;
this.formatter = formatter;
}
@Override
public void initialize() {
priceColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.price")));
amountColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.amountWithCur", Res.getBaseCurrencyCode())));
volumeColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.volume")));
marketColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.market")));
directionColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.offerType")));
dateColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.dateTime")));
tradeIdColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.tradeId")));
stateColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.state")));
avatarColumn.setText("");
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
tableView.setPlaceholder(new AutoTooltipLabel(Res.get("table.placeholder.noItems", Res.get("shared.trades"))));
setTradeIdColumnCellFactory();
setDirectionColumnCellFactory();
setAmountColumnCellFactory();
setPriceColumnCellFactory();
setVolumeColumnCellFactory();
setDateColumnCellFactory();
setMarketColumnCellFactory();
setStateColumnCellFactory();
setAvatarColumnCellFactory();
tradeIdColumn.setComparator(Comparator.comparing(o -> o.getTradable().getId()));
dateColumn.setComparator(Comparator.comparing(o -> o.getTradable().getDate()));
directionColumn.setComparator(Comparator.comparing(o -> o.getTradable().getOffer().getDirection()));
marketColumn.setComparator(Comparator.comparing(model::getMarketLabel));
priceColumn.setComparator((o1, o2) -> {
final Tradable tradable1 = o1.getTradable();
final Tradable tradable2 = o2.getTradable();
Price price1 = null;
Price price2 = null;
if (tradable1 != null)
price1 = tradable1 instanceof Trade ? ((Trade) tradable1).getTradePrice() : tradable1.getOffer().getPrice();
if (tradable2 != null)
price2 = tradable2 instanceof Trade ? ((Trade) tradable2).getTradePrice() : tradable2.getOffer().getPrice();
return price1 != null && price2 != null ? price1.compareTo(price2) : 0;
});
volumeColumn.setComparator((o1, o2) -> {
if (o1.getTradable() instanceof Trade && o2.getTradable() instanceof Trade) {
Volume tradeVolume1 = ((Trade) o1.getTradable()).getTradeVolume();
Volume tradeVolume2 = ((Trade) o2.getTradable()).getTradeVolume();
return tradeVolume1 != null && tradeVolume2 != null ? tradeVolume1.compareTo(tradeVolume2) : 0;
} else
return 0;
});
amountColumn.setComparator((o1, o2) -> {
if (o1.getTradable() instanceof Trade && o2.getTradable() instanceof Trade) {
Coin amount1 = ((Trade) o1.getTradable()).getTradeAmount();
Coin amount2 = ((Trade) o2.getTradable()).getTradeAmount();
return amount1 != null && amount2 != null ? amount1.compareTo(amount2) : 0;
} else
return 0;
});
avatarColumn.setComparator((o1, o2) -> {
if (o1.getTradable() instanceof Trade && o2.getTradable() instanceof Trade) {
NodeAddress tradingPeerNodeAddress1 = ((Trade) o1.getTradable()).getTradingPeerNodeAddress();
NodeAddress tradingPeerNodeAddress2 = ((Trade) o2.getTradable()).getTradingPeerNodeAddress();
String address1 = tradingPeerNodeAddress1 != null ? tradingPeerNodeAddress1.getFullAddress() : "";
String address2 = tradingPeerNodeAddress2 != null ? tradingPeerNodeAddress2.getFullAddress() : "";
return address1 != null && address2 != null ? address1.compareTo(address2) : 0;
} else
return 0;
});
stateColumn.setComparator((o1, o2) -> model.getState(o1).compareTo(model.getState(o2)));
dateColumn.setSortType(TableColumn.SortType.DESCENDING);
tableView.getSortOrder().add(dateColumn);
exportButton.setText(Res.get("shared.exportCSV"));
}
@Override
protected void activate() {
sortedList = new SortedList<>(model.getList());
sortedList.comparatorProperty().bind(tableView.comparatorProperty());
tableView.setItems(sortedList);
exportButton.setOnAction(event -> {
final ObservableList<TableColumn<ClosedTradableListItem, ?>> tableColumns = tableView.getColumns();
CSVEntryConverter<ClosedTradableListItem> headerConverter = transactionsListItem -> {
String[] columns = new String[7];
for (int i = 0; i < columns.length; i++)
columns[i] = tableColumns.get(i).getText();
return columns;
};
CSVEntryConverter<ClosedTradableListItem> contentConverter = item -> {
String[] columns = new String[7];
columns[0] = model.getTradeId(item);
columns[1] = model.getDate(item);
columns[2] = model.getAmount(item);
columns[3] = model.getPrice(item);
columns[4] = model.getVolume(item);
columns[5] = model.getDirectionLabel(item);
columns[6] = model.getState(item);
return columns;
};
GUIUtil.exportCSV("tradeHistory.csv", headerConverter, contentConverter,
new ClosedTradableListItem(null), sortedList, stage);
});
}
@Override
protected void deactivate() {
sortedList.comparatorProperty().unbind();
exportButton.setOnAction(null);
}
private void setTradeIdColumnCellFactory() {
tradeIdColumn.setCellValueFactory((offerListItem) -> new ReadOnlyObjectWrapper<>(offerListItem.getValue()));
tradeIdColumn.setCellFactory(
new Callback<TableColumn<ClosedTradableListItem, ClosedTradableListItem>, TableCell<ClosedTradableListItem,
ClosedTradableListItem>>() {
@Override
public TableCell<ClosedTradableListItem, ClosedTradableListItem> call(TableColumn<ClosedTradableListItem,
ClosedTradableListItem> column) {
return new TableCell<ClosedTradableListItem, ClosedTradableListItem>() {
private HyperlinkWithIcon field;
@Override
public void updateItem(final ClosedTradableListItem item, boolean empty) {
super.updateItem(item, empty);
if (item != null && !empty) {
field = new HyperlinkWithIcon(model.getTradeId(item));
field.setOnAction(event -> {
Tradable tradable = item.getTradable();
if (tradable instanceof Trade)
tradeDetailsWindow.show((Trade) tradable);
else if (tradable instanceof OpenOffer)
offerDetailsWindow.show(tradable.getOffer());
});
field.setTooltip(new Tooltip(Res.get("tooltip.openPopupForDetails")));
setGraphic(field);
} else {
setGraphic(null);
if (field != null)
field.setOnAction(null);
}
}
};
}
});
}
private void setDateColumnCellFactory() {
dateColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper<>(offer.getValue()));
dateColumn.setCellFactory(
new Callback<TableColumn<ClosedTradableListItem, ClosedTradableListItem>, TableCell<ClosedTradableListItem,
ClosedTradableListItem>>() {
@Override
public TableCell<ClosedTradableListItem, ClosedTradableListItem> call(
TableColumn<ClosedTradableListItem, ClosedTradableListItem> column) {
return new TableCell<ClosedTradableListItem, ClosedTradableListItem>() {
@Override
public void updateItem(final ClosedTradableListItem item, boolean empty) {
super.updateItem(item, empty);
if (item != null)
setGraphic(new AutoTooltipLabel(model.getDate(item)));
else
setGraphic(null);
}
};
}
});
}
private void setMarketColumnCellFactory() {
marketColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper<>(offer.getValue()));
marketColumn.setCellFactory(
new Callback<TableColumn<ClosedTradableListItem, ClosedTradableListItem>, TableCell<ClosedTradableListItem,
ClosedTradableListItem>>() {
@Override
public TableCell<ClosedTradableListItem, ClosedTradableListItem> call(
TableColumn<ClosedTradableListItem, ClosedTradableListItem> column) {
return new TableCell<ClosedTradableListItem, ClosedTradableListItem>() {
@Override
public void updateItem(final ClosedTradableListItem item, boolean empty) {
super.updateItem(item, empty);
setGraphic(new AutoTooltipLabel(model.getMarketLabel(item)));
}
};
}
});
}
private void setStateColumnCellFactory() {
stateColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper<>(offer.getValue()));
stateColumn.setCellFactory(
new Callback<TableColumn<ClosedTradableListItem, ClosedTradableListItem>, TableCell<ClosedTradableListItem,
ClosedTradableListItem>>() {
@Override
public TableCell<ClosedTradableListItem, ClosedTradableListItem> call(
TableColumn<ClosedTradableListItem, ClosedTradableListItem> column) {
return new TableCell<ClosedTradableListItem, ClosedTradableListItem>() {
@Override
public void updateItem(final ClosedTradableListItem item, boolean empty) {
super.updateItem(item, empty);
if (item != null)
setGraphic(new AutoTooltipLabel(model.getState(item)));
else
setGraphic(null);
}
};
}
});
}
@SuppressWarnings("UnusedReturnValue")
private TableColumn<ClosedTradableListItem, ClosedTradableListItem> setAvatarColumnCellFactory() {
avatarColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper<>(offer.getValue()));
avatarColumn.setCellFactory(
new Callback<TableColumn<ClosedTradableListItem, ClosedTradableListItem>, TableCell<ClosedTradableListItem,
ClosedTradableListItem>>() {
@Override
public TableCell<ClosedTradableListItem, ClosedTradableListItem> call(TableColumn<ClosedTradableListItem, ClosedTradableListItem> column) {
return new TableCell<ClosedTradableListItem, ClosedTradableListItem>() {
@Override
public void updateItem(final ClosedTradableListItem newItem, boolean empty) {
super.updateItem(newItem, empty);
if (newItem != null && !empty && newItem.getTradable() instanceof Trade) {
Trade trade = (Trade) newItem.getTradable();
int numPastTrades = model.getNumPastTrades(trade);
final NodeAddress tradingPeerNodeAddress = trade.getTradingPeerNodeAddress();
final Offer offer = trade.getOffer();
String role = Res.get("peerInfoIcon.tooltip.tradePeer");
Node peerInfoIcon = new PeerInfoIcon(tradingPeerNodeAddress,
role,
numPastTrades,
privateNotificationManager,
offer,
preferences,
model.accountAgeWitnessService,
formatter);
setPadding(new Insets(1, 0, 0, 0));
setGraphic(peerInfoIcon);
} else {
setGraphic(null);
}
}
};
}
});
return avatarColumn;
}
private void setAmountColumnCellFactory() {
amountColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper<>(offer.getValue()));
amountColumn.setCellFactory(
new Callback<TableColumn<ClosedTradableListItem, ClosedTradableListItem>, TableCell<ClosedTradableListItem,
ClosedTradableListItem>>() {
@Override
public TableCell<ClosedTradableListItem, ClosedTradableListItem> call(
TableColumn<ClosedTradableListItem, ClosedTradableListItem> column) {
return new TableCell<ClosedTradableListItem, ClosedTradableListItem>() {
@Override
public void updateItem(final ClosedTradableListItem item, boolean empty) {
super.updateItem(item, empty);
setGraphic(new AutoTooltipLabel(model.getAmount(item)));
}
};
}
});
}
private void setPriceColumnCellFactory() {
priceColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper<>(offer.getValue()));
priceColumn.setCellFactory(
new Callback<TableColumn<ClosedTradableListItem, ClosedTradableListItem>, TableCell<ClosedTradableListItem,
ClosedTradableListItem>>() {
@Override
public TableCell<ClosedTradableListItem, ClosedTradableListItem> call(
TableColumn<ClosedTradableListItem, ClosedTradableListItem> column) {
return new TableCell<ClosedTradableListItem, ClosedTradableListItem>() {
@Override
public void updateItem(final ClosedTradableListItem item, boolean empty) {
super.updateItem(item, empty);
setGraphic(new AutoTooltipLabel(model.getPrice(item)));
}
};
}
});
}
private void setVolumeColumnCellFactory() {
volumeColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper<>(offer.getValue()));
volumeColumn.setCellFactory(
new Callback<TableColumn<ClosedTradableListItem, ClosedTradableListItem>, TableCell<ClosedTradableListItem,
ClosedTradableListItem>>() {
@Override
public TableCell<ClosedTradableListItem, ClosedTradableListItem> call(
TableColumn<ClosedTradableListItem, ClosedTradableListItem> column) {
return new TableCell<ClosedTradableListItem, ClosedTradableListItem>() {
@Override
public void updateItem(final ClosedTradableListItem item, boolean empty) {
super.updateItem(item, empty);
if (item != null)
setGraphic(new AutoTooltipLabel(model.getVolume(item)));
else
setGraphic(null);
}
};
}
});
}
private void setDirectionColumnCellFactory() {
directionColumn.setCellValueFactory((offer) -> new ReadOnlyObjectWrapper<>(offer.getValue()));
directionColumn.setCellFactory(
new Callback<TableColumn<ClosedTradableListItem, ClosedTradableListItem>, TableCell<ClosedTradableListItem,
ClosedTradableListItem>>() {
@Override
public TableCell<ClosedTradableListItem, ClosedTradableListItem> call(
TableColumn<ClosedTradableListItem, ClosedTradableListItem> column) {
return new TableCell<ClosedTradableListItem, ClosedTradableListItem>() {
@Override
public void updateItem(final ClosedTradableListItem item, boolean empty) {
super.updateItem(item, empty);
setGraphic(new AutoTooltipLabel(model.getDirectionLabel(item)));
}
};
}
});
}
}
|
package me.vanpan.rctqqsdk;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.webkit.URLUtil;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.BaseActivityEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzonePublish;
import com.tencent.connect.share.QzoneShare;
import com.tencent.open.GameAppOperation;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import static android.content.ContentValues.TAG;
class ShareScene {
public static final int QQ = 0;
public static final int QQZone = 1;
public static final int Favorite = 2;
}
public class QQSDK extends ReactContextBaseJavaModule {
private static Tencent mTencent;
private String appId;
private String appName;
private Promise mPromise;
private static final String ACTIVITY_DOES_NOT_EXIST = "activity not found";
private static final String QQ_Client_NOT_INSYALLED_ERROR = "QQ client is not installed";
private static final String QQ_RESPONSE_ERROR = "QQ response is error";
private static final String QQ_CANCEL_BY_USER = "cancelled by user";
private static final String QZONE_SHARE_CANCEL = "QZone share is cancelled";
private static final String QQFAVORITES_CANCEL = "QQ Favorites is cancelled";
private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) {
if (requestCode == Constants.REQUEST_LOGIN) {
if (resultCode == Constants.ACTIVITY_OK) {
Tencent.onActivityResultData(requestCode, resultCode, intent, loginListener);
}
}
if (requestCode == Constants.REQUEST_QQ_SHARE) {
if (resultCode == Constants.ACTIVITY_OK) {
Tencent.onActivityResultData(requestCode, resultCode, intent, qqShareListener);
}
}
if (requestCode == Constants.REQUEST_QZONE_SHARE) {
if (resultCode == Constants.ACTIVITY_OK) {
Tencent.onActivityResultData(requestCode, resultCode, intent, qZoneShareListener);
}
}
}
};
public QQSDK(ReactApplicationContext reactContext) {
super(reactContext);
reactContext.addActivityEventListener(mActivityEventListener);
appId = this.getAppID(reactContext);
appName = this.getAppName(reactContext);
if (null == mTencent) {
mTencent = Tencent.createInstance(appId, reactContext);
}
}
@Override
public void initialize() {
super.initialize();
}
@Override
public String getName() {
return "QQSDK";
}
@Override
public void onCatalystInstanceDestroy() {
super.onCatalystInstanceDestroy();
if (mTencent != null) {
mTencent.releaseResource();
mTencent = null;
}
appId = null;
appName = null;
mPromise = null;
}
@ReactMethod
public void checkClientInstalled(Promise promise) {
Activity currentActivity = getCurrentActivity();
if (null == currentActivity) {
promise.reject("405",ACTIVITY_DOES_NOT_EXIST);
return;
}
Boolean installed = mTencent.isSupportSSOLogin(currentActivity);
if (installed) {
promise.resolve(true);
} else {
promise.reject("404", QQ_Client_NOT_INSYALLED_ERROR);
}
}
@ReactMethod
public void logout(Promise promise) {
Activity currentActivity = getCurrentActivity();
if (null == currentActivity) {
promise.reject("405",ACTIVITY_DOES_NOT_EXIST);
return;
}
mTencent.logout(currentActivity);
promise.resolve(true);
}
@ReactMethod
public void ssoLogin(final Promise promise) {
if (mTencent.isSessionValid()) {
WritableMap map = Arguments.createMap();
map.putString("userid", mTencent.getOpenId());
map.putString("access_token", mTencent.getAccessToken());
map.putDouble("expires_time", mTencent.getExpiresIn());
promise.resolve(map);
} else {
final Activity currentActivity = getCurrentActivity();
if (null == currentActivity) {
promise.reject("405",ACTIVITY_DOES_NOT_EXIST);
return;
}
Runnable runnable = new Runnable() {
@Override
public void run() {
mPromise = promise;
mTencent.login(currentActivity, "all",
loginListener);
}
};
UiThreadUtil.runOnUiThread(runnable);
}
}
@ReactMethod
public void shareText(String text,int shareScene, final Promise promise) {
final Activity currentActivity = getCurrentActivity();
if (null == currentActivity) {
promise.reject("405",ACTIVITY_DOES_NOT_EXIST);
return;
}
mPromise = promise;
final Bundle params = new Bundle();
switch (shareScene) {
case ShareScene.QQ:
promise.reject("500","AndroidQQ");
break;
case ShareScene.Favorite:
params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_TEXT);
params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, appName);
params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION, text);
params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName);
Runnable favoritesRunnable = new Runnable() {
@Override
public void run() {
mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener);
}
};
UiThreadUtil.runOnUiThread(favoritesRunnable);
break;
case ShareScene.QQZone:
params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzonePublish.PUBLISH_TO_QZONE_TYPE_PUBLISHMOOD);
params.putString(QzoneShare.SHARE_TO_QQ_TITLE, text);
Runnable zoneRunnable = new Runnable() {
@Override
public void run() {
mTencent.publishToQzone(currentActivity,params,qZoneShareListener);
}
};
UiThreadUtil.runOnUiThread(zoneRunnable);
break;
default:
break;
}
}
@ReactMethod
public void shareImage(String image,String title, String description,int shareScene, final Promise promise) {
final Activity currentActivity = getCurrentActivity();
Log.d("",image);
if (null == currentActivity) {
promise.reject("405",ACTIVITY_DOES_NOT_EXIST);
return;
}
mPromise = promise;
image = processImage(image);
final Bundle params = new Bundle();
switch (shareScene) {
case ShareScene.QQ:
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,image);
params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description);
Runnable qqRunnable = new Runnable() {
@Override
public void run() {
mTencent.shareToQQ(currentActivity,params,qqShareListener);
}
};
UiThreadUtil.runOnUiThread(qqRunnable);
break;
case ShareScene.Favorite:
ArrayList<String> imageUrls = new ArrayList<String>();
imageUrls.add(image);
params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_IMAGE_TEXT);
params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, title);
params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION, description);
params.putString(GameAppOperation.QQFAV_DATALINE_IMAGEURL,image);
params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName);
params.putStringArrayList(GameAppOperation.QQFAV_DATALINE_FILEDATA,imageUrls);
Runnable favoritesRunnable = new Runnable() {
@Override
public void run() {
mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener);
}
};
UiThreadUtil.runOnUiThread(favoritesRunnable);
break;
case ShareScene.QQZone:
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,image);
params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description);
params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
Runnable zoneRunnable = new Runnable() {
@Override
public void run() {
mTencent.shareToQQ(currentActivity,params,qqShareListener);
}
};
UiThreadUtil.runOnUiThread(zoneRunnable);
break;
default:
break;
}
}
@ReactMethod
public void shareNews(String url,String image,String title, String description,int shareScene, final Promise promise) {
final Activity currentActivity = getCurrentActivity();
if (null == currentActivity) {
promise.reject("405",ACTIVITY_DOES_NOT_EXIST);
return;
}
mPromise = promise;
final Bundle params = new Bundle();
switch (shareScene) {
case ShareScene.QQ:
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
if(image.startsWith("http:
params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,image);
} else {
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,processImage(image));
}
params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description);
Runnable qqRunnable = new Runnable() {
@Override
public void run() {
mTencent.shareToQQ(currentActivity,params,qqShareListener);
}
};
UiThreadUtil.runOnUiThread(qqRunnable);
break;
case ShareScene.Favorite:
image = processImage(image);
params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_DEFAULT);
params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, title);
params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION,description);
params.putString(GameAppOperation.QQFAV_DATALINE_IMAGEURL,image);
params.putString(GameAppOperation.QQFAV_DATALINE_URL,url);
params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName);
Runnable favoritesRunnable = new Runnable() {
@Override
public void run() {
mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener);
}
};
UiThreadUtil.runOnUiThread(favoritesRunnable);
break;
case ShareScene.QQZone:
image = processImage(image);
ArrayList<String> imageUrls = new ArrayList<String>();
imageUrls.add(image);
params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,description);
params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,url);
params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imageUrls);
Runnable zoneRunnable = new Runnable() {
@Override
public void run() {
mTencent.shareToQzone(currentActivity,params,qZoneShareListener);
}
};
UiThreadUtil.runOnUiThread(zoneRunnable);
break;
default:
break;
}
}
@ReactMethod
public void shareAudio(String url,String flashUrl,String image,String title, String description,int shareScene, final Promise promise) {
final Activity currentActivity = getCurrentActivity();
if (null == currentActivity) {
promise.reject("405",ACTIVITY_DOES_NOT_EXIST);
return;
}
mPromise = promise;
final Bundle params = new Bundle();
switch (shareScene) {
case ShareScene.QQ:
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
if(image.startsWith("http:
params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,image);
} else {
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,processImage(image));
}
params.putString(QQShare.SHARE_TO_QQ_AUDIO_URL, flashUrl);
params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description);
Runnable qqRunnable = new Runnable() {
@Override
public void run() {
mTencent.shareToQQ(currentActivity,params,qqShareListener);
}
};
UiThreadUtil.runOnUiThread(qqRunnable);
break;
case ShareScene.Favorite:
image = processImage(image);
params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_DEFAULT);
params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, title);
params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION,description);
params.putString(GameAppOperation.QQFAV_DATALINE_IMAGEURL,image);
params.putString(GameAppOperation.QQFAV_DATALINE_URL,url);
params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName);
params.putString(GameAppOperation.QQFAV_DATALINE_AUDIOURL,flashUrl);
Runnable favoritesRunnable = new Runnable() {
@Override
public void run() {
mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener);
}
};
UiThreadUtil.runOnUiThread(favoritesRunnable);
break;
case ShareScene.QQZone:
image = processImage(image);
ArrayList<String> imageUrls = new ArrayList<String>();
imageUrls.add(image);
params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,description);
params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,url);
params.putString(QzoneShare.SHARE_TO_QQ_AUDIO_URL,flashUrl);
params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imageUrls);
Runnable zoneRunnable = new Runnable() {
@Override
public void run() {
mTencent.shareToQzone(currentActivity,params,qZoneShareListener);
}
};
UiThreadUtil.runOnUiThread(zoneRunnable);
break;
default:
break;
}
}
@ReactMethod
public void shareVideo(String url,String flashUrl,String image,String title, String description,int shareScene, final Promise promise) {
final Activity currentActivity = getCurrentActivity();
if (null == currentActivity) {
promise.reject("405",ACTIVITY_DOES_NOT_EXIST);
return;
}
mPromise = promise;
final Bundle params = new Bundle();
switch (shareScene) {
case ShareScene.QQ:
promise.reject("500","AndroidQQ");
break;
case ShareScene.Favorite:
promise.reject("500","AndroidQQ");
break;
case ShareScene.QQZone:
ArrayList<String> imageUrls = new ArrayList<String>();
imageUrls.add(image);
params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzonePublish.PUBLISH_TO_QZONE_TYPE_PUBLISHVIDEO);
params.putString(QzonePublish.PUBLISH_TO_QZONE_IMAGE_URL, image);
params.putString(QzonePublish.PUBLISH_TO_QZONE_SUMMARY,description);
params.putString(QzonePublish.PUBLISH_TO_QZONE_VIDEO_PATH,flashUrl);
Runnable zoneRunnable = new Runnable() {
@Override
public void run() {
mTencent.shareToQzone(currentActivity,params,qZoneShareListener);
}
};
UiThreadUtil.runOnUiThread(zoneRunnable);
break;
default:
break;
}
}
@Nullable
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("QQ", ShareScene.QQ);
constants.put("QQZone", ShareScene.QQZone);
constants.put("Favorite", ShareScene.Favorite);
return constants;
}
/**
* Tencent SDK App ID
* @param reactContext
* @return
*/
private String getAppID(ReactApplicationContext reactContext) {
try {
ApplicationInfo appInfo = reactContext.getPackageManager()
.getApplicationInfo(reactContext.getPackageName(),
PackageManager.GET_META_DATA);
String key = appInfo.metaData.get("QQ_APP_ID").toString();
return key;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param reactContext
* @return
*/
private String getAppName(ReactApplicationContext reactContext) {
PackageManager packageManager = reactContext.getPackageManager();
ApplicationInfo applicationInfo = null;
try {
applicationInfo = packageManager.getApplicationInfo(reactContext.getPackageName(), 0);
} catch (final PackageManager.NameNotFoundException e) {}
final String AppName = (String)((applicationInfo != null) ? packageManager.getApplicationLabel(applicationInfo) : "AppName");
return AppName;
}
private String processImage(String image) {
if(URLUtil.isHttpUrl(image) || URLUtil.isHttpsUrl(image)) {
return saveBitmapToFile(getBitmapFromURL(image));
} else if (isBase64(image)) {
return saveBitmapToFile(decodeBase64ToBitmap(image));
} else if (URLUtil.isFileUrl(image) || image.startsWith("/") ){
File file = new File(image);
return file.getAbsolutePath();
} else {
return saveBitmapToFile(BitmapFactory.decodeResource(getReactApplicationContext().getResources(),getDrawableFileID(image)));
}
}
/**
* Base64
* @param image
* @return
*/
private boolean isBase64(String image) {
try {
byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
if (bitmap == null) {
return false;
}
return true;
} catch (Exception e) {
return false;
}
}
/**
* DrawbleID
* @param imageName
* @return
*/
private int getDrawableFileID(String imageName) {
ResourceDrawableIdHelper sResourceDrawableIdHelper = ResourceDrawableIdHelper.getInstance();
int id = sResourceDrawableIdHelper.getResourceDrawableId(getReactApplicationContext(),imageName);
return id;
}
/**
* URLBitmap
* @param src
* @return
*/
private static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (IOException e) {
return null;
}
}
/**
* Base64Bitmap
* @param Base64String
* @return
*/
private Bitmap decodeBase64ToBitmap(String Base64String) {
byte[] decode = Base64.decode(Base64String,Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
return bitmap;
}
/**
* bitmap
* @param bitmap
* @return
*/
private String saveBitmapToFile(Bitmap bitmap) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return null;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
return pictureFile.getAbsolutePath();
}
/**
*
* @return
*/
private File getOutputMediaFile(){
File mediaStorageDir = getCurrentActivity().getExternalCacheDir();
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="RN_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
/**
* token openid
*
* @param jsonObject
*/
public static void initOpenidAndToken(JSONObject jsonObject) {
try {
String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
&& !TextUtils.isEmpty(openId)) {
mTencent.setAccessToken(token, expires);
mTencent.setOpenId(openId);
}
} catch (Exception e) {
}
}
IUiListener loginListener = new IUiListener() {
@Override
public void onComplete(Object response) {
if (null == response) {
mPromise.reject("600",QQ_RESPONSE_ERROR);
return;
}
JSONObject jsonResponse = (JSONObject) response;
if (null != jsonResponse && jsonResponse.length() == 0) {
mPromise.reject("600",QQ_RESPONSE_ERROR);
return;
}
initOpenidAndToken(jsonResponse);
WritableMap map = Arguments.createMap();
map.putString("userid", mTencent.getOpenId());
map.putString("access_token", mTencent.getAccessToken());
map.putDouble("expires_time", mTencent.getExpiresIn());
mPromise.resolve(map);
}
@Override
public void onError(UiError e) {
mPromise.reject("600",e.errorMessage);
}
@Override
public void onCancel() {
mPromise.reject("603",QQ_CANCEL_BY_USER);
}
};
IUiListener qqShareListener = new IUiListener() {
@Override
public void onCancel() {
mPromise.reject("503",QQ_CANCEL_BY_USER);
}
@Override
public void onComplete(Object response) {
mPromise.resolve(true);
}
@Override
public void onError(UiError e) {
mPromise.reject("500",e.errorMessage);
}
};
/**
* QQZONE
*/
IUiListener qZoneShareListener = new IUiListener() {
@Override
public void onCancel() {
mPromise.reject("503",QZONE_SHARE_CANCEL);
}
@Override
public void onError(UiError e) {
mPromise.reject("500",e.errorMessage);
}
@Override
public void onComplete(Object response) {
mPromise.resolve(true);
}
};
IUiListener addToQQFavoritesListener = new IUiListener() {
@Override
public void onCancel() {
mPromise.reject("503",QQFAVORITES_CANCEL);
}
@Override
public void onComplete(Object response) {
mPromise.resolve(true);
}
@Override
public void onError(UiError e) {
mPromise.reject("500",e.errorMessage);
}
};
}
|
package org.jboss.as.console.client.domain.hosts;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.jboss.as.console.client.domain.model.Host;
import org.jboss.as.console.client.domain.model.ServerInstance;
import org.jboss.as.console.client.widgets.icons.ConsoleIcons;
import org.jboss.ballroom.client.widgets.common.DefaultButton;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A miller column based selection of host/serve combinations
*
* @author Heiko Braun
* @date 12/9/11
*/
public class HostServerTable {
private static final int ESCAPE = 27;
public final static double GOLDEN_RATIO = 1.618;
private boolean isRightToLeft = false;
private HostServerManagement presenter;
private CellList<Host> hostList;
private CellList<ServerInstance> serverList;
private PopupPanel popup;
private HorizontalPanel header;
private HTML currentDisplayedValue;
int popupWidth = -1;
private String description = null;
private HTML ratio;
public HostServerTable(HostServerManagement presenter) {
this.presenter = presenter;
}
public void setRightToLeft(boolean rightToLeft) {
isRightToLeft = rightToLeft;
}
public void setPopupWidth(int popupWidth) {
this.popupWidth = popupWidth;
}
public void setDescription(String description) {
this.description = description;
}
public Widget asWidget() {
final String panelId = "popup_"+ HTMLPanel.createUniqueId();
popup = new PopupPanel(true, true) {
@Override
protected void onPreviewNativeEvent(Event.NativePreviewEvent event) {
if (Event.ONKEYUP == event.getTypeInt()) {
if (event.getNativeEvent().getKeyCode() == ESCAPE) {
// Dismiss when escape is pressed
popup.hide();
}
}
}
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
}
};
popup.getElement().setId(panelId);
popup.setStyleName("default-popup");
VerticalPanel layout = new VerticalPanel();
layout.setStyleName("fill-layout-width");
layout.addStyleName("tablepicker-popup");
if(description!=null)
layout.add(new Label(description));
ratio = new HTML("RATIO HERE");
layout.add(ratio);
hostList = new CellList<Host>(new HostCell());
hostList.setSelectionModel(new SingleSelectionModel<Host>());
hostList.addStyleName("fill-layout-width");
serverList = new CellList<ServerInstance>(new ServerCell());
serverList.setSelectionModel(new SingleSelectionModel<ServerInstance>());
serverList.addStyleName("fill-layout-width");
hostList.getSelectionModel().addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
Host selectedHost = getSelectedHost();
presenter.loadServer(selectedHost);
}
});
serverList.getSelectionModel().addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
ServerInstance server = getSelectedServer();
presenter.onServerSelected(getSelectedHost(), getSelectedServer());
updateDisplay();
}
});
HorizontalPanel millerPanel = new HorizontalPanel();
millerPanel.setStyleName("fill-layout");
millerPanel.add(hostList);
millerPanel.add(serverList);
hostList.getElement().getParentElement().setAttribute("width", "50%");
serverList.getElement().getParentElement().setAttribute("width", "50%");
layout.add(millerPanel);
DefaultButton doneBtn = new DefaultButton("Done", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
popup.hide();
}
});
doneBtn.getElement().setAttribute("style","float:right");
layout.add(doneBtn);
popup.setWidget(layout);
currentDisplayedValue = new HTML(" ");
currentDisplayedValue.setStyleName("table-picker-value");
header = new HorizontalPanel();
header.setStyleName("table-picker");
header.add(currentDisplayedValue);
Image img = new Image(ConsoleIcons.INSTANCE.tablePicker());
header.add(img);
currentDisplayedValue.getElement().getParentElement().setAttribute("width", "100%");
img.getParent().getElement().setAttribute("width", "18");
header.getElement().setAttribute("width", "100%");
header.getElement().setAttribute("cellspacing", "0");
header.getElement().setAttribute("cellpadding", "0");
header.getElement().setAttribute("border", "0");
ClickHandler clickHandler = new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
openPanel();
}
};
currentDisplayedValue.addClickHandler(clickHandler);
img.addClickHandler(clickHandler);
return header;
}
private void updateDisplay() {
currentDisplayedValue.setHTML( // TODO: cope with long names
getSelectedHost().getName() + ": "
+ getSelectedServer().getName()
);
}
private Host getSelectedHost() {
return ((SingleSelectionModel<Host>) hostList.getSelectionModel()).getSelectedObject();
}
private ServerInstance getSelectedServer() {
return ((SingleSelectionModel<ServerInstance>) serverList.getSelectionModel()).getSelectedObject();
}
private void openPanel() {
int winWidth = popupWidth!=-1 ? popupWidth : header.getOffsetWidth() * 2;
int winHeight = (int) ( winWidth / GOLDEN_RATIO );
popup.setWidth(winWidth +"px");
popup.setHeight(winHeight + "px");
// right to left
if(isRightToLeft)
{
int popupLeft = header.getAbsoluteLeft() - (winWidth - header.getOffsetWidth());
popup.setPopupPosition(
popupLeft-15,
header.getAbsoluteTop()+21
);
}
else
{
int popupLeft = header.getAbsoluteLeft();
popup.setPopupPosition(
popupLeft,
header.getAbsoluteTop()+21
);
}
popup.show();
}
public void clearSelection() {
currentDisplayedValue.setText("");
}
/**
* Display the currently active servers for selection
* @param servers
*/
public void setServer(List<ServerInstance> servers) {
/*List<ServerInstance> active = new ArrayList<ServerInstance>();
for(ServerInstance instance : servers)
if(instance.isRunning())
active.add(instance);
ratio.setHTML("<i>Active Server: "+active.size()+" of "+servers.size()+" instances</i>");*/
serverList.setRowData(0, servers);
if(!servers.isEmpty())
serverList.getSelectionModel().setSelected(servers.get(0), true);
}
public void setHosts(List<Host> hosts) {
ratio.setText("");
hostList.setRowData(0, hosts);
// clear when hosts are updated
serverList.setRowData(0, Collections.EMPTY_LIST);
}
public void doBootstrap() {
if(hostList.getRowCount()>0)
{
hostList.getSelectionModel().setSelected(hostList.getVisibleItem(0), true);
presenter.loadServer(getSelectedHost());
}
}
interface Template extends SafeHtmlTemplates {
@Template("<div class='server-selection-host'>{0}</div>")
SafeHtml message(String title);
}
interface ServerTemplate extends SafeHtmlTemplates {
@Template("<div class='server-selection-server'>{0}</div>")
SafeHtml message(String title);
}
private static final Template HOST_TEMPLATE = GWT.create(Template.class);
private static final ServerTemplate SERVER_TEMPLATE = GWT.create(ServerTemplate.class);
public class HostCell extends AbstractCell<Host> {
@Override
public void render(
Context context,
Host host,
SafeHtmlBuilder safeHtmlBuilder)
{
safeHtmlBuilder.append(HOST_TEMPLATE.message(host.getName()));
}
}
public class ServerCell extends AbstractCell<ServerInstance> {
@Override
public void render(
Context context,
ServerInstance server,
SafeHtmlBuilder safeHtmlBuilder)
{
safeHtmlBuilder.append(SERVER_TEMPLATE.message(server.getName()));
}
}
}
|
package duro.runtime;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
public class InteractionHistory {
public static class Interaction implements Serializable {
private static final long serialVersionUID = 1L;
public final String interfaceId;
public final Instruction instruction;
public final Object output;
public Interaction(String interfaceId, Instruction instruction, Object output) {
this.interfaceId = interfaceId;
this.instruction = instruction;
this.output = output;
}
}
private int initialSize;
private List<Interaction> interactions;
private Hashtable<String, Integer> tracks = new Hashtable<String, Integer>();
public InteractionHistory(List<Interaction> interactions) {
this.interactions = interactions;
initialSize = interactions.size();
}
public boolean hasNewInteractions() {
return initialSize < interactions.size();
}
public List<Interaction> getNewInteractions() {
return new ArrayList<Interaction>(interactions.subList(initialSize, interactions.size()));
}
public void append(String interfaceId, Instruction instruction, Object output) {
interactions.add(new Interaction(interfaceId, instruction, output));
tracks.put(interfaceId, interactions.size() - 1);
}
public Object nextOutputFor(String interfaceId, int opcode) {
tracks.putIfAbsent(interfaceId, -1);
int trackIndex = tracks.get(interfaceId);
for(int i = trackIndex + 1; i < interactions.size(); i++) {
Interaction interaction = interactions.get(i);
if(/*interaction.instruction.opcode == opcode && */interaction.interfaceId.equals(interfaceId)) {
tracks.put(interfaceId, i);
return interaction.output;
}
}
return null;
}
}
|
package com.hazelcast.client.map;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.config.Config;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MapStoreConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.core.MapLoader;
import com.hazelcast.core.MapStore;
import com.hazelcast.map.mapstore.writebehind.ReachedMaxSizeException;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ProblematicTest;
import com.hazelcast.test.annotation.SlowTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import static com.hazelcast.test.HazelcastTestSupport.sleepSeconds;
import static junit.framework.Assert.assertEquals;
@RunWith(HazelcastSerialClassRunner.class)
@Category(SlowTest.class)
public class ClientMapStoreTest extends HazelcastTestSupport{
static final String MAP_NAME = "clientMapStoreLoad";
Config nodeConfig;
@Before
public void setup() {
nodeConfig = new Config();
MapConfig mapConfig = new MapConfig();
MapStoreConfig mapStoreConfig = new MapStoreConfig();
mapStoreConfig.setEnabled(true);
mapStoreConfig.setImplementation(new SimpleMapStore());
mapStoreConfig.setInitialLoadMode(MapStoreConfig.InitialLoadMode.EAGER);
mapConfig.setName(MAP_NAME);
mapConfig.setMapStoreConfig(mapStoreConfig);
nodeConfig.addMapConfig(mapConfig);
}
@After
public void tearDown() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testOneClient_KickOffMapStoreLoad() throws InterruptedException {
Hazelcast.newHazelcastInstance(nodeConfig);
ClientThread client1 = new ClientThread();
client1.start();
HazelcastTestSupport.assertJoinable(client1);
assertEquals(SimpleMapStore.MAX_KEYS, client1.mapSize);
}
@Test
public void testTwoClient_KickOffMapStoreLoad() throws InterruptedException {
Hazelcast.newHazelcastInstance(nodeConfig);
ClientThread[] clientThreads = new ClientThread[2];
for (int i = 0; i < clientThreads.length; i++) {
ClientThread client1 = new ClientThread();
client1.start();
clientThreads[i] = client1;
}
HazelcastTestSupport.assertJoinable(clientThreads);
for (ClientThread c : clientThreads) {
assertEquals(SimpleMapStore.MAX_KEYS, c.mapSize);
}
}
@Test
public void testOneClientKickOffMapStoreLoad_ThenNodeJoins() {
Hazelcast.newHazelcastInstance(nodeConfig);
ClientThread client1 = new ClientThread();
client1.start();
Hazelcast.newHazelcastInstance(nodeConfig);
HazelcastTestSupport.assertJoinable(client1);
assertEquals(SimpleMapStore.MAX_KEYS, client1.mapSize);
}
@Test
public void testForIssue2112() {
Hazelcast.newHazelcastInstance(nodeConfig);
ClientThread client1 = new ClientThread();
client1.start();
Hazelcast.newHazelcastInstance(nodeConfig);
ClientThread client2 = new ClientThread();
client2.start();
HazelcastTestSupport.assertJoinable(client1);
HazelcastTestSupport.assertJoinable(client2);
assertEquals(SimpleMapStore.MAX_KEYS, client1.mapSize);
assertEquals(SimpleMapStore.MAX_KEYS, client2.mapSize);
}
@Test
public void mapSize_After_MapStore_OperationQueue_OverFlow_Test() throws Exception{
Config config = new Config();
MapConfig mapConfig = new MapConfig();
MapStoreConfig mapStoreConfig = new MapStoreConfig();
final MapStoreBackup store = new MapStoreBackup();
final int delaySeconds = 4;
mapStoreConfig.setEnabled(true);
mapStoreConfig.setImplementation(store);
mapStoreConfig.setWriteDelaySeconds(delaySeconds);
mapConfig.setName(MAP_NAME);
mapConfig.setMapStoreConfig(mapStoreConfig);
config.addMapConfig(mapConfig);
HazelcastInstance server = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient();
final IMap map = client.getMap(MAP_NAME);
final int max = getMaxCapacity(server) + 1;
for(int i=0; i<max; i++){
map.putAsync(i, i);
}
Thread.sleep(1000 * (delaySeconds + 1));
assertEquals(max - 1, map.size());
}
@Test (expected = ReachedMaxSizeException.class )
public void mapStore_OperationQueue_AtMaxCapacity_Test() throws Exception{
Config config = new Config();
MapConfig mapConfig = new MapConfig();
MapStoreConfig mapStoreConfig = new MapStoreConfig();
final MapStoreBackup store = new MapStoreBackup();
final int longDelaySec = 60;
mapStoreConfig.setEnabled(true);
mapStoreConfig.setImplementation(store);
mapStoreConfig.setWriteDelaySeconds(longDelaySec);
mapConfig.setName(MAP_NAME);
mapConfig.setMapStoreConfig(mapStoreConfig);
config.addMapConfig(mapConfig);
HazelcastInstance server = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient();
final IMap map = client.getMap(MAP_NAME);
final int mapStoreQ_MaxCapacity = getMaxCapacity(server) + 1;
for(int i=0; i<mapStoreQ_MaxCapacity; i++){
map.put(i, i);
}
}
@Test
public void destroyMap_configedWith_MapStore() throws Exception{
Config config = new Config();
MapConfig mapConfig = new MapConfig();
MapStoreConfig mapStoreConfig = new MapStoreConfig();
final MapStoreBackup store = new MapStoreBackup();
final int delaySeconds = 4;
mapStoreConfig.setEnabled(true);
mapStoreConfig.setImplementation(store);
mapStoreConfig.setWriteDelaySeconds(delaySeconds);
mapConfig.setName(MAP_NAME);
mapConfig.setMapStoreConfig(mapStoreConfig);
config.addMapConfig(mapConfig);
HazelcastInstance server = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient();
IMap map = client.getMap(MAP_NAME);
for(int i=0; i<1; i++){
map.putAsync(i, i);
}
map.destroy();
}
static class SimpleMapStore implements MapStore<String, String>, MapLoader<String, String> {
public static final int MAX_KEYS = 30;
public static final int DELAY_SECONDS_PER_KEY = 1;
@Override
public String load(String key) {
sleepSeconds(DELAY_SECONDS_PER_KEY);
return key + "value";
}
@Override
public Map<String, String> loadAll(Collection<String> keys) {
Map<String, String> map = new HashMap<String, String>();
for (String key : keys) {
map.put(key, load(key));
}
return map;
}
@Override
public Set<String> loadAllKeys() {
Set<String> keys = new HashSet<String>();
for (int k = 0; k < MAX_KEYS; k++) { keys.add("key" + k); }
return keys;
}
@Override
public void delete(String key) {
sleepSeconds(DELAY_SECONDS_PER_KEY);
}
@Override
public void deleteAll(Collection<String> keys) {
for (String key : keys) {
delete(key);
}
}
@Override
public void store(String key, String value) {
sleepSeconds(DELAY_SECONDS_PER_KEY);
}
@Override
public void storeAll(Map<String, String> entries) {
for (Map.Entry<String, String> e : entries.entrySet()) {
store(e.getKey(), e.getValue());
}
}
}
private class ClientThread extends Thread {
public volatile int mapSize = 0;
public void run() {
HazelcastInstance client = HazelcastClient.newHazelcastClient();
IMap<String, String> map = client.getMap(ClientMapStoreTest.MAP_NAME);
mapSize = map.size();
}
}
public class MapStoreBackup implements MapStore<Object, Object> {
public final Map store = new ConcurrentHashMap();
@Override
public void store(Object key, Object value) {
store.put(key, value);
}
@Override
public void storeAll(Map<Object, Object> map) {
for (Map.Entry<Object, Object> kvp : map.entrySet()) {
store.put(kvp.getKey(), kvp.getValue());
}
}
@Override
public void delete(Object key) {
store.remove(key);
}
@Override
public void deleteAll(Collection<Object> keys) {
for (Object key : keys) {
store.remove(key);
}
}
@Override
public Object load(Object key) {
return store.get(key);
}
@Override
public Map<Object, Object> loadAll(Collection<Object> keys) {
Map result = new HashMap();
for (Object key : keys) {
final Object v = store.get(key);
if (v != null) {
result.put(key, v);
}
}
return result;
}
@Override
public Set<Object> loadAllKeys() {
return store.keySet();
}
}
private int getMaxCapacity(HazelcastInstance node) {
return getNode(node).getNodeEngine().getGroupProperties().MAP_WRITE_BEHIND_QUEUE_CAPACITY.getInteger();
}
}
|
package com.djonique.birdays.utils;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Locale;
public class Utils {
private static Calendar today = Calendar.getInstance();
private static Calendar dayOfBirthday = Calendar.getInstance();
public static String getDate(long date) {
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault());
return dateFormat.format(date);
}
private static int getDay(Calendar calendar) {
return calendar.get(Calendar.DAY_OF_MONTH);
}
private static int getMonth(Calendar calendar) {
return calendar.get(Calendar.MONTH);
}
private static int getYear(Calendar calendar) {
return calendar.get(Calendar.YEAR);
}
public static int getAge(long date) {
dayOfBirthday.setTimeInMillis(date);
int age = getYear(today) - getYear(dayOfBirthday);
if (getMonth(today) < getMonth(dayOfBirthday)) {
age
} else if (getMonth(today) == getMonth(dayOfBirthday) &&
getDay(today) < getDay(dayOfBirthday)) {
age
}
return age;
}
public static boolean isCurrentMonth(long date) {
boolean thisMonth = false;
dayOfBirthday.setTimeInMillis(date);
if (getMonth(dayOfBirthday) == getMonth(today)) {
thisMonth = true;
}
return thisMonth;
}
public static boolean isCurrentDay(long date) {
boolean thisDay = false;
dayOfBirthday.setTimeInMillis(date);
if (getDay(dayOfBirthday) == getDay(today) && isCurrentMonth(date)) {
thisDay = true;
}
return thisDay;
}
}
|
package com.proofpoint.http.client.jetty;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.io.CountingInputStream;
import com.google.common.net.HostAndPort;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.AbstractFuture;
import com.proofpoint.http.client.BodyGenerator;
import com.proofpoint.http.client.BodySource;
import com.proofpoint.http.client.DynamicBodySource;
import com.proofpoint.http.client.DynamicBodySource.Writer;
import com.proofpoint.http.client.HttpClientConfig;
import com.proofpoint.http.client.HttpRequestFilter;
import com.proofpoint.http.client.InputStreamBodySource;
import com.proofpoint.http.client.Request;
import com.proofpoint.http.client.RequestStats;
import com.proofpoint.http.client.ResponseHandler;
import com.proofpoint.http.client.ResponseTooLargeException;
import com.proofpoint.http.client.StaticBodyGenerator;
import com.proofpoint.log.Logger;
import com.proofpoint.stats.Distribution;
import com.proofpoint.tracetoken.TraceTokenScope;
import com.proofpoint.units.DataSize;
import com.proofpoint.units.DataSize.Unit;
import com.proofpoint.units.Duration;
import org.eclipse.jetty.client.ConnectionPool;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.client.HttpRequest;
import org.eclipse.jetty.client.PoolingHttpDestination;
import org.eclipse.jetty.client.Socks4Proxy;
import org.eclipse.jetty.client.api.Connection;
import org.eclipse.jetty.client.api.ContentProvider;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Response.Listener;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.http.HttpChannelOverHTTP;
import org.eclipse.jetty.client.http.HttpConnectionOverHTTP;
import org.eclipse.jetty.client.util.BytesContentProvider;
import org.eclipse.jetty.client.util.InputStreamContentProvider;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.util.ArrayQueue;
import org.eclipse.jetty.util.HttpCookieStore;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.weakref.jmx.Flatten;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.propagate;
import static com.proofpoint.tracetoken.TraceTokenManager.getCurrentRequestToken;
import static com.proofpoint.tracetoken.TraceTokenManager.registerRequestToken;
import static java.lang.Math.min;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
public class JettyHttpClient
implements com.proofpoint.http.client.HttpClient
{
private static final String[] DISABLED_CIPHERS = new String[] {
"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
"TLS_ECDHE_RSA_WITH_RC4_128_SHA",
"SSL_RSA_WITH_RC4_128_SHA",
"TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
"TLS_ECDH_RSA_WITH_RC4_128_SHA",
"SSL_RSA_WITH_RC4_128_MD5"
};
private static final AtomicLong nameCounter = new AtomicLong();
private static final String PLATFORM_STATS_KEY = "platform_stats";
private final HttpClient httpClient;
private final long maxContentLength;
private final Long requestTimeoutMillis;
private final long idleTimeoutMillis;
private final RequestStats stats = new RequestStats();
private final CachedDistribution queuedRequestsPerDestination;
private final CachedDistribution activeConnectionsPerDestination;
private final CachedDistribution idleConnectionsPerDestination;
private final CachedDistribution currentQueuedTime;
private final CachedDistribution currentRequestTime;
private final CachedDistribution currentRequestSendTime;
private final CachedDistribution currentResponseWaitTime;
private final CachedDistribution currentResponseProcessTime;
private final List<HttpRequestFilter> requestFilters;
private final Exception creationLocation = new Exception();
private final String name;
public JettyHttpClient()
{
this(new HttpClientConfig(), ImmutableList.<HttpRequestFilter>of());
}
public JettyHttpClient(HttpClientConfig config)
{
this(config, ImmutableList.<HttpRequestFilter>of());
}
public JettyHttpClient(HttpClientConfig config, Iterable<? extends HttpRequestFilter> requestFilters)
{
this(config, Optional.<JettyIoPool>absent(), requestFilters);
}
public JettyHttpClient(HttpClientConfig config, JettyIoPool jettyIoPool, Iterable<? extends HttpRequestFilter> requestFilters)
{
this(config, Optional.of(jettyIoPool), requestFilters);
}
private JettyHttpClient(HttpClientConfig config, Optional<JettyIoPool> jettyIoPool, Iterable<? extends HttpRequestFilter> requestFilters)
{
checkNotNull(config, "config is null");
checkNotNull(jettyIoPool, "jettyIoPool is null");
checkNotNull(requestFilters, "requestFilters is null");
maxContentLength = config.getMaxContentLength().toBytes();
Duration requestTimeout = config.getRequestTimeout();
if (requestTimeout == null) {
requestTimeoutMillis = null;
}
else {
requestTimeoutMillis = requestTimeout.toMillis();
}
idleTimeoutMillis = config.getIdleTimeout().toMillis();
creationLocation.fillInStackTrace();
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
sslContextFactory.addExcludeProtocols("SSLv3", "SSLv2Hello");
sslContextFactory.addExcludeCipherSuites(DISABLED_CIPHERS);
if (config.getKeyStorePath() != null) {
sslContextFactory.setKeyStorePath(config.getKeyStorePath());
sslContextFactory.setKeyStorePassword(config.getKeyStorePassword());
}
httpClient = new HttpClient(sslContextFactory);
httpClient.setMaxConnectionsPerDestination(config.getMaxConnectionsPerServer());
httpClient.setMaxRequestsQueuedPerDestination(config.getMaxRequestsQueuedPerDestination());
// disable cookies
httpClient.setCookieStore(new HttpCookieStore.Empty());
// timeouts
httpClient.setIdleTimeout(idleTimeoutMillis);
httpClient.setConnectTimeout(config.getConnectTimeout().toMillis());
httpClient.setAddressResolutionTimeout(config.getConnectTimeout().toMillis());
if (config.getConnectTimeout() != null) {
long connectTimeout = config.getConnectTimeout().toMillis();
httpClient.setConnectTimeout(connectTimeout);
httpClient.setAddressResolutionTimeout(connectTimeout);
}
HostAndPort socksProxy = config.getSocksProxy();
if (socksProxy != null) {
httpClient.getProxyConfiguration().getProxies().add(new Socks4Proxy(socksProxy.getHostText(), socksProxy.getPortOrDefault(1080)));
}
JettyIoPool pool = jettyIoPool.orNull();
if (pool == null) {
pool = new JettyIoPool("anonymous" + nameCounter.incrementAndGet(), new JettyIoPoolConfig());
}
name = pool.getName();
this.httpClient.setExecutor(pool.getExecutor());
this.httpClient.setByteBufferPool(pool.setByteBufferPool());
this.httpClient.setScheduler(pool.setScheduler());
try {
this.httpClient.start();
// remove the GZIP encoding from the client
// TODO: there should be a better way to to do this
this.httpClient.getContentDecoderFactories().clear();
}
catch (Exception e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw propagate(e);
}
this.requestFilters = ImmutableList.copyOf(requestFilters);
this.activeConnectionsPerDestination = new ConnectionPoolDistribution(httpClient,
(distribution, connectionPool) -> distribution.add(connectionPool.getActiveConnections().size()));
this.idleConnectionsPerDestination = new ConnectionPoolDistribution(httpClient,
(distribution, connectionPool) -> distribution.add(connectionPool.getIdleConnections().size()));
this.queuedRequestsPerDestination = new DestinationDistribution(httpClient,
(distribution, destination) -> distribution.add(destination.getHttpExchanges().size()));
this.currentQueuedTime = new RequestDistribution(httpClient, (distribution, listener, now) -> {
long started = listener.getRequestStarted();
if (started == 0) {
started = now;
}
distribution.add(NANOSECONDS.toMillis(started - listener.getCreated()));
});
this.currentRequestTime = new RequestDistribution(httpClient, (distribution, listener, now) -> {
long started = listener.getRequestStarted();
if (started == 0) {
return;
}
long finished = listener.getResponseFinished();
if (finished == 0) {
finished = now;
}
distribution.add(NANOSECONDS.toMillis(finished - started));
});
this.currentRequestSendTime = new RequestDistribution(httpClient, (distribution, listener, now) -> {
long started = listener.getRequestStarted();
if (started == 0) {
return;
}
long requestSent = listener.getRequestFinished();
if (requestSent == 0) {
requestSent = now;
}
distribution.add(NANOSECONDS.toMillis(requestSent - started));
});
this.currentResponseWaitTime = new RequestDistribution(httpClient, (distribution, listener, now) -> {
long requestSent = listener.getRequestFinished();
if (requestSent == 0) {
return;
}
long responseStarted = listener.getResponseStarted();
if (responseStarted == 0) {
responseStarted = now;
}
distribution.add(NANOSECONDS.toMillis(responseStarted - requestSent));
});
this.currentResponseProcessTime = new RequestDistribution(httpClient, (distribution, listener, now) -> {
long responseStarted = listener.getResponseStarted();
if (responseStarted == 0) {
return;
}
long finished = listener.getResponseFinished();
if (finished == 0) {
finished = now;
}
distribution.add(NANOSECONDS.toMillis(finished - responseStarted));
});
}
@Override
public <T, E extends Exception> T execute(Request request, ResponseHandler<T, E> responseHandler)
throws E
{
long requestStart = System.nanoTime();
AtomicLong bytesWritten = new AtomicLong(0);
// apply filters
request = applyRequestFilters(request);
// create jetty request and response listener
HttpRequest jettyRequest = buildJettyRequest(request, bytesWritten);
InputStreamResponseListener listener = new InputStreamResponseListener(maxContentLength)
{
@Override
public void onContent(Response response, ByteBuffer content)
{
// ignore empty blocks
if (content.remaining() == 0) {
return;
}
super.onContent(response, content);
}
};
// fire the request
jettyRequest.send(listener);
// wait for response to begin
Response response;
try {
response = listener.get(httpClient.getIdleTimeout(), MILLISECONDS);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
return responseHandler.handleException(request, e);
}
catch (TimeoutException e) {
return responseHandler.handleException(request, e);
}
catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
return responseHandler.handleException(request, (Exception) cause);
}
else {
return responseHandler.handleException(request, new RuntimeException(cause));
}
}
// process response
long responseStart = System.nanoTime();
JettyResponse jettyResponse = null;
T value;
try {
jettyResponse = new JettyResponse(response, listener.getInputStream());
value = responseHandler.handle(request, jettyResponse);
}
finally {
recordRequestComplete(stats, request, requestStart, bytesWritten.get(), jettyResponse, responseStart);
}
return value;
}
@Override
public <T, E extends Exception> HttpResponseFuture<T> executeAsync(Request request, ResponseHandler<T, E> responseHandler)
{
checkNotNull(request, "request is null");
checkNotNull(responseHandler, "responseHandler is null");
AtomicLong bytesWritten = new AtomicLong(0);
request = applyRequestFilters(request);
HttpRequest jettyRequest = buildJettyRequest(request, bytesWritten);
JettyResponseFuture<T, E> future = new JettyResponseFuture<>(request, jettyRequest, responseHandler, bytesWritten, stats);
BufferingResponseListener listener = new BufferingResponseListener(future, Ints.saturatedCast(maxContentLength));
try {
jettyRequest.send(listener);
}
catch (RuntimeException e) {
// normally this is a rejected execution exception because the client has been closed
future.failed(e);
}
return future;
}
private Request applyRequestFilters(Request request)
{
for (HttpRequestFilter requestFilter : requestFilters) {
request = requestFilter.filterRequest(request);
}
return request;
}
private HttpRequest buildJettyRequest(Request finalRequest, AtomicLong bytesWritten)
{
HttpRequest jettyRequest = (HttpRequest) httpClient.newRequest(finalRequest.getUri());
JettyRequestListener listener = new JettyRequestListener(finalRequest.getUri());
jettyRequest.onRequestBegin(request -> listener.onRequestBegin());
jettyRequest.onRequestSuccess(request -> listener.onRequestEnd());
jettyRequest.onResponseBegin(response -> listener.onResponseBegin());
jettyRequest.onComplete(result -> listener.onFinish());
jettyRequest.attribute(PLATFORM_STATS_KEY, listener);
// jetty client always adds the user agent header
// todo should there be a default?
jettyRequest.getHeaders().remove(HttpHeader.USER_AGENT);
jettyRequest.method(finalRequest.getMethod());
for (Entry<String, String> entry : finalRequest.getHeaders().entries()) {
jettyRequest.header(entry.getKey(), entry.getValue());
}
BodySource bodySource = finalRequest.getBodySource();
if (bodySource != null) {
if (bodySource instanceof StaticBodyGenerator) {
StaticBodyGenerator staticBodyGenerator = (StaticBodyGenerator) bodySource;
jettyRequest.content(new BytesContentProvider(staticBodyGenerator.getBody()));
bytesWritten.addAndGet(staticBodyGenerator.getBody().length);
}
else if (bodySource instanceof InputStreamBodySource) {
jettyRequest.content(new InputStreamContentProvider(new BodySourceInputStream((InputStreamBodySource) bodySource, bytesWritten), 4096, false));
}
else if (bodySource instanceof DynamicBodySource) {
jettyRequest.content(new DynamicBodySourceContentProvider((DynamicBodySource) bodySource, bytesWritten));
}
else if (bodySource instanceof BodyGenerator) {
jettyRequest.content(new BodyGeneratorContentProvider((BodyGenerator) bodySource, bytesWritten, httpClient.getExecutor()));
}
else {
throw new IllegalArgumentException("Request has unsupported BodySource type");
}
}
jettyRequest.followRedirects(finalRequest.isFollowRedirects());
// timeouts
if (requestTimeoutMillis != null) {
jettyRequest.timeout(requestTimeoutMillis, MILLISECONDS);
}
jettyRequest.idleTimeout(idleTimeoutMillis, MILLISECONDS);
return jettyRequest;
}
public List<HttpRequestFilter> getRequestFilters()
{
return requestFilters;
}
@Override
@Managed
@Flatten
public RequestStats getStats()
{
return stats;
}
@Managed
@Nested
public CachedDistribution getActiveConnectionsPerDestination()
{
return activeConnectionsPerDestination;
}
@Managed
@Nested
public CachedDistribution getIdleConnectionsPerDestination()
{
return idleConnectionsPerDestination;
}
@Managed
@Nested
public CachedDistribution getQueuedRequestsPerDestination()
{
return queuedRequestsPerDestination;
}
@Managed
@Nested
public CachedDistribution getCurrentQueuedTime()
{
return currentQueuedTime;
}
@Managed
@Nested
public CachedDistribution getCurrentRequestTime()
{
return currentRequestTime;
}
@Managed
@Nested
public CachedDistribution getCurrentRequestSendTime()
{
return currentRequestSendTime;
}
@Managed
@Nested
public CachedDistribution getCurrentResponseWaitTime()
{
return currentResponseWaitTime;
}
@Managed
@Nested
public CachedDistribution getCurrentResponseProcessTime()
{
return currentResponseProcessTime;
}
@Managed
public String dump()
{
return httpClient.dump();
}
@Managed
public void dumpStdErr()
{
httpClient.dumpStdErr();
}
@Managed
public String dumpAllDestinations()
{
return String.format("%s\t%s\t%s\t%s\t%s\n", "URI", "queued", "request", "wait", "response") +
httpClient.getDestinations().stream()
.map(JettyHttpClient::dumpDestination)
.collect(Collectors.joining("\n"));
}
@SuppressWarnings("UnusedDeclaration")
public String dumpDestination(URI uri)
{
Destination destination = httpClient.getDestination(uri.getScheme(), uri.getHost(), uri.getPort());
if (destination == null) {
return null;
}
return dumpDestination(destination);
}
private static String dumpDestination(Destination destination)
{
long now = System.nanoTime();
return getRequestListenersForDestination(destination).stream()
.map(request -> dumpRequest(now, request))
.sorted()
.collect(Collectors.joining("\n"));
}
private static List<JettyRequestListener> getRequestListenersForDestination(Destination destination)
{
return getRequestForDestination(destination).stream()
.map(request -> (JettyRequestListener) request.getAttributes().get(PLATFORM_STATS_KEY))
.filter(listener -> listener != null)
.collect(Collectors.toList());
}
private static List<org.eclipse.jetty.client.api.Request> getRequestForDestination(Destination destination)
{
PoolingHttpDestination<?> poolingHttpDestination = (PoolingHttpDestination<?>) destination;
Queue<HttpExchange> httpExchanges = poolingHttpDestination.getHttpExchanges();
List<org.eclipse.jetty.client.api.Request> requests = httpExchanges.stream()
.map(HttpExchange::getRequest)
.collect(Collectors.toList());
for (Connection connection : poolingHttpDestination.getConnectionPool().getActiveConnections()) {
HttpConnectionOverHTTP httpConnectionOverHTTP = (HttpConnectionOverHTTP) connection;
HttpChannelOverHTTP httpChannel = httpConnectionOverHTTP.getHttpChannel();
requests.add(httpChannel.getHttpExchange().getRequest());
}
return requests.stream().filter(request -> request != null).collect(Collectors.toList());
}
private static String dumpRequest(long now, JettyRequestListener listener)
{
long created = listener.getCreated();
long requestStarted = listener.getRequestStarted();
if (requestStarted == 0) {
requestStarted = now;
}
long requestFinished = listener.getRequestFinished();
if (requestFinished == 0) {
requestFinished = now;
}
long responseStarted = listener.getResponseStarted();
if (responseStarted == 0) {
responseStarted = now;
}
long finished = listener.getResponseFinished();
if (finished == 0) {
finished = now;
}
return String.format("%s\t%.1f\t%.1f\t%.1f\t%.1f",
listener.getUri(),
nanosToMillis(requestStarted - created),
nanosToMillis(requestFinished - requestStarted),
nanosToMillis(responseStarted - requestFinished),
nanosToMillis(finished - responseStarted));
}
private static double nanosToMillis(long nanos)
{
return new Duration(nanos, NANOSECONDS).getValue(MILLISECONDS);
}
@Override
public void close()
{
try {
httpClient.stop();
}
catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
catch (Exception ignored) {
}
}
@Override
public String toString()
{
return Objects.toStringHelper(this)
.addValue(name)
.toString();
}
@SuppressWarnings("UnusedDeclaration")
public StackTraceElement[] getCreationLocation()
{
return creationLocation.getStackTrace();
}
private static class JettyResponse
implements com.proofpoint.http.client.Response
{
private final Response response;
private final CountingInputStream inputStream;
JettyResponse(Response response, InputStream inputStream)
{
this.response = response;
this.inputStream = new CountingInputStream(inputStream);
}
@Override
public int getStatusCode()
{
return response.getStatus();
}
@Override
public String getStatusMessage()
{
return response.getReason();
}
@Override
public String getHeader(String name)
{
return response.getHeaders().getStringField(name);
}
@Override
public ListMultimap<String, String> getHeaders()
{
HttpFields headers = response.getHeaders();
ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
for (String name : headers.getFieldNamesCollection()) {
for (String value : headers.getValuesList(name)) {
builder.put(name, value);
}
}
return builder.build();
}
@Override
public long getBytesRead()
{
return inputStream.getCount();
}
@Override
public InputStream getInputStream()
{
return inputStream;
}
@Override
public String toString()
{
return Objects.toStringHelper(this)
.add("statusCode", getStatusCode())
.add("statusMessage", getStatusMessage())
.add("headers", getHeaders())
.toString();
}
}
private static class JettyResponseFuture<T, E extends Exception>
extends AbstractFuture<T>
implements HttpResponseFuture<T>
{
public enum JettyAsyncHttpState
{
WAITING_FOR_CONNECTION,
SENDING_REQUEST,
WAITING_FOR_RESPONSE,
PROCESSING_RESPONSE,
DONE,
FAILED,
CANCELED
}
private static final Logger log = Logger.get(JettyResponseFuture.class);
private final long requestStart = System.nanoTime();
private final AtomicReference<JettyAsyncHttpState> state = new AtomicReference<>(JettyAsyncHttpState.WAITING_FOR_CONNECTION);
private final Request request;
private final org.eclipse.jetty.client.api.Request jettyRequest;
private final ResponseHandler<T, E> responseHandler;
private final AtomicLong bytesWritten;
private final RequestStats stats;
private final String traceToken;
JettyResponseFuture(Request request, org.eclipse.jetty.client.api.Request jettyRequest, ResponseHandler<T, E> responseHandler, AtomicLong bytesWritten, RequestStats stats)
{
this.request = request;
this.jettyRequest = jettyRequest;
this.responseHandler = responseHandler;
this.bytesWritten = bytesWritten;
this.stats = stats;
traceToken = getCurrentRequestToken();
}
@Override
public String getState()
{
return state.get().toString();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning)
{
try {
state.set(JettyAsyncHttpState.CANCELED);
jettyRequest.abort(new CancellationException());
return super.cancel(mayInterruptIfRunning);
}
catch (Throwable e) {
setException(e);
return true;
}
}
protected void completed(Response response, InputStream content)
{
if (state.get() == JettyAsyncHttpState.CANCELED) {
return;
}
T value;
try {
value = processResponse(response, content);
}
catch (Throwable e) {
// this will be an instance of E from the response handler or an Error
storeException(e);
return;
}
state.set(JettyAsyncHttpState.DONE);
set(value);
}
private T processResponse(Response response, InputStream content)
throws E
{
// this time will not include the data fetching portion of the response,
// since the response is fully cached in memory at this point
long responseStart = System.nanoTime();
state.set(JettyAsyncHttpState.PROCESSING_RESPONSE);
JettyResponse jettyResponse = null;
T value;
try (TraceTokenScope ignored = registerRequestToken(traceToken)) {
jettyResponse = new JettyResponse(response, content);
value = responseHandler.handle(request, jettyResponse);
}
finally {
recordRequestComplete(stats, request, requestStart, bytesWritten.get(), jettyResponse, responseStart);
}
return value;
}
protected void failed(Throwable throwable)
{
if (state.get() == JettyAsyncHttpState.CANCELED) {
return;
}
// give handler a chance to rewrite the exception or return a value instead
if (throwable instanceof Exception) {
try (TraceTokenScope ignored = registerRequestToken(traceToken)) {
T value = responseHandler.handleException(request, (Exception) throwable);
// handler returned a value, store it in the future
state.set(JettyAsyncHttpState.DONE);
set(value);
return;
}
catch (Throwable newThrowable) {
throwable = newThrowable;
}
}
// at this point "throwable" will either be an instance of E
// from the response handler or not an instance of Exception
storeException(throwable);
}
private void storeException(Throwable throwable)
{
if (throwable instanceof CancellationException) {
state.set(JettyAsyncHttpState.CANCELED);
}
else {
state.set(JettyAsyncHttpState.FAILED);
}
if (throwable == null) {
throwable = new Throwable("Throwable is null");
log.error(throwable, "Something is broken");
}
setException(throwable);
}
@Override
public String toString()
{
return Objects.toStringHelper(this)
.add("requestStart", requestStart)
.add("state", state)
.add("request", request)
.toString();
}
}
private static void recordRequestComplete(RequestStats requestStats, Request request, long requestStart, long bytesWritten, JettyResponse response, long responseStart)
{
if (response == null) {
return;
}
Duration responseProcessingTime = Duration.nanosSince(responseStart);
Duration requestProcessingTime = new Duration(responseStart - requestStart, NANOSECONDS);
requestStats.record(request.getMethod(),
response.getStatusCode(),
bytesWritten,
response.getBytesRead(),
requestProcessingTime,
responseProcessingTime);
}
private static class BodySourceInputStream extends InputStream
{
private final InputStream delegate;
private final AtomicLong bytesWritten;
BodySourceInputStream(InputStreamBodySource bodySource, AtomicLong bytesWritten)
{
delegate = bodySource.getInputStream();
this.bytesWritten = bytesWritten;
}
@Override
public int read()
throws IOException
{
// We guarantee we don't call the int read() method of the delegate.
throw new UnsupportedOperationException();
}
@Override
public int read(byte[] b)
throws IOException
{
int read = delegate.read(b);
if (read > 0) {
bytesWritten.addAndGet(read);
}
return read;
}
@Override
public int read(byte[] b, int off, int len)
throws IOException
{
int read = delegate.read(b, off, len);
if (read > 0) {
bytesWritten.addAndGet(read);
}
return read;
}
@Override
public long skip(long n)
throws IOException
{
return delegate.skip(n);
}
@Override
public int available()
throws IOException
{
return delegate.available();
}
@Override
public void close()
{
// We guarantee we don't call this
throw new UnsupportedOperationException();
}
@Override
public void mark(int readlimit)
{
// We guarantee we don't call this
throw new UnsupportedOperationException();
}
@Override
public void reset()
throws IOException
{
// We guarantee we don't call this
throw new UnsupportedOperationException();
}
@Override
public boolean markSupported()
{
return false;
}
}
private static class DynamicBodySourceContentProvider
implements ContentProvider
{
private static final ByteBuffer DONE = ByteBuffer.allocate(0);
private final DynamicBodySource dynamicBodySource;
private final AtomicLong bytesWritten;
private final String traceToken;
DynamicBodySourceContentProvider(DynamicBodySource dynamicBodySource, AtomicLong bytesWritten)
{
this.dynamicBodySource = dynamicBodySource;
this.bytesWritten = bytesWritten;
traceToken = getCurrentRequestToken();
}
@Override
public long getLength()
{
return -1;
}
@Override
public Iterator<ByteBuffer> iterator()
{
final Queue<ByteBuffer> chunks = new ArrayQueue<>(4, 64);
Writer writer;
try (TraceTokenScope ignored = registerRequestToken(traceToken)) {
writer = dynamicBodySource.start(new DynamicBodySourceOutputStream(chunks));
}
catch (Exception e) {
throw propagate(e);
}
return new DynamicBodySourceIterator(chunks, writer, bytesWritten, traceToken);
}
private static class DynamicBodySourceOutputStream
extends OutputStream
{
private final Queue<ByteBuffer> chunks;
private DynamicBodySourceOutputStream(Queue<ByteBuffer> chunks)
{
this.chunks = chunks;
}
@Override
public void write(int b)
{
// must copy array since it could be reused
chunks.add(ByteBuffer.wrap(new byte[]{(byte) b}));
}
@Override
public void write(byte[] b, int off, int len)
{
// must copy array since it could be reused
byte[] copy = Arrays.copyOfRange(b, off, len);
chunks.add(ByteBuffer.wrap(copy));
}
@Override
public void close()
{
chunks.add(DONE);
}
}
private static class DynamicBodySourceIterator extends AbstractIterator<ByteBuffer>
implements Closeable
{
private final Queue<ByteBuffer> chunks;
private final Writer writer;
private final AtomicLong bytesWritten;
private final String traceToken;
@SuppressWarnings("AssignmentToCollectionOrArrayFieldFromParameter")
DynamicBodySourceIterator(Queue<ByteBuffer> chunks, Writer writer, AtomicLong bytesWritten, String traceToken)
{
this.chunks = chunks;
this.writer = writer;
this.bytesWritten = bytesWritten;
this.traceToken = traceToken;
}
@Override
protected ByteBuffer computeNext()
{
ByteBuffer chunk = chunks.poll();
while (chunk == null) {
try (TraceTokenScope ignored = registerRequestToken(traceToken)) {
writer.write();
}
catch (Exception e) {
throw propagate(e);
}
chunk = chunks.poll();
}
if (chunk == DONE) {
return endOfData();
}
bytesWritten.addAndGet(chunk.array().length);
return chunk;
}
@Override
public void close()
{
if (writer instanceof AutoCloseable) {
try (TraceTokenScope ignored = registerRequestToken(traceToken)) {
((AutoCloseable)writer).close();
}
catch (Exception e) {
throw propagate(e);
}
}
}
}
}
private static class BodyGeneratorContentProvider
implements ContentProvider
{
private static final ByteBuffer DONE = ByteBuffer.allocate(0);
private static final ByteBuffer EXCEPTION = ByteBuffer.allocate(0);
private final BodyGenerator bodyGenerator;
private final AtomicLong bytesWritten;
private final Executor executor;
private final String traceToken;
BodyGeneratorContentProvider(BodyGenerator bodyGenerator, AtomicLong bytesWritten, Executor executor)
{
this.bodyGenerator = bodyGenerator;
this.bytesWritten = bytesWritten;
this.executor = executor;
traceToken = getCurrentRequestToken();
}
@Override
public long getLength()
{
return -1;
}
@Override
public Iterator<ByteBuffer> iterator()
{
final ChunksQueue chunks = new ChunksQueue();
final AtomicReference<Exception> exception = new AtomicReference<>();
executor.execute(() -> {
BodyGeneratorOutputStream out = new BodyGeneratorOutputStream(chunks);
try (TraceTokenScope ignored = registerRequestToken(traceToken)) {
bodyGenerator.write(out);
out.close();
}
catch (Exception e) {
exception.set(e);
chunks.replaceAllWith(EXCEPTION);
}
});
return new ChunksIterator(chunks, exception, bytesWritten);
}
private static final class BodyGeneratorOutputStream
extends OutputStream
{
private final ChunksQueue chunks;
private BodyGeneratorOutputStream(ChunksQueue chunks)
{
this.chunks = chunks;
}
@Override
public void write(int b)
throws IOException
{
try {
// must copy array since it could be reused
chunks.put(ByteBuffer.wrap(new byte[] {(byte) b}));
}
catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
@Override
public void write(byte[] b, int off, int len)
throws IOException
{
try {
// must copy array since it could be reused
byte[] copy = Arrays.copyOfRange(b, off, len);
chunks.put(ByteBuffer.wrap(copy));
}
catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
@Override
public void close()
throws IOException
{
try {
chunks.put(DONE);
}
catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
}
private static class ChunksIterator extends AbstractIterator<ByteBuffer>
implements Closeable
{
private final ChunksQueue chunks;
private final AtomicReference<Exception> exception;
private final AtomicLong bytesWritten;
ChunksIterator(ChunksQueue chunks, AtomicReference<Exception> exception, AtomicLong bytesWritten)
{
this.chunks = chunks;
this.exception = exception;
this.bytesWritten = bytesWritten;
}
@Override
protected ByteBuffer computeNext()
{
ByteBuffer chunk;
try {
chunk = chunks.take();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted", e);
}
if (chunk == EXCEPTION) {
throw propagate(exception.get());
}
if (chunk == DONE) {
return endOfData();
}
bytesWritten.addAndGet(chunk.array().length);
return chunk;
}
@Override
public void close()
{
chunks.markDone();
}
}
private static class ChunksQueue
{
private final ByteBuffer[] items = new ByteBuffer[16];
private int takeIndex = 0;
private int putIndex = 0;
private int count = 0;
private boolean done = false;
private final ReentrantLock lock = new ReentrantLock(false);
private final Condition notEmpty = lock.newCondition();
private final Condition notFull = lock.newCondition();
private int inc(int i)
{
return (++i == items.length) ? 0 : i;
}
public void replaceAllWith(ByteBuffer e)
{
checkNotNull(e);
final ByteBuffer[] items = this.items;
final ReentrantLock lock = this.lock;
lock.lock();
try {
for (int i = takeIndex, k = count; k > 0; i = inc(i), k
items[i] = null;
}
items[0] = e;
count = 1;
putIndex = 1;
takeIndex = 0;
notEmpty.signal();
}
finally {
lock.unlock();
}
}
public void put(ByteBuffer e)
throws InterruptedException
{
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (!done && count == items.length) {
notFull.await();
}
if (done) {
throw new InterruptedException();
}
items[putIndex] = e;
putIndex = inc(putIndex);
++count;
notEmpty.signal();
}
finally {
lock.unlock();
}
}
public ByteBuffer take()
throws InterruptedException
{
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0) {
notEmpty.await();
}
final ByteBuffer[] items = this.items;
ByteBuffer x = items[takeIndex];
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
notFull.signal();
return x;
}
finally {
lock.unlock();
}
}
public void markDone()
{
final ReentrantLock lock = this.lock;
lock.lock();
try {
done = true;
notFull.signalAll();
}
finally {
lock.unlock();
}
}
}
}
private static class BufferingResponseListener
extends Listener.Adapter
{
private final JettyResponseFuture<?, ?> future;
private final int maxLength;
@GuardedBy("this")
private byte[] buffer = new byte[(int) new DataSize(64, Unit.KILOBYTE).toBytes()];
@GuardedBy("this")
private int size;
BufferingResponseListener(JettyResponseFuture<?, ?> future, int maxLength)
{
this.future = checkNotNull(future, "future is null");
Preconditions.checkArgument(maxLength > 0, "maxLength must be greater than zero");
this.maxLength = maxLength;
}
@Override
public synchronized void onHeaders(Response response)
{
long length = response.getHeaders().getLongField(HttpHeader.CONTENT_LENGTH.asString());
if (length > maxLength) {
response.abort(new ResponseTooLargeException());
}
if (length > buffer.length) {
buffer = Arrays.copyOf(buffer, Ints.saturatedCast(length));
}
}
@Override
public synchronized void onContent(Response response, ByteBuffer content)
{
int length = content.remaining();
int requiredCapacity = size + length;
if (requiredCapacity > buffer.length) {
if (requiredCapacity > maxLength) {
response.abort(new ResponseTooLargeException());
return;
}
// newCapacity = min(log2ceiling(requiredCapacity), maxLength);
int newCapacity = min(Integer.highestOneBit(requiredCapacity) << 1, maxLength);
buffer = Arrays.copyOf(buffer, newCapacity);
}
content.get(buffer, size, length);
size += length;
}
@Override
public synchronized void onComplete(Result result)
{
Throwable throwable = result.getFailure();
if (throwable != null) {
future.failed(throwable);
}
else {
future.completed(result.getResponse(), new ByteArrayInputStream(buffer, 0, size));
}
}
}
@ThreadSafe
public static class CachedDistribution
{
private final Supplier<Distribution> distributionSupplier;
@GuardedBy("this")
private Distribution distribution;
@GuardedBy("this")
private long lastUpdate = System.nanoTime();
public CachedDistribution(Supplier<Distribution> distributionSupplier)
{
this.distributionSupplier = distributionSupplier;
}
public synchronized Distribution getDistribution()
{
// refresh stats only once a second
if (NANOSECONDS.toMillis(System.nanoTime() - lastUpdate) > 1000) {
this.distribution = distributionSupplier.get();
this.lastUpdate = System.nanoTime();
}
return distribution;
}
@Managed
public double getMaxError()
{
return getDistribution().getMaxError();
}
@Managed
public double getCount()
{
return getDistribution().getCount();
}
@Managed
public double getTotal()
{
return getDistribution().getTotal();
}
@Managed
public long getP01()
{
return getDistribution().getP01();
}
@Managed
public long getP05()
{
return getDistribution().getP05();
}
@Managed
public long getP10()
{
return getDistribution().getP10();
}
@Managed
public long getP25()
{
return getDistribution().getP25();
}
@Managed
public long getP50()
{
return getDistribution().getP50();
}
@Managed
public long getP75()
{
return getDistribution().getP75();
}
@Managed
public long getP90()
{
return getDistribution().getP90();
}
@Managed
public long getP95()
{
return getDistribution().getP95();
}
@Managed
public long getP99()
{
return getDistribution().getP99();
}
@Managed
public long getMin()
{
return getDistribution().getMin();
}
@Managed
public long getMax()
{
return getDistribution().getMax();
}
@Managed
public Map<Double, Long> getPercentiles()
{
return getDistribution().getPercentiles();
}
}
private static class JettyRequestListener
{
enum State
{
CREATED, SENDING_REQUEST, AWAITING_RESPONSE, READING_RESPONSE, FINISHED
}
private final AtomicReference<State> state = new AtomicReference<>(State.CREATED);
private final URI uri;
private final long created = System.nanoTime();
private final AtomicLong requestStarted = new AtomicLong();
private final AtomicLong requestFinished = new AtomicLong();
private final AtomicLong responseStarted = new AtomicLong();
private final AtomicLong responseFinished = new AtomicLong();
public JettyRequestListener(URI uri)
{
this.uri = uri;
}
public URI getUri()
{
return uri;
}
public State getState()
{
return state.get();
}
public long getCreated()
{
return created;
}
public long getRequestStarted()
{
return requestStarted.get();
}
public long getRequestFinished()
{
return requestFinished.get();
}
public long getResponseStarted()
{
return responseStarted.get();
}
public long getResponseFinished()
{
return responseFinished.get();
}
public void onRequestBegin()
{
changeState(State.SENDING_REQUEST);
long now = System.nanoTime();
requestStarted.compareAndSet(0, now);
}
public void onRequestEnd()
{
changeState(State.AWAITING_RESPONSE);
long now = System.nanoTime();
requestStarted.compareAndSet(0, now);
requestFinished.compareAndSet(0, now);
}
private void onResponseBegin()
{
changeState(State.READING_RESPONSE);
long now = System.nanoTime();
requestStarted.compareAndSet(0, now);
requestFinished.compareAndSet(0, now);
responseStarted.compareAndSet(0, now);
}
private void onFinish()
{
changeState(State.FINISHED);
long now = System.nanoTime();
requestStarted.compareAndSet(0, now);
requestFinished.compareAndSet(0, now);
responseStarted.compareAndSet(0, now);
responseFinished.compareAndSet(0, now);
}
private synchronized void changeState(State newState)
{
if (state.get().ordinal() < newState.ordinal()) {
state.set(newState);
}
}
}
private static class ConnectionPoolDistribution
extends CachedDistribution
{
interface Processor
{
void process(Distribution distribution, ConnectionPool pool);
}
public ConnectionPoolDistribution(HttpClient httpClient, Processor processor)
{
super(() -> {
Distribution distribution = new Distribution();
for (Destination destination : httpClient.getDestinations()) {
PoolingHttpDestination<?> poolingHttpDestination = (PoolingHttpDestination<?>) destination;
processor.process(distribution, poolingHttpDestination.getConnectionPool());
}
return distribution;
});
}
}
private static class DestinationDistribution
extends CachedDistribution
{
interface Processor
{
void process(Distribution distribution, PoolingHttpDestination<?> destination);
}
public DestinationDistribution(HttpClient httpClient, Processor processor)
{
super(() -> {
Distribution distribution = new Distribution();
for (Destination destination : httpClient.getDestinations()) {
PoolingHttpDestination<?> poolingHttpDestination = (PoolingHttpDestination<?>) destination;
processor.process(distribution, poolingHttpDestination);
}
return distribution;
});
}
}
private static class RequestDistribution
extends CachedDistribution
{
interface Processor
{
void process(Distribution distribution, JettyRequestListener listener, long now);
}
public RequestDistribution(HttpClient httpClient, Processor processor)
{
super(() -> {
long now = System.nanoTime();
Distribution distribution = new Distribution();
for (Destination destination : httpClient.getDestinations()) {
for (JettyRequestListener listener : getRequestListenersForDestination(destination)) {
processor.process(distribution, listener, now);
}
}
return distribution;
});
}
}}
|
package com.itranswarp.shici.ddl;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.dialect.MySQL5InnoDBDialect;
import com.itranswarp.shici.model.ForeignKeys;
import com.itranswarp.shici.util.EncryptUtil;
import com.itranswarp.shici.util.FileUtil;
import com.itranswarp.warpdb.DDLGenerator;
public class DDL {
static final Log log = LogFactory.getLog(DDL.class);
public static void main(String[] args) throws Exception {
File file = new File(".").getAbsoluteFile();
String schemaOutput = file.getCanonicalPath() + File.separator + "target" + File.separator + "ddl.sql";
DDLGenerator generator = new DDLGenerator();
generator.export(Arrays.asList("com.itranswarp.shici"), MySQL5InnoDBDialect.class, schemaOutput);
String preInitOutput = generatePreInitOutput();
String postInitOutput = generatePostInitOutput();
log.info("Database initialize script was successfully exported to file: " + preInitOutput);
log.info("DDL script was successfully exported to file: " + schemaOutput);
String allOutput = file.getCanonicalPath() + File.separator + "target" + File.separator + "all.sql";
FileUtil.writeString(allOutput, preInitOutput + "\n" + FileUtil.readAsString(schemaOutput) + "\n"
+ postInitOutput + "\n\nselect \'database init ok.\' as \'MESSAGE:\';");
System.out.println("");
System.out.println("
System.out.println(" WARNING:");
System.out.println(" Copy and run the following command to init database.");
System.out.println("
System.out.println("");
System.out.println(String.join(" ", "mysql", "-uroot", "-p", "<", allOutput));
}
static String generatePreInitOutput() throws Exception {
String propertyName = "default.properties";
URL resource = DDL.class.getClassLoader().getResource(propertyName);
if (resource == null) {
throw new IOException("Properties file not found: " + propertyName);
}
Properties props = new Properties();
props.load(resource.openStream());
String url = props.getProperty("jdbc.url");
String user = props.getProperty("jdbc.user");
String password = props.getProperty("jdbc.password");
if (password.startsWith("AES:")) {
password = EncryptUtil.decryptByAES(password.substring(4));
}
String database = url.substring(url.lastIndexOf("/") + 1);
final String END = ";\n\n";
List<String> list = new ArrayList<String>();
list.add("drop database if exists " + database + END);
list.add("create database " + database + END);
list.add("grant all on " + database + ".* to \'" + user + "\'@\'localhost\' identified by \'" + password + "\'"
+ END);
list.add("use " + database + END);
return String.join("", list);
}
static String generatePostInitOutput() throws Exception {
return String.join("\n\n", ForeignKeys.FOREIGN_KEYS);
}
}
|
package dc_metadata;
import org.pmw.tinylog.Logger;
import java.util.HashMap;
/**
* Representation for a Contributor element.
*/
public class Contributor extends Element {
//static parsing characters
public static final String DELIM_NONNAME = "*";
// - dc.contributor.* || contributor role codes - //
public static String ACTOR = "actor";
public static String ADVISOR = "advisor";
public static String ADVISOR_CHAIR = "advisorChair";
public static String ADVISOR_DEPT_CHAIR= "advisorDeptChair";
public static String ARTIST = "artist";
public static String AUTHOR = "author";
public static String DESIGNER = "designer";
public static String DIRECTOR = "director";
public static String EDITOR = "editor";
public static String EDITOR_ART = "ArtEditor";
public static String EDITOR_CAMPUS = "CampusEditor";
public static String EDITOR_COPY = "CopyEditor";
public static String EDITOR_DEPUTY_MAN = "DeputyManagingEditor";
public static String EDITOR_EXECUTIVE = "ExecutiveEditor";
public static String EDITOR_FEATURE = "FeatureEditor";
public static String EDITOR_GRAPHIC_ART= "GraphicArtsEditor";
public static String EDITOR_MANAGING = "ManagingEditor";
public static String EDITOR_NEWS = "NewsEditor";
public static String EDITOR_PHOTO = "PhotographyEditor";
public static String EDITOR_PHOTO_ASST = "AsstPhotographyEditor";
public static String EDITOR_SPORTS = "SportsEditor";
public static String ILLUSTRATOR = "illustrator";
public static String MANAGER_ADVERTIS = "AdvManager";
public static String MANAGER_BUSINESS = "BusinessManager";
public static String MANAGER_PHOTO = "ManagerOfPhotography";
public static String ORGANIZATION = "organization";
public static String OTHER = "other";
public static String PHOTOGRAPHER = "photographer";
public static String PRODUCER = "producer";
public static String REPORTER = "reporter";
/**
* Set the dublin core standard information common to all Contributor elements
*/
private Contributor(){
uri = "http://purl.org/dc/elements/1.1/contributor";
name = "contributor";
label = "Contributor";
definition = "An entity responsible for making contributions to the resource.";
}
/**
* Set the qualifier and value information given the inputs
*/
private Contributor(String qualifier, String value){
this();
this.value = value;
this.qualifier = qualifier;
}
/**
* Return a contributor object whose qualifier has been selected with care.
* @param qualifierText the raw text from the metadata file
* @param fullName TODO switch to pass a 'Person' object
*/
public static Contributor createContributor(String qualifierText, String fullName) {
String qualifier = determineContributorQualifier(qualifierText);
String value = determineName(fullName).trim();
Logger.trace("CONTRIBUTOR created | qualifier: {}, value: {}.", qualifier, value);
return new Contributor(qualifier, value);
}
/**
* return a processed name...
* TODO figure out what all should or can be done at this stage to make this better formatted.
*/
private static String determineName(String valueText) {
return processName(valueText);
}
// - helpers - //
/**
* process a contributor line into a formatted line
* e.g. "fName mName mInitial lName" into "lName, fName mName mInitial lName"
*/
private static String processName(String line){
//prefix anything that's not a name with a
if(line.startsWith(DELIM_NONNAME))
return line.replace("*","");
//split names
String[] names = line.split(" ");
if(names.length == 1){
//single word entries should not be appended with anything.
return line.trim();
}else{
String lName = names[names.length-1];
String fName = line.substring(0, line.length() - lName.length() );
return lName + ", " + fName;
}
}
// - matching - //
/** given the all caps line, return which Contributor.qualifier type it represents, using help functions */
protected static String determineContributorQualifier(String line) {
String q = OTHER;
//AUTHOR/WRITER
if(matchAuthor(line) ){ q = AUTHOR; }
//EDITOR
else if (matchEditor(line)) {
if( matchExecutive(line) ){ q = EDITOR_EXECUTIVE; }
else if( matchArt(line) ){ q = matchGraphic(line)? EDITOR_GRAPHIC_ART : EDITOR_ART; }
else if( matchFeature(line) ){ q = EDITOR_FEATURE; }
else if( matchManaging(line) ){
q = (matchDeputy(line) || matchAsst(line)) ? EDITOR_DEPUTY_MAN : EDITOR_MANAGING; }
else if( matchCopy(line) ){ q = EDITOR_COPY; }
else if( matchPhoto(line) ){ q = matchAsst(line)? EDITOR_PHOTO_ASST : EDITOR_PHOTO; }
else if( matchSports(line) ){ q = EDITOR_SPORTS; }
else if( matchNews(line) ){ q = EDITOR_NEWS; }
else if( matchCampus(line) ){ q = EDITOR_CAMPUS; }
else if( matchGraphic(line) ){ q = EDITOR_GRAPHIC_ART;}
else { q = EDITOR; }
}
//ADVISOR, ARTIST, DESIGNER, ILLUSTRATOR, PHOTOGRAPHER, MANAGING(_BUSINESS)
else if( matchAdvisor(line)){
if( matchChair(line)){ q = matchDept(line)? ADVISOR_DEPT_CHAIR : ADVISOR_CHAIR; }
else{ q = ADVISOR; }
}
else if( matchActor(line) ){ q = ACTOR; }
else if( matchArtist(line) ){ q = ARTIST; }
else if( matchDesigner(line) ){ q = DESIGNER; }
else if( matchDirector(line) ){ q = matchArt(line)? EDITOR_ART : DIRECTOR; }
else if( matchIllustrator(line) ){ q = ILLUSTRATOR; }
else if( matchOrganization(line) ){ q = ORGANIZATION; }
else if( matchPhotographer(line) ){ q = PHOTOGRAPHER; }
else if( matchProducer(line) ){ q = PRODUCER; }
else if( matchReporter(line) ){ q = AUTHOR; }
else if( matchManaging(line)){
if( matchAdvertising(line) ){ q = MANAGER_ADVERTIS; }
if( matchBusiness(line) ){ q = MANAGER_BUSINESS; }
if( matchPhoto(line) ){ q = MANAGER_PHOTO; }
}
//OTHER
else{ q = AUTHOR
return q;
}
/* - Editors - */
/* EDITOR */
public static boolean matchEditor(String str ){
return str.contains("EDITOR");
}
/* EXECUTIVE */
public static boolean matchExecutive( String str ){
return str.contains("EXECUTIVE") || str.contains("CHIEF");
}
/* ART */
public static boolean matchArt( String str ){
return str.contains("ART");
}
/* COPY */
public static boolean matchCopy( String str ){
return str.contains("COPY");
}
/* FEATURE */
public static boolean matchFeature( String str){
return str.contains("FEATURE");
}
/* SPORTS */
public static boolean matchSports( String str ){
return str.contains("SPORTS");
}
/* NEWS */
public static boolean matchNews( String str ){
return str.contains("NEWS");
}
/* PHOTO */
public static boolean matchPhoto( String str ){
return str.contains("PHOTO");
}
/* MANAGING */
public static boolean matchManaging( String str ){
return str.contains("MANAG");
}
/* - Other contributor qualifiers - */
/* ADVISOR */
public static boolean matchAdvisor( String str ){
return str.contains("ADVISOR");
}
/* DESIGNER */
public static boolean matchDesigner( String str ){
return str.contains("DESIGNER");
}
/* ILLUSTRATOR */
public static boolean matchIllustrator( String str ){
return str.contains("ILLUSTRATOR");
}
/* PHOTOGRAPHER */
public static boolean matchPhotographer( String str ){
return str.contains("PHOTOGRAPHER");
}
/* ARTIST */
public static boolean matchArtist( String str ){
return str.contains("ARTIST");
}
/* BUSINESS */
public static boolean matchBusiness( String str ){
return str.contains("BUSINESS");
}
/* WRITER/AUTHOR */
public static boolean matchAuthor( String str ){
return str.contains("AUTHOR") || str.contains("WRITER") || str.contains("COLUMNIST");
}
/* ACTOR */
private static boolean matchActor(String str) { return str.contains("ACTOR"); }
/* Director */
private static boolean matchDirector(String str) { return str.contains("DIRECTOR"); }
/* ORGANIZATION */
private static boolean matchOrganization(String str) { return str.contains("ORGANIZ"); }
/* GRAPHIC */
private static boolean matchGraphic(String str) { return str.contains("GRAPHIC"); }
/* PRODUCER */
private static boolean matchProducer(String str) { return str.contains("PRODUCE"); }
/* ADVERTISING */
public static boolean matchAdvertising(String str){
return str.contains("ADVERT") || str.contains("AD ") || str.contains(" ADS");
}
/* REPORTER */
public static boolean matchReporter(String str){ return str.contains("REPORTER"); }
/* .CHAIR */
public static boolean matchChair(String str) { return str.contains("CHAIR"); }
/* .DEPT */
private static boolean matchDept(String str) { return str.contains("DEPT") || str.contains("DEPARTMENT"); }
/* .DEPUTY */
private static boolean matchDeputy(String str) { return str.contains("DEPUTY"); }
/* .CAMPUS */
private static boolean matchCampus(String str) { return str.contains("CAMPUS"); }
/* .ASST */
private static boolean matchAsst(String str) {
return str.contains("ASST") || str.contains("ASSIST") || str.contains("ASSOCIATE");
}
}
|
package com.melodies.bandup;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.Ack;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import static com.melodies.bandup.MainScreenActivity.ProfileFragment.DEFAULT;
public class ChatActivity extends AppCompatActivity {
private String sendTo;
private Socket mSocket;
Ack sendMessageAck = new Ack() {
@Override
public void call(Object... args) {
// If the message transmission succeeded or not
if (args[0].equals(false)) {
System.out.println("Sending message failed");
} else {
System.out.println("Sending message succeeded");
}
}
};
Ack addUserAck = new Ack() {
@Override
public void call(Object... args) {
// If the username is taken
if (args[0].equals(false)) {
}
}
};
/* Adds the message to the ScrollView and scrolls to the bottom. */
private void displayMessage(Boolean isUser, String sender, String message) {
ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
LinearLayout ll = (LinearLayout) findViewById(R.id.chatCells);
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = vi.inflate(R.layout.chat_message_cell, ll, false);
if (isUser) {
LinearLayout chatCell = (LinearLayout) myView.findViewById(R.id.chatMessageCell);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) chatCell.getLayoutParams();
params.gravity = Gravity.END;
chatCell.setLayoutParams(params);
}
TextView tv = (TextView) myView.findViewById(R.id.txtChatMessageText);
tv.setText(message);
ll.addView(myView);
scrollToBottom(scrollView);
}
/* Scroll to the bottom. */
private void scrollToBottom(final ScrollView scrollView) {
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
/* When the user taps on the Send Message button. */
public void onClickSend (View v) throws JSONException {
final EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
switch (v.getId()) {
case R.id.btnSend:
String message = txtMessage.getText().toString();
// Do not allow user to send empty string.
if (message.equals("")) {
return;
}
txtMessage.setText("");
// Create the JSON object to send the message.
final JSONObject msgObject = new JSONObject();
msgObject.put("nick", sendTo);
msgObject.put("message", message);
displayMessage(true, "You", message);
mSocket.emit("privatemsg", msgObject, sendMessageAck);
break;
}
}
public String getUserId() {
SharedPreferences srdPref = getSharedPreferences("UserIdRegister", Context.MODE_PRIVATE);
String userId = srdPref.getString("userId", DEFAULT);
return (!userId.equals(DEFAULT)) ? userId : "No data Found";
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
sendTo = extras.getString("SEND_TO_USER_ID");
}
else {
finish();
}
try {
mSocket = IO.socket(getResources().getString(R.string.api_address));
} catch (URISyntaxException e) {
Toast.makeText(ChatActivity.this, "URL parsing failed", Toast.LENGTH_SHORT).show();
}
setContentView(R.layout.activity_chat);
mSocket.on("recv_privatemsg", onNewMessage);
mSocket.connect();
mSocket.emit("adduser", getUserId(), addUserAck);
String url = getResources().getString(R.string.api_address).concat("/chat_history/").concat(sendTo);
// Get chat history.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
if (!response.isNull("chatHistory")) {
try {
JSONArray chatHistory = response.getJSONArray("chatHistory");
for (int i = 0; i < chatHistory.length(); i++) {
JSONObject item = chatHistory.getJSONObject(i);
if (!item.isNull("message")) {
Boolean isUser = getUserId().equals(item.getString("sender"));
displayMessage(isUser, item.getString("sender"), item.getString("message"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// If there is no chat found. No worries.
if (error.networkResponse.statusCode != 404) {
VolleySingleton.getInstance(ChatActivity.this).checkCauseOfError(ChatActivity.this, error);
}
}
});
VolleySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
// Listener to listen to the "recv_privatemsg" emission.
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
ChatActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// args[0] = from username
// args[1] = message
displayMessage(false, args[0].toString(), args[1].toString());
}
});
}
};
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("ONDESTROY");
mSocket.off();
mSocket.disconnect();
mSocket.off("recv_privatemsg", onNewMessage);
}
}
|
package com.radicalninja.pizzazz;
import android.app.Application;
import android.graphics.Color;
import android.util.Log;
import com.google.android.things.contrib.driver.sensehat.SenseHat;
import com.google.android.things.contrib.driver.ssd1306.Ssd1306;
import com.radicalninja.pizzazz.display.Oled1306Screen;
import com.radicalninja.pizzazz.ui.AbstractWindow;
import com.radicalninja.pizzazz.ui.MenuWindow;
import com.radicalninja.pizzazz.ui.WindowManager;
import com.radicalninja.pizzazz.util.Fonts;
import java.io.IOException;
public class Pizzazz extends Application {
private static final String TAG = Pizzazz.class.getSimpleName();
private static Pizzazz instance;
public static Pizzazz getInstance() {
return instance;
}
public Pizzazz() {
instance = this;
}
@Override
public void onCreate() {
super.onCreate();
Fonts.init(getAssets());
try {
SenseHat.openDisplay().draw(Color.BLACK);
} catch (IOException e) {
Log.e(TAG, "Error opening the SenseHat LED matrix.", e);
}
}
public void setupHwRev2(final WindowManager wm) {
final MenuWindow menuLeft = new MenuWindow("Left Window");
menuLeft.addMenuItem("Abc defg", null);
menuLeft.addMenuItem("Hijk lmn", null);
menuLeft.addMenuItem("Opq rstu", null);
menuLeft.addMenuItem("Vw xyz", null);
initDisplay(Ssd1306.I2C_ADDRESS_ALT, menuLeft, wm);
final MenuWindow menuRight = new MenuWindow("Right Window");
menuRight.addMenuItem("Lorem Ipsum", null);
menuRight.addMenuItem("Qwerty", null);
menuRight.addMenuItem("asdf", null);
menuRight.addMenuItem("jkl;", null);
menuRight.addMenuItem("Dvorak", null);
initDisplay(Ssd1306.I2C_ADDRESS, menuRight, wm);
}
private boolean initDisplay(final int i2cAddress, final AbstractWindow firstWindow, final WindowManager wm) {
try {
final Oled1306Screen screen = new Oled1306Screen(i2cAddress);
wm.registerDisplay(screen, firstWindow);
return true;
} catch (IOException e) {
Log.e(TAG, "There was an error attempting to open screen", e);
return false;
}
}
}
|
package com.zulip.android.util;
import com.zulip.android.ZulipApp;
public class UrlHelper {
public static String addHost(String url) {
if (!url.startsWith("http")) {
String hostUrl = ZulipApp.get().getServerHostUri();
if (hostUrl.endsWith("/")) {
url = hostUrl.substring(0, hostUrl.length() - 1) + url;
} else {
url = hostUrl + url;
}
}
return url;
}
}
|
package edu.byui.cs246.scandroid;
import android.util.Log;
import java.lang.reflect.Array;
import java.util.Observable;
import java.util.ArrayList;
public class Scanner extends Observable {
Integer delay; //delay in ms
ArrayList<ArrayList<Scan>> scans;
//observers managed by superclass
public void Scanner() { scans = new ArrayList<ArrayList<Scan>>(); }
public Scan scan() { //produces a scan object - scan is a verb here
if (!scans.isEmpty())
return scans.get(0).get(0);
else {
return null;
}
}
public void beginScanning() {};
public Scan getScan() {return new Scan();}
//TODO: List functions - maybe we need another class for the list...
public void insertSection() {};
public void insertScan(Scan scan) {
ArrayList<Scan> temp = new ArrayList();
temp.add(scan);
if (!scans.equals(null) && scans.isEmpty()) {
scans.add(0, temp);
}
else {
scans.get(0).add(0, scan);
}
Log.i("Info: ", "Inserting scan.");
notifyObservers();
}
public void clearList() {}
public Integer totalScanCount() { return scans.size();} //this needs loop through each sublist
public Integer listScanCount() { return scans.get(0).size();}
}
|
package fi.bitrite.android.ws.model;
import android.content.Context;
import android.content.res.Resources;
import android.os.Parcel;
import android.text.TextUtils;
import com.google.android.gms.maps.model.LatLng;
import com.yelp.parcelgen.JsonParser.DualCreator;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import fi.bitrite.android.ws.R;
public class Host extends _Host {
private long mUpdated;
public Host() {
super();
}
public Host(int id, String name, String fullname, String street, String additional, String city,
String province, String postalCode, String country, String mobilePhone,
String homePhone, String workPhone, String comments, String preferredNotice,
String maxCyclists, String notCurrentlyAvailable, String bed, String bikeshop,
String campground, String food, String kitchenUse, String laundry, String lawnspace,
String motel, String sag, String shower, String storage, String latitude,
String longitude, String login, String created, String languagesSpoken,
String picture, String profilePictureSmall, String profilePictureLarge) {
super(id, name, fullname, street, additional, city, province, postalCode, country,
mobilePhone, homePhone, workPhone, comments, preferredNotice, maxCyclists,
notCurrentlyAvailable, bed, bikeshop, campground, food, kitchenUse, laundry,
lawnspace, motel, sag, shower, storage, latitude, longitude, login, created,
languagesSpoken, picture, profilePictureSmall, profilePictureLarge);
}
public static final DualCreator<Host> CREATOR = new DualCreator<Host>() {
public Host[] newArray(int size) {
return new Host[size];
}
public Host createFromParcel(Parcel source) {
Host object = new Host();
object.readFromParcel(source);
return object;
}
@Override
public Host parse(JSONObject obj) throws JSONException {
Host newInstance = new Host();
newInstance.readFromJson(obj);
return newInstance;
}
};
public String getLocation() {
String location = "";
if (!TextUtils.isEmpty(getStreet())) {
location += getStreet() + "\n";
}
if (!TextUtils.isEmpty(getAdditional())) {
location += getAdditional() + "\n";
}
location += getCity() + ", " + getProvince().toUpperCase();
if (!TextUtils.isEmpty(getPostalCode())) {
location += " " + getPostalCode();
}
if (!TextUtils.isEmpty(getCountry())) {
location += ", " + getCountry().toUpperCase();
}
return location;
}
public String getNearbyServices(Context context) {
Resources r = context.getResources();
String nearbyServices = "";
if (!TextUtils.isEmpty(getMotel())) {
nearbyServices += r.getString(R.string.nearby_service_accommodation) + ": " + getMotel() + ", ";
}
if (!TextUtils.isEmpty(getBikeshop())) {
nearbyServices += r.getString(R.string.nearby_service_bikeshop) + ": " +getBikeshop() + ", ";
}
if (!TextUtils.isEmpty(getCampground())) {
nearbyServices += r.getString(R.string.nearby_service_campground) + ": " +getCampground() + ", ";
}
return nearbyServices;
}
public String getHostServices(Context context) {
StringBuilder sb = new StringBuilder();
Resources r = context.getResources();
if (hasService(getShower()))
sb.append(r.getString(R.string.host_service_shower) + ", ");
if (hasService(getFood()))
sb.append(r.getString(R.string.host_services_food) + ", ");
if (hasService(getBed()))
sb.append(r.getString(R.string.host_services_bed) + ", ");
if (hasService(getLaundry()))
sb.append(r.getString(R.string.host_service_laundry) + ", ");
if (hasService(getStorage()))
sb.append(r.getString(R.string.host_service_storage) + ", ");
if (hasService(getKitchenUse()))
sb.append(r.getString(R.string.host_service_kitchen) + ", ");
if (hasService(getLawnspace()))
sb.append(r.getString(R.string.host_service_tentspace) + ", ");
if (hasService(getSag()))
sb.append(context.getString(R.string.host_service_sag));
return sb.toString();
}
private boolean hasService(String service) {
return !TextUtils.isEmpty(service) && service.equals("1");
}
public boolean isNotCurrentlyAvailable() {
return hasService(mNotCurrentlyAvailable);
}
public long getUpdated() {
return mUpdated;
}
public void setUpdated(long updated) {
mUpdated = updated;
}
public String getMemberSince() {
return formatDate(getCreated());
}
public String getLastLogin() {
return getLogin();
}
public String getStreetCityAddress() {
String result = "";
if (mStreet != null && mStreet.length() > 0) {
result = mStreet + ", ";
}
result += mCity + ", " + mProvince.toUpperCase();
return result;
}
public Date getCreatedAsDate() {
return stringToDate(mCreated);
}
public Date getLastLoginAsDate() {
return stringToDate(mLogin);
}
private Date stringToDate(String s) {
int intDate = 0;
try {
intDate = Integer.parseInt(s);
} catch (Exception e) {
return null;
}
return new Date(intDate * 1000L);
}
private String formatDate(String timestamp) {
if (timestamp.isEmpty()) {
return "";
}
Date date = new Date(Long.parseLong(timestamp) * 1000);
DateFormat dateFormat = SimpleDateFormat.getDateInstance();
return dateFormat.format(date);
}
public LatLng getLatLng() {
return new LatLng(Double.parseDouble(mLatitude), Double.parseDouble(mLongitude));
}
}
|
package jp.blanktar.ruumusic;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Arrays;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.os.Build;
import android.content.Context;
import android.preference.PreferenceManager;
public abstract class RuuFileBase implements Comparable{
final Context context;
public final File path;
public RuuFileBase(@NonNull Context context, @NonNull String path) throws CanNotOpen{
try{
this.path = (new File(path)).getCanonicalFile();
}catch(IOException e){
throw new CanNotOpen(path);
}
this.context = context;
}
@NonNull
static List<String> getSupportedTypes(){
if(Build.VERSION.SDK_INT >= 12){
return Arrays.asList(".flac", ".aac", ".mp3", ".m4a", ".ogg", ".wav", ".3gp");
}else{
return Arrays.asList(".mp3", ".m4a", ".ogg", ".wav", ".3gp");
}
}
@NonNull
static String getRootDirectory(Context context){
return PreferenceManager.getDefaultSharedPreferences(context).getString("root_directory", "/");
}
@NonNull
public abstract String getFullPath();
public abstract boolean isDirectory();
@NonNull
public String getRuuPath() throws OutOfRootDirectory{
String root = getRootDirectory(context);
if(!getFullPath().startsWith(root)){
throw new OutOfRootDirectory();
}
return "/" + getFullPath().substring(root.length());
}
@NonNull
public String getName(){
return path.getName();
}
@NonNull
public RuuDirectory getParent() throws CanNotOpen{
String parent = path.getParent();
if(parent == null){
throw new CanNotOpen(null);
}else{
return new RuuDirectory(context, parent);
}
}
public boolean equals(@NonNull RuuFileBase file){
return isDirectory() == file.isDirectory() && path.equals(file.path);
}
public int depth(){
String pathStr = getFullPath();
return pathStr.length() - pathStr.replaceAll("/", "").length();
}
@Override
public int compareTo(@NonNull Object obj){
RuuFileBase file = (RuuFileBase)obj;
if(equals(file)){
return 0;
}else if(isDirectory() && file.isDirectory()){
if(((RuuDirectory)this).contains(file)){
return -1;
}else if(((RuuDirectory)file).contains(this)){
return 1;
}
}else if(!isDirectory() && !file.isDirectory()){
int depthDiff = file.depth() - depth();
if(depthDiff != 0){
return depthDiff;
}
}
return path.compareTo(file.path);
}
public class OutOfRootDirectory extends Throwable{
}
public class CanNotOpen extends Throwable{
final String path;
public CanNotOpen(@Nullable String path){
this.path = path;
}
}
}
|
package org.example.rest;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import io.vertx.core.Vertx;
import io.vertx.resourceadapter.VertxConnectionFactory;
@Path("/my")
@Stateless
public class MyEndpoint {
private static final String JNDI_NAME = "java:/eis/VertxConnectionFactory";
@Resource(mappedName = JNDI_NAME)
VertxConnectionFactory connectionFactory;
@GET
@Produces("text/plain")
public Response doGet() throws Exception {
Object obj = new InitialContext().lookup(JNDI_NAME);
System.out.println(connectionFactory instanceof VertxConnectionFactory);
System.out.println("VERTX: "+Vertx.class.getClassLoader());
System.out.println("VCF: "+VertxConnectionFactory.class.getClassLoader());
return Response.ok("Lookup: " + obj.getClass().getClassLoader()).build();
}
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package wyrl.io;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.util.*;
import wyautl.core.Automaton;
import wyautl.io.BinaryAutomataReader;
import wyautl.util.BigRational;
import wybs.io.BinaryInputStream;
import wybs.io.BinaryOutputStream;
import wyrl.core.Attribute;
import wyrl.core.Expr;
import wyrl.core.Pattern;
import wyrl.core.SpecFile;
import wyrl.core.Type;
import wyrl.core.Types;
import wyrl.core.SpecFile.RuleDecl;
import wyrl.util.*;
import static wyrl.core.Attribute.*;
import static wyrl.core.SpecFile.*;
public class NewJavaFileWriter {
private PrintWriter out;
public NewJavaFileWriter(Writer os) {
this.out = new PrintWriter(os);
}
public NewJavaFileWriter(OutputStream os) {
this.out = new PrintWriter(os);
}
public void write(SpecFile spec) throws IOException {
reset();
translate(spec,spec);
}
private void translate(SpecFile spec, SpecFile root) throws IOException {
PrintWriter saved = out;
if(root == spec) {
if (!spec.pkg.equals("")) {
myOut("package " + spec.pkg + ";");
myOut("");
}
writeImports();
myOut("public final class " + spec.name + " {");
}
for (Decl d : spec.declarations) {
if(d instanceof IncludeDecl) {
IncludeDecl id = (IncludeDecl) d;
SpecFile file = id.file;
translate(file,root);
} else if (d instanceof TermDecl) {
translate((TermDecl) d);
} else if (d instanceof RewriteDecl) {
translate((RewriteDecl) d,root);
}
}
if(root == spec) {
writeSchema(spec);
writeTypeTests();
writePatterns(spec);
writeRuleArrays(spec);
writeMainMethod();
}
if(root == spec) {
myOut("}");
out.close();
}
out = saved;
}
/**
* Reset all global information before proceeding to write out another file.
*/
protected void reset() {
termCounter = 0;
reductionCounter = 0;
inferenceCounter = 0;
}
protected void writeImports() {
myOut("import java.io.*;");
myOut("import java.util.*;");
myOut("import java.math.BigInteger;");
myOut("import wyautl.util.BigRational;");
myOut("import wyautl.io.*;");
myOut("import wyautl.core.*;");
myOut("import wyautl.rw.*;");
myOut("import wyrl.core.*;");
myOut("import wyrl.util.Runtime;");
myOut("import wyrl.util.AbstractRewriteRule;");
myOut("import wyrl.util.Pair;");
myOut();
}
public void translate(TermDecl decl) {
myOut(1, "// term " + decl.type);
String name = decl.type.name();
myOut(1, "public final static int K_" + name + " = "
+ termCounter++ + ";");
if (decl.type.element() == null) {
myOut(1, "public final static Automaton.Term " + name
+ " = new Automaton.Term(K_" + name + ");");
} else {
Type.Ref data = decl.type.element();
Type element = data.element();
if(element instanceof Type.Collection) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, int... r0) {" );
if(element instanceof Type.Set) {
myOut(2,"int r1 = automaton.add(new Automaton.Set(r0));");
} else if(element instanceof Type.Bag) {
myOut(2,"int r1 = automaton.add(new Automaton.Bag(r0));");
} else {
myOut(2,"int r1 = automaton.add(new Automaton.List(r0));");
}
myOut(2,"return automaton.add(new Automaton.Term(K_" + name + ", r1));");
myOut(1,"}");
myOut(1, "public final static int " + name
+ "(Automaton automaton, List<Integer> r0) {" );
if(element instanceof Type.Set) {
myOut(2,"int r1 = automaton.add(new Automaton.Set(r0));");
} else if(element instanceof Type.Bag) {
myOut(2,"int r1 = automaton.add(new Automaton.Bag(r0));");
} else {
myOut(2,"int r1 = automaton.add(new Automaton.List(r0));");
}
myOut(2,"return automaton.add(new Automaton.Term(K_" + name + ", r1));");
myOut(1,"}");
} else if(element instanceof Type.Int) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, long r0) {" );
myOut(2,"int r1 = automaton.add(new Automaton.Int(r0));");
myOut(2,"return automaton.add(new Automaton.Term(K_" + name + ", r1));");
myOut(1,"}");
myOut(1, "public final static int " + name
+ "(Automaton automaton, BigInteger r0) {" );
myOut(2,"int r1 = automaton.add(new Automaton.Int(r0));");
myOut(2,"return automaton.add(new Automaton.Term(K_" + name + ", r1));");
myOut(1,"}");
} else if(element instanceof Type.Real) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, long r0) {" );
myOut(2,"int r1 = automaton.add(new Automaton.Real(r0));");
myOut(2,"return automaton.add(new Automaton.Term(K_" + name + ", r1));");
myOut(1,"}");
myOut(1, "public final static int " + name
+ "(Automaton automaton, BigRational r0) {" );
myOut(2,"int r1 = automaton.add(new Automaton.Real(r0));");
myOut(2,"return automaton.add(new Automaton.Term(K_" + name + ", r1));");
myOut(1,"}");
} else if(element instanceof Type.Strung) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, String r0) {" );
myOut(2,"int r1 = automaton.add(new Automaton.Strung(r0));");
myOut(2,"return automaton.add(new Automaton.Term(K_" + name + ", r1));");
myOut(1,"}");
} else {
myOut(1, "public final static int " + name
+ "(Automaton automaton, " + type2JavaType(data) + " r0) {" );
myOut(2,"return automaton.add(new Automaton.Term(K_" + name + ", r0));");
myOut(1,"}");
}
}
myOut();
}
private int termCounter = 0;
private int reductionCounter = 0;
private int inferenceCounter = 0;
public void translate(RewriteDecl decl, SpecFile file) {
register(decl.pattern);
boolean isReduction = decl instanceof ReduceDecl;
Type param = decl.pattern.attribute(Attribute.Type.class).type;
myOut(1, "// " + decl.pattern);
if (isReduction) {
myOut(1, "private final static class Reduction_" + reductionCounter
+ " extends AbstractRewriteRule implements ReductionRule {");
} else {
myOut(1, "private final static class Inference_" + inferenceCounter
+ " extends AbstractRewriteRule implements InferenceRule {");
}
// Constructor
myOut();
if(isReduction) {
myOut(2, "public Reduction_" + reductionCounter++ + "(Pattern pattern) { super(pattern,SCHEMA); }");
} else {
myOut(2, "public Inference_" + inferenceCounter++ + "(Pattern pattern) { super(pattern,SCHEMA); }");
}
// Apply
myOut();
myOut(2,"public boolean apply(Automaton automaton, Object _state) {");
myOut(3,"Object[] state = (Object[]) _state;");
// first, unpack the state
Environment environment = new Environment();
int thus = environment.allocate(param,"this");
myOut(3, "int r" + thus + " = (Integer) state[0];");
for(Pair<String,Type> p : decl.pattern.declarations()) {
String name = p.first();
Type type = p.second();
int index = environment.allocate(type,name);
myOut(3, type2JavaType(type) + " r" + index + " = ("
+ type2JavaType(type,false) + ") state[" + index + "]; // " + name);
}
// second, translate the individual rules
for(RuleDecl rd : decl.rules) {
translate(3,rd,isReduction,environment,file);
}
myOut(3,"return false;");
myOut(2,"}");
myOut(1,"}"); // end class
}
public void register(Pattern p) {
if(p instanceof Pattern.Leaf) {
Pattern.Leaf pl = (Pattern.Leaf) p;
int typeIndex = register(pl.type);
} else if(p instanceof Pattern.Term) {
Pattern.Term pt = (Pattern.Term) p;
if(pt.data != null) {
register(pt.data);
}
} else if(p instanceof Pattern.Collection) {
Pattern.Collection pc = (Pattern.Collection) p;
for(Pair<Pattern,String> e : pc.elements) {
register(e.first());
}
}
}
public void translate(int level, RuleDecl decl, boolean isReduce, Environment environment, SpecFile file) {
int thus = environment.get("this");
// TODO: can optimise this by translating lets within the conditionals
// in the case that the conditionals don't refer to those lets. This
// will then prevent unnecessary object creation.
for(Pair<String,Expr> let : decl.lets) {
String letVar = let.first();
Expr letExpr = let.second();
int result = translate(level, letExpr, environment, file);
environment.put(result, letVar);
}
if(decl.condition != null) {
int condition = translate(level, decl.condition, environment, file);
myOut(level++, "if(r" + condition + ") {");
}
int result = translate(level, decl.result, environment, file);
result = coerceFromValue(level,decl.result,result,environment);
myOut(level, "if(r" + thus + " != r" + result + ") {");
myOut(level+1,"automaton.rewrite(r" + thus + ", r" + result + ");");
// FIXME: we can potentially get rid of the swap by requiring automaton
// to "reset" themselves to their original size before the rule began
// (and any junk states were added).
if(isReduce) {
myOut(level+1, "return true;");
} else {
myOut(level+1, "reduce(automaton,start);");
myOut(level+1, "if(!automaton.equals(original)) {");
myOut(level+2, "original.swap(automaton);");
myOut(level+2, "reduce(original,0);");
myOut(level+2, "return true;");
myOut(level+1, "}");
}
myOut(level,"}");
if(decl.condition != null) {
myOut(--level,"}");
}
}
public void writeSchema(SpecFile spec) {
myOut(1,
"
myOut(1, "// Schema");
myOut(1,
"
myOut();
myOut(1, "public static final Schema SCHEMA = new Schema(new Schema.Term[]{");
boolean firstTime=true;
for(TermDecl td : extractDecls(TermDecl.class,spec)) {
if (!firstTime) {
myOut(",");
}
firstTime=false;
myOut(2,"// " + td.type.toString());
indent(2);writeSchema(td.type);
}
myOut();
myOut(1, "});");
myOut();
}
public void writeRuleArrays(SpecFile spec) {
myOut(1,
"
myOut(1, "// rules");
myOut(1,
"
myOut();
myOut(1, "public static final InferenceRule[] inferences = new InferenceRule[]{");
int patternCounter = 0;
int inferCounter = 0;
for (Decl d : spec.declarations) {
if (d instanceof InferDecl) {
indent(2);
if (inferCounter != 0) {
out.println(",");
}
out.print("new Inference_" + inferCounter + "(pattern"
+ patternCounter + ")");
inferCounter++;
}
if (d instanceof RewriteDecl) {
patternCounter++;
}
}
myOut();
myOut(1, "};");
myOut(1, "public static final ReductionRule[] reductions = new ReductionRule[]{");
patternCounter = 0;
int reduceCounter = 0;
for (Decl d : spec.declarations) {
if (d instanceof ReduceDecl) {
indent(2);
if (reduceCounter != 0) {
out.println(",");
}
out.print("new Reduction_" + reduceCounter + "(pattern"
+ patternCounter + ")");
reduceCounter++;
}
if (d instanceof RewriteDecl) {
patternCounter++;
}
}
myOut();
myOut(1, "};");
myOut();
}
protected void writeTypeTests() throws IOException {
myOut(1,
"
myOut(1, "// Types");
myOut(1,
"
myOut();
for(int i=0;i!=typeRegister.size();++i) {
Type t = typeRegister.get(i);
JavaIdentifierOutputStream jout = new JavaIdentifierOutputStream();
BinaryOutputStream bout = new BinaryOutputStream(jout);
bout.write(t.toBytes());
bout.close();
// FIXME: strip out nominal types (and any other unneeded types).
myOut(1,"
myOut(1,"private static Type type" + i + " = Runtime.Type(\"" + jout.toString() + "\");");
}
myOut();
}
protected void writePatterns(SpecFile spec) throws IOException {
myOut(1,
"
myOut(1, "// Patterns");
myOut(1,
"
myOut();
int counter = 0;
for(Decl d : spec.declarations) {
if(d instanceof RewriteDecl) {
RewriteDecl rd = (RewriteDecl) d;
indent(1);
out.print( "private final static Pattern pattern" + counter++ + " = ");
translate(2,rd.pattern);
myOut(";");
}
}
}
public void translate(int level, Pattern p) {
if(p instanceof Pattern.Leaf) {
Pattern.Leaf pl = (Pattern.Leaf) p;
int typeIndex = register(pl.type);
out.print("new Pattern.Leaf(type" + typeIndex + ")");
} else if(p instanceof Pattern.Term) {
Pattern.Term pt = (Pattern.Term) p;
out.print("new Pattern.Term(\"" + pt.name + "\",");
if(pt.data != null) {
myOut();
indent(level);
translate(level+1,pt.data);
out.println(",");
indent(level);
} else {
out.print("null,");
}
if(pt.variable != null) {
out.print("\"" + pt.variable + "\")");
} else {
out.print("null)");
}
} else if (p instanceof Pattern.Collection) {
Pattern.Collection pc = (Pattern.Collection) p;
String kind;
if (p instanceof Pattern.Set) {
kind = "Set";
} else if (p instanceof Pattern.Bag) {
kind = "Bag";
} else {
kind = "List";
}
out.print("new Pattern." + kind + "(" + pc.unbounded
+ ", new Pair[]{");
for (int i = 0; i != pc.elements.length; ++i) {
Pair<Pattern, String> e = pc.elements[i];
Pattern ep = e.first();
String es = e.second();
if (i != 0) {
out.println(", ");
} else {
out.println();
}
indent(level);
out.print("new Pair(");
translate(level + 1, ep);
if (es == null) {
out.print(",null)");
} else {
out.print(", \"" + es + "\")");
}
}
out.print("})");
}
}
private void writeSchema(Type.Term tt) {
Automaton automaton = tt.automaton();
BitSet visited = new BitSet(automaton.nStates());
writeSchema(automaton.getRoot(0),automaton,visited);
}
private void writeSchema(int node, Automaton automaton, BitSet visited) {
if(node < 0) {
// bypass virtual node
} else if (visited.get(node)) {
out.print("Schema.Any");
return;
} else {
visited.set(node);
}
// you can scratch your head over why this is guaranteed ;)
Automaton.Term state = (Automaton.Term) automaton.get(node);
switch (state.kind) {
case wyrl.core.Types.K_Void:
out.print("Schema.Void");
break;
case wyrl.core.Types.K_Any:
out.print("Schema.Any");
break;
case wyrl.core.Types.K_Bool:
out.print("Schema.Bool");
break;
case wyrl.core.Types.K_Int:
out.print("Schema.Int");
break;
case wyrl.core.Types.K_Real:
out.print("Schema.Real");
break;
case wyrl.core.Types.K_String:
out.print("Schema.String");
break;
case wyrl.core.Types.K_Not:
out.print("Schema.Not(");
writeSchema(state.contents, automaton, visited);
out.print(")");
break;
case wyrl.core.Types.K_Ref:
writeSchema(state.contents, automaton, visited);
break;
case wyrl.core.Types.K_Meta:
out.print("Schema.Meta(");
writeSchema(state.contents, automaton, visited);
out.print(")");
break;
case wyrl.core.Types.K_Nominal: {
// bypass the nominal marker
Automaton.List list = (Automaton.List) automaton.get(state.contents);
writeSchema(list.get(1), automaton, visited);
break;
}
case wyrl.core.Types.K_Or: {
out.print("Schema.Or(");
Automaton.Set set = (Automaton.Set) automaton.get(state.contents);
for(int i=0;i!=set.size();++i) {
if(i != 0) { out.print(", "); }
writeSchema(set.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_Set: {
out.print("Schema.Set(");
Automaton.List list = (Automaton.List) automaton.get(state.contents);
// FIXME: need to deref unbounded bool here as well
out.print("true");
Automaton.Bag set = (Automaton.Bag) automaton.get(list.get(1));
for(int i=0;i!=set.size();++i) {
out.print(",");
writeSchema(set.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_Bag: {
out.print("Schema.Bag(");
Automaton.List list = (Automaton.List) automaton.get(state.contents);
// FIXME: need to deref unbounded bool here as well
out.print("true");
Automaton.Bag bag = (Automaton.Bag) automaton.get(list.get(1));
for(int i=0;i!=bag.size();++i) {
out.print(",");
writeSchema(bag.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_List: {
out.print("Schema.List(");
Automaton.List list = (Automaton.List) automaton.get(state.contents);
// FIXME: need to deref unbounded bool here as well
out.print("true");
Automaton.List list2 = (Automaton.List) automaton.get(list.get(1));
for(int i=0;i!=list2.size();++i) {
out.print(",");
writeSchema(list2.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_Term: {
out.print("Schema.Term(");
Automaton.List list = (Automaton.List) automaton.get(state.contents);
Automaton.Strung str = (Automaton.Strung) automaton.get(list.get(0));
out.print("\"" + str.value + "\"");
if(list.size() > 1) {
out.print(",");
writeSchema(list.get(1),automaton,visited);
}
out.print(")");
break;
}
default:
throw new RuntimeException("Unknown kind encountered: " + state.kind);
}
}
private <T extends Decl> ArrayList<T> extractDecls(Class<T> kind, SpecFile spec) {
ArrayList r = new ArrayList();
extractDecls(kind,spec,r);
return r;
}
private <T extends Decl> void extractDecls(Class<T> kind, SpecFile spec, ArrayList<T> decls) {
for(Decl d : spec.declarations) {
if(kind.isInstance(d)) {
decls.add((T)d);
} else if(d instanceof IncludeDecl) {
IncludeDecl id = (IncludeDecl) d;
extractDecls(kind,id.file,decls);
}
}
}
public int translate(int level, Expr code, Environment environment, SpecFile file) {
if (code instanceof Expr.Constant) {
return translate(level,(Expr.Constant) code, environment, file);
} else if (code instanceof Expr.UnOp) {
return translate(level,(Expr.UnOp) code, environment, file);
} else if (code instanceof Expr.BinOp) {
return translate(level,(Expr.BinOp) code, environment, file);
} else if (code instanceof Expr.NaryOp) {
return translate(level,(Expr.NaryOp) code, environment, file);
} else if (code instanceof Expr.Constructor) {
return translate(level,(Expr.Constructor) code, environment, file);
} else if (code instanceof Expr.ListAccess) {
return translate(level,(Expr.ListAccess) code, environment, file);
} else if (code instanceof Expr.ListUpdate) {
return translate(level,(Expr.ListUpdate) code, environment, file);
} else if (code instanceof Expr.Variable) {
return translate(level,(Expr.Variable) code, environment, file);
} else if (code instanceof Expr.Substitute) {
return translate(level,(Expr.Substitute) code, environment, file);
} else if(code instanceof Expr.Comprehension) {
return translate(level,(Expr.Comprehension) code, environment, file);
} else if(code instanceof Expr.TermAccess) {
return translate(level,(Expr.TermAccess) code, environment, file);
} else if(code instanceof Expr.Cast) {
return translate(level,(Expr.Cast) code, environment, file);
} else {
throw new RuntimeException("unknown expression encountered - " + code);
}
}
public int translate(int level, Expr.Cast code, Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
// first translate src expression, and coerce to a value
int src = translate(level, code.src, environment, file);
src = coerceFromRef(level, code.src, src, environment);
// TODO: currently we only support casting from integer to real!!
String body = "new Automaton.Real(r" + src + ".value)";
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.Constant code, Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
Object v = code.value;
String rhs;
if (v instanceof Boolean) {
rhs = v.toString();
} else if (v instanceof BigInteger) {
BigInteger bi = (BigInteger) v;
if(bi.bitLength() <= 64) {
rhs = "new Automaton.Int(" + bi.longValue() + ")";
} else {
rhs = "new Automaton.Int(\"" + bi.toString() + "\")";
}
} else if (v instanceof BigRational) {
BigRational br = (BigRational) v;
rhs = "new Automaton.Real(\"" + br.toString() + "\")";
if(br.isInteger()) {
long lv = br.longValue();
if(BigRational.valueOf(lv).equals(br)) {
// Yes, this will fit in a long value. Therefore, inline a
// long constant as this is faster.
rhs = "new Automaton.Real(" + lv + ")";
}
}
} else if (v instanceof String) {
rhs = "new Automaton.Strung(\"" + v + "\")";
} else {
throw new RuntimeException("unknown constant encountered (" + v
+ ")");
}
int target = environment.allocate(type);
myOut(level,comment(type2JavaType(type) + " r" + target + " = " + rhs + ";",code.toString()));
return target;
}
public int translate(int level, Expr.UnOp code, Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
int rhs = translate(level,code.mhs,environment,file);
rhs = coerceFromRef(level,code.mhs, rhs, environment);
String body;
switch (code.op) {
case LENGTHOF:
body = "r" + rhs + ".lengthOf()";
break;
case NUMERATOR:
body = "r" + rhs + ".numerator()";
break;
case DENOMINATOR:
body = "r" + rhs + ".denominator()";
break;
case NEG:
body = "r" + rhs + ".negate()";
break;
case NOT:
body = "!r" + rhs;
break;
default:
throw new RuntimeException("unknown unary expression encountered");
}
int target = environment.allocate(type);
myOut(level,comment(type2JavaType(type) + " r" + target + " = " + body + ";",code.toString()));
return target;
}
public int translate(int level, Expr.BinOp code, Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
Type lhs_t = code.lhs.attribute(Attribute.Type.class).type;
Type rhs_t = code.rhs.attribute(Attribute.Type.class).type;
int lhs = translate(level,code.lhs,environment,file);
String body;
if(code.op == Expr.BOp.IS && code.rhs instanceof Expr.Constant) {
// special case for runtime type tests
Expr.Constant c = (Expr.Constant) code.rhs;
Type test = (Type)c.value;
int typeIndex = register(test);
body = "Runtime.accepts(type" + typeIndex + ", automaton, r" + lhs + ", SCHEMA)";
} else if(code.op == Expr.BOp.AND) {
// special case to ensure short-circuiting of AND.
lhs = coerceFromRef(level,code.lhs, lhs, environment);
int target = environment.allocate(type);
myOut(level,comment( type2JavaType(type) + " r" + target + " = " + false + ";",code.toString()));
myOut(level++,"if(r" + lhs + ") {");
int rhs = translate(level,code.rhs,environment,file);
rhs = coerceFromRef(level,code.rhs, rhs, environment);
myOut(level,"r" + target + " = r" + rhs + ";");
myOut(--level,"}");
return target;
} else {
int rhs = translate(level,code.rhs,environment,file);
// First, convert operands into values (where appropriate)
switch(code.op) {
case EQ:
case NEQ:
if(lhs_t instanceof Type.Ref && rhs_t instanceof Type.Ref) {
// OK to do nothing here...
} else {
lhs = coerceFromRef(level,code.lhs, lhs, environment);
rhs = coerceFromRef(level,code.rhs, rhs, environment);
}
break;
case APPEND:
// append is a tricky case as we have support the non-symmetic cases
// for adding a single element to the end or the beginning of a
// list.
lhs_t = Type.unbox(lhs_t);
rhs_t = Type.unbox(rhs_t);
if(lhs_t instanceof Type.Collection) {
lhs = coerceFromRef(level,code.lhs, lhs, environment);
} else {
lhs = coerceFromValue(level, code.lhs, lhs, environment);
}
if(rhs_t instanceof Type.Collection) {
rhs = coerceFromRef(level,code.rhs, rhs, environment);
} else {
rhs = coerceFromValue(level,code.rhs, rhs, environment);
}
break;
case IN:
lhs = coerceFromValue(level,code.lhs,lhs,environment);
rhs = coerceFromRef(level,code.rhs,rhs,environment);
break;
default:
lhs = coerceFromRef(level,code.lhs,lhs,environment);
rhs = coerceFromRef(level,code.rhs,rhs,environment);
}
// Second, construct the body of the computation
switch (code.op) {
case ADD:
body = "r" + lhs + ".add(r" + rhs + ")";
break;
case SUB:
body = "r" + lhs + ".subtract(r" + rhs + ")";
break;
case MUL:
body = "r" + lhs + ".multiply(r" + rhs + ")";
break;
case DIV:
body = "r" + lhs + ".divide(r" + rhs + ")";
break;
case OR:
body = "r" + lhs + " || r" + rhs ;
break;
case EQ:
if(lhs_t instanceof Type.Ref && rhs_t instanceof Type.Ref) {
body = "r" + lhs + " == r" + rhs ;
} else {
body = "r" + lhs + ".equals(r" + rhs +")" ;
}
break;
case NEQ:
if(lhs_t instanceof Type.Ref && rhs_t instanceof Type.Ref) {
body = "r" + lhs + " != r" + rhs ;
} else {
body = "!r" + lhs + ".equals(r" + rhs +")" ;
}
break;
case LT:
body = "r" + lhs + ".compareTo(r" + rhs + ")<0";
break;
case LTEQ:
body = "r" + lhs + ".compareTo(r" + rhs + ")<=0";
break;
case GT:
body = "r" + lhs + ".compareTo(r" + rhs + ")>0";
break;
case GTEQ:
body = "r" + lhs + ".compareTo(r" + rhs + ")>=0";
break;
case APPEND:
if (lhs_t instanceof Type.Collection) {
body = "r" + lhs + ".append(r" + rhs + ")";
} else {
body = "r" + rhs + ".appendFront(r" + lhs + ")";
}
break;
case DIFFERENCE:
body = "r" + lhs + ".removeAll(r" + rhs + ")";
break;
case IN:
body = "r" + rhs + ".contains(r" + lhs + ")";
break;
case RANGE:
body = "Runtime.rangeOf(automaton,r" + lhs + ",r" + rhs + ")";
break;
default:
throw new RuntimeException("unknown binary operator encountered: "
+ code);
}
}
int target = environment.allocate(type);
myOut(level,comment( type2JavaType(type) + " r" + target + " = " + body + ";",code.toString()));
return target;
}
public int translate(int level, Expr.NaryOp code, Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
String body = "new Automaton.";
if(code.op == Expr.NOp.LISTGEN) {
body += "List(";
} else if(code.op == Expr.NOp.BAGGEN) {
body += "Bag(";
} else {
body += "Set(";
}
List<Expr> arguments = code.arguments;
for(int i=0;i!=arguments.size();++i) {
if(i != 0) {
body += ", ";
}
Expr argument = arguments.get(i);
int reg = translate(level, argument, environment, file);
reg = coerceFromValue(level, argument, reg, environment);
body += "r" + reg;
}
int target = environment.allocate(type);
myOut(level,comment(type2JavaType(type) + " r" + target + " = " + body + ");",code.toString()));
return target;
}
public int translate(int level, Expr.ListAccess code, Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
int src = translate(level,code.src, environment,file);
int idx = translate(level,code.index, environment,file);
src = coerceFromRef(level,code.src, src, environment);
idx = coerceFromRef(level,code.index, idx, environment);
String body = "r" + src + ".indexOf(r" + idx + ")";
int target = environment.allocate(type);
myOut(level,comment(type2JavaType(type) + " r" + target + " = " + body + ";",code.toString()));
return target;
}
public int translate(int level, Expr.ListUpdate code, Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
int src = translate(level,code.src, environment, file);
int idx = translate(level,code.index, environment, file);
int value = translate(level,code.value, environment, file);
src = coerceFromRef(level,code.src, src, environment);
idx = coerceFromRef(level,code.index, idx, environment);
value = coerceFromValue(level,code.value, value, environment);
String body = "r" + src + ".update(r" + idx + ", r" + value + ")";
int target = environment.allocate(type);
myOut(level,comment(type2JavaType(type) + " r" + target + " = " + body + ";",code.toString()));
return target;
}
public int translate(int level, Expr.Constructor code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
String body;
if (code.argument == null) {
body = code.name;
} else {
int arg = translate(level, code.argument, environment, file);
if(code.external) {
body = file.name + "$native." + code.name + "(automaton, r" + arg + ")";
} else {
arg = coerceFromValue(level,code.argument,arg,environment);
body = "new Automaton.Term(K_" + code.name + ",r"
+ arg + ")";
}
}
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.Variable code, Environment environment, SpecFile file) {
Integer operand = environment.get(code.var);
if(operand != null) {
return environment.get(code.var);
} else {
Type type = code
.attribute(Attribute.Type.class).type;
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + code.var + ";");
return target;
}
}
public int translate(int level, Expr.Substitute code, Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
// first, translate all subexpressions and make sure they are
// references.
int src = translate(level, code.src, environment, file);
src = coerceFromValue(level,code.src,src,environment);
int original = translate(level, code.original, environment, file);
original = coerceFromValue(level,code.original,original,environment);
int replacement = translate(level, code.replacement, environment, file);
replacement = coerceFromValue(level,code.replacement,replacement,environment);
// second, put in place the substitution
String body = "automaton.substitute(r" + src + ", r" + original + ", r" + replacement + ")";
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.TermAccess code, Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
// first translate src expression, and coerce to a value
int src = translate(level, code.src, environment, file);
src = coerceFromRef(level, code.src, src, environment);
String body = "r" + src + ".contents";
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.Comprehension expr, Environment environment, SpecFile file) {
Type type = expr.attribute(Attribute.Type.class).type;
int target = environment.allocate(type);
// first, translate all source expressions
int[] sources = new int[expr.sources.size()];
for(int i=0;i!=sources.length;++i) {
Pair<Expr.Variable,Expr> p = expr.sources.get(i);
int operand = translate(level,p.second(),environment,file);
operand = coerceFromRef(level,p.second(),operand,environment);
sources[i] = operand;
}
// TODO: initialise result set
myOut(level, "Automaton.List t" + target + " = new Automaton.List();");
int startLevel = level;
// initialise result register if needed
switch(expr.cop) {
case NONE:
myOut(level,type2JavaType(type) + " r" + target + " = true;");
myOut(level,"outer:");
break;
case SOME:
myOut(level,type2JavaType(type) + " r" + target + " = false;");
myOut(level,"outer:");
break;
}
// second, generate all the for loops
for (int i = 0; i != sources.length; ++i) {
Pair<Expr.Variable, Expr> p = expr.sources.get(i);
Expr.Variable variable = p.first();
Expr source = p.second();
Type.Collection sourceType = (Type.Collection) source
.attribute(Attribute.Type.class).type;
Type elementType = variable.attribute(Attribute.Type.class).type;
int index = environment.allocate(elementType, variable.var);
myOut(level++, "for(int i" + index + "=0;i" + index + "<r"
+ sources[i] + ".size();i" + index + "++) {");
String rhs = "r"+ sources[i] + ".get(i" + index + ")";
// FIXME: need a more general test for a reference type
if(!(elementType instanceof Type.Ref)) {
rhs = "automaton.get(" + rhs + ");";
}
myOut(level, type2JavaType(elementType) + " r" + index + " = (" + type2JavaType(elementType) + ") " + rhs + ";");
}
if(expr.condition != null) {
int condition = translate(level,expr.condition,environment,file);
myOut(level++,"if(r" + condition + ") {");
}
switch(expr.cop) {
case SETCOMP:
case BAGCOMP:
case LISTCOMP:
int result = translate(level,expr.value,environment,file);
result = coerceFromValue(level,expr.value,result,environment);
myOut(level,"t" + target + ".add(r" + result + ");");
break;
case NONE:
myOut(level,"r" + target + " = false;");
myOut(level,"break outer;");
break;
case SOME:
myOut(level,"r" + target + " = true;");
myOut(level,"break outer;");
break;
}
// finally, terminate all the for loops
while(level > startLevel) {
myOut(--level,"}");
}
switch(expr.cop) {
case SETCOMP:
myOut(level, type2JavaType(type) + " r" + target
+ " = new Automaton.Set(t" + target + ".toArray());");
break;
case BAGCOMP:
myOut(level, type2JavaType(type) + " r" + target
+ " = new Automaton.Bag(t" + target + ".toArray());");
break;
case LISTCOMP:
myOut(level, type2JavaType(type) + " r" + target
+ " = t" + target + ";");
break;
}
return target;
}
protected void writeMainMethod() {
myOut();
myOut(1,
"
myOut(1, "// Main Method");
myOut(1,
"
myOut();
myOut(1, "public static void main(String[] args) throws IOException {");
myOut(2, "try {");
myOut(3,
"PrettyAutomataReader reader = new PrettyAutomataReader(System.in,SCHEMA);");
myOut(3,
"PrettyAutomataWriter writer = new PrettyAutomataWriter(System.out,SCHEMA);");
myOut(3, "Automaton automaton = reader.read();");
myOut(3, "System.out.print(\"PARSED: \");");
myOut(3, "print(automaton);");
myOut(3, "new SimpleRewriter(inferences,reductions).apply(automaton);");
myOut(3, "System.out.print(\"REWROTE: \");");
myOut(3, "print(automaton);");
//myOut(3, "System.out.println(\"(Reductions=\" + numReductions + \", Inferences=\" + numInferences + \", Misinferences=\" + numMisinferences + \", steps = \" + numSteps + \")\");");
myOut(2, "} catch(PrettyAutomataReader.SyntaxError ex) {");
myOut(3, "System.err.println(ex.getMessage());");
myOut(2, "}");
myOut(1, "}");
myOut(1,"");
myOut(1,"static void print(Automaton automaton) {");
myOut(2,"try {");
myOut(3,
"PrettyAutomataWriter writer = new PrettyAutomataWriter(System.out,SCHEMA);");
myOut(3, "writer.write(automaton);");
myOut(3, "writer.flush();");
myOut(3, "System.out.println();");
myOut(2,"} catch(IOException e) { System.err.println(\"I/O error printing automaton\"); }");
myOut(1,"}");
}
public String comment(String code, String comment) {
int nspaces = 30 - code.length();
String r = "";
for(int i=0;i<nspaces;++i) {
r += " ";
}
return code + r + " // " + comment;
}
/**
* Convert a Wyrl type into its equivalent Java type.
*
* @param type
* @return
*/
public String type2JavaType(Type type) {
return type2JavaType(type,true);
}
/**
* Convert a Wyrl type into its equivalent Java type. The user specifies
* whether primitive types are allowed or not. If not then, for example,
* <code>Type.Int</code> becomes <code>int</code>; otherwise, it becomes
* <code>Integer</code>.
*
* @param type
* @return
*/
public String type2JavaType(Type type, boolean primitives) {
if (type instanceof Type.Any) {
return "Object";
} else if (type instanceof Type.Int) {
return "Automaton.Int";
} else if (type instanceof Type.Real) {
return "Automaton.Real";
} else if (type instanceof Type.Bool) {
return "boolean";
} else if (type instanceof Type.Strung) {
return "Automaton.Strung";
} else if (type instanceof Type.Term) {
return "Automaton.Term";
} else if (type instanceof Type.Ref) {
if(primitives) {
return "int";
} else {
return "Integer";
}
} else if (type instanceof Type.Nominal) {
Type.Nominal nom = (Type.Nominal) type;
return type2JavaType(nom.element(), primitives);
} else if (type instanceof Type.Or) {
return "Object";
} else if (type instanceof Type.List) {
return "Automaton.List";
} else if (type instanceof Type.Bag) {
return "Automaton.Bag";
} else if (type instanceof Type.Set) {
return "Automaton.Set";
}
throw new RuntimeException("unknown type encountered: " + type);
}
public int coerceFromValue(int level, Expr expr, int register, Environment environment) {
Type type = expr.attribute(Attribute.Type.class).type;
if(type instanceof Type.Ref) {
return register;
} else {
Type.Ref refType = Type.T_REF(type);
int result = environment.allocate(refType);
String src = "r" + register;
if(refType.element() instanceof Type.Bool) {
// special thing needed for bools
src = src + " ? Automaton.TRUE : Automaton.FALSE";
}
myOut(level, type2JavaType(refType) + " r" + result + " = automaton.add(" + src + ");");
return result;
}
}
public int coerceFromRef(int level, SyntacticElement elem, int register,
Environment environment) {
Type type = elem.attribute(Attribute.Type.class).type;
if (type instanceof Type.Ref) {
Type.Ref refType = (Type.Ref) type;
Type element = refType.element();
int result = environment.allocate(element);
String cast = type2JavaType(element);
String body = "automaton.get(r" + register + ")";
// special case needed for booleans
if(element instanceof Type.Bool) {
body = "((Automaton.Bool)" + body + ").value";
} else {
body = "(" + cast + ") " + body;
}
myOut(level, cast + " r" + result + " = " + body + ";");
return result;
} else {
return register;
}
}
protected void myOut() {
myOut(0, "");
}
protected void myOut(int level) {
myOut(level, "");
}
protected void myOut(String line) {
myOut(0, line);
}
protected void myOut(int level, String line) {
for (int i = 0; i < level; ++i) {
out.print("\t");
}
out.println(line);
}
protected void indent(int level) {
for (int i = 0; i < level; ++i) {
out.print("\t");
}
}
private HashMap<Type,Integer> registeredTypes = new HashMap<Type,Integer>();
private ArrayList<Type> typeRegister = new ArrayList<Type>();
private int register(Type t) {
t.automaton().canonicalise();
//Types.reduce(t.automaton());
Integer i = registeredTypes.get(t);
if(i == null) {
int r = typeRegister.size();
registeredTypes.put(t, r);
typeRegister.add(t);
return r;
} else {
return i;
}
}
private static final class Environment {
private final HashMap<String, Integer> var2idx = new HashMap<String, Integer>();
private final ArrayList<Pair<Type,String>> idx2var = new ArrayList<Pair<Type,String>>();
public int size() {
return idx2var.size();
}
public int allocate(Type t) {
int idx = idx2var.size();
idx2var.add(new Pair<Type,String>(t,null));
return idx;
}
public int allocate(Type t, String v) {
int idx = idx2var.size();
idx2var.add(new Pair<Type,String>(t,v));
var2idx.put(v, idx);
return idx;
}
public Integer get(String v) {
return var2idx.get(v);
}
public Pair<Type,String> get(int idx) {
return idx2var.get(idx);
}
public void put(int idx, String v) {
var2idx.put(v, idx);
idx2var.set(idx,
new Pair<Type, String>(idx2var.get(idx).first(), v));
}
public String toString() {
return var2idx.toString();
}
}
}
|
package org.msf.records.sync;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SyncResult;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.RequestFuture;
import org.msf.records.App;
import org.msf.records.net.OpenMrsChartServer;
import org.msf.records.net.model.ChartStructure;
import org.msf.records.net.model.ConceptList;
import org.msf.records.net.model.Location;
import org.msf.records.net.model.Patient;
import org.msf.records.net.model.PatientChart;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static org.msf.records.sync.ChartProviderContract.ChartColumns;
import static org.msf.records.sync.PatientProviderContract.PatientColumns;
/**
* Global sync adapter for syncing all client side database caches.
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = SyncAdapter.class.getSimpleName();
public static final String KNOWN_CHART_UUID = "ea43f213-66fb-4af6-8a49-70fd6b9ce5d4";
/**
* If this key is present with boolean value true then sync patients.
*/
public static String SYNC_PATIENTS = "SYNC_PATIENTS";
/**
* If this key is present with boolean value true then sync concepts.
*/
public static String SYNC_CONCEPTS = "SYNC_CONCEPTS";
/**
* If this key is present with boolean value true then sync the chart structure.
*/
public static String SYNC_CHART_STRUCTURE = "SYNC_CHART_STRUCTURE";
/**
* If this key is present with boolean value true then sync the observations.
*/
public static String SYNC_OBSERVATIONS = "SYNC_OBSERVATIONS";
/**
* If this key is present with boolean value true then sync locations.
*/
public static String SYNC_LOCATIONS = "SYNC_LOCATIONS";
/**
* Content resolver, for performing database operations.
*/
private final ContentResolver mContentResolver;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContentResolver = context.getContentResolver();
}
public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
mContentResolver = context.getContentResolver();
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
// Fire a broadcast indicating that sync has completed.
Intent syncStartedIntent =
new Intent(getContext(), SyncManager.SyncStatusBroadcastReceiver.class);
syncStartedIntent.putExtra(SyncManager.SYNC_STATUS, SyncManager.STARTED);
getContext().sendBroadcast(syncStartedIntent);
Intent syncFailedIntent =
new Intent(getContext(), SyncManager.SyncStatusBroadcastReceiver.class);
syncFailedIntent.putExtra(SyncManager.SYNC_STATUS, SyncManager.FAILED);
Log.i(TAG, "Beginning network synchronization");
try {
boolean specific = false;
if (extras.getBoolean(SYNC_PATIENTS)) {
specific = true;
// default behaviour
updatePatientData(syncResult);
}
if (extras.getBoolean(SYNC_CONCEPTS)) {
specific = true;
updateConcepts(provider, syncResult);
}
if (extras.getBoolean(SYNC_CHART_STRUCTURE)) {
specific = true;
updateChartStructure(provider, syncResult);
}
if (extras.getBoolean(SYNC_OBSERVATIONS)) {
specific = true;
updateObservations(provider, syncResult);
}
if (extras.getBoolean(SYNC_LOCATIONS)) {
specific = true;
updateLocations(provider, syncResult);
}
if (!specific) {
// If nothing is specified explicitly (such as from the android system menu),
// do everything.
updatePatientData(syncResult);
updateConcepts(provider, syncResult);
updateChartStructure(provider, syncResult);
updateObservations(provider, syncResult);
updateLocations(provider, syncResult);
}
} catch (RemoteException e) {
Log.e(TAG, "Error in RPC", e);
syncResult.stats.numIoExceptions++;
getContext().sendBroadcast(syncFailedIntent);
return;
} catch (OperationApplicationException e) {
Log.e(TAG, "Error updating database", e);
syncResult.databaseError = true;
getContext().sendBroadcast(syncFailedIntent);
return;
} catch (InterruptedException e){
Log.e(TAG, "Error interruption", e);
syncResult.stats.numIoExceptions++;
getContext().sendBroadcast(syncFailedIntent);
return;
} catch (ExecutionException e){
Log.e(TAG, "Error failed to execute", e);
syncResult.stats.numIoExceptions++;
getContext().sendBroadcast(syncFailedIntent);
return;
} catch (Exception e){
Log.e(TAG, "Error reading from network", e);
syncResult.stats.numIoExceptions++;
getContext().sendBroadcast(syncFailedIntent);
return;
}
Log.i(TAG, "Network synchronization complete");
// Fire a broadcast indicating that sync has completed.
Intent syncCompletedIntent =
new Intent(getContext(), SyncManager.SyncStatusBroadcastReceiver.class);
syncCompletedIntent.putExtra(SyncManager.SYNC_STATUS, SyncManager.COMPLETED);
getContext().sendBroadcast(syncCompletedIntent);
}
private void updatePatientData(SyncResult syncResult) throws InterruptedException, ExecutionException, RemoteException, OperationApplicationException {
final ContentResolver contentResolver = getContext().getContentResolver();
final String[] projection = PatientProjection.getProjectionColumns();
Log.d(TAG, "Before network call");
RequestFuture<List<Patient>> future = RequestFuture.newFuture();
App.getServer().listPatients("", "", "", future, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
}
}, TAG);
//No need for callbacks as the {@AbstractThreadedSyncAdapter} code is executed in a background thread
List<Patient> patients = future.get();
Log.d(TAG, "After network call");
ArrayList<ContentProviderOperation> batch = new ArrayList<>();
HashMap<String, Patient> patientsMap = new HashMap<>();
for (Patient p : patients) {
patientsMap.put(p.id, p);
}
// Get list of all items
Log.i(TAG, "Fetching local entries for merge");
Uri uri = PatientProviderContract.CONTENT_URI; // Get all entries
Cursor c = contentResolver.query(uri, projection, null, null, null);
assert c != null;
Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution...");
Log.i(TAG, "Found " + patients.size() + " external entries. Computing merge solution...");
String id;
String givenName, familyName, uuid, status, locationZone, locationTent, locationUuid;
String gender;
int ageMonths = -1, ageYears = -1;
long admissionTimestamp;
//iterate through the list of patients
while(c.moveToNext()){
syncResult.stats.numEntries++;
id = c.getString(PatientProjection.COLUMN_ID);
givenName = c.getString(PatientProjection.COLUMN_GIVEN_NAME);
familyName = c.getString(PatientProjection.COLUMN_FAMILY_NAME);
uuid = c.getString(PatientProjection.COLUMN_UUID);
status = c.getString(PatientProjection.COLUMN_STATUS);
admissionTimestamp = c.getLong(PatientProjection.COLUMN_ADMISSION_TIMESTAMP);
locationZone = c.getString(PatientProjection.COLUMN_LOCATION_ZONE);
locationTent = c.getString(PatientProjection.COLUMN_LOCATION_TENT);
locationUuid = c.getString(PatientProjection.COLUMN_LOCATION_UUID);
if (!c.isNull(PatientProjection.COLUMN_AGE_MONTHS)) {
ageMonths = c.getInt(PatientProjection.COLUMN_AGE_MONTHS);
}
if (!c.isNull(PatientProjection.COLUMN_AGE_YEARS)) {
ageYears = c.getInt(PatientProjection.COLUMN_AGE_YEARS);
}
gender = c.getString(PatientProjection.COLUMN_GENDER);
Patient patient = patientsMap.get(id);
if (patient != null) {
// Entry exists. Remove from entry map to prevent insert later.
patientsMap.remove(id);
// Check to see if the entry needs to be updated
Uri existingUri = PatientProviderContract.CONTENT_URI.buildUpon().appendPath(String.valueOf(id)).build();
//check if it needs updating
if ((patient.given_name != null && !patient.given_name.equals(givenName)) ||
(patient.family_name != null && !patient.family_name.equals(familyName)) ||
(patient.uuid != null && !patient.uuid.equals(uuid)) ||
(patient.status != null && !patient.status.equals(status)) ||
(patient.admission_timestamp != null &&
!patient.admission_timestamp.equals(admissionTimestamp)) ||
(patient.assigned_location != null &&
patient.assigned_location.uuid != null &&
!patient.assigned_location.uuid.equals(locationUuid)) ||
(patient.age.months != ageMonths) ||
(patient.age.years != ageYears) ||
(patient.gender != null && !patient.gender.equals(gender)) ||
(patient.id != null && !patient.id.equals(id))) {
// Update existing record
Log.i(TAG, "Scheduling update: " + existingUri);
batch.add(ContentProviderOperation.newUpdate(existingUri)
.withValue(PatientColumns.COLUMN_NAME_GIVEN_NAME, givenName)
.withValue(PatientColumns.COLUMN_NAME_FAMILY_NAME, familyName)
.withValue(PatientColumns.COLUMN_NAME_UUID, uuid)
.withValue(PatientColumns.COLUMN_NAME_STATUS, status)
.withValue(PatientColumns.COLUMN_NAME_ADMISSION_TIMESTAMP, admissionTimestamp)
.withValue(PatientColumns.COLUMN_NAME_LOCATION_UUID, locationUuid)
.withValue(PatientColumns.COLUMN_NAME_AGE_MONTHS, ageMonths)
.withValue(PatientColumns.COLUMN_NAME_AGE_YEARS, ageYears)
.withValue(PatientColumns.COLUMN_NAME_GENDER, gender)
.withValue(PatientColumns._ID, id)
.build());
syncResult.stats.numUpdates++;
} else {
Log.i(TAG, "No action required for " + existingUri);
}
} else {
// Entry doesn't exist. Remove it from the database.
Uri deleteUri = PatientProviderContract.CONTENT_URI.buildUpon()
.appendPath(id).build();
Log.i(TAG, "Scheduling delete: " + deleteUri);
batch.add(ContentProviderOperation.newDelete(deleteUri).build());
syncResult.stats.numDeletes++;
}
}
c.close();
for (Patient e : patientsMap.values()) {
Log.i(TAG, "Scheduling insert: entry_id=" + e.id);
ContentProviderOperation.Builder builder =
ContentProviderOperation.newInsert(PatientProviderContract.CONTENT_URI)
.withValue(PatientColumns._ID, e.id)
.withValue(PatientColumns.COLUMN_NAME_GIVEN_NAME, e.given_name)
.withValue(PatientColumns.COLUMN_NAME_FAMILY_NAME, e.family_name)
.withValue(PatientColumns.COLUMN_NAME_UUID, e.uuid)
.withValue(PatientColumns.COLUMN_NAME_STATUS, e.status)
.withValue(PatientColumns.COLUMN_NAME_ADMISSION_TIMESTAMP, e.admission_timestamp)
.withValue(PatientColumns.COLUMN_NAME_AGE_MONTHS, e.age.months)
.withValue(PatientColumns.COLUMN_NAME_AGE_YEARS, e.age.years)
.withValue(PatientColumns.COLUMN_NAME_GENDER, e.gender);
if (e.assigned_location != null) {
builder
.withValue(PatientColumns.COLUMN_NAME_LOCATION_UUID, e.assigned_location.uuid);
}
batch.add(builder.build());
syncResult.stats.numInserts++;
}
Log.i(TAG, "Merge solution ready. Applying batch update");
mContentResolver.applyBatch(PatientProviderContract.CONTENT_AUTHORITY, batch);
mContentResolver.notifyChange(PatientProviderContract.CONTENT_URI, null, false);
mContentResolver.notifyChange(PatientProviderContract.CONTENT_URI_PATIENT_ZONES, null, false);
mContentResolver.notifyChange(PatientProviderContract.CONTENT_URI_PATIENT_TENTS, null, false);
//TODO(giljulio) update the server as well as the client
}
private void updateConcepts(final ContentProviderClient provider, SyncResult syncResult)
throws InterruptedException, ExecutionException, RemoteException,
OperationApplicationException {
OpenMrsChartServer chartServer = new OpenMrsChartServer(App.getConnectionDetails());
RequestFuture<ConceptList> future = RequestFuture.newFuture();
chartServer.getConcepts(future, future); // errors handled by caller
ConceptList conceptList = future.get();
provider.applyBatch(ChartRpcToDb.conceptRpcToDb(conceptList, syncResult));
}
private void updateLocations(final ContentProviderClient provider, SyncResult syncResult)
throws InterruptedException, ExecutionException, RemoteException,
OperationApplicationException {
final ContentResolver contentResolver = getContext().getContentResolver();
final String[] projection = LocationProjection.getLocationProjection();
final String[] namesProjection = LocationProjection.getLocationNamesProjection();
Log.d(TAG, "Before network call");
RequestFuture<List<Location>> future = RequestFuture.newFuture();
App.getServer().listLocations(future, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
}
}, TAG);
//No need for callbacks as the {@AbstractThreadedSyncAdapter} code is executed in a background thread
List<Location> locations = future.get();
Log.d(TAG, "After network call");
ArrayList<ContentProviderOperation> batch = new ArrayList<>();
HashMap<String, Location> locationsMap = new HashMap<>();
for (Location location : locations) {
locationsMap.put(location.uuid, location);
}
// Get list of all items
Log.i(TAG, "Fetching local entries for merge");
Uri uri = LocationProviderContract.LOCATIONS_CONTENT_URI; // Location tree
Uri namesUri = LocationProviderContract.LOCATION_NAMES_CONTENT_URI; // Location names
Cursor c = contentResolver.query(uri, projection, null, null, null);
assert c != null;
Cursor namesCur = contentResolver.query(namesUri, namesProjection, null, null, null);
assert namesCur != null;
Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution...");
Log.i(TAG, "Found " + locations.size() + " external entries. Computing merge solution...");
String id, parentId;
// Build map of location names from the database.
HashMap<String, HashMap<String, String>> dbLocationNames =
new HashMap<String, HashMap<String, String>>();
while (namesCur.moveToNext()) {
String locationId = namesCur.getString(
LocationProjection.LOCATION_NAME_LOCATION_UUID_COLUMN);
String locale = namesCur.getString(LocationProjection.LOCATION_NAME_LOCALE_COLUMN);
String name = namesCur.getString(LocationProjection.LOCATION_NAME_NAME_COLUMN);
if (locationId == null || locale == null || name == null) {
continue;
}
if (!dbLocationNames.containsKey(locationId)) {
dbLocationNames.put(locationId, new HashMap<String, String>());
}
dbLocationNames.get(locationId).put(locale, name);
}
namesCur.close();
// Iterate through the list of locations
while(c.moveToNext()){
syncResult.stats.numEntries++;
id = c.getString(LocationProjection.LOCATION_LOCATION_UUID_COLUMN);
parentId = c.getString(LocationProjection.LOCATION_PARENT_UUID_COLUMN);
Location location = locationsMap.get(id);
if (location != null) {
// Entry exists. Remove from entry map to prevent insert later.
locationsMap.remove(id);
// Grab the names stored in the database for this location.
HashMap<String, String> locationNames = dbLocationNames.get(id);
// Check to see if the entry needs to be updated
Uri existingUri = uri.buildUpon().appendPath(String.valueOf(id)).build();
if (location.parent_uuid != null && !location.parent_uuid.equals(parentId)) {
// Update existing record
Log.i(TAG, "Scheduling update: " + existingUri);
batch.add(ContentProviderOperation.newUpdate(existingUri)
.withValue(LocationProviderContract.LocationColumns.LOCATION_UUID, id)
.withValue(LocationProviderContract.LocationColumns.PARENT_UUID, parentId)
.build());
syncResult.stats.numUpdates++;
} else {
Log.i(TAG, "No action required for " + existingUri);
}
if (location.names != null &&
(locationNames == null || !location.names.equals(locationNames))) {
Uri existingNamesUri = namesUri.buildUpon().appendPath(
String.valueOf(id)).build();
// Update location names by deleting any existing location names and
// repopulating.
Log.i(TAG, "Scheduling location names update: " + existingNamesUri);
batch.add(ContentProviderOperation.newDelete(existingNamesUri).build());
syncResult.stats.numDeletes++;
for (String locale : location.names.keySet()) {
batch.add(ContentProviderOperation.newInsert(existingNamesUri)
.withValue(
LocationProviderContract.LocationColumns.LOCATION_UUID, id)
.withValue(
LocationProviderContract.LocationColumns.LOCALE, locale)
.withValue(
LocationProviderContract.LocationColumns.NAME,
location.names.get(locale))
.build());
syncResult.stats.numInserts++;
}
}
} else {
// Entry doesn't exist. Remove it from the database.
Uri deleteUri = uri.buildUpon().appendPath(id).build();
Uri namesDeleteUri = namesUri.buildUpon().appendPath(id).build();
Log.i(TAG, "Scheduling delete: " + deleteUri);
batch.add(ContentProviderOperation.newDelete(deleteUri).build());
syncResult.stats.numDeletes++;
Log.i(TAG, "Scheduling delete: " + namesDeleteUri);
batch.add(ContentProviderOperation.newDelete(namesDeleteUri).build());
syncResult.stats.numDeletes++;
}
}
c.close();
for (Location e : locationsMap.values()) {
Log.i(TAG, "Scheduling insert: entry_id=" + e.uuid);
batch.add(ContentProviderOperation.newInsert(LocationProviderContract.LOCATIONS_CONTENT_URI)
.withValue(LocationProviderContract.LocationColumns.LOCATION_UUID, e.uuid)
.withValue(LocationProviderContract.LocationColumns.PARENT_UUID, e.parent_uuid)
.build());
syncResult.stats.numInserts++;
for (String locale : e.names.keySet()) {
Uri existingNamesUri = namesUri.buildUpon().appendPath(
String.valueOf(e.uuid)).build();
batch.add(ContentProviderOperation.newInsert(existingNamesUri)
.withValue(
LocationProviderContract.LocationColumns.LOCATION_UUID, e.uuid)
.withValue(
LocationProviderContract.LocationColumns.LOCALE, locale)
.withValue(
LocationProviderContract.LocationColumns.NAME,
e.names.get(locale))
.build());
syncResult.stats.numInserts++;
}
}
Log.i(TAG, "Merge solution ready. Applying batch update");
mContentResolver.applyBatch(PatientProviderContract.CONTENT_AUTHORITY, batch);
mContentResolver.notifyChange(LocationProviderContract.LOCATIONS_CONTENT_URI, null, false);
mContentResolver.notifyChange(
LocationProviderContract.LOCATION_NAMES_CONTENT_URI, null, false);
// TODO(akalachman): Update the server as well as the client
}
private void updateChartStructure(final ContentProviderClient provider, SyncResult syncResult)
throws InterruptedException, ExecutionException, RemoteException,
OperationApplicationException {
OpenMrsChartServer chartServer = new OpenMrsChartServer(App.getConnectionDetails());
RequestFuture<ChartStructure> future = RequestFuture.newFuture();
chartServer.getChartStructure(KNOWN_CHART_UUID, future, future); // errors handled by caller
ChartStructure conceptList = future.get();
// When we do a chart update, delete everything first.
provider.delete(ChartProviderContract.CHART_CONTENT_URI, null, null);
syncResult.stats.numDeletes++;
provider.applyBatch(ChartRpcToDb.chartStructureRpcToDb(conceptList, syncResult));
}
private void updateObservations(final ContentProviderClient provider, SyncResult syncResult)
throws InterruptedException, ExecutionException, RemoteException,
OperationApplicationException {
// Get call patients from the cache.
Uri uri = PatientProviderContract.CONTENT_URI; // Get all entries
Cursor c = provider.query(
uri, new String[]{PatientColumns.COLUMN_NAME_UUID}, null, null, null);
if (c.getCount() < 1) {
return;
}
OpenMrsChartServer chartServer = new OpenMrsChartServer(App.getConnectionDetails());
// Get the charts asynchronously using volley.
ArrayList<RequestFuture<PatientChart>> futures = new ArrayList<>();
while (c.moveToNext()) {
RequestFuture<PatientChart> future = RequestFuture.newFuture();
chartServer.getChart(c.getString(c.getColumnIndex(PatientColumns.COLUMN_NAME_UUID)),
future, future);
futures.add(future);
}
for (RequestFuture<PatientChart> future : futures) {
// As we are doing multiple request in parallel, deal with exceptions in the loop.
try {
PatientChart patientChart = future.get();
if (patientChart.uuid == null) {
Log.e(TAG, "null patient id in observation response");
continue;
}
// Delete all existing observations for the patient.
provider.delete(ChartProviderContract.OBSERVATIONS_CONTENT_URI,
ChartColumns.PATIENT_UUID + "=?",
new String[]{patientChart.uuid});
// Add the new observations
provider.applyBatch(ChartRpcToDb.observationsRpcToDb(patientChart, syncResult));
} catch (InterruptedException e) {
Log.e(TAG, "Error interruption: " + e.toString());
syncResult.stats.numIoExceptions++;
return;
} catch (ExecutionException e){
Log.e(TAG, "Error failed to execute: " + e.toString());
syncResult.stats.numIoExceptions++;
return;
} catch (Exception e){
Log.e(TAG, "Error reading from network: " + e.toString());
syncResult.stats.numIoExceptions++;
return;
}
}
}
}
|
package org.stepic.droid.util;
import android.os.Build;
import android.support.annotation.ColorInt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.stepic.droid.configuration.Config;
import org.stepic.droid.notifications.model.Notification;
import java.util.List;
import java.util.Locale;
import kotlin.collections.CollectionsKt;
import timber.log.Timber;
public class HtmlHelper {
/**
* Trims trailing whitespace. Removes any of these characters:
* 0009, HORIZONTAL TABULATION
* 000A, LINE FEED
* 000B, VERTICAL TABULATION
* 000C, FORM FEED
* 000D, CARRIAGE RETURN
* 001C, FILE SEPARATOR
* 001D, GROUP SEPARATOR
* 001E, RECORD SEPARATOR
* 001F, UNIT SEPARATOR
*
* @return "" if source is null, otherwise string with all trailing whitespace removed
*/
public static CharSequence trimTrailingWhitespace(CharSequence source) {
if (source == null)
return "";
int i = source.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(source.charAt(i))) {
}
return source.subSequence(0, i + 1);
}
public static boolean isForWebView(@NotNull String text) {
//FIXME REMOVE <img>??? and make ImageGetter with simple textview
//TODO: REGEXP IS SLOWER
return text.contains("wysiwyg-") ||
text.contains("<h") ||
text.contains("<img") ||
text.contains("<iframe") ||
text.contains("<audio") ||
hasLaTeX(text) ||
hasKotlinRunnableSample(text) ||
hasHighlightableCode(text);
}
public static boolean hasLaTeX(String textString) {
return textString.contains("$") || textString.contains("\\[") || textString.contains("math-tex");
}
private static boolean hasKotlinRunnableSample(String text) {
return text.contains("kotlin-runnable");
}
private static boolean hasHighlightableCode(String text) {
return text.contains("<code");
}
/**
* get meta value
*
* @param htmlText with meta tags
* @param metaKey meta key of 'name' attribute in meta tag
* @return value of 'content' attribute in tag meta with 'name' == metaKey
*/
@Nullable
public static String getValueOfMetaOrNull(String htmlText, String metaKey) {
Document document = Jsoup.parse(htmlText);
Elements elements = document.select("meta");
try {
return elements.attr("name", metaKey).last().attr("content"); //WTF? first is csrf param, but jsoup can't handle
} catch (Exception ex) {
return "";
}
}
@Nullable
public static Long parseCourseIdFromNotification(@NotNull Notification notification) {
String htmlRaw = notification.getHtmlText();
if (htmlRaw == null) return null;
return parseCourseIdFromNotification(htmlRaw);
}
@Nullable
public static Long parseIdFromSlug(String slug) {
Long id = null;
try {
id = Long.parseLong(slug);
} catch (NumberFormatException ignored) {
//often it is not number then it is "Some-Name-idNum" or just "-idNum"
}
if (id != null) {
//if, for example, -432 -> 432
return Math.abs(id);
}
int indexOfLastDash = slug.lastIndexOf("-");
if (indexOfLastDash < 0)
return null;
try {
String number = slug.substring(indexOfLastDash + 1, slug.length());
id = Long.parseLong(number);
} catch (NumberFormatException | IndexOutOfBoundsException ignored) {
}
return id;
}
private final static String syllabusModulePrefix = "syllabus?module=";
public static Integer parseModulePositionFromNotification(String htmlRaw) {
int indexOfStart = htmlRaw.indexOf(syllabusModulePrefix);
if (indexOfStart < 0) return null;
String begin = htmlRaw.substring(indexOfStart + syllabusModulePrefix.length());
int end = begin.indexOf("\"");
String substring = begin.substring(0, end);
try {
return Integer.parseInt(substring);
} catch (Exception exception) {
return null;
}
}
private static Long parseCourseIdFromNotification(String htmlRaw) {
int start = htmlRaw.indexOf('<');
int end = htmlRaw.indexOf('>');
if (start == -1 || end == -1) return null;
String substring = htmlRaw.substring(start, end);
String[] resultOfSplit = substring.split("-");
if (resultOfSplit.length > 0) {
String numb = resultOfSplit[resultOfSplit.length - 1];
StringBuilder n = new StringBuilder();
for (int i = 0; i < numb.length(); i++) {
if (Character.isDigit(numb.charAt(i))) {
n.append(numb.charAt(i));
}
}
if (n.length() > 0)
return Long.parseLong(n.toString());
return null;
}
return null;
}
private static String getStyle(@Nullable String fontPath, @ColorInt int textColorHighlight) {
final String fontStyle;
if (fontPath == null) {
fontStyle = DefaultFontStyle; // US locale to format floats with '.' instead of ','
} else {
fontStyle = String.format(Locale.US, CustomFontStyle, fontPath);
}
final String selectionColorStyle = String.format(Locale.getDefault(), SelectionColorStyle, 0xFFFFFF & textColorHighlight);
return fontStyle + selectionColorStyle;
}
private static String buildPage(CharSequence body, List<String> additionalScripts, String fontPath, @ColorInt int textColorHighlight, int widthPx, String baseUrl) {
if (hasKotlinRunnableSample(body.toString())) {
additionalScripts.add(KotlinRunnableSamplesScript);
}
if (hasHighlightableCode(body.toString())) {
additionalScripts.add(HighlightScript);
}
String scripts = CollectionsKt.joinToString(additionalScripts, "", "", "", -1, "", null);
String preBody = String.format(Locale.getDefault(), PRE_BODY, scripts, getStyle(fontPath, textColorHighlight), widthPx, baseUrl);
String modifiedBody = removeImageFixedHeightAttribute(body.toString());
return preBody + modifiedBody + POST_BODY;
}
public static String buildMathPage(CharSequence body, @ColorInt int textColorHighlight, int widthPx, String baseUrl) {
return buildPage(body, CollectionsKt.arrayListOf(MathJaxScript), null, textColorHighlight, widthPx, baseUrl);
}
public static String buildPageWithAdjustingTextAndImage(CharSequence body, @ColorInt int textColorHighlight, int widthPx, String baseUrl) {
return buildPage(body, CollectionsKt.mutableListOf(), null, textColorHighlight, widthPx, baseUrl);
}
public static String buildPageWithCustomFont(CharSequence body, String fontPath, @ColorInt int textColorHighlight, int widthPx, String baseUrl) {
return buildPage(body, CollectionsKt.mutableListOf(), fontPath, textColorHighlight, widthPx, baseUrl);
}
public static final String HORIZONTAL_SCROLL_LISTENER = "scrollListener";
private static final String HORIZONTAL_SCROLL_STYLE;
// this block is needed to force render of WebView
private static final String MIN_RENDERED_BLOCK =
"<div style=\"height: 1px; overflow: hidden; width: 1px; background-color: rgba(0,0,0,0.001); pointer-events: none; user-select: none; -webkit-user-select: none;\"></div>";
static {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
HORIZONTAL_SCROLL_STYLE =
"<style>\n" +
"body > * {\n" +
" max-width: 100%%;\n" +
" overflow-x: scroll;\n" +
" vertical-align: middle;\n" +
"}\n" +
"body > .no-scroll {\n" +
" overflow: visible !important;\n" +
"}" +
"</style>\n";
} else {
HORIZONTAL_SCROLL_STYLE = "";
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
POST_BODY =
MIN_RENDERED_BLOCK +
"</body>\n" +
"</html>";
} else {
POST_BODY =
"</body>\n" +
"</html>";
}
}
private static final String KotlinRunnableSamplesScript =
"<script src=\"https://unpkg.com/kotlin-playground@1\"></script>" +
"<script>\n" +
"document.addEventListener('DOMContentLoaded', function() {\n" +
" KotlinPlayground('kotlin-runnable', { \n" +
" callback: function(targetNode, mountNode) {\n" +
" mountNode.classList.add('no-scroll');\n" + // disable overflow for pg divs in order to disable overflow and show expand button
" }\n" +
" });\n" +
"});\n" +
"</script>";
private static final String KOTLIN_PLAYGROUND_SCROLL_RULE =
"elem.className !== 'CodeMirror-scroll' && elem.className !== 'code-output'";
private static final String DEFAULT_SCROLL_RULE =
"elem.parentElement.tagName !== 'BODY' && elem.parentElement.tagName !== 'HTML'";
private static final String HORIZONTAL_SCROLL_SCRIPT =
"<script type=\"text/javascript\">\n" +
"function measureScroll(x, y) {" +
"var elem = document.elementFromPoint(x, y);" +
"while(" + DEFAULT_SCROLL_RULE + " && " + KOTLIN_PLAYGROUND_SCROLL_RULE + ") {" +
"elem = elem.parentElement;" +
"}" +
HORIZONTAL_SCROLL_LISTENER + ".onScroll(elem.offsetWidth, elem.scrollWidth, elem.scrollLeft);" +
"}" +
"</script>\n";
//string with 2 format args
private static final String PRE_BODY = "<html>\n" +
"<head>\n" +
"<title>Step</title>\n" +
"%s" +
"%s" +
"<meta name=\"viewport\" content=\"width=" +
"%d" +
", user-scalable=no" +
", target-densitydpi=medium-dpi" +
"\" />" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"wysiwyg.css\"/>" +
HORIZONTAL_SCROLL_SCRIPT +
HORIZONTAL_SCROLL_STYLE +
"<base href=\"%s\">" +
"</head>\n"
+ "<body style='margin:0;padding:0;'>";
private static final String SelectionColorStyle =
"<style>\n"
+ "::selection { background: #%06X; }\n"
+ "</style>";
private static final String DefaultFontStyle =
"<style>\n"
+ "\nhtml{-webkit-text-size-adjust: 100%%;}"
+ "\nbody{font-family:Arial, Helvetica, sans-serif; line-height:1.6em;}"
+ "\nh1{font-size: 22px; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nh2{font-size: 19px; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nh3{font-size: 16px; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nimg { max-width: 100%%; }"
+ "</style>\n";
private static final String CustomFontStyle =
"<style>\n" +
"@font-face {" +
" font-family: 'Roboto';\n" +
" src: url(\"%s\")\n" +
"}"
+ "\nhtml{-webkit-text-size-adjust: 100%%;}"
+ "\nbody{font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;}"
+ "\nh1{font-size: 22px; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nh2{font-size: 19px; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nh3{font-size: 16px; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nimg { max-width: 100%%; }"
+ "</style>\n";
private static final String POST_BODY;
private static final String MathJaxScript =
"<script type=\"text/x-mathjax-config\">\n" +
" MathJax.Hub.Config({" +
"showMathMenu: false, " +
"messageStyle: \"none\", " +
"TeX: {extensions: [ \"color.js\"]}, " +
"tex2jax: {preview: \"none\", inlineMath: [['$','$'], ['\\\\(','\\\\)']]}});\n" +
"displayMath: [ ['$$','$$'], ['\\[','\\]'] ]" +
"</script>\n" +
"<script type=\"text/javascript\"\n" +
" src=\"file:///android_asset/MathJax/MathJax.js?config=TeX-AMS_HTML\">\n" +
"</script>\n";
private static final String HighlightScript =
"<script type=\"text/javascript\"\n" +
" src=\"file:///android_asset/scripts/highlight.pack.js\">\n" +
"</script>\n" +
"<script>hljs.initHighlightingOnLoad();</script>\n";
private static final String imageFixedHeightAttribute = "(height=\"\\d+\")";
public static String getUserPath(Config config, int userId) {
return new StringBuilder()
.append(config.getBaseUrl())
.append(AppConstants.WEB_URI_SEPARATOR)
.append("users")
.append(AppConstants.WEB_URI_SEPARATOR)
.append(userId)
.append("/?from_mobile_app=true")
.toString();
}
@Nullable
public static String parseNLinkInText(@NotNull String htmlText, String baseUrl, int position) {
try {
Document document = Jsoup.parse(htmlText);
document.setBaseUri(baseUrl);
Elements elements = document.getElementsByTag("a");
Element our = elements.get(position);
String absolute = our.absUrl("href");
Timber.d(absolute);
return absolute;
} catch (Exception exception) {
return null;
}
}
private static String removeImageFixedHeightAttribute(String body) {
Document document = Jsoup.parse(body);
Elements imgElements = document.getElementsByTag("img");
for (Element element : imgElements) {
element.removeAttr("height");
}
return document.html();
}
}
|
package org.commcare.android.view;
import java.util.Hashtable;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.models.Entity;
import org.commcare.android.util.DetailCalloutListener;
import org.commcare.android.util.FileUtil;
import org.commcare.android.util.MediaUtil;
import org.commcare.dalvik.R;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.graph.GraphData;
import org.commcare.util.CommCareSession;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import org.odk.collect.android.views.media.AudioButton;
import org.odk.collect.android.views.media.AudioController;
import org.odk.collect.android.views.media.ViewId;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* @author ctsims
*
*/
public class EntityDetailView extends FrameLayout {
private TextView label;
private TextView data;
private TextView spacer;
private Button callout;
private View addressView;
private Button addressButton;
private TextView addressText;
private ImageView imageView;
private AspectRatioLayout graphLayout;
private Hashtable<Integer, Hashtable<Integer, View>> graphViewsCache; // index => { orientation => GraphView }
private Hashtable<Integer, Intent> graphIntentsCache; // index => intent
private ImageButton videoButton;
private AudioButton audioButton;
private View valuePane;
private View currentView;
private AudioController controller;
private LinearLayout detailRow;
private LinearLayout.LayoutParams origValue;
private LinearLayout.LayoutParams origLabel;
private LinearLayout.LayoutParams fill;
private static final String FORM_VIDEO = "video";
private static final String FORM_AUDIO = "audio";
private static final String FORM_PHONE = "phone";
private static final String FORM_ADDRESS = "address";
private static final String FORM_IMAGE = "image";
private static final String FORM_GRAPH = "graph";
private static final int TEXT = 0;
private static final int PHONE = 1;
private static final int ADDRESS = 2;
private static final int IMAGE = 3;
private static final int VIDEO = 4;
private static final int AUDIO = 5;
private static final int GRAPH = 6;
int current = TEXT;
DetailCalloutListener listener;
public EntityDetailView(Context context, CommCareSession session, Detail d, Entity e, int index,
AudioController controller, int detailNumber) {
super(context);
this.controller = controller;
detailRow = (LinearLayout)View.inflate(context, R.layout.component_entity_detail_item, null);
label = (TextView)detailRow.findViewById(R.id.detail_type_text);
spacer = (TextView)detailRow.findViewById(R.id.entity_detail_spacer);
data = (TextView)detailRow.findViewById(R.id.detail_value_text);
currentView = data;
valuePane = detailRow.findViewById(R.id.detail_value_pane);
videoButton = (ImageButton)detailRow.findViewById(R.id.detail_video_button);
ViewId uniqueId = new ViewId(detailNumber, index, true);
String audioText = e.getFieldString(index);
audioButton = new AudioButton(context, audioText, uniqueId, controller, false);
detailRow.addView(audioButton);
audioButton.setVisibility(View.GONE);
callout = (Button)detailRow.findViewById(R.id.detail_value_phone);
//TODO: Still useful?
//callout.setInputType(InputType.TYPE_CLASS_PHONE);
addressView = (View)detailRow.findViewById(R.id.detail_address_view);
addressText = (TextView)addressView.findViewById(R.id.detail_address_text);
addressButton = (Button)addressView.findViewById(R.id.detail_address_button);
imageView = (ImageView)detailRow.findViewById(R.id.detail_value_image);
graphLayout = (AspectRatioLayout)detailRow.findViewById(R.id.graph);
graphViewsCache = new Hashtable<Integer, Hashtable<Integer, View>>();
graphIntentsCache = new Hashtable<Integer, Intent>();
origLabel = (LinearLayout.LayoutParams)label.getLayoutParams();
origValue = (LinearLayout.LayoutParams)valuePane.getLayoutParams();
fill = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
this.addView(detailRow, FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
setParams(session, d, e, index, detailNumber);
}
public void setCallListener(final DetailCalloutListener listener) {
this.listener = listener;
}
public void setParams(CommCareSession session, Detail d, Entity e, int index, int detailNumber) {
String labelText = d.getFields()[index].getHeader().evaluate();
label.setText(labelText);
spacer.setText(labelText);
Object field = e.getField(index);
String textField = e.getFieldString(index);
boolean veryLong = false;
String form = d.getTemplateForms()[index];
if(FORM_PHONE.equals(form)) {
callout.setText(textField);
if(current != PHONE) {
callout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listener.callRequested(callout.getText().toString());
}
});
this.removeView(currentView);
updateCurrentView(PHONE, callout);
}
} else if(FORM_ADDRESS.equals(form)) {
final String address = textField;
addressText.setText(address);
if(current != ADDRESS) {
addressButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listener.addressRequested(MediaUtil.getGeoIntentURI(address));
}
});
updateCurrentView(ADDRESS, addressView);
}
} else if(FORM_IMAGE.equals(form)) {
String imageLocation = textField;
Bitmap b = MediaUtil.getScaledImageFromReference(this.getContext(),imageLocation);
if(b == null) {
imageView.setImageDrawable(null);
} else {
//Ok, so. We should figure out whether our image is large or small.
if(b.getWidth() > (getScreenWidth() / 2)) {
veryLong = true;
}
imageView.setPadding(10, 10, 10, 10);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(b);
imageView.setId(23422634);
}
updateCurrentView(IMAGE, imageView);
} else if (FORM_GRAPH.equals(form) && field instanceof GraphData) { // if graph parsing had errors, they'll be stored as a string
// Fetch graph view from cache, or create it
View graphView = null;
int orientation = getResources().getConfiguration().orientation;
if (graphViewsCache.get(index) != null) {
graphView = graphViewsCache.get(index).get(orientation);
}
else {
graphViewsCache.put(index, new Hashtable<Integer, View>());
}
if (graphView == null) {
GraphView g = new GraphView(getContext(), labelText);
g.setClickable(true);
graphView = g.getView((GraphData) field);
graphViewsCache.get(index).put(orientation, graphView);
}
// Fetch full-screen graph intent from cache, or create it
Intent graphIntent = graphIntentsCache.get(index);
final Context context = getContext();
if (graphIntent == null) {
GraphView g = new GraphView(context, labelText);
GraphData intentData = (GraphData) field;
// Full-screen view should allow for zoom
if (Boolean.valueOf(intentData.getConfiguration("zoom", "false")).equals(Boolean.FALSE)) {
intentData = intentData.cloneConfiguration();
intentData.setConfiguration("zoom", "true");
}
graphIntent = g.getIntent(intentData);
graphIntentsCache.put(index, graphIntent);
}
final Intent finalIntent = graphIntent;
graphView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
context.startActivity(finalIntent);
return false;
}
});
graphLayout.removeAllViews();
graphLayout.addView(graphView, GraphView.getLayoutParams());
if (current != GRAPH) {
// Hide field label and expand value to take up full screen width
LinearLayout.LayoutParams graphValueLayout = new LinearLayout.LayoutParams(origValue);
graphValueLayout.weight = 10;
valuePane.setLayoutParams(graphValueLayout);
label.setVisibility(View.GONE);
data.setVisibility(View.GONE);
updateCurrentView(GRAPH, graphLayout);
}
} else if (FORM_AUDIO.equals(form)) {
ViewId uniqueId = new ViewId(detailNumber, index, true);
audioButton.modifyButtonForNewView(uniqueId, textField, true);
updateCurrentView(AUDIO, audioButton);
} else if(FORM_VIDEO.equals(form)) { //TODO: Why is this given a special string?
String videoLocation = textField;
String localLocation = null;
try{
localLocation = ReferenceManager._().DeriveReference(videoLocation).getLocalURI();
if(localLocation.startsWith("/")) {
//TODO: This should likely actually be happening with the getLocalURI _anyway_.
localLocation = FileUtil.getGlobalStringUri(localLocation);
}
} catch(InvalidReferenceException ire) {
Logger.log(AndroidLogger.TYPE_ERROR_CONFIG_STRUCTURE, "Couldn't understand video reference format: " + localLocation + ". Error: " + ire.getMessage());
}
final String location = localLocation;
videoButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listener.playVideo(location);
}
});
if(location == null) {
videoButton.setEnabled(false);
Logger.log(AndroidLogger.TYPE_ERROR_CONFIG_STRUCTURE, "No local video reference available for ref: " + videoLocation);
} else {
videoButton.setEnabled(true);
}
updateCurrentView(VIDEO, videoButton);
} else {
String text = textField;
data.setText(text);
if(text != null && text.length() > this.getContext().getResources().getInteger(R.integer.detail_size_cutoff)) {
veryLong = true;
}
updateCurrentView(TEXT, data);
}
if(veryLong) {
detailRow.setOrientation(LinearLayout.VERTICAL);
spacer.setVisibility(View.GONE);
label.setLayoutParams(fill);
valuePane.setLayoutParams(fill);
} else {
if(detailRow.getOrientation() != LinearLayout.HORIZONTAL) {
detailRow.setOrientation(LinearLayout.HORIZONTAL);
spacer.setVisibility(View.INVISIBLE);
label.setLayoutParams(origLabel);
valuePane.setLayoutParams(origValue);
}
}
}
/*
* Appropriately set current & currentView.
*/
private void updateCurrentView(int newCurrent, View newView) {
if (newCurrent != current) {
currentView.setVisibility(View.GONE);
newView.setVisibility(View.VISIBLE);
currentView = newView;
current = newCurrent;
}
if (current != GRAPH) {
label.setVisibility(View.VISIBLE);
LinearLayout.LayoutParams graphValueLayout = new LinearLayout.LayoutParams(origValue);
graphValueLayout.weight = 10;
valuePane.setLayoutParams(origValue);
data.setVisibility(View.VISIBLE);
}
}
/*
* Get current device screen width
*/
private int getScreenWidth() {
Display display = ((WindowManager) this.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
return display.getWidth();
}
}
|
package cmput301f17t01.bronzify;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import junit.framework.TestCase;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import cmput301f17t01.bronzify.adapters.HabitTypeAdapter;
import cmput301f17t01.bronzify.adapters.UserAdapter;
import cmput301f17t01.bronzify.exceptions.UserDoesNotExistException;
import cmput301f17t01.bronzify.exceptions.UserException;
import cmput301f17t01.bronzify.exceptions.UserExistsException;
import cmput301f17t01.bronzify.models.AppLocale;
import cmput301f17t01.bronzify.models.HabitType;
import cmput301f17t01.bronzify.models.User;
public class UserTest extends TestCase {
Date created = new Date();
private User user = new User("userID");
Boolean[] daysOfWeek = {false, true, false, true, false, false, false,};
HabitType habitType;
@Test
public void testSetup() {
AppLocale appLocale = AppLocale.getInstance();
appLocale.setUser(user);
habitType = new HabitType("name" , "reason", new Date(), daysOfWeek);
}
@Test
public void testJson() {
User user0 = new User("testID");
try {
user0.addHabitType(habitType);
} catch (Exception e) {
e.printStackTrace();
}
ArrayList<String> followRequests = new ArrayList<>();
followRequests.add("someone");
user.setPendingFollowRequests(followRequests);
ArrayList<String> following = new ArrayList<>();
following.add("someone else");
user.setFollowing(following);
Gson gsonUser = new GsonBuilder().registerTypeAdapter(User.class,
new UserAdapter()).create();
String json = gsonUser.toJson(user0);
User user2 = gsonUser.fromJson(json, User.class);
assertTrue((user0.getDateCreated().getTime() - user2.getDateCreated().getTime()) < 1000);
assertTrue((user0.getLastInfluenced().getTime() - user2.getLastInfluenced().getTime()) < 1000);
assertTrue((user0.getLastUpdated().getTime() - user2.getLastUpdated().getTime()) < 1000);
assertEquals(user0.getHabitTypes().size(), user2.getHabitTypes().size()); // relying on habiteventtest to confirm this
assertEquals(user0.getUserID(), user2.getUserID());
assertEquals(user0.getFollowing(), user2.getFollowing());
assertEquals(user0.getPendingFollowRequests(), user2.getPendingFollowRequests());
}
@Test
public void testToString() {
assertEquals("userID", user.toString());
}
@Test
public void testAddHabitType() {
Date updated = user.getLastUpdated();
try {
user.addHabitType(habitType);
} catch (Exception e) {
e.printStackTrace();
}
assertTrue(user.getHabitTypes().contains(habitType));
assertTrue(user.getLastUpdated().after(updated));
}
@Test
public void testSetHabitTypes() {
Date updated = user.getLastUpdated();
ArrayList<HabitType> habitTypes = new ArrayList<>();
habitTypes.add(habitType);
habitTypes.add(habitType);
habitTypes.add(habitType);
user.setHabitTypes(habitTypes);
assertEquals(3, user.getHabitTypes().size());
assertTrue(user.getLastUpdated().after(updated));
}
@Test
public void testSetFollowing() {
Date updated = user.getLastInfluenced();
ArrayList<String> following = new ArrayList<>();
following.add("1");
following.add("2");
following.add("someone");
user.setFollowing(following);
assertTrue(user.getFollowing().contains("someone"));
assertEquals(3, user.getFollowing().size());
assertTrue(user.getLastInfluenced().after(updated));
}
@Test
public void testSetPendingFollowRequests() {
Date updated = user.getLastInfluenced();
ArrayList<String> followRequests = new ArrayList<>();
followRequests.add("1");
followRequests.add("2");
followRequests.add("someone");
user.setPendingFollowRequests(followRequests);
assertTrue(user.getPendingFollowRequests().contains("someone"));
assertEquals(3, user.getPendingFollowRequests().size());
assertTrue(user.getLastInfluenced().after(updated));
}
@Test
public void testGetPendingFollowRequests() {
Date updated = user.getLastInfluenced();
ArrayList<String> followRequests = new ArrayList<>();
user.setPendingFollowRequests(followRequests);
assertFalse(user.getPendingFollowRequests().contains("someone"));
followRequests.add("1");
followRequests.add("2");
followRequests.add("someone");
user.setPendingFollowRequests(followRequests);
assertTrue(user.getPendingFollowRequests().contains("someone"));
assertEquals(3, user.getPendingFollowRequests().size());
assertTrue(user.getLastInfluenced().after(updated));
}
@Test
public void testGetHabitTypes() {
ArrayList<HabitType> habitTypes = new ArrayList<>();
habitTypes.add(habitType);
habitTypes.add(habitType);
habitTypes.add(habitType);
user.setHabitTypes(habitTypes);
assertEquals(3, user.getHabitTypes().size());
assertTrue(user.getHabitTypes().contains(habitType));
}
@Test
public void testGetLastInflucenced() {
Date date = new Date();
user.setLastInfluenced(date);
assertEquals(date, user.getLastInfluenced());
}
@Test
public void testSetLastInfluenced() {
Date date = new Date();
assertNotSame(date, user.getLastInfluenced());
user.setLastInfluenced(date);
assertEquals(date, user.getLastInfluenced());
}
@Test
public void testAddFollowing() {
user.setFollowing(new ArrayList<String>());
assertFalse(user.getFollowing().contains("following"));
user.addFollowing("following");
assertTrue(user.getFollowing().contains("following"));
}
@Test
public void removePendingFollowRequest() {
Date updated = user.getLastInfluenced();
ArrayList<String> followRequests = new ArrayList<>();
user.setPendingFollowRequests(followRequests);
user.addPendingFollowRequest("request");
assertTrue(user.getPendingFollowRequests().contains("request"));
user.removePendingFollowRequest("request");
assertFalse(user.getPendingFollowRequests().contains("request"));
assertTrue(user.getLastInfluenced().after(updated));
}
@Test
public void addPendingFollowRequest() {
Date updated = user.getLastInfluenced();
ArrayList<String> followRequests = new ArrayList<>();
user.setPendingFollowRequests(followRequests);
assertFalse(user.getPendingFollowRequests().contains("request"));
user.addPendingFollowRequest("request");
assertTrue(user.getPendingFollowRequests().contains("request"));
assertTrue(user.getLastInfluenced().after(updated));
}
@Test
public void testGetUserID() {
assertEquals("userID", user.getUserID());
}
@Test
public void testSetUserID() {
assertNotSame("newid", user.getUserID());
user.setUserID("newid");
assertEquals("newid", user.getUserID());
}
@Test
public void testGetDateCreated() {
assertEquals(created, user.getDateCreated());
}
@Test
public void testGetLastUpdated() {
Date date = new Date();
user.setLastUpdated(date);
assertEquals(date, user.getLastUpdated());
}
@Test
public void testSetLastUpdate() {
Date date = new Date();
assertNotSame(date, user.getLastUpdated());
user.setLastUpdated(date);
assertEquals(date, user.getLastUpdated());
}
}
|
package org.jbehave.core.reporters;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import org.jbehave.core.configuration.Keywords;
import org.jbehave.core.i18n.LocalizedKeywords;
import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.StoryLocation;
import org.jbehave.core.reporters.FilePrintStreamFactory.FileConfiguration;
import org.jbehave.core.reporters.FilePrintStreamFactory.FilePathResolver;
import static java.util.Arrays.asList;
public class StoryReporterBuilder {
public enum Format {
CONSOLE(org.jbehave.core.reporters.Format.CONSOLE),
IDE_CONSOLE(org.jbehave.core.reporters.Format.IDE_CONSOLE),
TXT(org.jbehave.core.reporters.Format.TXT),
HTML(org.jbehave.core.reporters.Format.HTML),
XML(org.jbehave.core.reporters.Format.XML),
STATS(org.jbehave.core.reporters.Format.STATS);
private org.jbehave.core.reporters.Format realFormat;
Format(org.jbehave.core.reporters.Format realFormat) {
this.realFormat = realFormat;
}
}
private List<org.jbehave.core.reporters.Format> formats = new ArrayList<org.jbehave.core.reporters.Format>();
private String relativeDirectory = new FileConfiguration().getRelativeDirectory();
private FilePathResolver pathResolver = new FileConfiguration().getPathResolver();
private URL codeLocation = CodeLocations.codeLocationFromPath("target/classes");
private Properties viewResources = FreemarkerViewGenerator.defaultViewProperties();
private boolean reportFailureTrace = false;
private Keywords keywords = new LocalizedKeywords();
public File outputDirectory() {
return filePrintStreamFactory("").outputDirectory();
}
public String relativeDirectory(){
return relativeDirectory;
}
public FilePathResolver pathResolver(){
return pathResolver;
}
public URL codeLocation() {
return codeLocation;
}
public List<org.jbehave.core.reporters.Format> formats() {
return formats;
}
public List<String> formatNames(boolean toLowerCase) {
Locale locale = Locale.getDefault();
if ( keywords instanceof LocalizedKeywords ){
locale = ((LocalizedKeywords)keywords).getLocale();
}
List<String> names = new ArrayList<String>();
for (org.jbehave.core.reporters.Format format : formats) {
String name = format.name();
if (toLowerCase) {
name = name.toLowerCase(locale);
}
names.add(name);
}
return names;
}
public Keywords keywords() {
return keywords;
}
public boolean reportFailureTrace() {
return reportFailureTrace;
}
public Properties viewResources() {
return viewResources;
}
public StoryReporterBuilder withRelativeDirectory(String relativeDirectory) {
this.relativeDirectory = relativeDirectory;
return this;
}
public StoryReporterBuilder withPathResolver(FilePathResolver pathResolver){
this.pathResolver = pathResolver;
return this;
}
public StoryReporterBuilder withCodeLocation(URL codeLocation) {
this.codeLocation = codeLocation;
return this;
}
public StoryReporterBuilder withDefaultFormats() {
return withFormats(Format.STATS);
}
/**
* Use the other withFormats() signature
* @param formats
* @return
*/
@Deprecated
public StoryReporterBuilder withFormats(Format... formats) {
List<org.jbehave.core.reporters.Format> formatz = new ArrayList<org.jbehave.core.reporters.Format>();
for (Format format : formats) {
formatz.add(format.realFormat);
}
this.formats.addAll(formatz);
return this;
}
public StoryReporterBuilder withFormats(org.jbehave.core.reporters.Format... formats) {
this.formats.addAll(asList(formats));
return this;
}
public StoryReporterBuilder withFailureTrace(boolean reportFailureTrace) {
this.reportFailureTrace = reportFailureTrace;
return this;
}
public StoryReporterBuilder withKeywords(Keywords keywords) {
this.keywords = keywords;
return this;
}
public StoryReporterBuilder withViewResources(Properties resources) {
this.viewResources = resources;
return this;
}
public StoryReporter build(String storyPath) {
Map<org.jbehave.core.reporters.Format, StoryReporter> delegates = new HashMap<org.jbehave.core.reporters.Format, StoryReporter>();
for (org.jbehave.core.reporters.Format format : formats) {
delegates.put(format, reporterFor(storyPath, format));
}
return new DelegatingStoryReporter(delegates.values());
}
public Map<String, StoryReporter> build(List<String> storyPaths) {
Map<String, StoryReporter> reporters = new HashMap<String, StoryReporter>();
for (String storyPath : storyPaths) {
reporters.put(storyPath, build(storyPath));
}
return reporters;
}
public StoryReporter reporterFor(String storyPath, Format format) {
FilePrintStreamFactory factory = filePrintStreamFactory(storyPath);
return format.realFormat.createStoryReporter(factory, this);
}
public StoryReporter reporterFor(String storyPath, org.jbehave.core.reporters.Format format) {
FilePrintStreamFactory factory = filePrintStreamFactory(storyPath);
return format.createStoryReporter(factory, this);
}
protected FilePrintStreamFactory filePrintStreamFactory(String storyPath) {
return new FilePrintStreamFactory(new StoryLocation(codeLocation, storyPath), fileConfiguration(""));
}
public FileConfiguration fileConfiguration(String extension) {
return new FileConfiguration(relativeDirectory, extension, pathResolver);
}
}
|
package com.jenjinstudios.client.net;
import com.jenjinstudios.core.io.Message;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Caleb Brinkman
*/
public class LoginTracker
{
private static final Logger LOGGER = Logger.getLogger(LoginTracker.class.getName());
private static final int MILLIS_IN_30_SECONDS = 30000;
private volatile boolean loggedIn;
private volatile boolean waitingForResponse;
private long loggedInTime;
private final AuthClient client;
public LoginTracker(AuthClient client) { this.client = client; }
public boolean isLoggedIn() { return loggedIn; }
public void setLoggedIn(boolean loggedIn) {
waitingForResponse = false;
this.loggedIn = loggedIn;
}
public long getLoggedInTime() { return loggedInTime; }
public void setLoggedInTime(long loggedInTime) { this.loggedInTime = loggedInTime; }
protected void sendLoginRequest() {
waitingForResponse = true;
Message message = AuthClient.generateLoginRequest(client.getUser());
client.getMessageIO().queueOutgoingMessage(message);
}
public boolean sendLoginRequestAndWaitForResponse() {
sendLoginRequest();
long startTime = System.currentTimeMillis();
while (waitingForResponse && ((System.currentTimeMillis() - startTime) < (long) MILLIS_IN_30_SECONDS))
{
waitTenMillis();
}
return loggedIn;
}
public void sendLogoutRequestAndWaitForResponse() {
sendLogoutRequest();
long startTime = System.currentTimeMillis();
while (waitingForResponse && ((System.currentTimeMillis() - startTime) < (long) MILLIS_IN_30_SECONDS))
{
waitTenMillis();
}
}
private void sendLogoutRequest() {
waitingForResponse = true;
Message message = AuthClient.generateLogoutRequest();
client.getMessageIO().queueOutgoingMessage(message);
}
private void waitTenMillis() {
try
{
Thread.sleep(10);
} catch (InterruptedException e)
{
LOGGER.log(Level.WARNING, "Interrupted while waiting for login response.");
}
}
}
|
package org.develnext.jphp.scripting;
import org.develnext.jphp.scripting.util.ReaderInputStream;
import php.runtime.env.Context;
import php.runtime.env.Environment;
import php.runtime.launcher.Launcher;
import php.runtime.memory.ArrayMemory;
import php.runtime.memory.support.MemoryUtils;
import php.runtime.reflection.ModuleEntity;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import javax.script.*;
import java.io.*;
import java.util.*;
public class JPHPScriptEngine extends AbstractScriptEngine implements Compilable {
private static final String __ENGINE_VERSION__ = "0.4";
private static final String __NAME__ = "JPHP Engine";
private static final String __SHORT_NAME__ = "jphp";
private static final String __LANGUAGE__ = "php";
private static final String __LANGUAGE_VERSION__ = "5.3";
private ScriptEngineFactory factory = null;
private Environment environment;
public JPHPScriptEngine() {
super();
Launcher launcher = new Launcher();
try {
launcher.run(false);
} catch (Throwable e) {
//pass
}
environment = new Environment(launcher.getCompileScope(), System.out);
environment.getDefaultBuffer().setImplicitFlush(true);
JPHPContext ctx = new JPHPContext();
ctx.setBindings(createBindings(), ScriptContext.ENGINE_SCOPE);
setContext(ctx);
put(LANGUAGE_VERSION, __LANGUAGE_VERSION__);
put(LANGUAGE, __LANGUAGE__);
put(ENGINE, __NAME__);
put(ENGINE_VERSION, __ENGINE_VERSION__);
put(NAME, __SHORT_NAME__);
}
@Override
public Object eval(String script, ScriptContext context) throws ScriptException {
return eval(new StringReader(script), context);
}
@Override
public Object eval(Reader reader, ScriptContext _ctx) throws ScriptException {
return compile(reader).eval(_ctx);
}
@Override
public CompiledScript compile(String script) throws ScriptException {
return compile(new StringReader(script));
}
@Override
public CompiledScript compile(Reader reader) throws ScriptException {
try {
InputStream is = new ReaderInputStream(reader);
Context context = new Context(is);
ModuleEntity module = environment.importModule(context);
return new JPHPCompiledScript(module, environment);
} catch (IOException e) {
throw new ScriptException(e);
} catch (Throwable e) {
throw new ScriptException(new Exception(e));
}
}
@Override
public Bindings createBindings() {
return new JPHPBindings(environment.getGlobals());
}
@Override
public synchronized ScriptEngineFactory getFactory() {
if (factory == null) {
factory = new JPHPScriptEngineFactory();
}
return factory;
}
public void setFactory(JPHPScriptEngineFactory f) {
factory = f;
}
public class JPHPBindings implements Bindings {
private ArrayMemory globals;
public JPHPBindings(ArrayMemory globals) {
this.globals = globals;
}
@Override
public Object put(String name, Object value) {
return globals.putAsKeyString(name, MemoryUtils.valueOf(value));
}
@Override
public void putAll(Map<? extends String, ? extends Object> toMerge) {
for (String key : toMerge.keySet()) {
put(key, toMerge.get(key));
}
}
@Override
public void clear() {
globals.clear();
}
@Override
public Set<String> keySet() {
Set<String> set = new HashSet<String>(size());
for (Object k : globals.keySet()) {
set.add(k.toString());
}
return set;
}
@Override
public Collection<Object> values() {
return new ArrayList<Object>(Arrays.asList(globals.values()));
}
@Override
public Set<Entry<String, Object>> entrySet() {
Set<Entry<String, Object>> set = new HashSet<Entry<String, Object>>(size());
for (Object k : globals.keySet()) {
set.add(new AbstractMap.SimpleEntry<String, Object>(k.toString(), get(k)));
}
return set;
}
@Override
public int size() {
return globals.size();
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsKey(Object key) {
return globals.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return false;
}
@Override
public Object get(Object key) {
return globals.getByScalar(key);
}
@Override
public Object remove(Object key) {
return globals.removeByScalar(key);
}
}
public class JPHPCompiledScript extends CompiledScript {
private ModuleEntity module;
private Environment environment;
public JPHPCompiledScript(ModuleEntity m, Environment env) {
module = m;
environment = env;
}
@Override
public Object eval(ScriptContext context) throws ScriptException {
try {
try {
return module.include(environment);
} catch (Exception e) {
environment.catchUncaught(e);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
} finally {
try {
environment.doFinal();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
} catch (Throwable e) {
throw new ScriptException(new Exception(e));
}
return null;
}
@Override
public ScriptEngine getEngine() {
return JPHPScriptEngine.this;
}
}
}
|
package com.fsck.k9.mail.store.imap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.fsck.k9.endtoend.framework.StubMailServer;
import com.fsck.k9.endtoend.framework.UserForImap;
import com.fsck.k9.mail.AuthType;
import com.fsck.k9.mail.AuthenticationFailedException;
import com.fsck.k9.mail.ConnectionSecurity;
import com.fsck.k9.mail.MessagingException;
import junit.framework.TestCase;
import static org.junit.Assert.assertArrayEquals;
public class ImapConnectionTest extends TestCase {
private static final String[] CAPABILITIES = new String[] { "IMAP4REV1", "LITERAL+", "QUOTA" };
private StubMailServer stubMailServer;
private ImapConnection connection;
private TestImapSettings settings;
@Override
public void setUp() throws Exception {
super.setUp();
stubMailServer = new StubMailServer();
settings = new TestImapSettings(UserForImap.TEST_USER);
connection = new ImapConnection(settings, null, null);
}
@Override
public void tearDown() throws Exception {
super.tearDown();
stubMailServer.stop();
}
public void testOpenConnectionWithoutRunningServerThrowsMessagingException() throws Exception {
stubMailServer.stop();
try {
connection.open();
fail("expected exception");
} catch (MessagingException e) {
assertFalse(connection.isOpen());
}
}
public void testOpenConnectionWithWrongCredentialsThrowsAuthenticationFailedException() throws Exception {
connection = new ImapConnection(new TestImapSettings("wrong", "password"), null, null);
try {
connection.open();
fail("expected exception");
} catch (AuthenticationFailedException e) {
assertTrue(e.getMessage().contains("Invalid login/password"));
assertFalse(connection.isOpen());
}
}
public void testConnectionIsInitiallyClosed() throws Exception {
assertFalse(connection.isOpen());
}
public void testSuccessfulOpenConnectionTogglesOpenState() throws Exception {
connection.open();
assertTrue(connection.isOpen());
}
public void testSuccessfulOpenAndCloseConnectionTogglesOpenState() throws Exception {
connection.open();
connection.close();
assertFalse(connection.isOpen());
}
public void testCapabilitiesAreInitiallyEmpty() throws Exception {
assertTrue(connection.getCapabilities().isEmpty());
}
public void testCapabilitiesListGetsParsedCorrectly() throws Exception {
connection.open();
List<String> capabilities = new ArrayList<String>(connection.getCapabilities());
Collections.sort(capabilities);
assertArrayEquals(CAPABILITIES, capabilities.toArray());
}
public void testHasCapabilityChecks() throws Exception {
connection.open();
for (String capability : CAPABILITIES) {
assertTrue(connection.hasCapability(capability));
}
assertFalse(connection.hasCapability("FROBAZIFCATE"));
}
public void testPathPrefixGetsSetCorrectly() throws Exception {
connection.open();
assertEquals("", settings.getPathPrefix());
}
public void testPathDelimiterGetsParsedCorrectly() throws Exception {
connection.open();
assertEquals(".", settings.getPathDelimiter());
}
public void testCombinedPrefixGetsSetCorrectly() throws Exception {
connection.open();
assertNull(settings.getCombinedPrefix());
}
private class TestImapSettings implements ImapSettings {
private String pathPrefix;
private String pathDelimiter;
private String username;
private String password;
private String combinedPrefix;
public TestImapSettings(UserForImap userForImap) {
this(userForImap.loginUsername, userForImap.password);
}
public TestImapSettings(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String getHost() {
return stubMailServer.getImapBindAddress();
}
@Override
public int getPort() {
return stubMailServer.getImapPort();
}
@Override
public ConnectionSecurity getConnectionSecurity() {
return ConnectionSecurity.NONE;
}
@Override
public AuthType getAuthType() {
return AuthType.PLAIN;
}
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getClientCertificateAlias() {
return null;
}
@Override
public boolean useCompression(int type) {
return false;
}
@Override
public String getPathPrefix() {
return pathPrefix;
}
@Override
public void setPathPrefix(String prefix) {
pathPrefix = prefix;
}
@Override
public String getPathDelimiter() {
return pathDelimiter;
}
@Override
public void setPathDelimiter(String delimiter) {
pathDelimiter = delimiter;
}
@Override
public String getCombinedPrefix() {
return combinedPrefix;
}
@Override
public void setCombinedPrefix(String prefix) {
combinedPrefix = prefix;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.