input
stringlengths 20
285k
| output
stringlengths 20
285k
|
|---|---|
private void importClass(String className) {
Class<?> clazz;
try {
clazz = this.classLoader.loadClass(className);
if(clazz.getAnnotation(Internal.class) != null)
return;
if (Operator.class.isAssignableFrom(clazz) && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) {
clazz = Class.forName(className, true, this.classLoader);
QueryUtil.LOG.trace("adding operator " + clazz);
this.getOperatorRegistry().put((Class<? extends Operator<?>>) clazz);
} else if (SopremoFormat.class.isAssignableFrom(clazz)
&& (clazz.getModifiers() & Modifier.ABSTRACT) == 0) {
clazz = Class.forName(className, true, this.classLoader);
QueryUtil.LOG.trace("adding operator " + clazz);
this.getFileFormatRegistry().put((Class<? extends SopremoFormat>) clazz);
} else if (BuiltinProvider.class.isAssignableFrom(clazz)) {
clazz = Class.forName(className, true, this.classLoader);
this.addFunctionsAndConstants(clazz);
} else if (IJsonNode.class.isAssignableFrom(clazz))
this.getTypeRegistry().put((Class<? extends IJsonNode>) clazz);
} catch (ClassNotFoundException e) {
QueryUtil.LOG.warn("could not load operator " + className + ": " + StringUtils.stringifyException(e));
} catch (NoClassDefFoundError e) {
QueryUtil.LOG.warn("could not load operator " + className + ": " + StringUtils.stringifyException(e));
}
}
|
private void importClass(String className) {
Class<?> clazz;
try {
clazz = this.classLoader.loadClass(className);
if(clazz.getAnnotation(Internal.class) != null)
return;
if (Operator.class.isAssignableFrom(clazz) && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) {
clazz = Class.forName(className, true, this.classLoader);
QueryUtil.LOG.trace("adding operator " + clazz);
this.getOperatorRegistry().put((Class<? extends Operator<?>>) clazz);
} else if (SopremoFormat.class.isAssignableFrom(clazz)
&& (clazz.getModifiers() & Modifier.ABSTRACT) == 0) {
clazz = Class.forName(className, true, this.classLoader);
QueryUtil.LOG.trace("adding operator " + clazz);
this.getFileFormatRegistry().put((Class<? extends SopremoFormat>) clazz);
} else if (BuiltinProvider.class.isAssignableFrom(clazz)) {
clazz = Class.forName(className, true, this.classLoader);
this.addFunctionsAndConstants(clazz);
} else if (IJsonNode.class.isAssignableFrom(clazz))
this.getTypeRegistry().put((Class<? extends IJsonNode>) clazz);
} catch (Exception e) {
QueryUtil.LOG.warn("could not load operator " + className + ": " + StringUtils.stringifyException(e));
}
}
|
protected void onDraw(Canvas canvas) {
if (mOpenProgress == 0 && mHintProgress == 1)
return;
if (mPaint == null) {
mPaint = new Paint();
}
final Point screenSize = Util.getScreenSize(null);
final int width = Math.min(screenSize.x, screenSize.y);
final int height = Math.max(screenSize.x, screenSize.y);
final float buttonOffset = Util.dpToPx(getContext(), 12);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(4.0f);
mPaint.setARGB((int) (255.0f - 255.0f * mHintProgress), 255, 255, 255);
canvas.drawCircle(height - mEdgePadding + buttonOffset, width / 2, mHintProgress * mRingRadius, mPaint);
canvas.drawCircle(height - mEdgePadding + buttonOffset, width / 2, mHintProgress * mRingRadius * 0.66f, mPaint);
canvas.drawCircle(height - mEdgePadding + buttonOffset, width / 2, mHintProgress * mRingRadius * 0.33f, mPaint);
final float ringRadius = (float) mRingRadius * mOpenProgress;
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(0x88888888);
canvas.drawCircle(height - mEdgePadding, width / 2, ringRadius, mPaint);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(4.0f);
mPaint.setColor(0x88DDDDDD);
canvas.drawCircle(height - mEdgePadding, width / 2, ringRadius, mPaint);
for (int i = 0; i < SLOT_MAX; i++) {
mPaint.setAlpha((int) (255.0f * mOpenProgress));
PadButton button = mButtons[i];
if (button == null) continue;
final float radAngle = (float) ((float) (i * (180.0f / 4.0f) + 90.0f) * Math.PI / 180.0f);
final float x = (float) (height + ringRadius * Math.cos(radAngle) - mButtonSize);
final float y = (float) (width / 2 - button.mNormalBitmap.getWidth() / 2 - ringRadius * Math.sin(radAngle));
canvas.save();
canvas.translate(x + button.mNormalBitmap.getWidth() / 2, y + button.mNormalBitmap.getWidth() / 2);
canvas.rotate(mCurrentOrientation);
if (button.mIsHovering) {
canvas.drawBitmap(button.mHoverBitmap, -button.mNormalBitmap.getWidth() / 2, -button.mNormalBitmap.getWidth() / 2, mPaint);
} else {
canvas.drawBitmap(button.mNormalBitmap, -button.mNormalBitmap.getWidth() / 2, -button.mNormalBitmap.getWidth() / 2, mPaint);
}
canvas.restore();
if (mOpenProgress == 1.0f) {
animateAlpha(button.mIsHovering, button);
} else {
animateAlpha(false, button);
}
if ((button.mIsHovering || button.mHintTextAlpha > 0.0f) && mOpenProgress == 1.0f) {
int alpha = (int) (255 * (button.mHintTextAlpha));
mPaint.setTextSize(36);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setShadowLayer(12, 0, 0, 0xEE333333 * ((alpha & 0xFF) << 24));
mPaint.setAlpha(alpha);
float measureText = mPaint.measureText(button.mHintText);
canvas.save();
canvas.translate(x - measureText / 2 - Util.dpToPx(getContext(), 4),
y + button.mNormalBitmap.getWidth() / 2 - mPaint.getTextSize() / 2);
canvas.rotate(mCurrentOrientation);
canvas.drawText(button.mHintText, 0, 0, mPaint);
canvas.restore();
}
button.mLastDrawnX = x;
button.mLastDrawnY = y;
}
}
|
protected void onDraw(Canvas canvas) {
if (mOpenProgress == 0 && mHintProgress == 1)
return;
if (mPaint == null) {
mPaint = new Paint();
}
final Point screenSize = Util.getScreenSize(null);
final int width = Math.min(screenSize.x, screenSize.y);
final int height = Math.max(screenSize.x, screenSize.y);
final float buttonOffset = Util.dpToPx(getContext(), 12);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(4.0f);
mPaint.setARGB((int) (255.0f - 255.0f * mHintProgress), 255, 255, 255);
canvas.drawCircle(height - mEdgePadding + buttonOffset, width / 2, mHintProgress * mRingRadius, mPaint);
canvas.drawCircle(height - mEdgePadding + buttonOffset, width / 2, mHintProgress * mRingRadius * 0.66f, mPaint);
canvas.drawCircle(height - mEdgePadding + buttonOffset, width / 2, mHintProgress * mRingRadius * 0.33f, mPaint);
final float ringRadius = (float) mRingRadius * mOpenProgress;
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(0x88888888);
canvas.drawCircle(height - mEdgePadding, width / 2, ringRadius, mPaint);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(4.0f);
mPaint.setColor(0x88DDDDDD);
canvas.drawCircle(height - mEdgePadding, width / 2, ringRadius, mPaint);
for (int i = 0; i < SLOT_MAX; i++) {
mPaint.setAlpha((int) (255.0f * mOpenProgress));
PadButton button = mButtons[i];
if (button == null) continue;
final float radAngle = (float) ((float) (i * (180.0f / 4.0f) + 90.0f) * Math.PI / 180.0f);
final float x = (float) (height + ringRadius * Math.cos(radAngle) - mButtonSize);
final float y = (float) (width / 2 - button.mNormalBitmap.getWidth() / 2 - ringRadius * Math.sin(radAngle));
canvas.save();
canvas.translate(x + button.mNormalBitmap.getWidth() / 2, y + button.mNormalBitmap.getWidth() / 2);
canvas.rotate(mCurrentOrientation);
if (button.mIsHovering) {
canvas.drawBitmap(button.mHoverBitmap, -button.mNormalBitmap.getWidth() / 2, -button.mNormalBitmap.getWidth() / 2, mPaint);
} else {
canvas.drawBitmap(button.mNormalBitmap, -button.mNormalBitmap.getWidth() / 2, -button.mNormalBitmap.getWidth() / 2, mPaint);
}
canvas.restore();
if (mOpenProgress == 1.0f) {
animateAlpha(button.mIsHovering, button);
} else {
animateAlpha(false, button);
}
if ((button.mIsHovering || button.mHintTextAlpha > 0.0f) && mOpenProgress == 1.0f) {
int alpha = (int) (255 * (button.mHintTextAlpha));
mPaint.setStyle(Paint.Style.FILL);
mPaint.setTextSize(36);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setShadowLayer(12, 0, 0, 0xEE333333 * ((alpha & 0xFF) << 24));
mPaint.setAlpha(alpha);
float measureText = mPaint.measureText(button.mHintText);
canvas.save();
canvas.translate(x - measureText / 2 - Util.dpToPx(getContext(), 4),
y + button.mNormalBitmap.getWidth() / 2 - mPaint.getTextSize() / 2);
canvas.rotate(mCurrentOrientation);
canvas.drawText(button.mHintText, 0, 0, mPaint);
canvas.restore();
}
button.mLastDrawnX = x;
button.mLastDrawnY = y;
}
}
|
public void shouldUploadANCVisitFormSuccessfully() throws SchedulerException, ParseException {
final String staffId = staffGenerator.createStaff(browser, homePage);
DataGenerator dataGenerator = new DataGenerator();
String patientFirstName = "patient first name" + dataGenerator.randomString(5);
final TestPatient testPatient = TestPatient.with(patientFirstName, staffId)
.patientType(TestPatient.PATIENT_TYPE.PREGNANT_MOTHER)
.estimatedDateOfBirth(false);
PatientPage patientPage = browser.toCreatePatient(homePage);
patientPage.create(testPatient);
TestANCEnrollment ancEnrollment = TestANCEnrollment.create().withStaffId(staffId)
.withRegistrationToday(RegistrationToday.IN_PAST);
SearchPatientPage searchPatientPage = browser.toSearchPatient(patientPage);
searchPatientPage.searchWithName(patientFirstName);
searchPatientPage.displaying(testPatient);
PatientEditPage patientEditPage = browser.toPatientEditPage(searchPatientPage, testPatient);
final ANCEnrollmentPage ancEnrollmentPage = browser.toEnrollANCPage(patientEditPage);
ancEnrollmentPage.save(ancEnrollment);
final LocalDate nextANCVisitDate = DateUtil.today().plusDays(5);
String nextVisitDate = new SimpleDateFormat("yyyy-MM-dd").format(nextANCVisitDate.toDate());
XformHttpClient.XformResponse xformResponse = createAncVisit(staffId, testPatient, ancEnrollmentPage, nextANCVisitDate);
verifyAncVisitSchedules(ancEnrollmentPage, xformResponse, nextANCVisitDate.minusWeeks(1).toDate(),
nextANCVisitDate.toDate(), nextANCVisitDate.plusWeeks(1).toDate(), nextANCVisitDate.plusWeeks(2).toDate());
String motechId = ancEnrollmentPage.motechId();
OpenMRSPatientPage openMRSPatientPage = openMRSBrowser.toOpenMRSPatientPage(openMRSDB.getOpenMRSId(motechId));
String encounterId = openMRSPatientPage.chooseEncounter("ANCVISIT");
OpenMRSEncounterPage openMRSEncounterPage = openMRSBrowser.toOpenMRSEncounterPage(encounterId);
openMRSEncounterPage.displaying(asList(
new OpenMRSObservationVO("WEIGHT (KG)", "65.67"),
new OpenMRSObservationVO("URINE GLUCOSE TEST", "POSITIVE"),
new OpenMRSObservationVO("HIV POST-TEST COUNSELING", "true"),
new OpenMRSObservationVO("HIV TEST RESULT", "POSITIVE"),
new OpenMRSObservationVO("PMTCT TREATMENT", "true"),
new OpenMRSObservationVO("PMTCT", "true"),
new OpenMRSObservationVO("MALE INVOLVEMENT", "false"),
new OpenMRSObservationVO("VDRL TREATMENT", "true"),
new OpenMRSObservationVO("COMMENTS", "comments"),
new OpenMRSObservationVO("ESTIMATED DATE OF CONFINEMENT","03 February 2012 00:00:00 IST"),
new OpenMRSObservationVO("ESTIMATED DATE OF CONFINEMENT","03 August 2012 00:00:00 IST"),
new OpenMRSObservationVO("PREGNANCY STATUS","true"),
new OpenMRSObservationVO("DATE OF CONFINEMENT CONFIRMED","true"),
new OpenMRSObservationVO("TETANUS TOXOID DOSE", "1.0"),
new OpenMRSObservationVO("IPT REACTION", "REACTIVE"),
new OpenMRSObservationVO("URINE PROTEIN TEST", "POSITIVE"),
new OpenMRSObservationVO("COMMUNITY", "community"),
new OpenMRSObservationVO("SERIAL NUMBER", "4ds65"),
new OpenMRSObservationVO("INTERMITTENT PREVENTATIVE TREATMENT DOSE", "1.0"),
new OpenMRSObservationVO("FUNDAL HEIGHT", "4.3"),
new OpenMRSObservationVO("SYSTOLIC BLOOD PRESSURE", "10.0"),
new OpenMRSObservationVO("HEMOGLOBIN", "13.8"),
new OpenMRSObservationVO("FETAL HEART RATE", "4.0"),
new OpenMRSObservationVO("HIV PRE-TEST COUNSELING", "true"),
new OpenMRSObservationVO("VDRL", "NON-REACTIVE"),
new OpenMRSObservationVO("VISIT NUMBER", "4.0"),
new OpenMRSObservationVO("ANC PNC LOCATION", "2.0"),
new OpenMRSObservationVO("REFERRED", "true"),
new OpenMRSObservationVO("DEWORMER", "true"),
new OpenMRSObservationVO("NEXT ANC DATE", nextVisitDate),
new OpenMRSObservationVO("DIASTOLIC BLOOD PRESSURE", "67.0"),
new OpenMRSObservationVO("INSECTICIDE TREATED NET USAGE", "false"),
new OpenMRSObservationVO("HOUSE", "house")
));
}
|
public void shouldUploadANCVisitFormSuccessfully() throws SchedulerException, ParseException {
final String staffId = staffGenerator.createStaff(browser, homePage);
DataGenerator dataGenerator = new DataGenerator();
String patientFirstName = "patient first name" + dataGenerator.randomString(5);
final TestPatient testPatient = TestPatient.with(patientFirstName, staffId)
.patientType(TestPatient.PATIENT_TYPE.PREGNANT_MOTHER)
.estimatedDateOfBirth(false);
PatientPage patientPage = browser.toCreatePatient(homePage);
patientPage.create(testPatient);
TestANCEnrollment ancEnrollment = TestANCEnrollment.create().withStaffId(staffId)
.withRegistrationToday(RegistrationToday.IN_PAST);
SearchPatientPage searchPatientPage = browser.toSearchPatient(patientPage);
searchPatientPage.searchWithName(patientFirstName);
searchPatientPage.displaying(testPatient);
PatientEditPage patientEditPage = browser.toPatientEditPage(searchPatientPage, testPatient);
final ANCEnrollmentPage ancEnrollmentPage = browser.toEnrollANCPage(patientEditPage);
ancEnrollmentPage.save(ancEnrollment);
final LocalDate nextANCVisitDate = DateUtil.newDate(2012,4,10);
XformHttpClient.XformResponse xformResponse = createAncVisit(staffId, testPatient, ancEnrollmentPage, nextANCVisitDate);
verifyAncVisitSchedules(ancEnrollmentPage, xformResponse, nextANCVisitDate.minusWeeks(1).toDate(),
nextANCVisitDate.toDate(), nextANCVisitDate.plusWeeks(1).toDate(), nextANCVisitDate.plusWeeks(2).toDate());
String motechId = ancEnrollmentPage.motechId();
OpenMRSPatientPage openMRSPatientPage = openMRSBrowser.toOpenMRSPatientPage(openMRSDB.getOpenMRSId(motechId));
String encounterId = openMRSPatientPage.chooseEncounter("ANCVISIT");
OpenMRSEncounterPage openMRSEncounterPage = openMRSBrowser.toOpenMRSEncounterPage(encounterId);
openMRSEncounterPage.displaying(asList(
new OpenMRSObservationVO("WEIGHT (KG)", "65.67"),
new OpenMRSObservationVO("URINE GLUCOSE TEST", "POSITIVE"),
new OpenMRSObservationVO("HIV POST-TEST COUNSELING", "true"),
new OpenMRSObservationVO("HIV TEST RESULT", "POSITIVE"),
new OpenMRSObservationVO("PMTCT TREATMENT", "true"),
new OpenMRSObservationVO("PMTCT", "true"),
new OpenMRSObservationVO("MALE INVOLVEMENT", "false"),
new OpenMRSObservationVO("VDRL TREATMENT", "true"),
new OpenMRSObservationVO("COMMENTS", "comments"),
new OpenMRSObservationVO("ESTIMATED DATE OF CONFINEMENT","03 February 2012 00:00:00 IST"),
new OpenMRSObservationVO("ESTIMATED DATE OF CONFINEMENT","03 August 2012 00:00:00 IST"),
new OpenMRSObservationVO("PREGNANCY STATUS","true"),
new OpenMRSObservationVO("DATE OF CONFINEMENT CONFIRMED","true"),
new OpenMRSObservationVO("TETANUS TOXOID DOSE", "1.0"),
new OpenMRSObservationVO("IPT REACTION", "REACTIVE"),
new OpenMRSObservationVO("URINE PROTEIN TEST", "POSITIVE"),
new OpenMRSObservationVO("COMMUNITY", "community"),
new OpenMRSObservationVO("SERIAL NUMBER", "4ds65"),
new OpenMRSObservationVO("INTERMITTENT PREVENTATIVE TREATMENT DOSE", "1.0"),
new OpenMRSObservationVO("FUNDAL HEIGHT", "4.3"),
new OpenMRSObservationVO("SYSTOLIC BLOOD PRESSURE", "10.0"),
new OpenMRSObservationVO("HEMOGLOBIN", "13.8"),
new OpenMRSObservationVO("FETAL HEART RATE", "4.0"),
new OpenMRSObservationVO("HIV PRE-TEST COUNSELING", "true"),
new OpenMRSObservationVO("VDRL", "NON-REACTIVE"),
new OpenMRSObservationVO("VISIT NUMBER", "4.0"),
new OpenMRSObservationVO("ANC PNC LOCATION", "2.0"),
new OpenMRSObservationVO("REFERRED", "true"),
new OpenMRSObservationVO("DEWORMER", "true"),
new OpenMRSObservationVO("NEXT ANC DATE", "10 April 2012 00:00:00 IST"),
new OpenMRSObservationVO("DIASTOLIC BLOOD PRESSURE", "67.0"),
new OpenMRSObservationVO("INSECTICIDE TREATED NET USAGE", "false"),
new OpenMRSObservationVO("HOUSE", "house")
));
}
|
public boolean onContextItemSelected(android.view.MenuItem item) {
ExpandableListContextMenuInfo expInfo = (ExpandableListContextMenuInfo) item.getMenuInfo();
int groupPosition = ExpandableListView.getPackedPositionGroup(expInfo.packedPosition);
long keyRingRowId = getExpandableListAdapter().getGroupId(groupPosition);
switch (item.getItemId()) {
case Id.menu.update:
long updateKeyId = 0;
PGPPublicKeyRing updateKeyRing = ProviderHelper.getPGPPublicKeyRingByRowId(
mKeyListActivity, keyRingRowId);
if (updateKeyRing != null) {
updateKeyId = PgpHelper.getMasterKey(updateKeyRing).getKeyID();
}
if (updateKeyId == 0) {
return true;
}
Intent queryIntent = new Intent(mKeyListActivity, KeyServerQueryActivity.class);
queryIntent.setAction(KeyServerQueryActivity.ACTION_LOOK_UP_KEY_ID_AND_RETURN);
queryIntent.putExtra(KeyServerQueryActivity.EXTRA_KEY_ID, updateKeyId);
startActivityForResult(queryIntent, Id.request.look_up_key_id);
return true;
case Id.menu.exportToServer:
Intent uploadIntent = new Intent(mKeyListActivity, KeyServerUploadActivity.class);
uploadIntent.setAction(KeyServerUploadActivity.ACTION_EXPORT_KEY_TO_SERVER);
uploadIntent.putExtra(KeyServerUploadActivity.EXTRA_KEYRING_ROW_ID, keyRingRowId);
startActivityForResult(uploadIntent, Id.request.export_to_server);
return true;
case Id.menu.signKey:
long keyId = 0;
PGPPublicKeyRing signKeyRing = ProviderHelper.getPGPPublicKeyRingByRowId(
mKeyListActivity, keyRingRowId);
if (signKeyRing != null) {
keyId = PgpHelper.getMasterKey(signKeyRing).getKeyID();
}
if (keyId == 0) {
return true;
}
Intent signIntent = new Intent(mKeyListActivity, SignKeyActivity.class);
signIntent.putExtra(SignKeyActivity.EXTRA_KEY_ID, keyId);
startActivity(signIntent);
return true;
case Id.menu.share_qr_code:
long masterKeyId = ProviderHelper.getPublicMasterKeyId(mKeyListActivity, keyRingRowId);
Intent qrCodeIntent = new Intent(mKeyListActivity, ShareActivity.class);
qrCodeIntent.setAction(ShareActivity.ACTION_SHARE_KEYRING_WITH_QR_CODE);
qrCodeIntent.putExtra(ShareActivity.EXTRA_MASTER_KEY_ID, masterKeyId);
startActivityForResult(qrCodeIntent, 0);
return true;
case Id.menu.share_nfc:
long masterKeyId2 = ProviderHelper.getPublicMasterKeyId(mKeyListActivity, keyRingRowId);
Intent nfcIntent = new Intent(mKeyListActivity, ShareNfcBeamActivity.class);
nfcIntent.setAction(ShareNfcBeamActivity.ACTION_SHARE_KEYRING_WITH_NFC);
nfcIntent.putExtra(ShareNfcBeamActivity.EXTRA_MASTER_KEY_ID, masterKeyId2);
startActivityForResult(nfcIntent, 0);
return true;
case Id.menu.share:
long masterKeyId3 = ProviderHelper.getPublicMasterKeyId(mKeyListActivity, keyRingRowId);
Intent shareIntent = new Intent(mKeyListActivity, ShareActivity.class);
shareIntent.setAction(ShareActivity.ACTION_SHARE_KEYRING);
shareIntent.putExtra(ShareActivity.EXTRA_MASTER_KEY_ID, masterKeyId3);
startActivityForResult(shareIntent, 0);
return true;
default:
return super.onContextItemSelected(item);
}
}
|
public boolean onContextItemSelected(android.view.MenuItem item) {
ExpandableListContextMenuInfo expInfo = (ExpandableListContextMenuInfo) item.getMenuInfo();
int groupPosition = ExpandableListView.getPackedPositionGroup(expInfo.packedPosition);
long keyRingRowId = getExpandableListAdapter().getGroupId(groupPosition);
switch (item.getItemId()) {
case Id.menu.update:
long updateKeyId = 0;
PGPPublicKeyRing updateKeyRing = ProviderHelper.getPGPPublicKeyRingByRowId(
mKeyListActivity, keyRingRowId);
if (updateKeyRing != null) {
updateKeyId = PgpHelper.getMasterKey(updateKeyRing).getKeyID();
}
if (updateKeyId == 0) {
return true;
}
Intent queryIntent = new Intent(mKeyListActivity, KeyServerQueryActivity.class);
queryIntent.setAction(KeyServerQueryActivity.ACTION_LOOK_UP_KEY_ID_AND_RETURN);
queryIntent.putExtra(KeyServerQueryActivity.EXTRA_KEY_ID, updateKeyId);
startActivityForResult(queryIntent, Id.request.look_up_key_id);
return true;
case Id.menu.exportToServer:
Intent uploadIntent = new Intent(mKeyListActivity, KeyServerUploadActivity.class);
uploadIntent.setAction(KeyServerUploadActivity.ACTION_EXPORT_KEY_TO_SERVER);
uploadIntent.putExtra(KeyServerUploadActivity.EXTRA_KEYRING_ROW_ID, (int)keyRingRowId);
startActivityForResult(uploadIntent, Id.request.export_to_server);
return true;
case Id.menu.signKey:
long keyId = 0;
PGPPublicKeyRing signKeyRing = ProviderHelper.getPGPPublicKeyRingByRowId(
mKeyListActivity, keyRingRowId);
if (signKeyRing != null) {
keyId = PgpHelper.getMasterKey(signKeyRing).getKeyID();
}
if (keyId == 0) {
return true;
}
Intent signIntent = new Intent(mKeyListActivity, SignKeyActivity.class);
signIntent.putExtra(SignKeyActivity.EXTRA_KEY_ID, keyId);
startActivity(signIntent);
return true;
case Id.menu.share_qr_code:
long masterKeyId = ProviderHelper.getPublicMasterKeyId(mKeyListActivity, keyRingRowId);
Intent qrCodeIntent = new Intent(mKeyListActivity, ShareActivity.class);
qrCodeIntent.setAction(ShareActivity.ACTION_SHARE_KEYRING_WITH_QR_CODE);
qrCodeIntent.putExtra(ShareActivity.EXTRA_MASTER_KEY_ID, masterKeyId);
startActivityForResult(qrCodeIntent, 0);
return true;
case Id.menu.share_nfc:
long masterKeyId2 = ProviderHelper.getPublicMasterKeyId(mKeyListActivity, keyRingRowId);
Intent nfcIntent = new Intent(mKeyListActivity, ShareNfcBeamActivity.class);
nfcIntent.setAction(ShareNfcBeamActivity.ACTION_SHARE_KEYRING_WITH_NFC);
nfcIntent.putExtra(ShareNfcBeamActivity.EXTRA_MASTER_KEY_ID, masterKeyId2);
startActivityForResult(nfcIntent, 0);
return true;
case Id.menu.share:
long masterKeyId3 = ProviderHelper.getPublicMasterKeyId(mKeyListActivity, keyRingRowId);
Intent shareIntent = new Intent(mKeyListActivity, ShareActivity.class);
shareIntent.setAction(ShareActivity.ACTION_SHARE_KEYRING);
shareIntent.putExtra(ShareActivity.EXTRA_MASTER_KEY_ID, masterKeyId3);
startActivityForResult(shareIntent, 0);
return true;
default:
return super.onContextItemSelected(item);
}
}
|
protected void fire(Unit unit, Map map) {
Bullet bullet = new Bullet();
bullet.setDamageToDeal(unit.getUnitType().getAttackDamage());
bullet.setStartX(unit.getX());
bullet.setStartY(unit.getY());
bullet.setGoalX(target.getPoint().getX());
bullet.setGoalY(target.getPoint().getY());
if (unit.getUnitType() == UnitType.LAUNCHER) {
switch (new Random().nextInt(20)) {
case 0:
bullet.setGoalX(unit.getX()+1);
bullet.setGoalY(unit.getY());
break;
case 1:
bullet.setGoalX(unit.getX()-1);
bullet.setGoalY(unit.getY());
break;
case 2:
bullet.setGoalX(unit.getX());
bullet.setGoalY(unit.getY()+1);
break;
case 3:
bullet.setGoalX(unit.getX());
bullet.setGoalY(unit.getY()-1);
break;
case 4:
bullet.setGoalX(unit.getX()-1);
bullet.setGoalY(unit.getY()-1);
break;
case 5:
bullet.setGoalX(unit.getX()+1);
bullet.setGoalY(unit.getY()-1);
break;
case 6:
bullet.setGoalX(unit.getX()-1);
bullet.setGoalY(unit.getY()+1);
break;
case 7:
bullet.setGoalX(unit.getX()+1);
bullet.setGoalY(unit.getY()+1);
break;
}
}
int bulletTicksToMove = (int) Math.round(unit.getUnitType().getBulletSpeed() * Map.getDistanceBetween(unit.getPoint(), target.getPoint()));
bullet.setTicksToMove(bulletTicksToMove);
bullet.setTicksToMoveTotal(bulletTicksToMove);
bullet.setBulletType(BulletType.TANK_SHOT);
map.addBullet(bullet);
unit.setTicksReloading(unit.getUnitType().getTicksToAttack());
}
|
protected void fire(Unit unit, Map map) {
Bullet bullet = new Bullet();
bullet.setDamageToDeal(unit.getUnitType().getAttackDamage());
bullet.setStartX(unit.getX());
bullet.setStartY(unit.getY());
bullet.setGoalX(target.getPoint().getX());
bullet.setGoalY(target.getPoint().getY());
if (unit.getUnitType() == UnitType.LAUNCHER) {
switch (new Random().nextInt(20)) {
case 0:
bullet.setGoalX(target.getPoint().getX()+1);
bullet.setGoalY(target.getPoint().getY());
break;
case 1:
bullet.setGoalX(target.getPoint().getX()-1);
bullet.setGoalY(target.getPoint().getY());
break;
case 2:
bullet.setGoalX(target.getPoint().getX());
bullet.setGoalY(target.getPoint().getY()+1);
break;
case 3:
bullet.setGoalX(target.getPoint().getX());
bullet.setGoalY(target.getPoint().getY()-1);
break;
case 4:
bullet.setGoalX(target.getPoint().getX()-1);
bullet.setGoalY(target.getPoint().getY()-1);
break;
case 5:
bullet.setGoalX(target.getPoint().getX()+1);
bullet.setGoalY(target.getPoint().getY()-1);
break;
case 6:
bullet.setGoalX(target.getPoint().getX()-1);
bullet.setGoalY(target.getPoint().getY()+1);
break;
case 7:
bullet.setGoalX(target.getPoint().getX()+1);
bullet.setGoalY(target.getPoint().getY()+1);
break;
}
}
int bulletTicksToMove = (int) Math.round(unit.getUnitType().getBulletSpeed() * Map.getDistanceBetween(unit.getPoint(), target.getPoint()));
bullet.setTicksToMove(bulletTicksToMove);
bullet.setTicksToMoveTotal(bulletTicksToMove);
bullet.setBulletType(BulletType.TANK_SHOT);
map.addBullet(bullet);
unit.setTicksReloading(unit.getUnitType().getTicksToAttack());
}
|
public void onClose() {
getPlayer().getMainScreen().removeWidget(this);
getPlayer().closeActiveWindow();
}
|
public void onClose() {
getScreen().removeWidget(this);
getScreen().getPlayer().closeActiveWindow();
}
|
public static void main(String[] args) throws Exception
{
GetOpt opts = new GetOpt();
opts.addBoolean('l', "lcm", false, "use lcm for input (log)");
opts.addBoolean('r', "reader", true, "use imageReader for input (direct)");
opts.addString('c', "camera", "0", "camera to use for input (index if lcm, url if using imageReader)");
if (!opts.parse(args))
{
System.out.println("option error: " + opts.getReason());
}
if (opts.getBoolean("help"))
{
System.out.println("Usage: displays images from camera specified");
opts.doHelp();
System.exit(1);
}
if(opts.getBoolean("lcm"))
{
new CameraExample(Integer.parseInt(opts.getString("camera")));
}
if(opts.getBoolean("reader"))
{
new CameraExample(opts.getString("camera"));
}
}
|
public static void main(String[] args) throws Exception
{
GetOpt opts = new GetOpt();
opts.addBoolean('h', "help", false, "see this help screen");
opts.addBoolean('l', "lcm", false, "use lcm for input (log)");
opts.addBoolean('r', "reader", true, "use imageReader for input (direct)");
opts.addString('c', "camera", "0", "camera to use for input (index if lcm, url if using imageReader)");
if (!opts.parse(args))
{
System.out.println("option error: " + opts.getReason());
}
if (opts.getBoolean("help"))
{
System.out.println("Usage: displays images from camera specified");
opts.doHelp();
System.exit(1);
}
if(opts.getBoolean("lcm"))
{
new CameraExample(Integer.parseInt(opts.getString("camera")));
}
if(opts.getBoolean("reader"))
{
new CameraExample(opts.getString("camera"));
}
}
|
public void activityTest() throws InterruptedException {
NewBoardImpl newBoard = new NewBoardImpl(UUID.randomUUID().toString(), BoardCategory.CARS_MOTORCYCLES);
Board createdBoard = pinterest1.createBoard(newBoard);
Board createdBoard2 = pinterest2.createBoard(newBoard);
String newDescription = UUID.randomUUID().toString();
double newPrice = 10;
NewPinImpl newPin = new NewPinImpl(newDescription, newPrice, webLink, imageLink, null);
Pin createdPin = pinterest1.addPin(createdBoard, newPin);
Pin createdPin2 = pinterest2.addPin(createdBoard2, newPin);
int waitPeriod = 2000;
Thread.sleep(waitPeriod);
Pin repinedPin = pinterest1.repin(createdPin2, createdBoard, UUID.randomUUID().toString());
Thread.sleep(waitPeriod);
pinterest1.likePin(createdPin);
Thread.sleep(waitPeriod);
String comment = UUID.randomUUID().toString();
pinterest1.addComment(createdPin2, comment);
Thread.sleep(waitPeriod);
pinterest1.unfollowUser(pinterest2.getUser());
pinterest1.followUser(pinterest2.getUser());
Thread.sleep(waitPeriod);
pinterest1.followBoard(createdBoard2);
Thread.sleep(waitPeriod);
Map<ActivityType, Activity> activityMap = new HashMap<ActivityType, Activity>();
for(Activity activity : pinterest1.getUser().getActivity()) {
activityMap.put(activity.getActivityType(), activity);
}
assertEquals(createdBoard2, ((FollowBoardActivity)activityMap.get(ActivityType.FOLLOW_BOARD)).getBoard());
assertEquals(pinterest2.getUser(), ((FollowUserActivity)activityMap.get(ActivityType.FOLLOW_USER)).getUser());
assertEquals(createdPin2, ((CommentActivity)activityMap.get(ActivityType.COMMENT)).getPin());
assertEquals(comment, ((CommentActivity)activityMap.get(ActivityType.COMMENT)).getCommentMessage());
assertEquals(createdPin, ((PinActivity)activityMap.get(ActivityType.LIKE)).getPin());
assertEquals(repinedPin, ((PinActivity)activityMap.get(ActivityType.REPIN)).getPin());
assertEquals(createdPin, ((PinActivity)activityMap.get(ActivityType.PIN)).getPin());
assertEquals(createdBoard, ((CreateBoardActivity)activityMap.get(ActivityType.CREATE_BOARD)).getBoard());
pinterest1.deleteBoard(createdBoard);
pinterest2.deleteBoard(createdBoard2);
}
|
public void activityTest() throws InterruptedException {
NewBoardImpl newBoard = new NewBoardImpl(UUID.randomUUID().toString(), BoardCategory.CARS_MOTORCYCLES);
Board createdBoard = pinterest1.createBoard(newBoard);
Board createdBoard2 = pinterest2.createBoard(newBoard);
String newDescription = UUID.randomUUID().toString();
double newPrice = 10;
NewPinImpl newPin = new NewPinImpl(newDescription, newPrice, webLink, imageLink, null);
Pin createdPin = pinterest1.addPin(createdBoard, newPin);
Pin createdPin2 = pinterest2.addPin(createdBoard2, newPin);
int waitPeriod = 2000;
Thread.sleep(waitPeriod);
String comment = UUID.randomUUID().toString();
pinterest1.addComment(createdPin2, comment);
Thread.sleep(waitPeriod);
Pin repinedPin = pinterest1.repin(createdPin2, createdBoard, UUID.randomUUID().toString());
Thread.sleep(waitPeriod);
pinterest1.likePin(createdPin);
Thread.sleep(waitPeriod);
pinterest1.unfollowUser(pinterest2.getUser());
pinterest1.followUser(pinterest2.getUser());
Thread.sleep(waitPeriod);
pinterest1.followBoard(createdBoard2);
Thread.sleep(waitPeriod);
Map<ActivityType, Activity> activityMap = new HashMap<ActivityType, Activity>();
for(Activity activity : pinterest1.getUser().getActivity()) {
activityMap.put(activity.getActivityType(), activity);
}
assertEquals(createdBoard2, ((FollowBoardActivity)activityMap.get(ActivityType.FOLLOW_BOARD)).getBoard());
assertEquals(pinterest2.getUser(), ((FollowUserActivity)activityMap.get(ActivityType.FOLLOW_USER)).getUser());
assertEquals(createdPin2, ((CommentActivity)activityMap.get(ActivityType.COMMENT)).getPin());
assertEquals(comment, ((CommentActivity)activityMap.get(ActivityType.COMMENT)).getCommentMessage());
assertEquals(createdPin, ((PinActivity)activityMap.get(ActivityType.LIKE)).getPin());
assertEquals(repinedPin, ((PinActivity)activityMap.get(ActivityType.REPIN)).getPin());
assertEquals(createdPin, ((PinActivity)activityMap.get(ActivityType.PIN)).getPin());
assertEquals(createdBoard, ((CreateBoardActivity)activityMap.get(ActivityType.CREATE_BOARD)).getBoard());
pinterest1.deleteBoard(createdBoard);
pinterest2.deleteBoard(createdBoard2);
}
|
private static Record getRecord(String baseformat, int listenCount,
int months) throws SQLException {
System.err.println("Getting: " + baseformat + " and " + listenCount
+ " and " + months);
String cd_extra = "AND riploc IS NOT NULL";
int min_score = 5;
if (months > 3)
min_score = 7;
if (!baseformat.equalsIgnoreCase("cd"))
cd_extra = "";
String sql = "SELECT recordnumber from formats,records LEFT JOIN score_table ON recordnumber = record_id WHERE format = formatnumber "
+ cd_extra
+ " AND baseformat = ? AND simon_rank_count = ? AND simon_score_date < 'today'::date - "
+ months
+ "*'1 month'::interval AND simon_score > "
+ min_score + " ORDER BY boughtdate ASC LIMIT 1";
PreparedStatement ps = Connect.getConnection()
.getPreparedStatement(sql);
ps.setString(1, baseformat);
ps.setInt(2, listenCount);
ResultSet rs = Connect.getConnection().executeQuery(ps);
if (rs.next())
return GetRecords.create().getRecord(rs.getInt(1));
return null;
}
|
private static Record getRecord(String baseformat, int listenCount,
int months) throws SQLException {
System.err.println("Getting: " + baseformat + " and " + listenCount
+ " and " + months);
String cd_extra = "AND riploc IS NOT NULL";
int min_score = 5;
if (months > 3)
min_score = 7;
if (!baseformat.equalsIgnoreCase("cd"))
cd_extra = "";
String sql = "SELECT recordnumber from formats,records LEFT JOIN score_table ON recordnumber = record_id WHERE format = formatnumber "
+ cd_extra
+ " AND baseformat = ? AND simon_rank_count = ? AND simon_score_date < 'today'::date - "
+ months
+ "*'1 month'::interval AND simon_score > "
+ min_score
+ " AND salepricepence < 0 ORDER BY boughtdate ASC LIMIT 1";
PreparedStatement ps = Connect.getConnection()
.getPreparedStatement(sql);
ps.setString(1, baseformat);
ps.setInt(2, listenCount);
ResultSet rs = Connect.getConnection().executeQuery(ps);
if (rs.next())
return GetRecords.create().getRecord(rs.getInt(1));
return null;
}
|
public String text(Value value) {
if (value.getObjectValue() != null) {
for (ObjectProperty prop : value.getObjectValue().getProperties()) {
Value propValue = prop.getPropValue();
if (propValue != null) {
String stringValue = propValue.getStringValue();
if (stringValue != null) {
if ("name".equalsIgnoreCase(prop.getPropName())) {
return prop.getPropName() + ": " + stringValue;
} else if ("id".equalsIgnoreCase(prop.getPropName())) {
return prop.getPropName() + ": " + stringValue;
}
}
}
}
for (ObjectProperty prop : value.getObjectValue().getProperties()) {
if (prop.getPropValue() != null && prop.getPropValue().getStringValue() != null) {
return prop.getPropValue() + ": " + prop.getPropValue().getStringValue();
}
}
return "Object";
} else if (value.getArrayValue() != null) {
return "Array";
} else {
return null;
}
}
|
public String text(Value value) {
if (value.getObjectValue() != null) {
for (ObjectProperty prop : value.getObjectValue().getProperties()) {
Value propValue = prop.getPropValue();
if (propValue != null) {
String stringValue = propValue.getStringValue();
if (stringValue != null) {
if ("name".equalsIgnoreCase(prop.getPropName())) {
return prop.getPropName() + ": " + stringValue;
} else if ("id".equalsIgnoreCase(prop.getPropName())) {
return prop.getPropName() + ": " + stringValue;
}
}
}
}
for (ObjectProperty prop : value.getObjectValue().getProperties()) {
if (prop.getPropValue() != null && prop.getPropValue().getStringValue() != null) {
return prop.getPropName() + ": " + prop.getPropValue().getStringValue();
}
}
return "Object";
} else if (value.getArrayValue() != null) {
return "Array";
} else {
return null;
}
}
|
public void startSource() {
String pipeline = "ximagesrc use-damage=false remote=false ! video/x-raw-rgb,framerate=" + frameRate + "/1 ! ffmpegcolorspace ! videoscale ! video/x-raw-rgb,width=" + captureWidth + ",height=" + captureHeight + ",bpp=32,depth=24, red_mask=65280, green_mask=16711680, blue_mask=-16777216,endianness=4321 ! ffmpegcolorspace name=tosink";
pipe = Pipeline.launch(pipeline);
sink = new RGBDataSink("desktopsink", this);
Element end = pipe.getElementByName("tosink");
pipe.add(sink);
end.link(sink);
pipe.getBus().connect(new Bus.EOS() {
@Override
public void endOfStream(GstObject arg0) {
pipe.stop();
}
});
pipe.getBus().connect(new Bus.ERROR() {
@Override
public void errorMessage(GstObject arg0, int arg1, String arg2) {
error(name + " Error: " + arg0 + "," + arg1 + ", " + arg2);
stopSource();
}
});
pipe.play();
}
|
public void startSource() {
String pipeline = "ximagesrc use-damage=false remote=false ! video/x-raw-rgb,framerate=" + frameRate + "/1 ! ffmpegcolorspace ! videoscale method=2 ! video/x-raw-rgb,width=" + outputWidth + ",height=" + outputHeight + ",bpp=32,depth=24, red_mask=65280, green_mask=16711680, blue_mask=-16777216,endianness=4321 ! ffmpegcolorspace name=tosink";
pipe = Pipeline.launch(pipeline);
sink = new RGBDataSink("desktopsink", this);
Element end = pipe.getElementByName("tosink");
pipe.add(sink);
end.link(sink);
pipe.getBus().connect(new Bus.EOS() {
@Override
public void endOfStream(GstObject arg0) {
pipe.stop();
}
});
pipe.getBus().connect(new Bus.ERROR() {
@Override
public void errorMessage(GstObject arg0, int arg1, String arg2) {
error(name + " Error: " + arg0 + "," + arg1 + ", " + arg2);
stopSource();
}
});
pipe.play();
}
|
public static List<World> intellWorld(String input, World currWorld){
List<World> matches = new ArrayList<World>();
input = input.toLowerCase();
if (input.equals("nether") || input.equals("thenether") || input.equals("the_nether")
|| input.equals("end") || input.equals("theend") || input.equals("the_end")
|| input.equals("overworld") || input.equals("theoverworld") || input.equals("the_overworld")){
String cWorld = currWorld.getName();
String wBase = cWorld.split(":")[0];
String toWorld = null;
if (input.contains("nether")){
toWorld = wBase + "_nether";
}
if (input.contains("end")){
toWorld = wBase + "_the_end";
}
if (input.contains("overworld")){
toWorld = wBase;
}
World toSend = Bukkit.getWorld(toWorld);
if (toSend != null){
matches.add(toSend);
}
}
if (matches.size() == 0){
matches = world(input);
}
return matches;
}
|
public static List<World> intellWorld(String input, World currWorld){
List<World> matches = new ArrayList<World>();
input = input.toLowerCase();
if (input.equals("nether") || input.equals("thenether") || input.equals("the_nether")
|| input.equals("end") || input.equals("theend") || input.equals("the_end")
|| input.equals("overworld") || input.equals("theoverworld") || input.equals("the_overworld")){
String cWorld = currWorld.getName();
String wBase = cWorld.split("_")[0];
String toWorld = null;
if (input.contains("nether")){
toWorld = wBase + "_nether";
}
if (input.contains("end")){
toWorld = wBase + "_the_end";
}
if (input.contains("overworld")){
toWorld = wBase;
}
World toSend = Bukkit.getWorld(toWorld);
if (toSend != null){
matches.add(toSend);
}
}
if (matches.size() == 0){
matches = world(input);
}
return matches;
}
|
public void displayLastType(final String type)
{
fxInfo.removeAllRows();
if(type.equals("ring"))
{
fxInfo.setText(0, 0, Rcbu.constants.phoneIsRinging());
return;
}
if(type.equals("lock"))
{
final TextBox tbPass = new TextBox();
final Button btnPass = new Button(Rcbu.constants.setPassword());
fxInfo.setText(0,0,Rcbu.constants.toLockYourPhone());
fxInfo.setText(1, 0, Rcbu.constants.password());
fxInfo.setWidget(1, 1, tbPass);
fxInfo.setWidget(2, 0, btnPass);
fxInfo.getFlexCellFormatter().setColSpan(0, 0, 2);
fxInfo.getFlexCellFormatter().setColSpan(2, 0, 2);
btnPass.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(Window.confirm(Rcbu.constants.areYouSure()))
sendMessage(type+tbPass.getText());
}
});
return;
}
fxInfo.setText(0, 0, Rcbu.constants.loadingData());
((TransformDataAsync) GWT.create(TransformData.class)).getLastTypeForCurrentRegUser(type, new AsyncCallback<DataTransfer>() {
@Override
public void onSuccess(DataTransfer result) {
Button btnRefresh = new Button(Rcbu.constants.sendNotifToRefresh());
btnRefresh.addClickHandler(new ClickHandler() {
@Override public void onClick(ClickEvent event) {
sendMessage(type);
}
});
fxInfo.setWidget(0, 0, btnRefresh);
fxInfo.getFlexCellFormatter().setColSpan(0, 0, 2);
if(result==null)
{
fxInfo.setText(1, 0, Rcbu.constants.notDataFound());
fxInfo.getFlexCellFormatter().setColSpan(1, 0, 2);
return;
}
final HashMap<String,String> map=result.getData();
int i=1;
if(map==null)
return;
for (String key : map.keySet()) {
fxInfo.setText(i, 0, key);
fxInfo.setText(i, 1, map.get(key));
i++;
}
if(result.getType().equals("GEOLOC")&&i>0)
{
String ApiKey = "ABQIAAAAXpEB7Go1TVzVyQBm4VXr7BT2E6_VxY2Ak13-OcHSQevEFnxe1xRmwlx8Scb6CVGYiwOvPWgNQh_eoA";
if(Window.Location.getProtocol().startsWith("https"))
ApiKey="ABQIAAAAYXiByvugTLk9egeRM901lxTTqgRoTvkyqtnpNyMv68yzun4bLBRWHuXHxezjMlB74rbct142iIaMIg";
Maps.loadMapsApi(ApiKey, "2", false, new Runnable() {@Override public void run() {
LatLng lat = LatLng.newInstance(Double.valueOf(map.get("lat")), Double.valueOf(map.get("long")));
MapWidget gmap=new MapWidget(lat,15);
gmap.setStyleName("gmap");
gmap.addOverlay(new Marker(lat));
gmap.getInfoWindow().open(lat,new InfoWindowContent(Rcbu.constants.lastKnownPosition()));
gmap.addControl(new LargeMapControl());
gmap.setSize("400px", "300px");
fxInfo.setWidget(0, 3, gmap);
fxInfo.getFlexCellFormatter().setRowSpan(0, 3, map.size()+2);
}});
}
}
@Override
public void onFailure(Throwable caught) {}
});
}
|
public void displayLastType(final String type)
{
fxInfo.removeAllRows();
if(type.equals("ring"))
{
fxInfo.setText(0, 0, Rcbu.constants.phoneIsRinging());
return;
}
if(type.equals("lock"))
{
final TextBox tbPass = new TextBox();
final Button btnPass = new Button(Rcbu.constants.setPassword());
fxInfo.setText(0,0,Rcbu.constants.toLockYourPhone());
fxInfo.setText(1, 0, Rcbu.constants.password());
fxInfo.setWidget(1, 1, tbPass);
fxInfo.setWidget(2, 0, btnPass);
fxInfo.getFlexCellFormatter().setColSpan(0, 0, 2);
fxInfo.getFlexCellFormatter().setColSpan(2, 0, 2);
btnPass.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(Window.confirm(Rcbu.constants.areYouSure()))
sendMessage(type+tbPass.getText());
}
});
return;
}
fxInfo.setText(0, 0, Rcbu.constants.loadingData());
((TransformDataAsync) GWT.create(TransformData.class)).getLastTypeForCurrentRegUser(type, new AsyncCallback<DataTransfer>() {
@Override
public void onSuccess(DataTransfer result) {
Button btnRefresh = new Button(Rcbu.constants.sendNotifToRefresh());
btnRefresh.addClickHandler(new ClickHandler() {
@Override public void onClick(ClickEvent event) {
sendMessage(type);
}
});
fxInfo.setWidget(0, 0, btnRefresh);
fxInfo.getFlexCellFormatter().setColSpan(0, 0, 2);
if(result==null)
{
fxInfo.setText(1, 0, Rcbu.constants.notDataFound());
fxInfo.getFlexCellFormatter().setColSpan(1, 0, 2);
return;
}
final HashMap<String,String> map=result.getData();
int i=1;
if(map==null)
return;
for (String key : map.keySet()) {
fxInfo.setText(i, 0, key);
fxInfo.setText(i, 1, map.get(key));
i++;
}
if(result.getType().toUpperCase().equals("GEOLOC")&&i>0)
{
String ApiKey = "ABQIAAAAXpEB7Go1TVzVyQBm4VXr7BT2E6_VxY2Ak13-OcHSQevEFnxe1xRmwlx8Scb6CVGYiwOvPWgNQh_eoA";
if(Window.Location.getProtocol().startsWith("https"))
ApiKey="ABQIAAAAYXiByvugTLk9egeRM901lxTTqgRoTvkyqtnpNyMv68yzun4bLBRWHuXHxezjMlB74rbct142iIaMIg";
Maps.loadMapsApi(ApiKey, "2", false, new Runnable() {@Override public void run() {
LatLng lat = LatLng.newInstance(Double.valueOf(map.get("lat")), Double.valueOf(map.get("long")));
MapWidget gmap=new MapWidget(lat,15);
gmap.setStyleName("gmap");
gmap.addOverlay(new Marker(lat));
gmap.getInfoWindow().open(lat,new InfoWindowContent(Rcbu.constants.lastKnownPosition()));
gmap.addControl(new LargeMapControl());
gmap.setSize("400px", "300px");
fxInfo.setWidget(0, 3, gmap);
fxInfo.getFlexCellFormatter().setRowSpan(0, 3, map.size()+2);
}});
}
}
@Override
public void onFailure(Throwable caught) {}
});
}
|
protected IModelElement getSourceElementAtTop(int position)
throws ModelException {
if (this instanceof ISourceReference) {
IModelElement[] children = getChildren();
for (int i = children.length - 1; i >= 0; i--) {
IModelElement aChild = children[i];
if (aChild instanceof SourceRefElement) {
SourceRefElement child = (SourceRefElement) children[i];
ISourceRange range = child.getSourceRange();
int start = range.getOffset();
int end = start + range.getLength();
if (start <= position && position <= end) {
if (child instanceof IField) {
int declarationStart = start;
SourceRefElement candidate = null;
do {
range = ((IField) child).getNameRange();
if (position <= range.getOffset()
+ range.getLength()) {
candidate = child;
} else {
return candidate == null ? child
.getSourceElementAt(position)
: candidate
.getSourceElementAt(position);
}
child = --i >= 0 ? (SourceRefElement) children[i]
: null;
} while (child != null
&& child.getSourceRange().getOffset() == declarationStart);
return candidate.getSourceElementAt(position);
} else if (child instanceof IParent) {
return child.getSourceElementAt(position);
} else {
return child;
}
}
}
}
} else {
Assert.isTrue(false);
}
return this;
}
|
protected IModelElement getSourceElementAtTop(int position)
throws ModelException {
if (this instanceof ISourceReference) {
IModelElement[] children = getChildren();
for (int i = children.length - 1; i >= 0; i--) {
IModelElement aChild = children[i];
if (aChild instanceof SourceRefElement) {
SourceRefElement child = (SourceRefElement) children[i];
ISourceRange range = child.getSourceRange();
int start = range.getOffset();
int end = start + range.getLength();
if (start <= position && position <= end) {
if (child instanceof IField) {
int declarationStart = start;
SourceRefElement candidate = null;
do {
range = ((IField) child).getNameRange();
if (position <= range.getOffset()
+ range.getLength()) {
candidate = child;
} else {
return candidate == null ? child
.getSourceElementAt(position)
: candidate
.getSourceElementAt(position);
}
child = --i >= 0 ? (SourceRefElement) children[i]
: null;
} while (child instanceof IField
&& child.getSourceRange().getOffset() == declarationStart);
return candidate.getSourceElementAt(position);
} else if (child instanceof IParent) {
return child.getSourceElementAt(position);
} else {
return child;
}
}
}
}
} else {
Assert.isTrue(false);
}
return this;
}
|
protected ModuleSpec findModule(ModuleIdentifier moduleIdentifier) throws ModuleLoadException {
try {
File moduleFile = repository.getArtifact(moduleIdentifier.getName(), moduleIdentifier.getSlot());
if (moduleFile == null)
return null;
Module module = readModule(moduleIdentifier, moduleFile);
if (module == null)
throw new ModuleLoadException("No module descriptor in module: " + moduleFile);
final List<DependencySpec> deps = new ArrayList<DependencySpec>();
ModuleSpec.Builder builder = ModuleSpec.build(moduleIdentifier);
ResourceLoader resourceLoader = ResourceLoaderProvider.getResourceLoader(moduleIdentifier, repository, moduleFile);
ResourceLoaderSpec rls = ResourceLoaderSpec.createResourceLoaderSpec(resourceLoader, PathFilters.acceptAll());
builder.addResourceRoot(rls);
Graph.Vertex<ModuleIdentifier, Boolean> vertex = graph.createVertex(moduleIdentifier, moduleIdentifier);
DependencySpec lds = DependencySpec.createLocalDependencySpec();
builder.addDependency(lds);
deps.add(lds);
Iterable<? extends Import> imports = CeylonToJava.toIterable(module.getDependencies());
if (imports != null) {
Node<Import> root = new Node<Import>();
for (Import i : imports) {
if (i.getOptional()) {
String path = CeylonToJava.toString(i.getName());
Node<Import> current = root;
String[] tokens = path.split("\\.");
for (String token : tokens) {
Node<Import> child = current.getChild(token);
if (child == null)
child = current.addChild(token);
current = child;
}
current.setValue(i);
} else {
DependencySpec mds = createModuleDependency(i);
builder.addDependency(mds);
deps.add(mds);
}
ModuleIdentifier mi = createModuleIdentifier(i);
Graph.Vertex<ModuleIdentifier, Boolean> dv = graph.createVertex(mi, mi);
Graph.Edge.create(false, vertex, dv);
}
if (root.isEmpty() == false) {
LocalLoader onDemandLoader = new OnDemandLocalLoader(moduleIdentifier, this, root);
builder.setFallbackLoader(onDemandLoader);
}
}
createModuleDependency(vertex, deps, builder, LANGUAGE);
final DependencySpec sds = DependencySpec.createModuleDependencySpec(
PathFilters.match(CEYLON_RUNTIME_PATH),
PathFilters.rejectAll(),
this,
RUNTIME,
false
);
builder.addDependency(sds);
deps.add(sds);
dependencies.put(moduleIdentifier, deps);
return builder.create();
} catch (ModuleLoadException mle) {
throw mle;
} catch (Exception e) {
throw new ModuleLoadException(e);
}
}
|
protected ModuleSpec findModule(ModuleIdentifier moduleIdentifier) throws ModuleLoadException {
try {
File moduleFile = repository.getArtifact(moduleIdentifier.getName(), moduleIdentifier.getSlot());
if (moduleFile == null)
return null;
Module module = readModule(moduleIdentifier, moduleFile);
if (module == null)
throw new ModuleLoadException("No module descriptor in module: " + moduleFile);
final List<DependencySpec> deps = new ArrayList<DependencySpec>();
ModuleSpec.Builder builder = ModuleSpec.build(moduleIdentifier);
ResourceLoader resourceLoader = ResourceLoaderProvider.getResourceLoader(moduleIdentifier, repository, moduleFile);
ResourceLoaderSpec rls = ResourceLoaderSpec.createResourceLoaderSpec(resourceLoader, PathFilters.acceptAll());
builder.addResourceRoot(rls);
Graph.Vertex<ModuleIdentifier, Boolean> vertex = graph.createVertex(moduleIdentifier, moduleIdentifier);
DependencySpec lds = DependencySpec.createLocalDependencySpec();
builder.addDependency(lds);
deps.add(lds);
Iterable<? extends Import> imports = CeylonToJava.toIterable(module.getDependencies());
if (imports != null) {
Node<Import> root = new Node<Import>();
for (Import i : imports) {
if (i.getOptional()) {
String path = CeylonToJava.toString(i.getName());
Node<Import> current = root;
String[] tokens = path.split("\\.");
for (String token : tokens) {
Node<Import> child = current.getChild(token);
if (child == null)
child = current.addChild(token);
current = child;
}
current.setValue(i);
} else {
DependencySpec mds = createModuleDependency(i);
builder.addDependency(mds);
deps.add(mds);
}
ModuleIdentifier mi = createModuleIdentifier(i);
Graph.Vertex<ModuleIdentifier, Boolean> dv = graph.createVertex(mi, mi);
Graph.Edge.create(i.getExport(), vertex, dv);
}
if (root.isEmpty() == false) {
LocalLoader onDemandLoader = new OnDemandLocalLoader(moduleIdentifier, this, root);
builder.setFallbackLoader(onDemandLoader);
}
}
createModuleDependency(vertex, deps, builder, LANGUAGE);
final DependencySpec sds = DependencySpec.createModuleDependencySpec(
PathFilters.match(CEYLON_RUNTIME_PATH),
PathFilters.rejectAll(),
this,
RUNTIME,
false
);
builder.addDependency(sds);
deps.add(sds);
dependencies.put(moduleIdentifier, deps);
return builder.create();
} catch (ModuleLoadException mle) {
throw mle;
} catch (Exception e) {
throw new ModuleLoadException(e);
}
}
|
protected void updateCommand(InCommand command) {
if (!(command instanceof MessageCommand)) {
return;
}
MessageCommand msgc = (MessageCommand) command;
if (msgc.isPrivateToUs(_listener.getIRCConnection().getClientState())) {
return;
}
ReplacerEnvironment env = new ReplacerEnvironment(SiteBot.GLOBAL_ENV);
env.add("botnick",_listener.getIRCConnection().getClientState().getNick().getNick());
env.add("ircnick", msgc.getSource().getNick());
String msg = msgc.getMessage().trim();
if (msg.startsWith(_listener.getCommandPrefix() + "rank")) {
User user;
try {
user = _listener.getIRCConfig().lookupUser(msgc.getSource());
} catch (NoSuchUserException e) {
_listener.sayChannel(msgc.getDest(),
ReplacerUtils.jprintf("ident.noident", env, SiteBot.class));
return;
}
env.add("ftpuser",user.getName());
if (!_listener.getIRCConfig().checkIrcPermission(_listener.getCommandPrefix() + "rank",user)) {
_listener.sayChannel(msgc.getDest(),
ReplacerUtils.jprintf("ident.denymsg", env, SiteBot.class));
return;
}
String lookupuser;
try {
lookupuser = msgc.getMessage().substring((_listener.getCommandPrefix() + "rank ").length());
} catch (ArrayIndexOutOfBoundsException e) {
lookupuser = user.getName();
} catch (StringIndexOutOfBoundsException e) {
lookupuser = user.getName();
}
String exemptgroups = ReplacerUtils.jprintf("top.exempt", env,
Rank.class);
try {
User luser = getConnectionManager().getGlobalContext().getUserManager()
.getUserByName(lookupuser);
StringTokenizer st = new StringTokenizer(exemptgroups, " ");
while (st.hasMoreTokens()) {
if (luser.isMemberOf(st.nextToken())) {
env.add("eusr", luser.getName());
env.add("egrp", luser.getGroup());
_listener.sayChannel(msgc.getDest(), ReplacerUtils
.jprintf("exempt", env, Rank.class));
return;
}
}
} catch (NoSuchUserException e2) {
_listener.sayChannel(msgc.getDest(), "Not a valid username");
return;
} catch (UserFileException e2) {
_listener.sayChannel(msgc.getDest(), "Error opening user file");
return;
}
Collection<User> users = null;
try {
users = getConnectionManager().getGlobalContext().getUserManager().getAllUsers();
} catch (UserFileException e) {
getConnection().sendCommand(
new MessageCommand(msgc.getDest(),
"Error processing userfiles"));
return;
}
String type = "MONTHUP";
ArrayList<User> users2 = new ArrayList<User>(users);
Collections.sort(users2, new UserComparator(type));
int i = 0;
int msgtype = 1;
User user1 = null;
User user2 = null;
for (Iterator iter = users.iterator(); iter.hasNext();) {
user1 = (User) iter.next();
i = i + 1;
env.add("ppos", "" + i);
env.add("puser", user1.getName());
env.add("pmnup", Bytes.formatBytes(user1
.getUploadedBytesMonth()));
env.add("pupfilesmonth", "" + user1.getUploadedFilesMonth());
env.add("pmnrateup", TransferStatistics.getUpRate(user1,
Trial.PERIOD_MONTHLY));
env.add("pgroup", user1.getGroup());
StringTokenizer st2 = new StringTokenizer(exemptgroups, " ");
while (st2.hasMoreTokens()) {
if (user1.isMemberOf(st2.nextToken())) {
i = i - 1;
break;
}
}
if (user1.getName().equals(lookupuser)) {
break;
} else
msgtype = 2;
user2 = (User) iter.next();
i = i + 1;
env.add("pos", "" + i);
env.add("user", user2.getName());
env.add("mnup", Bytes
.formatBytes(user2.getUploadedBytesMonth()));
env.add("upfilesmonth", "" + user2.getUploadedFilesMonth());
env.add("mnrateup", TransferStatistics.getUpRate(user2,
Trial.PERIOD_MONTHLY));
env.add("toup", Bytes.formatBytes(user1.getUploadedBytesMonth()
- user2.getUploadedBytesMonth()));
env.add("group", user2.getGroup());
StringTokenizer st3 = new StringTokenizer(exemptgroups, " ");
while (st3.hasMoreTokens()) {
if (user2.isMemberOf(st3.nextToken())) {
i = i - 1;
break;
}
}
if (user2.getName().equals(lookupuser)) {
break;
} else
msgtype = 3;
}
if (msgtype == 1)
_listener.sayChannel(msgc.getDest(), ReplacerUtils.jprintf(
"msg1", env, Rank.class));
else if (msgtype == 2) {
if (!user1.equals(null) && !user2.equals(null))
env.add("toup", Bytes.formatBytes(user1
.getUploadedBytesMonth()
- user2.getUploadedBytesMonth()));
_listener.sayChannel(msgc.getDest(), ReplacerUtils.jprintf(
"msg2", env, Rank.class));
} else if (msgtype == 3) {
if (!user1.equals(null) && !user2.equals(null))
env.add("toup", Bytes.formatBytes(user2
.getUploadedBytesMonth()
- user1.getUploadedBytesMonth()));
_listener.sayChannel(msgc.getDest(), ReplacerUtils.jprintf(
"msg3", env, Rank.class));
}
}
}
|
protected void updateCommand(InCommand command) {
if (!(command instanceof MessageCommand)) {
return;
}
MessageCommand msgc = (MessageCommand) command;
if (msgc.isPrivateToUs(_listener.getIRCConnection().getClientState())) {
return;
}
ReplacerEnvironment env = new ReplacerEnvironment(SiteBot.GLOBAL_ENV);
env.add("botnick",_listener.getIRCConnection().getClientState().getNick().getNick());
env.add("ircnick", msgc.getSource().getNick());
String msg = msgc.getMessage().trim();
if (msg.startsWith(_listener.getCommandPrefix() + "rank")) {
User user;
try {
user = _listener.getIRCConfig().lookupUser(msgc.getSource());
} catch (NoSuchUserException e) {
_listener.sayChannel(msgc.getDest(),
ReplacerUtils.jprintf("ident.noident", env, SiteBot.class));
return;
}
env.add("ftpuser",user.getName());
if (!_listener.getIRCConfig().checkIrcPermission(_listener.getCommandPrefix() + "rank",user)) {
_listener.sayChannel(msgc.getDest(),
ReplacerUtils.jprintf("ident.denymsg", env, SiteBot.class));
return;
}
String lookupuser;
try {
lookupuser = msgc.getMessage().substring((_listener.getCommandPrefix() + "rank ").length());
} catch (ArrayIndexOutOfBoundsException e) {
lookupuser = user.getName();
} catch (StringIndexOutOfBoundsException e) {
lookupuser = user.getName();
}
String exemptgroups = ReplacerUtils.jprintf("top.exempt", env,
Rank.class);
try {
User luser = getConnectionManager().getGlobalContext().getUserManager()
.getUserByName(lookupuser);
StringTokenizer st = new StringTokenizer(exemptgroups, " ");
while (st.hasMoreTokens()) {
if (luser.isMemberOf(st.nextToken())) {
env.add("eusr", luser.getName());
env.add("egrp", luser.getGroup());
_listener.sayChannel(msgc.getDest(), ReplacerUtils
.jprintf("exempt", env, Rank.class));
return;
}
}
} catch (NoSuchUserException e2) {
_listener.sayChannel(msgc.getDest(), "Not a valid username");
return;
} catch (UserFileException e2) {
_listener.sayChannel(msgc.getDest(), "Error opening user file");
return;
}
Collection<User> users = null;
try {
users = getConnectionManager().getGlobalContext().getUserManager().getAllUsers();
} catch (UserFileException e) {
getConnection().sendCommand(
new MessageCommand(msgc.getDest(),
"Error processing userfiles"));
return;
}
String type = "MONTHUP";
ArrayList<User> users2 = new ArrayList<User>(users);
Collections.sort(users2, new UserComparator(type));
int i = 0;
int msgtype = 1;
User user1 = null;
User user2 = null;
for (Iterator iter = users.iterator(); iter.hasNext();) {
user1 = (User) iter.next();
i = i + 1;
env.add("ppos", "" + i);
env.add("puser", user1.getName());
env.add("pmnup", Bytes.formatBytes(user1
.getUploadedBytesMonth()));
env.add("pupfilesmonth", "" + user1.getUploadedFilesMonth());
env.add("pmnrateup", TransferStatistics.getUpRate(user1,
Trial.PERIOD_MONTHLY));
env.add("pgroup", user1.getGroup());
StringTokenizer st2 = new StringTokenizer(exemptgroups, " ");
while (st2.hasMoreTokens()) {
if (user1.isMemberOf(st2.nextToken())) {
i = i - 1;
break;
}
}
if (user1.getName().equals(lookupuser)) {
break;
} else
msgtype = 2;
user2 = (User) iter.next();
i = i + 1;
env.add("pos", "" + i);
env.add("user", user2.getName());
env.add("mnup", Bytes
.formatBytes(user2.getUploadedBytesMonth()));
env.add("upfilesmonth", "" + user2.getUploadedFilesMonth());
env.add("mnrateup", TransferStatistics.getUpRate(user2,
Trial.PERIOD_MONTHLY));
env.add("toup", Bytes.formatBytes(user1.getUploadedBytesMonth()
- user2.getUploadedBytesMonth()));
env.add("group", user2.getGroup());
StringTokenizer st3 = new StringTokenizer(exemptgroups, " ");
while (st3.hasMoreTokens()) {
if (user2.isMemberOf(st3.nextToken())) {
i = i - 1;
break;
}
}
if (user2.getName().equals(lookupuser)) {
break;
} else
msgtype = 3;
}
if (msgtype == 1)
_listener.sayChannel(msgc.getDest(), ReplacerUtils.jprintf(
"msg1", env, Rank.class));
else if (msgtype == 2) {
if (!user1.equals(null) && !user2.equals(null))
env.add("toup", Bytes.formatBytes(user2
.getUploadedBytesMonth()
- user1.getUploadedBytesMonth()));
_listener.sayChannel(msgc.getDest(), ReplacerUtils.jprintf(
"msg2", env, Rank.class));
} else if (msgtype == 3) {
if (!user1.equals(null) && !user2.equals(null))
env.add("toup", Bytes.formatBytes(user2
.getUploadedBytesMonth()
- user1.getUploadedBytesMonth()));
_listener.sayChannel(msgc.getDest(), ReplacerUtils.jprintf(
"msg3", env, Rank.class));
}
}
}
|
public void processEncodedText( byte[] string ) throws IOException
{
final float fontSizeText = graphicsState.getTextState().getFontSize();
final float horizontalScalingText = graphicsState.getTextState().getHorizontalScalingPercent()/100f;
final float riseText = graphicsState.getTextState().getRise();
final float wordSpacingText = graphicsState.getTextState().getWordSpacing();
final float characterSpacingText = graphicsState.getTextState().getCharacterSpacing();
final PDFont font = graphicsState.getTextState().getFont();
boolean isType3Font = font instanceof PDType3Font;
PDMatrix fontMatrix = font.getFontMatrix();
final float glyphSpaceToTextSpaceFactor = 1f/fontMatrix.getValue( 0, 0 );
float spaceWidthText=0;
try
{
spaceWidthText = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor);
}
catch (Throwable exception)
{
log.warn( exception, exception);
}
if( spaceWidthText == 0 )
{
spaceWidthText = (font.getAverageFontWidth()/glyphSpaceToTextSpaceFactor);
spaceWidthText *= .80f;
}
float maxVerticalDisplacementText = 0;
Matrix textStateParameters = new Matrix();
textStateParameters.setValue(0,0, fontSizeText*horizontalScalingText);
textStateParameters.setValue(1,1, fontSizeText);
textStateParameters.setValue(2,1, riseText);
int pageRotation = page.findRotation();
float pageHeight = page.findMediaBox().getHeight();
float pageWidth = page.findMediaBox().getWidth();
int codeLength = 1;
for( int i=0; i<string.length; i+=codeLength)
{
codeLength = 1;
String c = font.encode( string, i, codeLength );
if( c == null && i+1<string.length)
{
codeLength++;
c = font.encode( string, i, codeLength );
}
float spaceWidthDisp = spaceWidthText * fontSizeText * horizontalScalingText * textMatrix.getValue(0, 0) * getGraphicsState().getCurrentTransformationMatrix().getValue(0, 0);
float characterHorizontalDisplacementText = font.getFontWidth( string, i, codeLength );
if (isType3Font)
{
characterHorizontalDisplacementText = characterHorizontalDisplacementText * fontMatrix.getValue(0, 0);
}
else
{
characterHorizontalDisplacementText = characterHorizontalDisplacementText/1000f;
}
maxVerticalDisplacementText =
Math.max(
maxVerticalDisplacementText,
characterHorizontalDisplacementText);
float spacingText = 0;
if( (string[i] == 0x20) && codeLength == 1 )
{
spacingText += wordSpacingText;
}
Matrix textMatrixStart = textStateParameters.multiply(textMatrix).multiply(getGraphicsState().getCurrentTransformationMatrix());
float tx = ((characterHorizontalDisplacementText)*fontSizeText)*horizontalScalingText;
float ty = 0;
Matrix td = new Matrix();
td.setValue( 2, 0, tx );
td.setValue( 2, 1, ty );
Matrix textMatrixEnd = textStateParameters.multiply(td).multiply(textMatrix).multiply(getGraphicsState().getCurrentTransformationMatrix());
tx = ((characterHorizontalDisplacementText)*fontSizeText+characterSpacingText+spacingText)*horizontalScalingText;
td.setValue( 2, 0, tx );
textMatrix = td.multiply( textMatrix );
float widthText = textMatrixEnd.getXPosition() - textMatrixStart.getXPosition();
if( c != null )
{
validCharCnt++;
}
else
{
c = "?";
}
totalCharCnt++;
float totalVerticalDisplacementDisp = maxVerticalDisplacementText * fontSizeText;
processTextPosition(
new TextPosition(
pageRotation,
pageWidth,
pageHeight,
textMatrixStart,
textMatrixEnd,
totalVerticalDisplacementDisp,
widthText,
spaceWidthDisp,
c,
font,
fontSizeText,
(int)(fontSizeText * textMatrix.getXScale())
));
}
}
|
public void processEncodedText( byte[] string ) throws IOException
{
final float fontSizeText = graphicsState.getTextState().getFontSize();
final float horizontalScalingText = graphicsState.getTextState().getHorizontalScalingPercent()/100f;
final float riseText = graphicsState.getTextState().getRise();
final float wordSpacingText = graphicsState.getTextState().getWordSpacing();
final float characterSpacingText = graphicsState.getTextState().getCharacterSpacing();
final PDFont font = graphicsState.getTextState().getFont();
boolean isType3Font = font instanceof PDType3Font;
PDMatrix fontMatrix = font.getFontMatrix();
float fontMatrixXScaling = fontMatrix.getValue(0, 0);
float fontMatrixYScaling = fontMatrix.getValue(1, 1);
final float glyphSpaceToTextSpaceFactor = 1f/fontMatrix.getValue( 0, 0 );
float spaceWidthText=0;
try
{
spaceWidthText = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor);
}
catch (Throwable exception)
{
log.warn( exception, exception);
}
if( spaceWidthText == 0 )
{
spaceWidthText = (font.getAverageFontWidth()/glyphSpaceToTextSpaceFactor);
spaceWidthText *= .80f;
}
float maxVerticalDisplacementText = 0;
Matrix textStateParameters = new Matrix();
textStateParameters.setValue(0,0, fontSizeText*horizontalScalingText);
textStateParameters.setValue(1,1, fontSizeText);
textStateParameters.setValue(2,1, riseText);
int pageRotation = page.findRotation();
float pageHeight = page.findMediaBox().getHeight();
float pageWidth = page.findMediaBox().getWidth();
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
int codeLength = 1;
for( int i=0; i<string.length; i+=codeLength)
{
codeLength = 1;
String c = font.encode( string, i, codeLength );
if( c == null && i+1<string.length)
{
codeLength++;
c = font.encode( string, i, codeLength );
}
float spaceWidthDisp = spaceWidthText * fontSizeText * horizontalScalingText * textMatrix.getValue(0, 0) * ctm.getValue(0, 0);
float characterHorizontalDisplacementText = font.getFontWidth( string, i, codeLength );
float characterVerticalDisplacementText = font.getFontHeight( string, i, codeLength );
if (isType3Font)
{
characterHorizontalDisplacementText = characterHorizontalDisplacementText * fontMatrixXScaling;
characterVerticalDisplacementText = characterVerticalDisplacementText * fontMatrixYScaling;
}
else
{
characterHorizontalDisplacementText = characterHorizontalDisplacementText/1000f;
characterVerticalDisplacementText = characterVerticalDisplacementText/1000f;
}
maxVerticalDisplacementText =
Math.max(
maxVerticalDisplacementText,
characterVerticalDisplacementText);
float spacingText = 0;
if( (string[i] == 0x20) && codeLength == 1 )
{
spacingText += wordSpacingText;
}
Matrix textMatrixStart = textStateParameters.multiply(textMatrix).multiply(ctm);
float tx = ((characterHorizontalDisplacementText)*fontSizeText)*horizontalScalingText;
float ty = 0;
Matrix td = new Matrix();
td.setValue( 2, 0, tx );
td.setValue( 2, 1, ty );
Matrix textMatrixEnd = textStateParameters.multiply(td).multiply(textMatrix).multiply(ctm);
tx = ((characterHorizontalDisplacementText)*fontSizeText+characterSpacingText+spacingText)*horizontalScalingText;
td.setValue( 2, 0, tx );
textMatrix = td.multiply( textMatrix );
float widthText = textMatrixEnd.getXPosition() - textMatrixStart.getXPosition();
if( c != null )
{
validCharCnt++;
}
else
{
c = "?";
}
totalCharCnt++;
float totalVerticalDisplacementDisp = maxVerticalDisplacementText * fontSizeText * textMatrix.getYScale();
processTextPosition(
new TextPosition(
pageRotation,
pageWidth,
pageHeight,
textMatrixStart,
textMatrixEnd,
totalVerticalDisplacementDisp,
widthText,
spaceWidthDisp,
c,
font,
fontSizeText,
(int)(fontSizeText * textMatrix.getXScale())
));
}
}
|
public MessageParser(BufferedReader in, PrintWriter out, String file)
throws IOException,
MessageParseException {
file = file.substring(0, file.length() - 5);
MessageHeaderParser mhp = new MessageHeaderParser();
mhp.parse(in);
out.println("<html>");
out.println("<body>");
out.println("<table>");
if (mhp.getHeaderField("Date") != null) {
DateParser dp = new DateParser();
dp.setTargetFormat(YAMM.getString("longdate"));
String date = null;
try {
date = dp.parse(mhp.getHeaderField("Date"));
} catch (ParseException pe) {
date = "";
}
out.println("<tr><td>" + YAMM.getString("mail.date") +
"</td><td>" + date + "</td></tr>");
}
if (mhp.getHeaderField("From") != null) {
String from = makeClickable(mhp.getHeaderField("From"));
out.println("<tr><td>" + YAMM.getString("mail.from") +
"</td><td>" + from + "</td></tr>");
}
if (mhp.getHeaderField("To") != null) {
String to = makeClickable(mhp.getHeaderField("To"));
out.println("<tr><td>" + YAMM.getString("mail.to") +
"</td><td>" + to + "</td></tr>");
}
if (mhp.getHeaderField("Reply-To") != null) {
String replyto = makeClickable(
mhp.getHeaderField("Reply-To"));
out.println("<tr><td>" +
YAMM.getString("mail.reply_to") + "</td><td>" +
replyto + "</td></tr>");
}
if (mhp.getHeaderField("Subject") != null) {
out.println("<tr><td>" +
YAMM.getString("mail.subject") + "</td><td>" +
Mailbox.unMime(mhp.getHeaderField("Subject")) +
"</td></tr>");
}
out.println("</table>");
out.println("<br><pre>");
String boundary = null;
String temp = mhp.getHeaderField("Content-Type");
String contentType = "";
if (temp != null) {
contentType = temp.toLowerCase();
if (temp.indexOf("boundary=\"") != -1) {
boundary = temp.substring(
temp.indexOf("boundary=\"") + 10,
temp.indexOf("\"",
temp.indexOf("boundary=\"") + 11));
}
}
if (mhp.getHeaderField("MIME-Version") != null) {
for (;;) {
if (boundary != null) {
if (in.readLine().equals("--" +
boundary)) {
new Attachment().parse(in,
null);
break;
}
} else {
break;
}
}
}
MessageBodyParser mbp = new MessageBodyParser(true);
for (;;) {
int test = mbp.parse(in, out, boundary);
if (test == MessageBodyParser.ATTACHMENT &&
contentType.indexOf("multipart/alternative") == -1) {
Attachment a = new Attachment();
PrintWriter AtOut = new PrintWriter(
new BufferedOutputStream(
new FileOutputStream(file +
".attach." +
attachments)));
for (;;) {
test = a.parse(in, AtOut);
if (test == Attachment.MESSAGE &&
contentType.indexOf("multipart/alternative") == -1) {
break;
} else if (test == Attachment.
ATTACHMENT) {
attachments++;
AtOut.close();
AtOut = new PrintWriter(new
BufferedOutputStream(
new FileOutputStream(
file +
".attach." +
attachments)));
continue;
} else {
return;
}
}
} else if (test == MessageBodyParser.END) {
break;
} else if (test == MessageBodyParser.ATTACHMENT) {
break;
}
}
out.println("</pre></body>");
out.println("</html>");
}
|
public MessageParser(BufferedReader in, PrintWriter out, String file)
throws IOException,
MessageParseException {
file = file.substring(0, file.length() - 5);
MessageHeaderParser mhp = new MessageHeaderParser();
mhp.parse(in);
out.println("<html>");
out.println("<body>");
out.println("<table>");
if (mhp.getHeaderField("Date") != null) {
DateParser dp = new DateParser();
dp.setTargetFormat(YAMM.getString("longdate"));
String date = null;
try {
date = dp.parse(mhp.getHeaderField("Date"));
} catch (ParseException pe) {
date = "";
}
out.println("<tr><td>" + YAMM.getString("mail.date") +
"</td><td>" + date + "</td></tr>");
}
if (mhp.getHeaderField("From") != null) {
String from = makeClickable(mhp.getHeaderField("From"));
out.println("<tr><td>" + YAMM.getString("mail.from") +
"</td><td>" + from + "</td></tr>");
}
if (mhp.getHeaderField("To") != null) {
String to = makeClickable(mhp.getHeaderField("To"));
out.println("<tr><td>" + YAMM.getString("mail.to") +
"</td><td>" + to + "</td></tr>");
}
if (mhp.getHeaderField("Reply-To") != null) {
String replyto = makeClickable(
mhp.getHeaderField("Reply-To"));
out.println("<tr><td>" +
YAMM.getString("mail.reply_to") + "</td><td>" +
replyto + "</td></tr>");
}
if (mhp.getHeaderField("Subject") != null) {
out.println("<tr><td>" +
YAMM.getString("mail.subject") + "</td><td>" +
Mailbox.unMime(mhp.getHeaderField("Subject")) +
"</td></tr>");
}
out.println("</table>");
out.println("<br><pre>");
String boundary = null;
String temp = mhp.getHeaderField("Content-Type");
String contentType = "";
if (temp != null) {
contentType = temp.toLowerCase();
if (temp.indexOf("boundary=\"") != -1) {
boundary = temp.substring(
temp.indexOf("boundary=\"") + 10,
temp.indexOf("\"",
temp.indexOf("boundary=\"") + 11));
}
}
if (mhp.getHeaderField("MIME-Version") != null) {
for (;;) {
if (boundary != null) {
if (in.readLine().equals("--" +
boundary)) {
new Attachment().parse(in,
null);
break;
}
} else {
break;
}
}
}
MessageBodyParser mbp = new MessageBodyParser(true);
boolean parseMore = true;
for (;;) {
int test = mbp.parse(in, out, boundary);
if (!parseMore) break;
if (test == MessageBodyParser.ATTACHMENT &&
contentType.indexOf("multipart/alternative") == -1) {
Attachment a = new Attachment();
PrintWriter AtOut = new PrintWriter(
new BufferedOutputStream(
new FileOutputStream(file +
".attach." +
attachments)));
for (;;) {
test = a.parse(in, AtOut);
if (test == Attachment.MESSAGE &&
contentType.indexOf("multipart/alternative") == -1) {
break;
} else if (test == Attachment.
ATTACHMENT) {
attachments++;
AtOut.close();
AtOut = new PrintWriter(new
BufferedOutputStream(
new FileOutputStream(
file +
".attach." +
attachments)));
continue;
} else {
parseMore = false;
break;
}
}
} else if (test == MessageBodyParser.END) {
break;
} else if (test == MessageBodyParser.ATTACHMENT) {
break;
}
}
out.println("</pre></body>");
out.println("</html>");
}
|
public void execute() throws MojoFailureException, MojoExecutionException {
if (installGems) {
for (String s : gems) {
installGem(parseGem(s));
}
}
List<String> allArgs = new ArrayList<String>();
allArgs.add(cucumberBin().getAbsolutePath());
allArgs.addAll(Arrays.asList(args));
allArgs.add((features != null) ? features : "features");
Java jruby = jruby(allArgs);
try {
jruby.execute();
} catch (BuildException e) {
throw new MojoFailureException("Cucumber failed", e);
}
}
|
public void execute() throws MojoFailureException, MojoExecutionException {
if (installGems) {
for (String s : gems) {
installGem(parseGem(s));
}
}
List<String> allArgs = new ArrayList<String>();
allArgs.add("-r");
allArgs.add("cuke4duke/cucumber_ext");
allArgs.add(cucumberBin().getAbsolutePath());
allArgs.addAll(Arrays.asList(args));
allArgs.add((features != null) ? features : "features");
Java jruby = jruby(allArgs);
try {
jruby.execute();
} catch (BuildException e) {
throw new MojoFailureException("Cucumber failed", e);
}
}
|
public void writeValue(XmlWriter writer, String nsUri, String prefix, String localName, Object val, String href, Map<String, String> nsPrefixes) {
Element supportedLocks = writer.begin("D:supportedlock").open();
SupportedLocks slocks = (SupportedLocks) val;
if (slocks.getResource() instanceof LockableResource) {
Element lockentry = writer.begin("D:lockentry").open();
writer.begin("D:lockscope").open(false).writeText("<D:exclusive/>").close();
writer.begin("D:locktype").open(false).writeText("<D:write/>").close();
lockentry.close();
}
supportedLocks.close();
}
|
public void writeValue(XmlWriter writer, String nsUri, String prefix, String localName, Object val, String href, Map<String, String> nsPrefixes) {
Element supportedLocks = writer.begin("D:supportedlock").open();
SupportedLocks slocks = (SupportedLocks) val;
if (slocks != null && slocks.getResource() instanceof LockableResource) {
Element lockentry = writer.begin("D:lockentry").open();
writer.begin("D:lockscope").open(false).writeText("<D:exclusive/>").close();
writer.begin("D:locktype").open(false).writeText("<D:write/>").close();
lockentry.close();
}
supportedLocks.close();
}
|
public void testIsValid() {
XmlDataController controller = new XmlDataController();
List<String> parameters = new ArrayList<String>();
String testPackage = "src/org/hackystat/sensor/xmldata/testdataset/";
parameters.add(new File("") + testPackage + "testArgList.txt");
Option option = OptionFactory.getInstance(controller, ArgListOption.OPTION_NAME,
parameters);
Assert.assertTrue("ArgList accept only 1 argument.", option.isValid());
option.process();
parameters = new ArrayList<String>();
option = ArgListOption.createOption(controller, parameters);
Assert.assertFalse("ArgList accept only 1 argument.", option.isValid());
parameters = new ArrayList<String>();
parameters.add("Foo.xml");
option = ArgListOption.createOption(controller, parameters);
Assert.assertFalse("An invalid file should invalid this option.", option.isValid());
}
|
public void testIsValid() {
XmlDataController controller = new XmlDataController();
List<String> parameters = new ArrayList<String>();
String testPackage = "src/org/hackystat/sensor/xmldata/testdataset/";
File testArgList = new File(System.getProperty("user.dir"), testPackage + "testArgList.txt");
parameters.add(testArgList.toString());
Option option = OptionFactory.getInstance(controller, ArgListOption.OPTION_NAME,
parameters);
Assert.assertTrue("ArgList accept only 1 argument.", option.isValid());
option.process();
parameters = new ArrayList<String>();
option = ArgListOption.createOption(controller, parameters);
Assert.assertFalse("ArgList accept only 1 argument.", option.isValid());
parameters = new ArrayList<String>();
parameters.add("Foo.xml");
option = ArgListOption.createOption(controller, parameters);
Assert.assertFalse("An invalid file should invalid this option.", option.isValid());
}
|
private void createUI()
{
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = fileMenu.add("Open");
openItem.addActionListener(new CommandLoad());
openItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_O, InputEvent.CTRL_MASK));
JMenuItem saveItem = fileMenu.add("Save");
saveItem.addActionListener(new CommandSave());
saveItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_S, InputEvent.CTRL_MASK));
fileMenu.addSeparator();
JMenuItem startServerItem = fileMenu.add("Start server");
startServerItem.addActionListener(new CommandServerStart());
JMenuItem stopServerItem = fileMenu.add("Stop server");
stopServerItem.addActionListener(new CommandServerStop());
JMenu runMenu = new JMenu("Run");
JMenuItem runProgramItem = runMenu.add("Run all");
runProgramItem.addActionListener(new CommandRunProgram());
runProgramItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_R, InputEvent.CTRL_MASK));
JMenuItem runSelectionItem = runMenu.add("Run selection");
runSelectionItem.addActionListener(new CommandRunSelection());
runSelectionItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_D, InputEvent.CTRL_MASK));
JMenu fontMenu = new JMenu("Font");
for (int fontSize = 12; fontSize <= 30; fontSize += 2)
{
JMenuItem fontItem = fontMenu.add("" + fontSize + " normal");
fontItem.addActionListener(
new CommandSetFontSize(
new Font(Font.MONOSPACED, Font.PLAIN, fontSize)));
fontItem = fontMenu.add("" + fontSize + " bold");
fontItem.addActionListener(
new CommandSetFontSize(
new Font(Font.MONOSPACED, Font.BOLD, fontSize)));
}
menuBar.add(fileMenu);
menuBar.add(runMenu);
menuBar.add(fontMenu);
setJMenuBar(menuBar);
Box toolPanel = Box.createVerticalBox();
toolPanel.setAlignmentX(LEFT_ALIGNMENT);
Box buttonPanel = Box.createHorizontalBox();
buttonPanel.setAlignmentX(LEFT_ALIGNMENT);
toolPanel.add(buttonPanel);
mMessagePane = new JTextArea(4, 30);
mMessagePane.setAlignmentX(LEFT_ALIGNMENT);
mMessagePane.setText("");
mMessagePane.setEditable(false);
JScrollPane messageScrollPane = new JScrollPane();
messageScrollPane.setViewportView(mMessagePane);
messageScrollPane.setAlignmentX(LEFT_ALIGNMENT);
toolPanel.add(messageScrollPane);
JButton button;
button = new JButton("Run all");
button.addActionListener(new CommandRunProgram());
button.setAlignmentX(LEFT_ALIGNMENT);
buttonPanel.add(button);
button = new JButton("Run selection");
button.addActionListener(new CommandRunSelection());
button.setAlignmentX(LEFT_ALIGNMENT);
buttonPanel.add(button);
button = new JButton("Reset client");
button.addActionListener(new CommandResetClient());
button.setAlignmentX(LEFT_ALIGNMENT);
button = new JButton("Load...");
button.addActionListener(new CommandLoad());
button.setAlignmentX(LEFT_ALIGNMENT);
button = new JButton("Save...");
button.addActionListener(new CommandSave());
button.setAlignmentX(LEFT_ALIGNMENT);
button = new JButton("Start server");
button.addActionListener(new CommandServerStart());
button.setAlignmentX(LEFT_ALIGNMENT);
button = new JButton("Stop server");
button.addActionListener(new CommandServerStop());
button.setAlignmentX(LEFT_ALIGNMENT);
JLabel label = new JLabel();
String ipAddress = getServerIpAddress();
if (null != ipAddress)
{
label.setText(
" Host address: " + ipAddress +
" (use 10.0.2.2 for localhost in Android emulator)");
}
else
{
label.setText("No Internet connection");
}
label.setAlignmentX(LEFT_ALIGNMENT);
buttonPanel.add(label);
mEditor = new Editor();
mEditor.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_LUA);
mEditor.setHighlightCurrentLine(false);
mEditor.setText(""
+ "---------------------------------------------------\n"
+ "-- Welcome to the Wonderful World of Mobile Lua! --\n"
+ "---------------------------------------------------\n"
+ "\n"
+ "-- Run this code to display a coloured rectangle.\n"
+ "Screen:SetColor(255, 255, 255)\n"
+ "Screen:Fill()\n"
+ "Screen:SetColor(200, 0, 0)\n"
+ "Screen:Fill(0, 0, 300, 300)\n"
+ "Screen:Update()\n");
mEditor.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
mEditor.setRoundedSelectionEdges(false);
SyntaxScheme syntaxSceheme = mEditor.getDefaultSyntaxScheme();
syntaxSceheme.setStyle(Token.SEPARATOR, new Style(Color.BLACK, null));
syntaxSceheme.setStyle(Token.LITERAL_STRING_DOUBLE_QUOTE, new Style(
new Color(0, 0, 175), null));
syntaxSceheme.setStyle(Token.LITERAL_CHAR, new Style(new Color(0, 0,
175), null));
mEditor.setSyntaxScheme(syntaxSceheme);
RTextScrollPane scrollPane = new RTextScrollPane(mEditor);
scrollPane.setLineNumbersEnabled(true);
Container mainEditor = new Container();
mainEditor.setLayout(new BoxLayout(mainEditor, BoxLayout.PAGE_AXIS));
mainEditor.add(scrollPane, BorderLayout.CENTER);
this.add(toolPanel, BorderLayout.SOUTH);
this.add(mainEditor, BorderLayout.CENTER);
setSize(1000, 700);
setVisible(true);
}
|
private void createUI()
{
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = fileMenu.add("Open");
openItem.addActionListener(new CommandLoad());
openItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_O, InputEvent.CTRL_MASK));
JMenuItem saveItem = fileMenu.add("Save");
saveItem.addActionListener(new CommandSave());
saveItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_S, InputEvent.CTRL_MASK));
fileMenu.addSeparator();
JMenuItem startServerItem = fileMenu.add("Start server");
startServerItem.addActionListener(new CommandServerStart());
JMenuItem stopServerItem = fileMenu.add("Stop server");
stopServerItem.addActionListener(new CommandServerStop());
JMenu runMenu = new JMenu("Run");
JMenuItem runProgramItem = runMenu.add("Run all");
runProgramItem.addActionListener(new CommandRunProgram());
runProgramItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_R, InputEvent.CTRL_MASK));
JMenuItem runSelectionItem = runMenu.add("Run selection");
runSelectionItem.addActionListener(new CommandRunSelection());
runSelectionItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_D, InputEvent.CTRL_MASK));
JMenu fontMenu = new JMenu("Font");
for (int fontSize = 12; fontSize <= 30; fontSize += 2)
{
JMenuItem fontItem = fontMenu.add("" + fontSize + " normal");
fontItem.addActionListener(
new CommandSetFontSize(
new Font(Font.MONOSPACED, Font.PLAIN, fontSize)));
fontItem = fontMenu.add("" + fontSize + " bold");
fontItem.addActionListener(
new CommandSetFontSize(
new Font(Font.MONOSPACED, Font.BOLD, fontSize)));
}
menuBar.add(fileMenu);
menuBar.add(runMenu);
menuBar.add(fontMenu);
setJMenuBar(menuBar);
Box toolPanel = Box.createVerticalBox();
toolPanel.setAlignmentX(LEFT_ALIGNMENT);
Box buttonPanel = Box.createHorizontalBox();
buttonPanel.setAlignmentX(LEFT_ALIGNMENT);
toolPanel.add(buttonPanel);
mMessagePane = new JTextArea(4, 30);
mMessagePane.setAlignmentX(LEFT_ALIGNMENT);
mMessagePane.setText("");
mMessagePane.setEditable(false);
JScrollPane messageScrollPane = new JScrollPane();
messageScrollPane.setViewportView(mMessagePane);
messageScrollPane.setAlignmentX(LEFT_ALIGNMENT);
toolPanel.add(messageScrollPane);
JButton button;
button = new JButton("Run all");
button.addActionListener(new CommandRunProgram());
button.setAlignmentX(LEFT_ALIGNMENT);
buttonPanel.add(button);
button = new JButton("Run selection");
button.addActionListener(new CommandRunSelection());
button.setAlignmentX(LEFT_ALIGNMENT);
buttonPanel.add(button);
button = new JButton("Reset client");
button.addActionListener(new CommandResetClient());
button.setAlignmentX(LEFT_ALIGNMENT);
button = new JButton("Load...");
button.addActionListener(new CommandLoad());
button.setAlignmentX(LEFT_ALIGNMENT);
button = new JButton("Save...");
button.addActionListener(new CommandSave());
button.setAlignmentX(LEFT_ALIGNMENT);
button = new JButton("Start server");
button.addActionListener(new CommandServerStart());
button.setAlignmentX(LEFT_ALIGNMENT);
button = new JButton("Stop server");
button.addActionListener(new CommandServerStop());
button.setAlignmentX(LEFT_ALIGNMENT);
JLabel label = new JLabel();
String ipAddress = getServerIpAddress();
if (null != ipAddress)
{
label.setText(
" Host address: " + ipAddress +
" (use 10.0.2.2 for localhost in Android emulator)");
}
else
{
label.setText("No Internet connection");
}
label.setAlignmentX(LEFT_ALIGNMENT);
buttonPanel.add(label);
mEditor = new Editor();
mEditor.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_LUA);
mEditor.setHighlightCurrentLine(false);
mEditor.setText(""
+ "---------------------------------------------------\n"
+ "-- Welcome to the Wonderful World of Mobile Lua! --\n"
+ "---------------------------------------------------\n"
+ "\n"
+ "-- Run this code to display a coloured rectangle.\n"
+ "Screen:SetColor(255, 255, 255)\n"
+ "Screen:Fill()\n"
+ "Screen:SetColor(200, 0, 0)\n"
+ "Screen:FillRect(0, 0, 300, 300)\n"
+ "Screen:Update()\n");
mEditor.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
mEditor.setRoundedSelectionEdges(false);
SyntaxScheme syntaxSceheme = mEditor.getDefaultSyntaxScheme();
syntaxSceheme.setStyle(Token.SEPARATOR, new Style(Color.BLACK, null));
syntaxSceheme.setStyle(Token.LITERAL_STRING_DOUBLE_QUOTE, new Style(
new Color(0, 0, 175), null));
syntaxSceheme.setStyle(Token.LITERAL_CHAR, new Style(new Color(0, 0,
175), null));
mEditor.setSyntaxScheme(syntaxSceheme);
RTextScrollPane scrollPane = new RTextScrollPane(mEditor);
scrollPane.setLineNumbersEnabled(true);
Container mainEditor = new Container();
mainEditor.setLayout(new BoxLayout(mainEditor, BoxLayout.PAGE_AXIS));
mainEditor.add(scrollPane, BorderLayout.CENTER);
this.add(toolPanel, BorderLayout.SOUTH);
this.add(mainEditor, BorderLayout.CENTER);
setSize(1000, 700);
setVisible(true);
}
|
public void init(GameContainer gc)
throws SlickException {
int i = 0;
DDSystem system = new DDSystem();
ActionBox ab = new ActionBox(i++, 0, 0);
GMToolsBox gmt = new GMToolsBox(i++,0,0);
system.linkBoxes(ab);
system.server();
int size = 10;
CharacterSheet[] sheet = new CharacterSheet[size];
for(int j = 0; j < size; j++) sheet[j] = new CharacterSheet();
for (int j = 0; j < size; j++)
{
sheet[j].fillBasic("Name" + j,
"Skanks-Worth",
0,
"Elvish, Common",
0,
1,
5,
150,
200,
"Chaotic Neutral",
"Apple",
"Noble",
"Archer");
sheet[j].fillAbilities();
CharacterClass barb = sheet[j].chooseClass(0);
sheet[j].fillRecorder(barb);
sheet[j].fillAttacksAndDefense(barb);
sheet[j].setNetID(NetworkSystem.GM_USER_ID);
sheet[j].setImage(new DDImage("Images/Test/DungeonCrawl_ProjectUtumnoTileset.png", 2530, 1440, 33, 34));
}
HolderTuple[] holder;
Integer[] inPlay;
Component[] comp;
PlaceCharacter[] place = new PlaceCharacter[size];
String temp;
for (int k = 0; k < size; k++)
{
System.out.println("Adding character " + sheet[k].getName() + ": ");
place[k] = gmt.addCharacter(GMToolsBox.Holder.MOB, sheet[k]);
System.out.println("Characters in mob holder:");
holder = gmt.getHolder(GMToolsBox.Holder.MOB);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in player holder:");
holder = gmt.getHolder(GMToolsBox.Holder.PLAYER);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in play:");
inPlay = gmt.getCharactersInPlay();
temp = "";
for (int j = 0; j < inPlay.length; j++) temp += (inPlay[j] + ", " );
System.out.println(temp);
System.out.println("Components left:");
comp = gmt.getComponents();
for (int j = 0; j < comp.length; j++) System.out.println("CompID: " + comp[j].getId());
}
World world = new World("TESTME");
system.setMap(world.world[0][0]);
Wall wall = new Wall("walll", null,0,0, world.world[0][0]);
world.world[0][0].massPlaceObjectsLine(0, 0, 10, 0, wall);
world.world[0][0].massPlaceObjectsLine(0, 1, 0, 19, wall);
world.world[0][0].massPlaceObjectsLine(1, 10, 10, 10, wall);
world.world[0][0].massPlaceObjectsLine(10, 9, 10, 1, wall);
world.world[0][0].massPlaceObjectsLine(1, 19, 10, 19, wall);
world.world[0][0].massPlaceObjectsLine(10, 11, 10, 19, wall);
world.world[0][0].removeObjects(6, 0);
world.world[0][0].removeObjects(7, 0);
world.world[0][0].removeObjects(6, 10);
world.world[0][0].removeObjects(7, 10);
System.out.println("The world: ");
System.out.println(world.world[0][0].toString());
int x = 5;
int y = 6;
int k = 0;
place[k] = gmt.addCharacter(GMToolsBox.Holder.MOB, sheet[k]);
System.out.println("Placing " + sheet[k].getName() + " at " + x + ", " + y);
place[k].testPlace();
System.out.println("placement options:");
System.out.println(world.world[0][0].toString());
ObjectsPriorityStack stack = world.world[0][0].objectsStack[x][y];
((TargetBlock)stack.peek()).select();
System.out.println(world.world[0][0].toString());
System.out.println("Characters in mob holder:");
holder = gmt.getHolder(GMToolsBox.Holder.MOB);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in player holder:");
holder = gmt.getHolder(GMToolsBox.Holder.PLAYER);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in play:");
inPlay = gmt.getCharactersInPlay();
temp = "";
for (int j = 0; j < inPlay.length; j++) temp += (inPlay[j] + ", " );
System.out.println(temp);
System.out.println("Components left:");
comp = gmt.getComponents();
for (int j = 0; j < comp.length; j++) System.out.println("CompID: " + comp[j].getId());
k = 5;
x+= 2;
place[k] = gmt.addCharacter(GMToolsBox.Holder.MOB, sheet[k]);
System.out.println("Placing " + sheet[k].getName() + " at " + x + ", " + y);
place[k].testPlace();
System.out.println("placement options:");
System.out.println(world.world[0][0].toString());
stack = world.world[0][0].objectsStack[x][y];
((TargetBlock)stack.peek()).select();
System.out.println(world.world[0][0].toString());
System.out.println("Characters in mob holder:");
holder = gmt.getHolder(GMToolsBox.Holder.MOB);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in player holder:");
holder = gmt.getHolder(GMToolsBox.Holder.PLAYER);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in play:");
inPlay = gmt.getCharactersInPlay();
temp = "";
for (int j = 0; j < inPlay.length; j++) temp += (inPlay[j] + ", " );
System.out.println(temp);
System.out.println("Components left:");
comp = gmt.getComponents();
for (int j = 0; j < comp.length; j++) System.out.println("CompID: " + comp[j].getId());;
}
|
public void init(GameContainer gc)
throws SlickException {
int i = 0;
DDSystem system = new DDSystem();
ActionBox ab = new ActionBox(i++, 0, 0);
GMToolsBox gmt = new GMToolsBox(i++,0,0);
system.linkBoxes(ab);
system.server();
int size = 10;
CharacterSheet[] sheet = new CharacterSheet[size];
for(int j = 0; j < size; j++) sheet[j] = new CharacterSheet();
for (int j = 0; j < size; j++)
{
sheet[j].fillBasic("Name" + j,
"Skanks-Worth",
0,
"Elvish, Common",
0,
1,
5,
150,
200,
"Chaotic Neutral",
"Apple",
"Noble",
"Archer");
sheet[j].fillAbilities();
CharacterClass barb = sheet[j].chooseClass(0);
sheet[j].fillRecorder(barb);
sheet[j].fillAttacksAndDefense(barb);
sheet[j].setNetID(NetworkSystem.GM_USER_ID);
sheet[j].setImage(new DDImage("Images/Test/DungeonCrawl_ProjectUtumnoTileset.png", 2530, 1440, 33, 34));
}
HolderTuple[] holder;
Integer[] inPlay;
Component[] comp;
PlaceCharacter[] place = new PlaceCharacter[size];
String temp;
for (int k = 0; k < size; k++)
{
System.out.println("Adding character " + sheet[k].getName() + ": ");
place[k] = gmt.addCharacter(GMToolsBox.Holder.MOB, sheet[k]);
System.out.println("Characters in mob holder:");
holder = gmt.getHolder(GMToolsBox.Holder.MOB);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in player holder:");
holder = gmt.getHolder(GMToolsBox.Holder.PLAYER);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in play:");
inPlay = gmt.getCharactersInPlay();
temp = "";
for (int j = 0; j < inPlay.length; j++) temp += (inPlay[j] + ", " );
System.out.println(temp);
System.out.println("Components left:");
comp = gmt.getComponents();
for (int j = 0; j < comp.length; j++) System.out.println("CompID: " + comp[j].getId());
}
World world = new World("TESTME");
system.setMap(world.world[0][0]);
Wall wall = new Wall("walll", null,0,0, world.world[0][0]);
world.world[0][0].massPlaceObjectsLine(0, 0, 10, 0, wall);
world.world[0][0].massPlaceObjectsLine(0, 1, 0, 19, wall);
world.world[0][0].massPlaceObjectsLine(1, 10, 10, 10, wall);
world.world[0][0].massPlaceObjectsLine(10, 9, 10, 1, wall);
world.world[0][0].massPlaceObjectsLine(1, 19, 10, 19, wall);
world.world[0][0].massPlaceObjectsLine(10, 11, 10, 19, wall);
world.world[0][0].removeObjects(6, 0);
world.world[0][0].removeObjects(7, 0);
world.world[0][0].removeObjects(6, 10);
world.world[0][0].removeObjects(7, 10);
System.out.println("The world: ");
System.out.println(world.world[0][0].toString());
int x = 5;
int y = 6;
int k = 0;
System.out.println("Placing " + sheet[k].getName() + " at " + x + ", " + y);
place[k].testPlace();
System.out.println("placement options:");
System.out.println(world.world[0][0].toString());
ObjectsPriorityStack stack = world.world[0][0].objectsStack[x][y];
((TargetBlock)stack.peek()).select();
System.out.println(world.world[0][0].toString());
System.out.println("Characters in mob holder:");
holder = gmt.getHolder(GMToolsBox.Holder.MOB);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in player holder:");
holder = gmt.getHolder(GMToolsBox.Holder.PLAYER);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in play:");
inPlay = gmt.getCharactersInPlay();
temp = "";
for (int j = 0; j < inPlay.length; j++) temp += (inPlay[j] + ", " );
System.out.println(temp);
System.out.println("Components left:");
comp = gmt.getComponents();
for (int j = 0; j < comp.length; j++) System.out.println("CompID: " + comp[j].getId());
k = 5;
x+= 2;
System.out.println("Placing " + sheet[k].getName() + " at " + x + ", " + y);
place[k].testPlace();
System.out.println("placement options:");
System.out.println(world.world[0][0].toString());
stack = world.world[0][0].objectsStack[x][y];
((TargetBlock)stack.peek()).select();
System.out.println(world.world[0][0].toString());
System.out.println("Characters in mob holder:");
holder = gmt.getHolder(GMToolsBox.Holder.MOB);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in player holder:");
holder = gmt.getHolder(GMToolsBox.Holder.PLAYER);
for(int j = 0; j < holder.length; j++) System.out.println("Component ID: " + holder[j].id + " Name: " + holder[j].sheet.getName());
System.out.println("Characters in play:");
inPlay = gmt.getCharactersInPlay();
temp = "";
for (int j = 0; j < inPlay.length; j++) temp += (inPlay[j] + ", " );
System.out.println(temp);
System.out.println("Components left:");
comp = gmt.getComponents();
for (int j = 0; j < comp.length; j++) System.out.println("CompID: " + comp[j].getId());;
}
|
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
String currentUserId = externalLogic.getCurrentUserId();
UIMessage.make(tofill, "view-report-title", "viewreport.page.title");
ReportParameters reportViewParams = (ReportParameters) viewparams;
Long evaluationId = reportViewParams.evaluationId;
if (evaluationId != null) {
UIInternalLink.make(tofill, "summary-toplink", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID));
UIInternalLink.make(tofill, "report-groups-title", UIMessage.make("reportgroups.page.title"),
new TemplateViewParameters(ReportChooseGroupsProducer.VIEW_ID, reportViewParams.evaluationId));
EvalEvaluation evaluation = evalsLogic.getEvaluationById(reportViewParams.evaluationId);
if (!currentUserId.equals(evaluation.getOwner()) &&
!externalLogic.isUserAdmin(currentUserId)) {
throw new SecurityException("Invalid user attempting to access reports page: " + currentUserId);
}
EvalTemplate template = evaluation.getTemplate();
List allTemplateItems = new ArrayList(template.getTemplateItems());
if (!allTemplateItems.isEmpty()) {
if (reportViewParams.groupIds == null || reportViewParams.groupIds.length == 0) {
Map evalGroups = evalsLogic.getEvaluationGroups(new Long[] { evaluationId }, false);
List groups = (List) evalGroups.get(evaluationId);
groupIds = new String[groups.size()];
for (int i = 0; i < groups.size(); i++) {
EvalGroup currGroup = (EvalGroup) groups.get(i);
groupIds[i] = currGroup.evalGroupId;
}
} else {
groupIds = reportViewParams.groupIds;
}
UIInternalLink.make(tofill, "fullEssayResponse", UIMessage.make("viewreport.view.essays"), new EssayResponseParams(
ReportsViewEssaysProducer.VIEW_ID, reportViewParams.evaluationId, groupIds));
UIInternalLink.make(tofill, "csvResultsReport", UIMessage.make("viewreport.view.csv"), new CSVReportViewParams(
"csvResultsReport", template.getId(), reportViewParams.evaluationId, groupIds));
List answerableItemsList = TemplateItemUtils.getAnswerableTemplateItems(allTemplateItems);
UIBranchContainer courseSection = null;
UIBranchContainer instructorSection = null;
if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_COURSE, answerableItemsList)) {
courseSection = UIBranchContainer.make(tofill, "courseSection:");
UIMessage.make(courseSection, "report-course-questions", "viewreport.itemlist.coursequestions");
for (int i = 0; i < answerableItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) answerableItemsList.get(i);
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(templateItem.getItemCategory())) {
UIBranchContainer branch = UIBranchContainer.make(courseSection, "itemrow:first", i + "");
if (i % 2 == 1)
branch.decorators = new DecoratorList( new UIStyleDecorator("itemsListOddLine") );
renderTemplateItemResults(templateItem, evaluation.getId(), displayNumber, branch);
displayNumber++;
}
}
}
if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_INSTRUCTOR, answerableItemsList)) {
instructorSection = UIBranchContainer.make(tofill, "instructorSection:");
UIMessage.make(instructorSection, "report-instructor-questions", "viewreport.itemlist.instructorquestions");
for (int i = 0; i < answerableItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) answerableItemsList.get(i);
if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(templateItem.getItemCategory())) {
UIBranchContainer branch = UIBranchContainer.make(instructorSection, "itemrow:first", i + "");
if (i % 2 == 1)
branch.decorators = new DecoratorList( new UIStyleDecorator("itemsListOddLine") );
renderTemplateItemResults(templateItem, evaluation.getId(), i, branch);
displayNumber++;
}
}
}
}
} else {
throw new IllegalArgumentException("Evaluation id is required to view report");
}
}
|
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
String currentUserId = externalLogic.getCurrentUserId();
UIMessage.make(tofill, "view-report-title", "viewreport.page.title");
ReportParameters reportViewParams = (ReportParameters) viewparams;
Long evaluationId = reportViewParams.evaluationId;
if (evaluationId != null) {
UIInternalLink.make(tofill, "summary-toplink", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID));
UIInternalLink.make(tofill, "report-groups-title", UIMessage.make("reportgroups.page.title"),
new TemplateViewParameters(ReportChooseGroupsProducer.VIEW_ID, reportViewParams.evaluationId));
EvalEvaluation evaluation = evalsLogic.getEvaluationById(reportViewParams.evaluationId);
if (!currentUserId.equals(evaluation.getOwner()) &&
!externalLogic.isUserAdmin(currentUserId)) {
throw new SecurityException("Invalid user attempting to access reports page: " + currentUserId);
}
EvalTemplate template = evaluation.getTemplate();
List allTemplateItems = new ArrayList(template.getTemplateItems());
if (!allTemplateItems.isEmpty()) {
if (reportViewParams.groupIds == null || reportViewParams.groupIds.length == 0) {
Map evalGroups = evalsLogic.getEvaluationGroups(new Long[] { evaluationId }, false);
List groups = (List) evalGroups.get(evaluationId);
groupIds = new String[groups.size()];
for (int i = 0; i < groups.size(); i++) {
EvalGroup currGroup = (EvalGroup) groups.get(i);
groupIds[i] = currGroup.evalGroupId;
}
} else {
groupIds = reportViewParams.groupIds;
}
UIInternalLink.make(tofill, "fullEssayResponse", UIMessage.make("viewreport.view.essays"), new EssayResponseParams(
ReportsViewEssaysProducer.VIEW_ID, reportViewParams.evaluationId, groupIds));
UIInternalLink.make(tofill, "csvResultsReport", UIMessage.make("viewreport.view.csv"), new CSVReportViewParams(
"csvResultsReport", template.getId(), reportViewParams.evaluationId, groupIds));
List answerableItemsList = TemplateItemUtils.getAnswerableTemplateItems(allTemplateItems);
UIBranchContainer courseSection = null;
UIBranchContainer instructorSection = null;
if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_COURSE, answerableItemsList)) {
courseSection = UIBranchContainer.make(tofill, "courseSection:");
UIMessage.make(courseSection, "report-course-questions", "viewreport.itemlist.coursequestions");
for (int i = 0; i < answerableItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) answerableItemsList.get(i);
if (EvalConstants.ITEM_CATEGORY_COURSE.equals(templateItem.getItemCategory())) {
UIBranchContainer branch = UIBranchContainer.make(courseSection, "itemrow:first", i + "");
if (i % 2 == 1)
branch.decorators = new DecoratorList( new UIStyleDecorator("") );
renderTemplateItemResults(templateItem, evaluation.getId(), displayNumber, branch);
displayNumber++;
}
}
}
if (TemplateItemUtils.checkTemplateItemsCategoryExists(EvalConstants.ITEM_CATEGORY_INSTRUCTOR, answerableItemsList)) {
instructorSection = UIBranchContainer.make(tofill, "instructorSection:");
UIMessage.make(instructorSection, "report-instructor-questions", "viewreport.itemlist.instructorquestions");
for (int i = 0; i < answerableItemsList.size(); i++) {
EvalTemplateItem templateItem = (EvalTemplateItem) answerableItemsList.get(i);
if (EvalConstants.ITEM_CATEGORY_INSTRUCTOR.equals(templateItem.getItemCategory())) {
UIBranchContainer branch = UIBranchContainer.make(instructorSection, "itemrow:first", i + "");
if (i % 2 == 1)
branch.decorators = new DecoratorList( new UIStyleDecorator("") );
renderTemplateItemResults(templateItem, evaluation.getId(), i, branch);
displayNumber++;
}
}
}
}
} else {
throw new IllegalArgumentException("Evaluation id is required to view report");
}
}
|
public void createFieldEditors() {
if(System.getProperty("os.name").equals("Mac OS X")){
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser", getFieldEditorParent()));
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser", getFieldEditorParent()));
}
else {
addField(new FileFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser",getFieldEditorParent()));
addField(new FileFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser",getFieldEditorParent()));
addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
}
|
public void createFieldEditors() {
if(System.getProperty("os.name").equals("Mac OS X")){
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser", getFieldEditorParent()));
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser", getFieldEditorParent()));
}
else {
addField(new FileFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser",getFieldEditorParent()));
addField(new FileFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser",getFieldEditorParent()));
}
addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
|
public ShowGroup(PageParameters parameters) {
Object p = parameters.get("id");
Long id = null;
try {
id = Long.parseLong(p.toString());
} catch (NumberFormatException e) {
error("Hibás paraméter!");
throw new RestartResponseException(getApplication().getHomePage());
}
final Group group = userManager.findGroupWithCsoporttagsagokById(id);
final User user = userManager.findUserWithCsoporttagsagokById(getSession().getUserId());
if (group == null) {
error("A megadott kör nem létezik!");
throw new RestartResponseException(getApplication().getHomePage());
}
if (group.getName().contains("Informatikus-hallgatók")) {
setHeaderLabelText("MAVE adatlapja");
} else {
setHeaderLabelText(group.getName());
}
add(new FeedbackPanel("pagemessages"));
add(new BookmarkablePageLink<GroupHistory>("detailView", GroupHistory.class,
new PageParameters("id=" + group.getId().toString())));
Link<EditGroupInfo> editPageLink = new BookmarkablePageLink<EditGroupInfo>("editPage", EditGroupInfo.class,
new PageParameters("id=" + group.getId().toString()));
if (user != null && isUserGroupLeader(group)) {
editPageLink.setVisible(true);
} else {
editPageLink.setVisible(false);
}
add(editPageLink);
Link<ChangeDelegates> editDelegates =
new BookmarkablePageLink<ChangeDelegates>("editDelegates", ChangeDelegates.class,
new PageParameters("id=" + group.getId().toString()));
if (user != null && isUserGroupLeader(group) && group.getIsSvie()) {
editDelegates.setVisible(true);
} else {
editDelegates.setVisible(false);
}
add(editDelegates);
setDefaultModel(new CompoundPropertyModel<Group>(group));
add(new Label("name"));
add(new Label("founded"));
add(new Label("svieMs", (group.getIsSvie() ? "igen" : "nem")));
add(new SmartLinkLabel("webPage"));
add(new SmartLinkLabel("mailingList"));
add(new MultiLineLabel("introduction"));
Link<Void> applyLink = new Link<Void>("applyToGroup") {
@Override
public void onClick() {
userManager.addUserToGroup(user, group, new Date(), null);
getSession().info("Sikeres jelentkezés");
setResponsePage(ShowUser.class);
return;
}
};
applyLink.add(new ConfirmationBoxRenderer("Biztosan szeretnél jelentkezni a körbe?"));
if (user != null && user.getGroups().contains(group)) {
applyLink.setVisible(false);
}
add(applyLink);
List<Membership> activeMembers = group.getActiveMemberships();
List<Membership> inactiveMembers = group.getInactiveMemberships();
Panel adminOrActivePanel;
Panel adminOrOldBoysPanel;
if (isUserGroupLeader(group) || hasUserDelegatedPostInGroup(group)) {
adminOrActivePanel = new AdminMembershipsPanel("adminOrActive", activeMembers);
adminOrOldBoysPanel = new AdminOldBoysPanel("adminOrOldBoy", inactiveMembers);
} else {
adminOrActivePanel = new ActiveMembershipsPanel("adminOrActive", activeMembers);
adminOrOldBoysPanel = new OldBoysPanel("adminOrOldBoy", inactiveMembers);
}
add(adminOrActivePanel);
add(adminOrOldBoysPanel);
}
|
public ShowGroup(PageParameters parameters) {
Object p = parameters.get("id");
Long id = null;
try {
id = Long.parseLong(p.toString());
} catch (NumberFormatException e) {
error("Hibás paraméter!");
throw new RestartResponseException(getApplication().getHomePage());
}
final Group group = userManager.findGroupWithCsoporttagsagokById(id);
final User user = userManager.findUserWithCsoporttagsagokById(getSession().getUserId());
if (group == null) {
error("A megadott kör nem létezik!");
throw new RestartResponseException(getApplication().getHomePage());
}
if (group.getName().contains("Informatikus-hallgatók")) {
setHeaderLabelText("MAVE adatlapja");
} else {
setHeaderLabelText(group.getName());
}
add(new FeedbackPanel("pagemessages"));
add(new BookmarkablePageLink<GroupHistory>("detailView", GroupHistory.class,
new PageParameters("id=" + group.getId().toString())));
Link<EditGroupInfo> editPageLink = new BookmarkablePageLink<EditGroupInfo>("editPage", EditGroupInfo.class,
new PageParameters("id=" + group.getId().toString()));
if (user != null && isUserGroupLeader(group)) {
editPageLink.setVisible(true);
} else {
editPageLink.setVisible(false);
}
add(editPageLink);
Link<ChangeDelegates> editDelegates =
new BookmarkablePageLink<ChangeDelegates>("editDelegates", ChangeDelegates.class,
new PageParameters("id=" + group.getId().toString()));
if (user != null && isUserGroupLeader(group) && group.getIsSvie()) {
editDelegates.setVisible(true);
} else {
editDelegates.setVisible(false);
}
add(editDelegates);
setDefaultModel(new CompoundPropertyModel<Group>(group));
add(new Label("name"));
add(new Label("founded"));
add(new Label("svieMs", (group.getIsSvie() ? "igen" : "nem")));
add(new SmartLinkLabel("webPage"));
add(new SmartLinkLabel("mailingList"));
add(new MultiLineLabel("introduction"));
Link<Void> applyLink = new Link<Void>("applyToGroup") {
@Override
public void onClick() {
userManager.addUserToGroup(user, group, new Date(), null);
getSession().info("Sikeres jelentkezés");
setResponsePage(ShowUser.class);
return;
}
};
applyLink.add(new ConfirmationBoxRenderer("Biztosan szeretnél jelentkezni a körbe?"));
if (user == null || user.getGroups().contains(group)) {
applyLink.setVisible(false);
}
add(applyLink);
List<Membership> activeMembers = group.getActiveMemberships();
List<Membership> inactiveMembers = group.getInactiveMemberships();
Panel adminOrActivePanel;
Panel adminOrOldBoysPanel;
if (isUserGroupLeader(group) || hasUserDelegatedPostInGroup(group)) {
adminOrActivePanel = new AdminMembershipsPanel("adminOrActive", activeMembers);
adminOrOldBoysPanel = new AdminOldBoysPanel("adminOrOldBoy", inactiveMembers);
} else {
adminOrActivePanel = new ActiveMembershipsPanel("adminOrActive", activeMembers);
adminOrOldBoysPanel = new OldBoysPanel("adminOrOldBoy", inactiveMembers);
}
add(adminOrActivePanel);
add(adminOrOldBoysPanel);
}
|
public boolean validateTab() {
Runtimer timer = new Runtimer();
timer.start();
boolean isRawData = studyType.equalsIgnoreCase("rawdata");
System.out.println("StudyType: " + studyType + " + " + isRawData);
if (txtProgram == null || txtProject == null || txtStudyName == null
|| txtStudyType == null) {
Messagebox.show("Error: All fields are required", "Upload Error",
Messagebox.OK, Messagebox.ERROR);
return false;
}
if (txtProgram.isEmpty() || txtProject.isEmpty()
|| txtStudyName.isEmpty() || txtStudyType.isEmpty()
) {
Messagebox.show("Error: All fields are required", "Upload Error",
Messagebox.OK, Messagebox.ERROR);
return false;
}
if (tempFile == null || !isVariableDataVisible) {
Messagebox.show("Error: You must upload a data first",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
if(startYear < Calendar.getInstance().get(Calendar.YEAR)){
Messagebox.show("Error: Invalid start year. Year must be greater or equal than the present year(" + Calendar.getInstance().get(Calendar.YEAR) + " )",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
if(endYear < Calendar.getInstance().get(Calendar.YEAR)){
Messagebox.show("Error: Invalid end year. Year must be greater or equal than the present year(" + Calendar.getInstance().get(Calendar.YEAR) + " )",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
UserFileManager fileMan = new UserFileManager();
StudyRawDataManagerImpl studyRawData = new StudyRawDataManagerImpl(isRawData);
StudyDerivedDataManagerImpl studyDerivedDataMan = new StudyDerivedDataManagerImpl();
if (study == null) {
study = new Study();
}
study.setName(txtStudyName);
study.setStudytypeid(new StudyTypeManagerImpl().getStudyTypeByName(
txtStudyType).getId());
study.setProgramid(new ProgramManagerImpl().getProgramByName(
txtProgram, userId).getId());
study.setProjectid(new ProjectManagerImpl().getProjectByName(
txtProject, userId).getId());
study.setStartyear(String.valueOf(startYear));
study.setEndyear(String.valueOf(String.valueOf(endYear)));
if (uploadTo.equals("database")) {
studyRawData.addStudyRawData(study,columnList.toArray(new String[columnList.size()]),dataList);
}
else{
fileMan.createNewFileFromUpload(1, study.getId(), dataFileName, tempFile, (isRaw) ? "rd":"dd");
}
for(GenotypeFileModel genoFile : genotypeFileList){
fileMan.createNewFileFromUpload(1, study.getId(), genoFile.name, genoFile.tempFile,"gd");
}
this.setStudyID(study.getId());
this.isRaw = isRawData;
System.out.println("Timer ends in: " + timer.end());
return true;
}
|
public boolean validateTab() {
Runtimer timer = new Runtimer();
timer.start();
boolean isRawData = studyType.equalsIgnoreCase("rawdata");
System.out.println("StudyType: " + studyType + " + " + isRawData);
if (txtProgram == null || txtProject == null || txtStudyName == null
|| txtStudyType == null) {
Messagebox.show("Error: All fields are required", "Upload Error",
Messagebox.OK, Messagebox.ERROR);
return false;
}
if (txtProgram.isEmpty() || txtProject.isEmpty()
|| txtStudyName.isEmpty() || txtStudyType.isEmpty()
) {
Messagebox.show("Error: All fields are required", "Upload Error",
Messagebox.OK, Messagebox.ERROR);
return false;
}
if (tempFile == null || !isVariableDataVisible) {
Messagebox.show("Error: You must upload a data first",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
if(startYear < Calendar.getInstance().get(Calendar.YEAR)){
Messagebox.show("Error: Invalid start year. Year must be greater or equal than the present year(" + Calendar.getInstance().get(Calendar.YEAR) + " )",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
if(endYear < Calendar.getInstance().get(Calendar.YEAR)){
Messagebox.show("Error: Invalid end year. Year must be greater or equal than the present year(" + Calendar.getInstance().get(Calendar.YEAR) + " )",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
UserFileManager fileMan = new UserFileManager();
StudyRawDataManagerImpl studyRawData = new StudyRawDataManagerImpl(isRawData);
if (study == null) {
study = new Study();
}
study.setName(txtStudyName);
study.setStudytypeid(new StudyTypeManagerImpl().getStudyTypeByName(
txtStudyType).getId());
study.setProgramid(new ProgramManagerImpl().getProgramByName(
txtProgram, userId).getId());
study.setProjectid(new ProjectManagerImpl().getProjectByName(
txtProject, userId).getId());
study.setStartyear(String.valueOf(startYear));
study.setEndyear(String.valueOf(String.valueOf(endYear)));
if (uploadTo.equals("database")) {
studyRawData.addStudyRawData(study,columnList.toArray(new String[columnList.size()]),dataList);
}
else{
fileMan.createNewFileFromUpload(1, study.getId(), dataFileName, tempFile, (isRaw) ? "rd":"dd");
}
for(GenotypeFileModel genoFile : genotypeFileList){
fileMan.createNewFileFromUpload(1, study.getId(), genoFile.name, genoFile.tempFile,"gd");
}
this.setStudyID(study.getId());
this.isRaw = isRawData;
System.out.println("Timer ends in: " + timer.end());
return true;
}
|
public Object[] getAllValues() {
if (getSize() == 0)
return new Object[0];
ArrayList results = new ArrayList(getSize());
Iterator iter = internal.values().iterator();
while (iter.hasNext()) {
Object value = iter.next();
if (value.getClass().isArray()) {
Object[] values = (Object[]) iter.next();
for (int i = 0; i < values.length; i++)
results.add(values[i]);
} else
results.add(value);
}
return results.toArray();
}
|
public Object[] getAllValues() {
if (getSize() == 0)
return new Object[0];
ArrayList results = new ArrayList(getSize());
Iterator iter = internal.values().iterator();
while (iter.hasNext()) {
Object value = iter.next();
if (value.getClass().isArray()) {
Object[] values = (Object[]) value;
for (int i = 0; i < values.length; i++)
results.add(values[i]);
} else
results.add(value);
}
return results.toArray();
}
|
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_account);
userImage = (ImageView) findViewById(R.id.createUserImage);
micImage = (ImageView) findViewById(R.id.accountCreationRecorderButton);
List<UserAccount> userAccounts = database.getUserAccounts();
if (userAccounts.size() == 1) {
UserAccount userAccount = userAccounts.get(0);
EditText userNameTextField = ((EditText) findViewById(R.id.createEditChildName));
userNameTextField.setText(userAccount.getUserName());
userImage.setImageDrawable(ImageUtils
.byteArrayToDrawable(userAccount.getUserImage()));
}
Button createSaveButton = (Button) findViewById(R.id.createSaveButton);
createSaveButton.setOnClickListener(this);
ImageButton createUploadPhotoButton = (ImageButton) findViewById(R.id.createUploadPhotoButton);
createUploadPhotoButton.setOnClickListener(this);
micImage.setOnClickListener(this);
}
|
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_account);
userImage = (ImageView) findViewById(R.id.createUserImage);
micImage = (ImageView) findViewById(R.id.accountCreationRecorderButton);
List<UserAccount> userAccounts = database.getUserAccounts();
if (userAccounts.size() == 1) {
UserAccount userAccount = userAccounts.get(0);
EditText userNameTextField = ((EditText) findViewById(R.id.createEditChildName));
userNameTextField.setText(userAccount.getUserName());
userImage.setImageDrawable(ImageUtils
.byteArrayToDrawable(userAccount.getUserImage()));
userImage.setMaxHeight(400);
userImage.setMaxWidth(400);
userImage.setAdjustViewBounds(false);
}
Button createSaveButton = (Button) findViewById(R.id.createSaveButton);
createSaveButton.setOnClickListener(this);
ImageButton createUploadPhotoButton = (ImageButton) findViewById(R.id.createUploadPhotoButton);
createUploadPhotoButton.setOnClickListener(this);
micImage.setOnClickListener(this);
}
|
public void write(Device d, SLayoutManager l)
throws IOException
{
SGridLayout layout = (SGridLayout)l;
SContainer container = layout.getContainer();
List components = layout.getComponents();
boolean header = layout.getHeader();
boolean relative = layout.isRelative();
int width = layout.getWidth();
int cellSpacing = layout.getCellSpacing();
int cellPadding = layout.getCellPadding();
int border = layout.getBorder();
int cols = layout.getColumns();
int rows = layout.getRows();
d.print("\n<table ");
if ( Utils.hasSpanAttributes( container ) )
{
d.print("style=\"");
Utils.writeSpanAttributes( d, (SComponent) container );
d.print("\" ");
}
if (cellSpacing >= 0)
d.print(" cellspacing=\"").print(cellSpacing).print("\"");
else
d.print(" cellspacing=\"0\"");
if (cellPadding >= 0)
d.print(" cellpadding=\"").print(cellPadding).print("\"");
else
d.print(" cellpadding=\"0\"");
CGUtil.writeSize( d, container );
if (border > 0)
d.print(" border=\"").print(border).print("\"");
else
d.print(" border=\"0\"");
if (container != null && container.getBackground() != null)
d.print(" bgcolor=\"#").
print(Utils.toColorString(container.getBackground())).print("\"");
d.print(">\n");
if (cols <= 0)
cols = components.size() / rows;
boolean firstRow = true;
int col = 0;
for (Iterator iter = components.iterator(); iter.hasNext();) {
if (col == 0)
d.print("<tr>");
else if (col%cols == 0 && iter.hasNext()) {
d.print("</tr>\n<tr>");
firstRow = false;
}
SComponent c = (SComponent)iter.next();
if (firstRow && header) {
d.print("<th");
Utils.printTableCellAlignment(d, c);
if (c instanceof SContainer) {
Utils.printTableCellColors(d, c);
}
d.print(">");
}
else {
d.print("<td");
Utils.printTableCellAlignment(d, c);
if (c instanceof SContainer) {
Utils.printTableCellColors(d, c);
}
d.print(">");
}
c.write(d);
if (firstRow && header)
d.print("</th>");
else
d.print("</td>");
col++;
if (!iter.hasNext())
d.print("</tr>\n");
}
d.print("</table>");
}
|
public void write(Device d, SLayoutManager l)
throws IOException
{
SGridLayout layout = (SGridLayout)l;
SContainer container = layout.getContainer();
List components = layout.getComponents();
boolean header = layout.getHeader();
boolean relative = layout.isRelative();
int width = layout.getWidth();
int cellSpacing = layout.getCellSpacing();
int cellPadding = layout.getCellPadding();
int border = layout.getBorder();
int cols = layout.getColumns();
int rows = layout.getRows();
d.print("\n<table ");
if ( Utils.hasSpanAttributes( container ) )
{
d.print("style=\"");
Utils.writeSpanAttributes( d, (SComponent) container );
d.print("\" ");
}
if (cellSpacing >= 0)
d.print(" cellspacing=\"").print(cellSpacing).print("\"");
else
d.print(" cellspacing=\"0\"");
if (cellPadding >= 0)
d.print(" cellpadding=\"").print(cellPadding).print("\"");
else
d.print(" cellpadding=\"0\"");
CGUtil.writeSize( d, container );
if (border > 0)
d.print(" border=\"").print(border).print("\"");
else
d.print(" border=\"0\"");
if (container != null && container.getBackground() != null)
d.print(" bgcolor=\"#").
print(Utils.toColorString(container.getBackground())).print("\"");
d.print(">\n");
if (cols <= 0)
cols = components.size() / rows;
boolean firstRow = true;
int col = 0;
for (Iterator iter = components.iterator(); iter.hasNext();) {
if (col == 0)
d.print("<tr>");
else if (col%cols == 0 && iter.hasNext()) {
d.print("</tr>\n<tr>");
firstRow = false;
}
SComponent c = (SComponent)iter.next();
if (firstRow && header) {
d.print("<th");
Utils.printTableCellAlignment(d, c);
if (c instanceof SContainer && c.isVisible()) {
Utils.printTableCellColors(d, c);
}
d.print(">");
}
else {
d.print("<td");
Utils.printTableCellAlignment(d, c);
if (c instanceof SContainer && c.isVisible()) {
Utils.printTableCellColors(d, c);
}
d.print(">");
}
c.write(d);
if (firstRow && header)
d.print("</th>");
else
d.print("</td>");
col++;
if (!iter.hasNext())
d.print("</tr>\n");
}
d.print("</table>");
}
|
public RoutineChangedDialogData open(String rouName, String infile1, String infile2, boolean isSave, boolean isMult) {
result = new RoutineChangedDialogData();
routineName = rouName;
isSaveValue = isSave;
final Shell shell = new Shell(getParent(), SWT.DIALOG_TRIM |
SWT.APPLICATION_MODAL);
String strVal = MPiece.getPiece(VistaConnection.getCurrentServer(),";");
strVal = "Routine "+routineName+" Changed on Server '"+strVal+"'";
String strProject = MPiece.getPiece(VistaConnection.getCurrentServer(),";",4);
if (! (strProject.compareTo("") == 0)) {
strVal = strVal + " (Project "+strProject+")";
}
shell.setText(strVal);
shell.setSize(400,200);
file1 = infile1;
file2 = infile2;
lblQuestion = new Label(shell, SWT.NONE);
lblQuestion.setLocation(20,10);
lblQuestion.setSize(350,20);
lblQuestion.setText("The version on the server has changed. Do you still want to save");
if (! isSave) {
lblQuestion.setText("The version on the server has changed. Do you still want to load");
}
Label lblQ2 = new Label(shell, SWT.NONE);
lblQ2.setLocation(20,30);
lblQ2.setSize(350,20);
lblQ2.setText("this version on the server? (note that the changes HAVE");
String projectName = VistaConnection.getCurrentProject();
if (projectName.compareTo("") == 0) {
projectName = MEditorPrefs.getPrefs(MEditorPlugin.P_PROJECT_NAME);
}
Label lblQ4 = new Label(shell, SWT.NONE);
lblQ4.setLocation(20,50);
lblQ4.setSize(350,20);
lblQ4.setText("been saved in the "+projectName+" directory and you may open that");
if (! isSave) {
lblQ2.setText("this version from the server?");
lblQ4.setText("");
}
if (isMult) {
lblQ2.setText("this version on the Server?");
lblQ4.setText("");
}
Label lblQ5 = new Label(shell, SWT.NONE);
lblQ5.setLocation(20,70);
lblQ5.setSize(350,20);
lblQ5.setText("file later (not loading from the server), edit it and then save to ");
Label lblQ7 = new Label(shell, SWT.NONE);
lblQ7.setLocation(20,90);
lblQ7.setSize(350,20);
lblQ7.setText("the server.)");
if ((!isSave)|| isMult) {
lblQ5.setText("");
lblQ7.setText("");
}
chkSaveCopy = new Button(shell, SWT.CHECK);
chkSaveCopy.setText("Check to Save a Copy");
chkSaveCopy.setLocation(20,110);
chkSaveCopy.setSize(300,20);
if (!isSave) {
chkSaveCopy.setVisible(false);
chkSaveCopy.setSelection(false);
}
btnOK = new Button(shell, SWT.PUSH);
btnOK.setText("&OK");
btnOK.setLocation(20,130);
btnOK.setSize(55,25);
shell.setDefaultButton(btnOK);
btnCancel = new Button(shell, SWT.PUSH);
btnCancel.setText("&Cancel");
btnCancel.setLocation(320,130);
btnCancel.setSize(55,25);
btnView = new Button(shell, SWT.PUSH);
btnView.setText("&View");
btnView.setLocation(168,130);
btnView.setSize(55,25);
if (isMult && isSave) {
textString = "the version being saved to the server";
}
else {
textString = "the PREVIOUS version loaded from the server";
}
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == btnView) {
try {
RoutineCompare.compareRoutines(file1,file2,textString,routineName,isSaveValue);
} catch (Exception e) {
MessageDialog.openInformation(
MEditorUtilities.getIWorkbenchWindow().getShell(),
"M-Editor Plug-in",
"Error encountered while comparing versions on server "+e.getMessage());
}
}
if (event.widget == btnOK) {
result.setReturnValue(true);
result.setSaveServerRoutine(chkSaveCopy.getSelection());
shell.setVisible(false);
shell.close();
}
if (event.widget == btnCancel) {
result.setReturnValue(false);
result.setSaveServerRoutine(false);
shell.setVisible(false);
shell.close();
}
}
};
btnOK.addListener(SWT.Selection, listener);
btnCancel.addListener(SWT.Selection, listener);
btnView.addListener(SWT.Selection, listener);
shell.open();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
return result;
}
|
public RoutineChangedDialogData open(String rouName, String infile1, String infile2, boolean isSave, boolean isMult) {
result = new RoutineChangedDialogData();
routineName = rouName;
isSaveValue = isSave;
final Shell shell = new Shell(getParent(), SWT.DIALOG_TRIM |
SWT.APPLICATION_MODAL | SWT.CENTER);
String strVal = MPiece.getPiece(VistaConnection.getCurrentServer(),";");
strVal = "Routine "+routineName+" Changed on Server '"+strVal+"'";
String strProject = MPiece.getPiece(VistaConnection.getCurrentServer(),";",4);
if (! (strProject.compareTo("") == 0)) {
strVal = strVal + " (Project "+strProject+")";
}
shell.setText(strVal);
shell.setSize(400,200);
file1 = infile1;
file2 = infile2;
lblQuestion = new Label(shell, SWT.NONE);
lblQuestion.setLocation(20,10);
lblQuestion.setSize(350,20);
lblQuestion.setText("The version on the server has changed. Do you still want to save");
if (! isSave) {
lblQuestion.setText("The version on the server has changed. Do you still want to load");
}
Label lblQ2 = new Label(shell, SWT.NONE);
lblQ2.setLocation(20,30);
lblQ2.setSize(350,20);
lblQ2.setText("this version onto the server? (note that the changes HAVE");
String projectName = VistaConnection.getCurrentProject();
if (projectName.compareTo("") == 0) {
projectName = MEditorPrefs.getPrefs(MEditorPlugin.P_PROJECT_NAME);
}
Label lblQ4 = new Label(shell, SWT.NONE);
lblQ4.setLocation(20,50);
lblQ4.setSize(350,20);
lblQ4.setText("been saved in the "+projectName+" directory and you may open that");
if (! isSave) {
lblQ2.setText("this version from the server?");
lblQ4.setText("");
}
if (isMult) {
lblQ2.setText("this version on the Server?");
lblQ4.setText("");
}
Label lblQ5 = new Label(shell, SWT.NONE);
lblQ5.setLocation(20,70);
lblQ5.setSize(350,20);
lblQ5.setText("file later (not loading from the server), edit it and then save to ");
Label lblQ7 = new Label(shell, SWT.NONE);
lblQ7.setLocation(20,90);
lblQ7.setSize(350,20);
lblQ7.setText("the server.)");
if ((!isSave)|| isMult) {
lblQ5.setText("");
lblQ7.setText("");
}
chkSaveCopy = new Button(shell, SWT.CHECK);
chkSaveCopy.setText("Check to Save a Copy");
chkSaveCopy.setLocation(20,110);
chkSaveCopy.setSize(300,20);
if (!isSave) {
chkSaveCopy.setVisible(false);
chkSaveCopy.setSelection(false);
}
btnOK = new Button(shell, SWT.PUSH);
btnOK.setText("&OK");
btnOK.setLocation(20,130);
btnOK.setSize(55,25);
shell.setDefaultButton(btnOK);
btnCancel = new Button(shell, SWT.PUSH);
btnCancel.setText("&Cancel");
btnCancel.setLocation(320,130);
btnCancel.setSize(55,25);
btnView = new Button(shell, SWT.PUSH);
btnView.setText("&View");
btnView.setLocation(168,130);
btnView.setSize(55,25);
if (isMult && isSave) {
textString = "the version being saved to the server";
}
else {
textString = "the PREVIOUS version loaded from the server";
}
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == btnView) {
try {
RoutineCompare.compareRoutines(file1,file2,textString,routineName,isSaveValue);
} catch (Exception e) {
MessageDialog.openInformation(
MEditorUtilities.getIWorkbenchWindow().getShell(),
"M-Editor Plug-in",
"Error encountered while comparing versions on server "+e.getMessage());
}
}
if (event.widget == btnOK) {
result.setReturnValue(true);
result.setSaveServerRoutine(chkSaveCopy.getSelection());
shell.setVisible(false);
shell.close();
}
if (event.widget == btnCancel) {
result.setReturnValue(false);
result.setSaveServerRoutine(false);
shell.setVisible(false);
shell.close();
}
}
};
btnOK.addListener(SWT.Selection, listener);
btnCancel.addListener(SWT.Selection, listener);
btnView.addListener(SWT.Selection, listener);
shell.open();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
return result;
}
|
public void step() {
for (int i = 0; i < Constants.PLANTS_CREATED_PER_TURN; i++) {
int r = (int) (grid.nRows() * Math.random());
int c = (int) (grid.nCols() * Math.random());
if (!grid.get(c, r).plant() && !grid.get(c, r).rock()) {
grid.get(c, r).putPlant();
} else {
i--;
}
}
int cr = 0;
for (Reference<Tile> e : grid) {
if (e.contents() != null && e.contents().critter()) {
cr++;
}
}
double prob = Constants.PLANT_GROW_PROB / (cr == 0 ? 1 : cr);
for (Reference<Tile> e : grid) {
Tile t = e.contents();
if (t.plant()) {
for (HexDir d : HexDir.values()) {
if (e.adj(d) != null
&& !e.adj(d).contents().plant()
&& Math.random() < prob) {
e.adj(d).contents().putPlant();
}
}
}
if (t.critter()) {
if (!WAIT) {
t.getCritter().randomAct();
}
if (t.critter()) {
t.getCritter().timeStep();
}
}
}
timesteps++;
System.out.println("-----------------" + timesteps);
}
|
public void step() {
for (int i = 0; i < Constants.PLANTS_CREATED_PER_TURN; i++) {
int r = (int) (grid.nRows() * Math.random());
int c = (int) (grid.nCols() * Math.random());
if (!grid.get(c, r).plant() && !grid.get(c, r).rock()) {
grid.get(c, r).putPlant();
} else {
i--;
}
}
int cr = 0;
for (Reference<Tile> e : grid) {
if (e.contents() != null && e.contents().critter()) {
cr++;
}
}
double prob = Constants.PLANT_GROW_PROB / (cr == 0 ? 1 : cr);
for (Reference<Tile> e : grid) {
Tile t = e.contents();
if (t.plant()) {
for (HexDir d : HexDir.values()) {
if (e.adj(d) != null
&& !e.adj(d).contents().plant()
&& !e.adj(d).contents().rock()
&& Math.random() < prob) {
e.adj(d).contents().putPlant();
}
}
}
if (t.critter()) {
if (!WAIT) {
t.getCritter().randomAct();
}
if (t.critter()) {
t.getCritter().timeStep();
}
}
}
timesteps++;
System.out.println("-----------------" + timesteps);
}
|
public void simpleUnsubscribe(MSymbol symbol){
if (symbol != null){
MarketDataFeedService marketDataFeed = getMarketDataFeedService();
if (marketDataFeed != null){
Pair<ISubscription, Message> pair = simpleSubscriptions.remove(symbol);
ISubscription subscription = pair.getFirstMember();
if (pair != null && subscription!=null){
try {
marketDataFeed.unsubscribe(subscription);
} catch (MarketceteraException e) {
PhotonPlugin.getMainConsoleLogger().warn("Error unsubscribing to updates for "+symbol);
}
}
}
}
}
|
public void simpleUnsubscribe(MSymbol symbol){
if (symbol != null){
MarketDataFeedService marketDataFeed = getMarketDataFeedService();
if (marketDataFeed != null){
Pair<ISubscription, Message> pair = simpleSubscriptions.remove(symbol);
if (pair != null) {
ISubscription subscription = pair.getFirstMember();
if (subscription!=null){
try {
marketDataFeed.unsubscribe(subscription);
} catch (MarketceteraException e) {
PhotonPlugin.getMainConsoleLogger().warn("Error unsubscribing to updates for "+symbol);
}
}
}
}
}
}
|
protected boolean setValues(float x, float y, int pressure,
float deltaThreshold, boolean start) {
if (deltaThreshold == 0 || position.getDistance(x, y) >= deltaThreshold) {
if (start) {
lastPosition = null;
delta.set(0, 0);
count = 0;
} else {
lastPosition = position;
delta.set(x - position.x, y - position.y);
count++;
}
position = new Point(x, y);
this.pressure = pressure / 255.0;
return true;
}
return false;
}
|
protected boolean setValues(float x, float y, int pressure,
float deltaThreshold, boolean start) {
if (deltaThreshold == 0 || position.getDistance(x, y) >= deltaThreshold) {
if (start) {
lastPosition = null;
delta = new Point();
count = 0;
} else {
lastPosition = position;
delta.set(x - position.x, y - position.y);
count++;
}
position = new Point(x, y);
this.pressure = pressure / 255.0;
return true;
}
return false;
}
|
public static <K, V> Object convert(Class<V> valueClazz, Class<K> keyClazz, CValue value) throws ConstrettoException {
if (value instanceof CPrimitive) {
return convertPrimitive(valueClazz, (CPrimitive) value);
} else if (value instanceof CArray) {
return convertList(valueClazz, (CArray) value);
} else if (value instanceof CObject) {
return convertMap(keyClazz, valueClazz, (CObject) value);
} else {
throw new ConstrettoException("ivalid datatype, parsing haz failed");
}
}
|
public static <K, V> Object convert(Class<V> valueClazz, Class<K> keyClazz, CValue value) throws ConstrettoException {
if (value instanceof CPrimitive) {
return convertPrimitive(valueClazz, (CPrimitive) value);
} else if (value instanceof CArray) {
return convertList(valueClazz, (CArray) value);
} else if (value instanceof CObject) {
return convertMap(keyClazz, valueClazz, (CObject) value);
} else {
throw new ConstrettoException("invalid datatype, parsing haz failed");
}
}
|
public String addFile(InputStream inputStream, String filename) {
try {
File file;
File ff = new File(directory);
if (filename == null) {
file = File.createTempFile("versus", ".tmp", ff);
} else {
int idx = filename.lastIndexOf(".");
if (idx != -1) {
file = File.createTempFile(filename.substring(0, idx), filename.substring(idx), ff);
} else {
file = File.createTempFile(filename, ".tmp", ff);
}
}
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
return file.getName();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
|
public String addFile(InputStream inputStream, String filename) {
try {
File file;
File ff = new File(directory);
if (filename == null) {
file = File.createTempFile("versus", ".tmp", ff);
} else {
int idx = filename.lastIndexOf(".");
if (idx != -1) {
file = File.createTempFile(filename.substring(0, idx), filename.substring(idx), ff);
} else {
file = File.createTempFile(filename, ".tmp", ff);
}
}
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
return file.getName();
} catch (FileNotFoundException e) {
System.err.println("Upload directory not found: " + directory);
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
|
public void mousePressed(MouseEvent evt)
{
int x = evt.getX();
int y = evt.getY();
EditWindow wnd = (EditWindow)evt.getSource();
Highlighter highlighter = wnd.getHighlighter();
if (evt.getClickCount() == 2)
{
if (highlighter.getNumHighlights() >= 1)
{
EditMenu.getInfoCommand(true);
return;
}
}
if (ClickZoomWireListener.isRightMouse(evt))
{
AffineTransform trans = outlineNode.rotateOutAboutTrueCenter();
Point2D [] origPoints = outlineNode.getTrace();
if (origPoints == null)
{
Point2D [] newPoints = new Point2D[1];
newPoints[0] = new Point2D.Double(outlineNode.getAnchorCenterX(), outlineNode.getAnchorCenterY());
EditWindow.gridAlign(newPoints[0]);
setNewPoints(newPoints, 0);
point = 0;
oldX = newPoints[point].getX();
oldY = newPoints[point].getY();
} else if (origPoints.length == 1)
{
Point2D [] newPoints = new Point2D[2];
newPoints[0] = new Point2D.Double(outlineNode.getAnchorCenterX() + origPoints[0].getX(),
outlineNode.getAnchorCenterY() + origPoints[0].getY());
trans.transform(newPoints[0], newPoints[0]);
EditWindow.gridAlign(newPoints[0]);
newPoints[1] = new Point2D.Double(newPoints[0].getX() + 2, newPoints[0].getY() + 2);
EditWindow.gridAlign(newPoints[1]);
setNewPoints(newPoints, 1);
point = 1;
oldX = newPoints[point].getX();
oldY = newPoints[point].getY();
} else
{
Point2D [] newPoints = new Point2D[origPoints.length+1];
int j = 0;
for(int i=0; i<origPoints.length; i++)
{
if (origPoints[i] != null)
{
newPoints[j] = new Point2D.Double(outlineNode.getAnchorCenterX() + origPoints[i].getX(),
outlineNode.getAnchorCenterY() + origPoints[i].getY());
}
j++;
if (i == point)
{
newPoints[j] = wnd.screenToDatabase(x, y);
EditWindow.gridAlign(newPoints[j]);
j++;
}
}
trans.transform(newPoints, 0, newPoints, 0, newPoints.length);
setNewPoints(newPoints, point+1);
oldX = newPoints[point+1].getX();
oldY = newPoints[point+1].getY();
}
doingMotionDrag = true;
wnd.repaint();
return;
}
Point2D pt = wnd.screenToDatabase(x, y);
Highlight found = highlighter.findObject(pt, wnd, true, false, false, false, true, false, false);
doingMotionDrag = false;
if (found != null)
{
high = highlighter.getOneHighlight();
assert (high == found);
outlineNode = (NodeInst)highlighter.getOneElectricObject(NodeInst.class);
if (high != null && outlineNode != null)
{
point = high.getPoint();
Point2D [] origPoints = outlineNode.getTrace();
if (origPoints != null)
{
doingMotionDrag = true;
EditWindow.gridAlign(pt);
oldX = pt.getX();
oldY = pt.getY();
}
}
}
wnd.repaint();
}
|
public void mousePressed(MouseEvent evt)
{
int x = evt.getX();
int y = evt.getY();
EditWindow wnd = (EditWindow)evt.getSource();
Highlighter highlighter = wnd.getHighlighter();
if (evt.getClickCount() == 2)
{
if (highlighter.getNumHighlights() >= 1)
{
EditMenu.getInfoCommand(true);
return;
}
}
if (ClickZoomWireListener.isRightMouse(evt))
{
AffineTransform trans = outlineNode.rotateOutAboutTrueCenter();
Point2D [] origPoints = outlineNode.getTrace();
if (origPoints == null)
{
Point2D [] newPoints = new Point2D[1];
newPoints[0] = new Point2D.Double(outlineNode.getAnchorCenterX(), outlineNode.getAnchorCenterY());
EditWindow.gridAlign(newPoints[0]);
setNewPoints(newPoints, 0);
point = 0;
oldX = newPoints[point].getX();
oldY = newPoints[point].getY();
} else if (origPoints.length == 1)
{
Point2D [] newPoints = new Point2D[2];
newPoints[0] = new Point2D.Double(outlineNode.getAnchorCenterX() + origPoints[0].getX(),
outlineNode.getAnchorCenterY() + origPoints[0].getY());
trans.transform(newPoints[0], newPoints[0]);
EditWindow.gridAlign(newPoints[0]);
newPoints[1] = new Point2D.Double(newPoints[0].getX() + 2, newPoints[0].getY() + 2);
EditWindow.gridAlign(newPoints[1]);
setNewPoints(newPoints, 1);
point = 1;
oldX = newPoints[point].getX();
oldY = newPoints[point].getY();
} else
{
Point2D [] newPoints = new Point2D[origPoints.length+1];
int j = 0;
for(int i=0; i<origPoints.length; i++)
{
if (origPoints[i] != null)
{
newPoints[j] = new Point2D.Double(outlineNode.getAnchorCenterX() + origPoints[i].getX(),
outlineNode.getAnchorCenterY() + origPoints[i].getY());
}
j++;
if (i == point)
{
newPoints[j] = wnd.screenToDatabase(x, y);
EditWindow.gridAlign(newPoints[j]);
j++;
}
}
trans.transform(newPoints, 0, newPoints, 0, newPoints.length);
setNewPoints(newPoints, point+1);
oldX = newPoints[point+1].getX();
oldY = newPoints[point+1].getY();
}
doingMotionDrag = true;
wnd.repaint();
return;
}
Point2D pt = wnd.screenToDatabase(x, y);
Highlight found = highlighter.findObject(pt, wnd, true, false, false, false, true, true, false);
doingMotionDrag = false;
if (found != null)
{
high = highlighter.getOneHighlight();
assert (high == found);
outlineNode = (NodeInst)highlighter.getOneElectricObject(NodeInst.class);
if (high != null && outlineNode != null)
{
point = high.getPoint();
Point2D [] origPoints = outlineNode.getTrace();
if (origPoints != null)
{
doingMotionDrag = true;
EditWindow.gridAlign(pt);
oldX = pt.getX();
oldY = pt.getY();
}
}
}
wnd.repaint();
}
|
public <T extends OTObject> T setResourcesFromSchema(OTObjectInternal otObjectImpl, Class<T> otObjectClass)
{
Constructor<T> [] memberConstructors = otObjectClass.getConstructors();
Constructor<T> resourceConstructor = memberConstructors[0];
Class<?> [] params = resourceConstructor.getParameterTypes();
if(memberConstructors.length > 1) {
System.err.println("OTObjects should only have 1 constructor");
return null;
}
if(params == null | params.length == 0) {
try {
return otObjectClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
OTResourceSchemaHandler handler = null;
Object constructorParams [] = new Object [params.length];
int nextParam = 0;
if(params[0].isInterface() &&
OTResourceSchema.class.isAssignableFrom(params[0])){
Class<? extends OTResourceSchema> schemaClass = (Class<? extends OTResourceSchema>)params[0];
handler = new OTResourceSchemaHandler(otObjectImpl, otrunk,
schemaClass);
Class<?> [] interfaceList = new Class[] { schemaClass };
Object resources =
Proxy.newProxyInstance(schemaClass.getClassLoader(),
interfaceList, handler);
constructorParams[0] = resources;
nextParam++;
}
for(int i=nextParam; i<params.length; i++) {
constructorParams[i] = otrunk.getService(params[i]);
if(constructorParams[i] == null) {
System.err.println("No service could be found to handle the\n" +
" requirement of: " + otObjectClass + "\n" +
" for: " + params[i]);
return null;
}
}
T otObject = null;
try {
otObject = resourceConstructor.newInstance(constructorParams);
handler.setEventSource(otObject);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return otObject;
}
|
public <T extends OTObject> T setResourcesFromSchema(OTObjectInternal otObjectImpl, Class<T> otObjectClass)
{
Constructor<T> [] memberConstructors = (Constructor<T> [])otObjectClass.getConstructors();
Constructor<T> resourceConstructor = memberConstructors[0];
Class<?> [] params = resourceConstructor.getParameterTypes();
if(memberConstructors.length > 1) {
System.err.println("OTObjects should only have 1 constructor");
return null;
}
if(params == null | params.length == 0) {
try {
return otObjectClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
OTResourceSchemaHandler handler = null;
Object constructorParams [] = new Object [params.length];
int nextParam = 0;
if(params[0].isInterface() &&
OTResourceSchema.class.isAssignableFrom(params[0])){
Class<? extends OTResourceSchema> schemaClass = (Class<? extends OTResourceSchema>)params[0];
handler = new OTResourceSchemaHandler(otObjectImpl, otrunk,
schemaClass);
Class<?> [] interfaceList = new Class[] { schemaClass };
Object resources =
Proxy.newProxyInstance(schemaClass.getClassLoader(),
interfaceList, handler);
constructorParams[0] = resources;
nextParam++;
}
for(int i=nextParam; i<params.length; i++) {
constructorParams[i] = otrunk.getService(params[i]);
if(constructorParams[i] == null) {
System.err.println("No service could be found to handle the\n" +
" requirement of: " + otObjectClass + "\n" +
" for: " + params[i]);
return null;
}
}
T otObject = null;
try {
otObject = resourceConstructor.newInstance(constructorParams);
handler.setEventSource(otObject);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return otObject;
}
|
public static WebArchive createProcessApplication() {
BpmnModelInstance process = Bpmn.createExecutableProcess(TEST_PROCESS)
.startEvent()
.serviceTask()
.delegateExpression("${bpmnElementRetrievalDelegate}")
.done();
return initWebArchiveDeployment()
.addClass(BpmnElementRetrievalDelegate.class)
.addAsResource(new StringAsset(Bpmn.convertToString(process)), "testProcess.bpmn20.xml");
}
|
public static WebArchive createProcessApplication() {
BpmnModelInstance process = Bpmn.createExecutableProcess(TEST_PROCESS)
.startEvent()
.serviceTask()
.camundaDelegateExpression("${bpmnElementRetrievalDelegate}")
.done();
return initWebArchiveDeployment()
.addClass(BpmnElementRetrievalDelegate.class)
.addAsResource(new StringAsset(Bpmn.convertToString(process)), "testProcess.bpmn20.xml");
}
|
public void login(final String email, final String password) throws IOException, SerializationException {
if (!started) {
startupLock.lock();
try {
try {
log.debug("Waiting to login until user service is started");
startupCondition.await();
} catch (InterruptedException e) {
return;
}
} finally {
startupLock.unlock();
}
}
MetadataServerConfig msc = new MetadataServerConfig(rbnb.getConfig().getMetadataServerUrl());
log.info("Attempting login as user " + email);
try {
UserMsg.Builder ub = UserMsg.newBuilder();
SerializationManager sm = rbnb.getSerializationManager();
sm.setCreds(email, password);
sm.getObjectFromUrl(ub, msc.getUserUrl(email));
User tryUser = new User(ub.build());
tryUser.setPassword(password);
rbnb.getConfig().setMetadataServerUsername(email);
rbnb.getConfig().setMetadataServerPassword(password);
rbnb.saveConfig();
usersByEmail.clear();
usersById.clear();
playlists.clear();
myPlaylistIdsByTitle.clear();
usersByEmail.put(email, tryUser);
usersById.put(tryUser.getUserId(), tryUser);
this.msc = msc;
me = tryUser;
log.info("Login as " + email + " successful");
rbnb.getExecutor().execute(new CatchingRunnable() {
public void doRun() throws Exception {
rbnb.getEventService().fireLoggedIn();
synchronized (UserService.this) {
usersByEmail.put(me.getEmail(), me);
usersById.put(me.getUserId(), me);
}
rbnb.getEventService().fireUserChanged(me);
rbnb.getTaskService().runTask(new InitialFetchTask());
}
});
if (rbnb.getMina() != null && rbnb.getMina().isConnectedToSupernode()) {
rbnb.setStatus(RobonoboStatus.Connected);
rbnb.getEventService().fireStatusChanged();
}
} catch (IOException e) {
log.error("Caught exception logging in", e);
throw e;
} catch (SerializationException e) {
log.error("Caught exception logging in", e);
throw e;
}
}
|
public void login(final String email, final String password) throws IOException, SerializationException {
if (!started) {
startupLock.lock();
try {
try {
log.debug("Waiting to login until user service is started");
startupCondition.await();
} catch (InterruptedException e) {
return;
}
} finally {
startupLock.unlock();
}
}
MetadataServerConfig msc = new MetadataServerConfig(rbnb.getConfig().getMetadataServerUrl());
log.info("Attempting login as user " + email);
try {
UserMsg.Builder ub = UserMsg.newBuilder();
SerializationManager sm = rbnb.getSerializationManager();
sm.setCreds(email, password);
sm.getObjectFromUrl(ub, msc.getUserUrl(email));
User tryUser = new User(ub.build());
tryUser.setPassword(password);
rbnb.getConfig().setMetadataServerUsername(email);
rbnb.getConfig().setMetadataServerPassword(password);
rbnb.saveConfig();
usersByEmail.clear();
usersById.clear();
playlists.clear();
myPlaylistIdsByTitle.clear();
usersByEmail.put(email, tryUser);
usersById.put(tryUser.getUserId(), tryUser);
this.msc = msc;
me = tryUser;
log.info("Login as " + email + " successful");
rbnb.getExecutor().execute(new CatchingRunnable() {
public void doRun() throws Exception {
synchronized (UserService.this) {
usersByEmail.put(me.getEmail(), me);
usersById.put(me.getUserId(), me);
}
rbnb.getEventService().fireLoggedIn();
rbnb.getEventService().fireUserChanged(me);
rbnb.getTaskService().runTask(new InitialFetchTask());
}
});
if (rbnb.getMina() != null && rbnb.getMina().isConnectedToSupernode()) {
rbnb.setStatus(RobonoboStatus.Connected);
rbnb.getEventService().fireStatusChanged();
}
} catch (IOException e) {
log.error("Caught exception logging in", e);
throw e;
} catch (SerializationException e) {
log.error("Caught exception logging in", e);
throw e;
}
}
|
public void onEntityDamage(EntityDamageEvent event) {
if(event.isCancelled()) {
return;
}
if(!(event.getEntity() instanceof HumanEntity)) {
return;
}
HumanEntity human = (HumanEntity) event.getEntity();
PowerArmourComponents loadout = new PowerArmourComponents();
loadout.head = human.getInventory().getHelmet().getType();
loadout.body = human.getInventory().getChestplate().getType();
loadout.legs = human.getInventory().getLeggings().getType();
loadout.feet = human.getInventory().getBoots().getType();
loadout.hand = human.getItemInHand().getType();
parent.log.info(parent.armourList.keySet().toString());
for(PowerArmourAbilities a : parent.armourList.keySet()) {
PowerArmourComponents c = parent.armourList.get(a);
if(c.head != Material.AIR && loadout.head != c.head) { continue; }
if(c.body != Material.AIR && loadout.body != c.body) { continue; }
if(c.legs != Material.AIR && loadout.legs != c.legs) { continue; }
if(c.feet != Material.AIR && loadout.feet != c.feet) { continue; }
if(c.hand != Material.AIR && loadout.hand != c.hand) { parent.log.info("failed on hand check - wanted " + c.hand + ", got" + loadout.hand); continue; }
if(a.getAbilities().contains(event.getCause())) {
event.setCancelled(true);
if(event.getCause().toString().toUpperCase().contains("FIRE"))
{
human.setFireTicks(0);
}
return;
}
}
}
|
public void onEntityDamage(EntityDamageEvent event) {
if(event.isCancelled()) {
return;
}
if(!(event.getEntity() instanceof HumanEntity)) {
return;
}
HumanEntity human = (HumanEntity) event.getEntity();
PowerArmourComponents loadout = new PowerArmourComponents();
loadout.head = human.getInventory().getHelmet().getType();
loadout.body = human.getInventory().getChestplate().getType();
loadout.legs = human.getInventory().getLeggings().getType();
loadout.feet = human.getInventory().getBoots().getType();
loadout.hand = human.getItemInHand().getType();
parent.log.info(parent.armourList.keySet().toString());
for(PowerArmourAbilities a : parent.armourList.keySet()) {
PowerArmourComponents c = parent.armourList.get(a);
if(c.head != Material.AIR && loadout.head != c.head) { continue; }
if(c.body != Material.AIR && loadout.body != c.body) { continue; }
if(c.legs != Material.AIR && loadout.legs != c.legs) { continue; }
if(c.feet != Material.AIR && loadout.feet != c.feet) { continue; }
if(c.hand != Material.AIR && loadout.hand != c.hand) { continue; }
if(a.getAbilities().contains(event.getCause())) {
event.setCancelled(true);
if(event.getCause().toString().toUpperCase().contains("FIRE"))
{
human.setFireTicks(0);
}
return;
}
}
}
|
public final Remesh compute()
{
LOGGER.info("Run "+getClass().getName());
mesh.getTrace().println("# Begin Remesh");
if (analyticMetric != null || !metricsPartitionMap.isEmpty())
{
for (Triangle t : mesh.getTriangles())
{
if (!t.isReadable())
continue;
AnalyticMetricInterface metric = metricsPartitionMap.get(t.getGroupId());
if (metric == null)
metric = analyticMetric;
if (metric.equals(LATER_BINDING))
throw new RuntimeException("Cannot determine metrics, either set 'size' or 'metricsMap' arguments, or call Remesh.setAnalyticMetric()");
for (Vertex v : t.vertex)
{
double[] pos = v.getUV();
EuclidianMetric3D curMetric = metrics.get(v);
EuclidianMetric3D newMetric = new EuclidianMetric3D(metric.getTargetSize(pos[0], pos[1], pos[2]));
if (curMetric == null || curMetric.getUnitBallBBox()[0] > newMetric.getUnitBallBBox()[0])
metrics.put(v, newMetric);
}
}
}
ArrayList<Vertex> nodes = new ArrayList<Vertex>();
ArrayList<Vertex> triNodes = new ArrayList<Vertex>();
ArrayList<EuclidianMetric3D> triMetrics = new ArrayList<EuclidianMetric3D>();
Map<Vertex, Vertex> neighborMap = new HashMap<Vertex, Vertex>();
int nrIter = 0;
int processed = 0;
int skippedNodes = 0;
AbstractHalfEdge h = null;
AbstractHalfEdge sym = null;
double[][] temp = new double[4][3];
for (Triangle f : mesh.getTriangles())
f.clearAttributes(AbstractHalfEdge.MARKED);
boolean reversed = true;
while (true)
{
nrIter++;
reversed = !reversed;
int maxNodes = 0;
int checked = 0;
int tooNearNodes = 0;
nodes.clear();
surroundingTriangle.clear();
mapTriangleVertices.clear();
neighborMap.clear();
skippedNodes = 0;
LOGGER.fine("Check all edges");
for(Triangle t : mesh.getTriangles())
{
if (t.hasAttributes(AbstractHalfEdge.OUTER))
continue;
h = t.getAbstractHalfEdge(h);
sym = t.getAbstractHalfEdge(sym);
triNodes.clear();
triMetrics.clear();
Collection<Vertex> newVertices = mapTriangleVertices.get(t);
if (newVertices == null)
newVertices = new ArrayList<Vertex>();
int nrTriNodes = 0;
for (int i = 0; i < 3; i++)
{
h = h.next();
if (h.hasAttributes(AbstractHalfEdge.IMMUTABLE))
continue;
if (h.hasAttributes(AbstractHalfEdge.MARKED))
{
continue;
}
if (!h.hasAttributes(AbstractHalfEdge.NONMANIFOLD))
{
sym = h.sym(sym);
sym.setAttributes(AbstractHalfEdge.MARKED);
}
else
{
for (Iterator<AbstractHalfEdge> it = h.fanIterator(); it.hasNext(); )
{
AbstractHalfEdge f = it.next();
f.setAttributes(AbstractHalfEdge.MARKED);
f.sym().setAttributes(AbstractHalfEdge.MARKED);
}
}
Vertex start = h.origin();
Vertex end = h.destination();
EuclidianMetric3D mS = metrics.get(start);
EuclidianMetric3D mE = metrics.get(end);
double l = interpolatedDistance(start, mS, end, mE);
if (l < maxlen)
{
h.setAttributes(AbstractHalfEdge.MARKED);
continue;
}
int nrNodes = addCandidatePoints(h, l, reversed, triNodes, triMetrics, neighborMap);
if (nrNodes > nrTriNodes)
{
nrTriNodes = nrNodes;
}
checked++;
}
if (nrTriNodes > maxNodes)
maxNodes = nrTriNodes;
if (!triNodes.isEmpty())
{
int prime = PrimeFinder.nextPrime(nrTriNodes);
int imax = triNodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2;
for (int i = 0; i < imax; i++)
{
Vertex v = triNodes.get(index);
EuclidianMetric3D metric = triMetrics.get(index);
assert metric != null;
double localSize = 0.5 * metric.getUnitBallBBox()[0];
double localSize2 = localSize * localSize;
Vertex bgNear = neighborBgMap.get(neighborMap.get(v));
Triangle bgT = liaison.findSurroundingTriangle(v, bgNear, localSize2, true).getTri();
liaison.addVertex(v, bgT);
liaison.move(v, v.getUV());
double[] uv = v.getUV();
Vertex n = kdTree.getNearestVertex(metric, uv);
if (allowNearNodes || interpolatedDistance(v, metric, n, metrics.get(n)) > minlen)
{
kdTree.add(v);
metrics.put(v, metric);
nodes.add(v);
newVertices.add(v);
surroundingTriangle.put(v, t);
double d0 = v.sqrDistance3D(bgT.vertex[0]);
double d1 = v.sqrDistance3D(bgT.vertex[1]);
double d2 = v.sqrDistance3D(bgT.vertex[2]);
if (d0 <= d1 && d0 <= d2)
neighborBgMap.put(v, bgT.vertex[0]);
else if (d1 <= d0 && d1 <= d2)
neighborBgMap.put(v, bgT.vertex[1]);
else
neighborBgMap.put(v, bgT.vertex[2]);
}
else
{
tooNearNodes++;
liaison.removeVertex(v);
}
index += prime;
if (index >= imax)
index -= imax;
}
if (!newVertices.isEmpty())
mapTriangleVertices.put(t, newVertices);
}
}
if (nodes.isEmpty())
break;
for (Vertex v : nodes)
{
kdTree.remove(v);
}
LOGGER.fine("Try to insert "+nodes.size()+" nodes");
int prime = PrimeFinder.nextPrime(maxNodes);
int imax = nodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2 - prime;
int totNrSwap = 0;
for (int i = 0; i < imax; i++)
{
index += prime;
if (index >= imax)
index -= imax;
Vertex v = nodes.get(index);
Triangle start = surroundingTriangle.remove(v);
AbstractHalfEdge ot = MeshLiaison.findNearestEdge(v, start);
sym = ot.sym(sym);
if (ot.hasAttributes(AbstractHalfEdge.IMMUTABLE))
{
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
ot.clearAttributes(AbstractHalfEdge.MARKED);
sym.clearAttributes(AbstractHalfEdge.MARKED);
continue;
}
if (!ot.hasAttributes(AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
{
Vertex o = ot.origin();
Vertex d = ot.destination();
Vertex n = sym.apex();
double[] pos = v.getUV();
Matrix3D.computeNormal3D(o.getUV(), n.getUV(), pos, temp[0], temp[1], temp[2]);
Matrix3D.computeNormal3D(n.getUV(), d.getUV(), pos, temp[0], temp[1], temp[3]);
if (Matrix3D.prodSca(temp[2], temp[3]) <= 0.0)
{
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
ot.clearAttributes(AbstractHalfEdge.MARKED);
sym.clearAttributes(AbstractHalfEdge.MARKED);
continue;
}
}
else
{
double [] xo = ot.origin().getUV();
double [] xd = ot.destination().getUV();
double xNorm2 =
(xd[0] - xo[0]) * (xd[0] - xo[0]) +
(xd[1] - xo[1]) * (xd[1] - xo[1]) +
(xd[2] - xo[2]) * (xd[2] - xo[2]);
if (xNorm2 > 0)
{
double[] pos = v.getUV();
double xScal = (1.0 / xNorm2) * (
(xd[0] - xo[0]) * (pos[0] - xo[0]) +
(xd[1] - xo[1]) * (pos[1] - xo[1]) +
(xd[2] - xo[2]) * (pos[2] - xo[2])
);
if (xScal < 0.01 || xScal > 0.99)
{
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
ot.clearAttributes(AbstractHalfEdge.MARKED);
sym.clearAttributes(AbstractHalfEdge.MARKED);
continue;
}
v.moveTo(
xo[0] + xScal * (xd[0] - xo[0]),
xo[1] + xScal * (xd[1] - xo[1]),
xo[2] + xScal * (xd[2] - xo[2]));
mesh.getTrace().moveVertex(v);
}
else
{
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
ot.clearAttributes(AbstractHalfEdge.MARKED);
sym.clearAttributes(AbstractHalfEdge.MARKED);
continue;
}
}
ot.clearAttributes(AbstractHalfEdge.MARKED);
sym.clearAttributes(AbstractHalfEdge.MARKED);
Map<Triangle, Collection<Vertex>> verticesToDispatch = collectVertices(ot);
ot = mesh.vertexSplit(ot, v);
assert ot.destination() == v : v+" "+ot;
dispatchVertices(v, verticesToDispatch);
kdTree.add(v);
processed++;
afterSplitHook();
HalfEdge edge = (HalfEdge) ot;
edge = edge.prev();
Vertex s = edge.origin();
boolean advance = true;
do
{
advance = true;
if (edge.checkSwap3D(mesh, coplanarity) >= 0.0)
{
edge.getTri().clearAttributes(AbstractHalfEdge.MARKED);
edge.sym().getTri().clearAttributes(AbstractHalfEdge.MARKED);
Map<Triangle, Collection<Vertex>> vTri = collectVertices(edge);
edge = (HalfEdge) mesh.edgeSwap(edge);
dispatchVertices(null, vTri);
totNrSwap++;
advance = false;
}
else
edge = edge.nextApexLoop();
}
while (!advance || edge.origin() != s);
afterSwapHook();
if (processed > 0 && (processed % progressBarStatus) == 0)
LOGGER.info("Vertices inserted: "+processed);
}
afterIterationHook();
assert mesh.isValid();
if (hasRidges)
{
assert mesh.checkNoInvertedTriangles();
}
assert mesh.checkNoDegeneratedTriangles();
assert surroundingTriangle.isEmpty() : "surroundingTriangle still contains "+surroundingTriangle.size()+" vertices";
if (LOGGER.isLoggable(Level.FINE))
{
LOGGER.fine("Mesh now contains "+mesh.getTriangles().size()+" triangles");
if (checked > 0)
LOGGER.fine(checked+" edges checked");
if (imax > 0)
LOGGER.fine(imax+" nodes added");
if (tooNearNodes > 0)
LOGGER.fine(tooNearNodes+" nodes are too near from existing vertices and cannot be inserted");
if (skippedNodes > 0)
LOGGER.fine(skippedNodes+" nodes are skipped");
if (totNrSwap > 0)
LOGGER.fine(totNrSwap+" edges have been swapped during processing");
}
if (nodes.size() == skippedNodes)
break;
}
LOGGER.info("Number of inserted vertices: "+processed);
LOGGER.fine("Number of iterations to insert all nodes: "+nrIter);
if (nrFailedInterpolations > 0)
LOGGER.info("Number of failed interpolations: "+nrFailedInterpolations);
LOGGER.config("Leave compute()");
mesh.getTrace().println("# End Remesh");
return this;
}
|
public final Remesh compute()
{
LOGGER.info("Run "+getClass().getName());
mesh.getTrace().println("# Begin Remesh");
if (analyticMetric != null || !metricsPartitionMap.isEmpty())
{
for (Triangle t : mesh.getTriangles())
{
if (!t.isReadable())
continue;
AnalyticMetricInterface metric = metricsPartitionMap.get(t.getGroupId());
if (metric == null)
metric = analyticMetric;
if (metric.equals(LATER_BINDING))
throw new RuntimeException("Cannot determine metrics, either set 'size' or 'metricsMap' arguments, or call Remesh.setAnalyticMetric()");
for (Vertex v : t.vertex)
{
double[] pos = v.getUV();
EuclidianMetric3D curMetric = metrics.get(v);
EuclidianMetric3D newMetric = new EuclidianMetric3D(metric.getTargetSize(pos[0], pos[1], pos[2]));
if (curMetric == null || curMetric.getUnitBallBBox()[0] > newMetric.getUnitBallBBox()[0])
metrics.put(v, newMetric);
}
}
}
ArrayList<Vertex> nodes = new ArrayList<Vertex>();
ArrayList<Vertex> triNodes = new ArrayList<Vertex>();
ArrayList<EuclidianMetric3D> triMetrics = new ArrayList<EuclidianMetric3D>();
Map<Vertex, Vertex> neighborMap = new HashMap<Vertex, Vertex>();
int nrIter = 0;
int processed = 0;
int skippedNodes = 0;
AbstractHalfEdge h = null;
AbstractHalfEdge sym = null;
double[][] temp = new double[4][3];
for (Triangle f : mesh.getTriangles())
f.clearAttributes(AbstractHalfEdge.MARKED);
mesh.tagIf(AbstractHalfEdge.IMMUTABLE, AbstractHalfEdge.MARKED);
boolean reversed = true;
while (true)
{
nrIter++;
reversed = !reversed;
int maxNodes = 0;
int checked = 0;
int tooNearNodes = 0;
nodes.clear();
surroundingTriangle.clear();
mapTriangleVertices.clear();
neighborMap.clear();
skippedNodes = 0;
LOGGER.fine("Check all edges");
for(Triangle t : mesh.getTriangles())
{
if (t.hasAttributes(AbstractHalfEdge.OUTER))
continue;
h = t.getAbstractHalfEdge(h);
sym = t.getAbstractHalfEdge(sym);
triNodes.clear();
triMetrics.clear();
Collection<Vertex> newVertices = mapTriangleVertices.get(t);
if (newVertices == null)
newVertices = new ArrayList<Vertex>();
int nrTriNodes = 0;
for (int i = 0; i < 3; i++)
{
h = h.next();
if (h.hasAttributes(AbstractHalfEdge.MARKED))
{
continue;
}
if (!h.hasAttributes(AbstractHalfEdge.NONMANIFOLD))
{
sym = h.sym(sym);
sym.setAttributes(AbstractHalfEdge.MARKED);
}
else
{
for (Iterator<AbstractHalfEdge> it = h.fanIterator(); it.hasNext(); )
{
AbstractHalfEdge f = it.next();
f.setAttributes(AbstractHalfEdge.MARKED);
f.sym().setAttributes(AbstractHalfEdge.MARKED);
}
}
Vertex start = h.origin();
Vertex end = h.destination();
EuclidianMetric3D mS = metrics.get(start);
EuclidianMetric3D mE = metrics.get(end);
double l = interpolatedDistance(start, mS, end, mE);
if (l < maxlen)
{
h.setAttributes(AbstractHalfEdge.MARKED);
continue;
}
int nrNodes = addCandidatePoints(h, l, reversed, triNodes, triMetrics, neighborMap);
if (nrNodes > nrTriNodes)
{
nrTriNodes = nrNodes;
}
checked++;
}
if (nrTriNodes > maxNodes)
maxNodes = nrTriNodes;
if (!triNodes.isEmpty())
{
int prime = PrimeFinder.nextPrime(nrTriNodes);
int imax = triNodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2;
for (int i = 0; i < imax; i++)
{
Vertex v = triNodes.get(index);
EuclidianMetric3D metric = triMetrics.get(index);
assert metric != null;
double localSize = 0.5 * metric.getUnitBallBBox()[0];
double localSize2 = localSize * localSize;
Vertex bgNear = neighborBgMap.get(neighborMap.get(v));
Triangle bgT = liaison.findSurroundingTriangle(v, bgNear, localSize2, true).getTri();
liaison.addVertex(v, bgT);
liaison.move(v, v.getUV());
double[] uv = v.getUV();
Vertex n = kdTree.getNearestVertex(metric, uv);
if (allowNearNodes || interpolatedDistance(v, metric, n, metrics.get(n)) > minlen)
{
kdTree.add(v);
metrics.put(v, metric);
nodes.add(v);
newVertices.add(v);
surroundingTriangle.put(v, t);
double d0 = v.sqrDistance3D(bgT.vertex[0]);
double d1 = v.sqrDistance3D(bgT.vertex[1]);
double d2 = v.sqrDistance3D(bgT.vertex[2]);
if (d0 <= d1 && d0 <= d2)
neighborBgMap.put(v, bgT.vertex[0]);
else if (d1 <= d0 && d1 <= d2)
neighborBgMap.put(v, bgT.vertex[1]);
else
neighborBgMap.put(v, bgT.vertex[2]);
}
else
{
tooNearNodes++;
liaison.removeVertex(v);
}
index += prime;
if (index >= imax)
index -= imax;
}
if (!newVertices.isEmpty())
mapTriangleVertices.put(t, newVertices);
}
}
if (nodes.isEmpty())
break;
for (Vertex v : nodes)
{
kdTree.remove(v);
}
LOGGER.fine("Try to insert "+nodes.size()+" nodes");
int prime = PrimeFinder.nextPrime(maxNodes);
int imax = nodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2 - prime;
int totNrSwap = 0;
for (int i = 0; i < imax; i++)
{
index += prime;
if (index >= imax)
index -= imax;
Vertex v = nodes.get(index);
Triangle start = surroundingTriangle.remove(v);
AbstractHalfEdge ot = MeshLiaison.findNearestEdge(v, start);
sym = ot.sym(sym);
if (ot.hasAttributes(AbstractHalfEdge.IMMUTABLE))
{
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
if (!ot.hasAttributes(AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
{
Vertex o = ot.origin();
Vertex d = ot.destination();
Vertex n = sym.apex();
double[] pos = v.getUV();
Matrix3D.computeNormal3D(o.getUV(), n.getUV(), pos, temp[0], temp[1], temp[2]);
Matrix3D.computeNormal3D(n.getUV(), d.getUV(), pos, temp[0], temp[1], temp[3]);
if (Matrix3D.prodSca(temp[2], temp[3]) <= 0.0)
{
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
}
else
{
double [] xo = ot.origin().getUV();
double [] xd = ot.destination().getUV();
double xNorm2 =
(xd[0] - xo[0]) * (xd[0] - xo[0]) +
(xd[1] - xo[1]) * (xd[1] - xo[1]) +
(xd[2] - xo[2]) * (xd[2] - xo[2]);
if (xNorm2 > 0)
{
double[] pos = v.getUV();
double xScal = (1.0 / xNorm2) * (
(xd[0] - xo[0]) * (pos[0] - xo[0]) +
(xd[1] - xo[1]) * (pos[1] - xo[1]) +
(xd[2] - xo[2]) * (pos[2] - xo[2])
);
if (xScal < 0.01 || xScal > 0.99)
{
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
v.moveTo(
xo[0] + xScal * (xd[0] - xo[0]),
xo[1] + xScal * (xd[1] - xo[1]),
xo[2] + xScal * (xd[2] - xo[2]));
mesh.getTrace().moveVertex(v);
}
else
{
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
}
Map<Triangle, Collection<Vertex>> verticesToDispatch = collectVertices(ot);
ot = mesh.vertexSplit(ot, v);
assert ot.destination() == v : v+" "+ot;
dispatchVertices(v, verticesToDispatch);
kdTree.add(v);
processed++;
afterSplitHook();
HalfEdge edge = (HalfEdge) ot;
edge = edge.prev();
Vertex s = edge.origin();
boolean advance = true;
do
{
advance = true;
if (edge.checkSwap3D(mesh, coplanarity) >= 0.0)
{
edge.getTri().clearAttributes(AbstractHalfEdge.MARKED);
edge.sym().getTri().clearAttributes(AbstractHalfEdge.MARKED);
Map<Triangle, Collection<Vertex>> vTri = collectVertices(edge);
edge = (HalfEdge) mesh.edgeSwap(edge);
dispatchVertices(null, vTri);
totNrSwap++;
advance = false;
}
else
edge = edge.nextApexLoop();
}
while (!advance || edge.origin() != s);
afterSwapHook();
if (processed > 0 && (processed % progressBarStatus) == 0)
LOGGER.info("Vertices inserted: "+processed);
}
afterIterationHook();
assert mesh.isValid();
if (hasRidges)
{
assert mesh.checkNoInvertedTriangles();
}
assert mesh.checkNoDegeneratedTriangles();
assert surroundingTriangle.isEmpty() : "surroundingTriangle still contains "+surroundingTriangle.size()+" vertices";
if (LOGGER.isLoggable(Level.FINE))
{
LOGGER.fine("Mesh now contains "+mesh.getTriangles().size()+" triangles");
if (checked > 0)
LOGGER.fine(checked+" edges checked");
if (imax > 0)
LOGGER.fine(imax+" nodes added");
if (tooNearNodes > 0)
LOGGER.fine(tooNearNodes+" nodes are too near from existing vertices and cannot be inserted");
if (skippedNodes > 0)
LOGGER.fine(skippedNodes+" nodes are skipped");
if (totNrSwap > 0)
LOGGER.fine(totNrSwap+" edges have been swapped during processing");
}
if (nodes.size() == skippedNodes)
break;
}
LOGGER.info("Number of inserted vertices: "+processed);
LOGGER.fine("Number of iterations to insert all nodes: "+nrIter);
if (nrFailedInterpolations > 0)
LOGGER.info("Number of failed interpolations: "+nrFailedInterpolations);
LOGGER.config("Leave compute()");
mesh.getTrace().println("# End Remesh");
return this;
}
|
public void run()
{
ServerMessage msg;
try {
msg = (ServerMessage) inputStream.readObject();
System.out.println("RECIEVED:" + msg.getMessage());
switch (msg.getType()) {
case ServerMessage.CLIENT_READ:
case ServerMessage.CLIENT_APPEND:
currentBallotNumber++;
ServerMessage ballot = new ServerMessage(ServerMessage.PAXOS_PREPARE, currentBallotNumber + "," + this.getId(), socket.getLocalAddress().getHostAddress() );
for (int i = 0; i < Server.StatServers.size(); i++){
sendMessage(Server.StatServers.get(i), 3000, ballot);
}
case ServerMessage.PAXOS_PREPARE:
int proposedBallot = Integer.parseInt(msg.getMessage().split(",")[0]);
if (proposedBallot >= currentBallotNumber){
this.currentBallotNumber = proposedBallot;
ServerMessage ackMessage = new ServerMessage(ServerMessage.PAXOS_ACK, currentBallotNumber + ","+ currentAcceptNum + "," + this.acceptValue ,socket.getLocalAddress().getHostAddress() );
sendMessage(msg.getSourceAddress(), 3000, ackMessage);
}
case ServerMessage.PAXOS_ACK:
case ServerMessage.PAXOS_DECIDE:
case ServerMessage.PAXOS_ACCEPT:
case ServerMessage.TWOPHASE_VOTE_REQUEST:
case ServerMessage.TWOPHASE_VOTE_YES:
case ServerMessage.TWOPHASE_VOTE_NO:
case ServerMessage.TWOPHASE_ABORT:
case ServerMessage.TWOPHASE_COMMIT:
}
}
catch (IOException e) {
System.out.println(" Exception reading Streams: " + e);
System.exit(1);
}
catch(ClassNotFoundException ex) {
System.exit(1);
}
}
|
public void run()
{
ServerMessage msg;
try {
msg = (ServerMessage) inputStream.readObject();
System.out.println("RECIEVED:" + msg.getMessage());
switch (msg.getType()) {
case ServerMessage.CLIENT_READ:
case ServerMessage.CLIENT_APPEND:
currentBallotNumber++;
ServerMessage ballot = new ServerMessage(ServerMessage.PAXOS_PREPARE, currentBallotNumber + "," + this.getId(), socket.getLocalAddress().getHostAddress() );
for (int i = 0; i < Server.StatServers.size(); i++){
sendMessage(Server.StatServers.get(i), 3000, ballot);
}
break;
case ServerMessage.PAXOS_PREPARE:
int proposedBallot = Integer.parseInt(msg.getMessage().split(",")[0]);
if (proposedBallot >= currentBallotNumber){
this.currentBallotNumber = proposedBallot;
ServerMessage ackMessage = new ServerMessage(ServerMessage.PAXOS_ACK, currentBallotNumber + ","+ currentAcceptNum + "," + this.acceptValue ,socket.getLocalAddress().getHostAddress() );
sendMessage(msg.getSourceAddress(), 3000, ackMessage);
}
break;
case ServerMessage.PAXOS_ACK:
case ServerMessage.PAXOS_DECIDE:
case ServerMessage.PAXOS_ACCEPT:
case ServerMessage.TWOPHASE_VOTE_REQUEST:
case ServerMessage.TWOPHASE_VOTE_YES:
case ServerMessage.TWOPHASE_VOTE_NO:
case ServerMessage.TWOPHASE_ABORT:
case ServerMessage.TWOPHASE_COMMIT:
}
}
catch (IOException e) {
System.out.println(" Exception reading Streams: " + e);
System.exit(1);
}
catch(ClassNotFoundException ex) {
System.exit(1);
}
}
|
public void castSpell(Player player)
{
if (checkInventoryRequirements(player.getInventory()))
{
Block targetBlock = player.getTargetBlock(null, 101);
if ((targetBlock.getType() != Material.AIR) && (targetBlock.getType() != Material.BEDROCK))
{
Location loc = targetBlock.getLocation();
Location playerLoc = player.getLocation();
double xdiff = loc.getX() - playerLoc.getX();
double ydiff = loc.getZ() - playerLoc.getZ();
double xdiffsq = xdiff * xdiff;
double ydiffsq = ydiff * ydiff;
double xyadd = xdiffsq + ydiffsq;
double distance = Math.sqrt(xyadd);
if (distance < 30)
{
removeRequiredItemsFromInventory(player.getInventory());
if (canPlaceCactus(targetBlock))
{
Material originalTargetMaterial = targetBlock.getType();
boolean sandstoneSupport = false;
if (targetBlock.getRelative(0, -1, 0).getType() == Material.AIR)
{
targetBlock.getRelative(0, -1, 0).setType(Material.SANDSTONE);
sandstoneSupport = true;
}
targetBlock.setType(Material.SAND);
for (int i = 1; i <= 3; i++)
{
targetBlock.getRelative(0, i, 0).setType(Material.CACTUS);
}
player.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new RunnableDestroyCactus(targetBlock, originalTargetMaterial, sandstoneSupport), 300);
player.sendMessage("SPIKES SPIKES SPIKES BABY");
}
else
{
player.sendMessage("Cannot cast! A cactus wouldn't fit there!");
}
}
else
{
player.sendMessage("Could not cast! Target is out of range!");
}
}
}
else
{
player.sendMessage("Could not cast! Requires 4 cacti and 1 sand.");
}
}
|
public void castSpell(Player player)
{
if (checkInventoryRequirements(player.getInventory()))
{
Block targetBlock = player.getTargetBlock(null, 101);
if ((targetBlock.getType() != Material.AIR) && (targetBlock.getType() != Material.BEDROCK))
{
Location loc = targetBlock.getLocation();
Location playerLoc = player.getLocation();
double xdiff = loc.getX() - playerLoc.getX();
double ydiff = loc.getZ() - playerLoc.getZ();
double xdiffsq = xdiff * xdiff;
double ydiffsq = ydiff * ydiff;
double xyadd = xdiffsq + ydiffsq;
double distance = Math.sqrt(xyadd);
if (distance < 30)
{
if (canPlaceCactus(targetBlock))
{
removeRequiredItemsFromInventory(player.getInventory());
Material originalTargetMaterial = targetBlock.getType();
boolean sandstoneSupport = false;
if (targetBlock.getRelative(0, -1, 0).getType() == Material.AIR)
{
targetBlock.getRelative(0, -1, 0).setType(Material.SANDSTONE);
sandstoneSupport = true;
}
targetBlock.setType(Material.SAND);
for (int i = 1; i <= 3; i++)
{
targetBlock.getRelative(0, i, 0).setType(Material.CACTUS);
}
player.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new RunnableDestroyCactus(targetBlock, originalTargetMaterial, sandstoneSupport), 300);
player.sendMessage("SPIKES SPIKES SPIKES BABY");
}
else
{
player.sendMessage("Cannot cast! A cactus wouldn't fit there!");
}
}
else
{
player.sendMessage("Could not cast! Target is out of range!");
}
}
}
else
{
player.sendMessage("Could not cast! Requires 4 cacti and 1 sand.");
}
}
|
public void pushMessage(IPipe pipe, IMessage message) {
if (message instanceof StatusMessage) {
StatusMessage statusMsg = (StatusMessage) message;
data.sendStatus(statusMsg.getBody());
}
else if (message instanceof RTMPMessage) {
RTMPMessage rtmpMsg = (RTMPMessage) message;
IRTMPEvent msg = rtmpMsg.getBody();
if (msg.getHeader() == null) {
msg.setHeader(new Header());
}
msg.getHeader().setTimerRelative(rtmpMsg.isTimerRelative());
switch(msg.getDataType()){
case Constants.TYPE_STREAM_METADATA:
Notify notify = new Notify(((Notify) msg).getData().asReadOnlyBuffer());
notify.setHeader(msg.getHeader());
notify.setTimestamp(msg.getTimestamp());
video.write(notify);
if (msg.getHeader().isTimerRelative())
totalVideo += msg.getTimestamp();
else
totalVideo = msg.getTimestamp();
break;
case Constants.TYPE_VIDEO_DATA:
VideoData videoData = new VideoData(((VideoData) msg).getData().asReadOnlyBuffer());
videoData.setHeader(msg.getHeader());
if (audioTime > 0) {
msg.setTimestamp(msg.getTimestamp() + audioTime);
if (msg.getTimestamp() < 0)
msg.setTimestamp(0);
videoData.getHeader().setTimer(msg.getTimestamp());
audioTime = 0;
}
videoData.setTimestamp(msg.getTimestamp());
videoReceived = true;
video.write(videoData);
if (msg.getHeader().isTimerRelative())
totalVideo += msg.getTimestamp();
else
totalVideo = msg.getTimestamp();
break;
case Constants.TYPE_AUDIO_DATA:
AudioData audioData = new AudioData(((AudioData) msg).getData().asReadOnlyBuffer());
audioData.setHeader(msg.getHeader());
audioData.setTimestamp(msg.getTimestamp());
if (index > 0 && index % 5 != 0 && msg.getTimestamp() > 0) {
audioData.setTimestamp(msg.getTimestamp() - 1);
msg.getHeader().setTimer(audioData.getTimestamp());
}
index++;
audio.write(audioData);
if (!videoReceived)
if (msg.getHeader().isTimerRelative())
audioTime += msg.getTimestamp();
else
audioTime = msg.getTimestamp();
if (msg.getHeader().isTimerRelative())
totalAudio += msg.getTimestamp();
else
totalAudio = msg.getTimestamp();
break;
case Constants.TYPE_PING:
msg.getHeader().setTimerRelative(false);
msg.setTimestamp(0);
conn.ping((Ping) msg);
break;
case Constants.TYPE_BYTES_READ:
msg.getHeader().setTimerRelative(false);
msg.setTimestamp(0);
conn.getChannel((byte) 2).write((BytesRead) msg);
break;
default:
data.write(msg);
break;
}
}
}
|
public void pushMessage(IPipe pipe, IMessage message) {
if (message instanceof StatusMessage) {
StatusMessage statusMsg = (StatusMessage) message;
data.sendStatus(statusMsg.getBody());
}
else if (message instanceof RTMPMessage) {
RTMPMessage rtmpMsg = (RTMPMessage) message;
IRTMPEvent msg = rtmpMsg.getBody();
if (msg.getHeader() == null) {
msg.setHeader(new Header());
}
msg.getHeader().setTimerRelative(rtmpMsg.isTimerRelative());
switch(msg.getDataType()){
case Constants.TYPE_STREAM_METADATA:
Notify notify = new Notify(((Notify) msg).getData().asReadOnlyBuffer());
notify.setHeader(msg.getHeader());
notify.setTimestamp(msg.getTimestamp());
video.write(notify);
if (msg.getHeader().isTimerRelative())
totalVideo += msg.getTimestamp();
else
totalVideo = msg.getTimestamp();
break;
case Constants.TYPE_VIDEO_DATA:
VideoData videoData = new VideoData(((VideoData) msg).getData().asReadOnlyBuffer());
videoData.setHeader(msg.getHeader());
if (audioTime > 0) {
msg.setTimestamp(msg.getTimestamp() + audioTime);
if (msg.getTimestamp() < 0)
msg.setTimestamp(0);
videoData.getHeader().setTimer(msg.getTimestamp());
audioTime = 0;
}
videoData.setTimestamp(msg.getTimestamp());
videoReceived = true;
video.write(videoData);
if (msg.getHeader().isTimerRelative())
totalVideo += msg.getTimestamp();
else
totalVideo = msg.getTimestamp();
break;
case Constants.TYPE_AUDIO_DATA:
AudioData audioData = new AudioData(((AudioData) msg).getData().asReadOnlyBuffer());
audioData.setHeader(msg.getHeader());
audioData.setTimestamp(msg.getTimestamp());
index++;
audio.write(audioData);
if (!videoReceived)
if (msg.getHeader().isTimerRelative())
audioTime += msg.getTimestamp();
else
audioTime = msg.getTimestamp();
if (msg.getHeader().isTimerRelative())
totalAudio += msg.getTimestamp();
else
totalAudio = msg.getTimestamp();
break;
case Constants.TYPE_PING:
msg.getHeader().setTimerRelative(false);
msg.setTimestamp(0);
conn.ping((Ping) msg);
break;
case Constants.TYPE_BYTES_READ:
msg.getHeader().setTimerRelative(false);
msg.setTimestamp(0);
conn.getChannel((byte) 2).write((BytesRead) msg);
break;
default:
data.write(msg);
break;
}
}
}
|
public void save() {
load();
options.setProperty("server-ip", "127.0.0.1");
options.setProperty("online-mode", simpleServerOptions.get("onlineMode"));
options.setProperty("server-port", simpleServerOptions.get("internalPort"));
options.setProperty("max-players", simpleServerOptions.get("maxPlayers"));
options.setProperty("level-name", simpleServerOptions.get("levelName"));
options.setProperty("spawn-animals", simpleServerOptions.get("spawnAnimals"));
options.setProperty("spawn-monsters", simpleServerOptions.get("spawnMonsters"));
options.setProperty("allow-flight", simpleServerOptions.get("allowFlight"));
options.setProperty("pvp", simpleServerOptions.get("pvp"));
options.setProperty("view-distance", simpleServerOptions.get("viewDistance"));
options.setProperty("allow-nether", simpleServerOptions.get("allowNether"));
super.save();
}
|
public void save() {
load();
options.setProperty("server-ip", "127.0.0.1");
options.setProperty("online-mode", simpleServerOptions.get("onlineMode"));
options.setProperty("server-port", simpleServerOptions.get("internalPort"));
options.setProperty("max-players", simpleServerOptions.get("maxPlayers"));
options.setProperty("level-name", simpleServerOptions.get("levelName"));
options.setProperty("spawn-animals", simpleServerOptions.get("spawnAnimals"));
options.setProperty("spawn-monsters", simpleServerOptions.get("spawnMonsters"));
options.setProperty("allow-flight", simpleServerOptions.get("allowFlight"));
options.setProperty("pvp", simpleServerOptions.get("pvp"));
options.setProperty("view-distance", simpleServerOptions.get("viewDistance"));
options.setProperty("allow-nether", simpleServerOptions.get("allowNether"));
options.setProperty("world-seed", simpleServerOptions.get("worldSeed"));
super.save();
}
|
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
ValidationUtils.rejectIfEmpty(e, "nickname", "nickname.empty");
}
|
public void validate(Object obj, Errors e) {
ValidationUtils
.rejectIfEmpty(e, "name", "name.empty", "Can't be empty");
ValidationUtils.rejectIfEmpty(e, "nickname", "nickname.empty",
"Can't be empty");
}
|
private void genStats(BugReportModule br, Chapter ch, Node node, boolean detectBugs, String csvPrefix) {
PackageInfoPlugin pkgInfo = (PackageInfoPlugin) br.getPlugin("PackageInfoPlugin");
BugState bug = null;
PreText pre = new PreText(ch);
Chapter kernelWakeLock = new Chapter(br, "Kernel Wake locks");
Pattern pKWL = Pattern.compile(".*?\"(.*?)\": (.*?) \\((.*?) times\\)");
Table tgKWL = new Table(Table.FLAG_SORT, kernelWakeLock);
tgKWL.setCSVOutput(br, "battery_" + csvPrefix + "_kernel_wakelocks");
tgKWL.setTableName(br, "battery_" + csvPrefix + "_kernel_wakelocks");
tgKWL.addColumn("Kernel Wakelock", null, Table.FLAG_NONE, "kernel_wakelock varchar");
tgKWL.addColumn("Count", null, Table.FLAG_ALIGN_RIGHT, "count int");
tgKWL.addColumn("Time", null, Table.FLAG_ALIGN_RIGHT, "time varchar");
tgKWL.addColumn("Time(ms)", null, Table.FLAG_ALIGN_RIGHT, "time_ms int");
tgKWL.begin();
Chapter wakeLock = new Chapter(br, "Wake locks");
new Hint(wakeLock).add("Hint: hover over the UID to see it's name.");
Pattern pWL = Pattern.compile("Wake lock (.*?): (.*?) ([a-z]+) \\((.*?) times\\)");
Table tgWL = new Table(Table.FLAG_SORT, wakeLock);
tgWL.setCSVOutput(br, "battery_" + csvPrefix + "_wakelocks");
tgWL.setTableName(br, "battery_" + csvPrefix + "_wakelocks");
tgWL.addColumn("UID", null, Table.FLAG_ALIGN_RIGHT, "uid int");
tgWL.addColumn("Wake lock", null, Table.FLAG_NONE, "wakelock varchar");
tgWL.addColumn("Type", null, Table.FLAG_NONE, "type varchar");
tgWL.addColumn("Count", null, Table.FLAG_ALIGN_RIGHT, "count int");
tgWL.addColumn("Time", null, Table.FLAG_ALIGN_RIGHT, "time varchar");
tgWL.addColumn("Time(ms)", null, Table.FLAG_ALIGN_RIGHT, "time_ms int");
tgWL.begin();
Chapter cpuPerUid = new Chapter(br, "CPU usage per UID");
new Hint(cpuPerUid).add("Hint: hover over the UID to see it's name.");
Pattern pProc = Pattern.compile("Proc (.*?):");
Pattern pCPU = Pattern.compile("CPU: (.*?) usr \\+ (.*?) krn");
Table tgCU = new Table(Table.FLAG_SORT, cpuPerUid);
tgCU.setCSVOutput(br, "battery_" + csvPrefix + "_cpu_per_uid");
tgCU.setTableName(br, "battery_" + csvPrefix + "_cpu_per_uid");
tgCU.addColumn("UID", null, Table.FLAG_ALIGN_RIGHT, "uid int");
tgCU.addColumn("Usr (ms)", null, Table.FLAG_ALIGN_RIGHT, "usr_ms int");
tgCU.addColumn("Krn (ms)", null, Table.FLAG_ALIGN_RIGHT, "krn_ms int");
tgCU.addColumn("Total (ms)", null, Table.FLAG_ALIGN_RIGHT, "total_ms int");
tgCU.addColumn("Usr (min)", null, Table.FLAG_ALIGN_RIGHT, "usr_min int");
tgCU.addColumn("Krn (min)", null, Table.FLAG_ALIGN_RIGHT, "krn_min int");
tgCU.addColumn("Total (min)", null, Table.FLAG_ALIGN_RIGHT, "total_min int");
tgCU.begin();
Chapter cpuPerProc = new Chapter(br, "CPU usage per Proc");
new Hint(cpuPerUid).add("Hint: hover over the UID to see it's name.");
Table tgCP = new Table(Table.FLAG_SORT, cpuPerProc);
tgCP.setCSVOutput(br, "battery_" + csvPrefix + "_cpu_per_proc");
tgCP.setTableName(br, "battery_" + csvPrefix + "_cpu_per_proc");
tgCP.addColumn("UID", null, Table.FLAG_ALIGN_RIGHT, "uid int");
tgCP.addColumn("Proc", null, Table.FLAG_NONE, "proc varchar");
tgCP.addColumn("Usr", null, Table.FLAG_ALIGN_RIGHT, "usr int");
tgCP.addColumn("Usr (ms)", null, Table.FLAG_ALIGN_RIGHT, "usr_ms int");
tgCP.addColumn("Krn", null, Table.FLAG_ALIGN_RIGHT, "krn int");
tgCP.addColumn("Krn (ms)", null, Table.FLAG_ALIGN_RIGHT, "krn_ms int");
tgCP.addColumn("Total (ms)", null, Table.FLAG_ALIGN_RIGHT, "total_ms int");
tgCP.begin();
Chapter net = new Chapter(br, "Network traffic");
new Hint(cpuPerUid).add("Hint: hover over the UID to see it's name.");
Pattern pNet = Pattern.compile("Network: (.*?) received, (.*?) sent");
Table tgNet = new Table(Table.FLAG_SORT, net);
tgNet.setCSVOutput(br, "battery_" + csvPrefix + "_net");
tgNet.setTableName(br, "battery_" + csvPrefix + "_net");
tgNet.addColumn("UID", null, Table.FLAG_ALIGN_RIGHT, "uid int");
tgNet.addColumn("Received (B)", null, Table.FLAG_ALIGN_RIGHT, "received_b int");
tgNet.addColumn("Sent (B)", null, Table.FLAG_ALIGN_RIGHT, "sent_b int");
tgNet.addColumn("Total (B)", null, Table.FLAG_ALIGN_RIGHT, "total_b int");
tgNet.begin();
long sumRecv = 0, sumSent = 0;
HashMap<String, CpuPerUid> cpuPerUidStats = new HashMap<String, CpuPerUid>();
for (Node item : node) {
String line = item.getLine();
if (line.startsWith("#")) {
String sUID = line.substring(1, line.length() - 1);
PackageInfoPlugin.UID uid = null;
String uidName = sUID;
Anchor uidLink = null;
if (pkgInfo != null) {
int uidInt = Integer.parseInt(sUID);
uid = pkgInfo.getUID(uidInt);
if (uid != null) {
uidName = uid.getFullName();
uidLink = pkgInfo.getAnchorToUid(uid);
}
}
for (Node subNode : item) {
String s = subNode.getLine();
if (s.startsWith("Wake lock") && !s.contains("(nothing executed)")) {
Matcher m = pWL.matcher(s);
if (m.find()) {
String name = m.group(1);
String sTime = m.group(2);
String type = m.group(3);
String sCount = m.group(4);
long ts = readTs(sTime.replace(" ", ""));
tgWL.setNextRowStyle(colorizeTime(ts));
tgWL.addData(uidName, new Link(uidLink, sUID));
tgWL.addData(name);
tgWL.addData(type);
tgWL.addData(sCount);
tgWL.addData(sTime);
tgWL.addData(new ShadedValue(ts));
if (ts > WAKE_LOG_BUG_THRESHHOLD) {
bug = createBug(br, bug);
bug.list.add("Wake lock: " + name);
}
} else {
System.err.println("Could not parse line: " + s);
}
} else if (s.startsWith("Network: ")) {
Matcher m = pNet.matcher(s);
if (m.find()) {
long recv = parseBytes(m.group(1));
long sent = parseBytes(m.group(2));
sumRecv += recv;
sumSent += sent;
tgNet.addData(uidName, new Link(uidLink, sUID));
tgNet.addData(new ShadedValue(recv));
tgNet.addData(new ShadedValue(sent));
tgNet.addData(new ShadedValue(recv + sent));
} else {
System.err.println("Could not parse line: " + s);
}
} else if (s.startsWith("Proc ")) {
Matcher mProc = pProc.matcher(s);
if (mProc.find()) {
String procName = mProc.group(1);
Node cpuItem = subNode.findChildStartsWith("CPU:");
if (cpuItem != null) {
Matcher m = pCPU.matcher(cpuItem.getLine());
if (m.find()) {
String sUsr = m.group(1);
long usr = readTs(sUsr.replace(" ", ""));
String sKrn = m.group(2);
long krn = readTs(sKrn.replace(" ", ""));
CpuPerUid cpu = cpuPerUidStats.get(sUID);
if (cpu == null) {
cpu = new CpuPerUid();
cpu.uidLink = uidLink;
cpu.uidName = uidName;
cpuPerUidStats.put(sUID, cpu);
}
cpu.usr += usr;
cpu.krn += krn;
tgCP.addData(uidName, new Link(uidLink, sUID));
tgCP.addData(procName);
tgCP.addData(sUsr);
tgCP.addData(new ShadedValue(usr));
tgCP.addData(sKrn);
tgCP.addData(new ShadedValue(krn));
tgCP.addData(new ShadedValue(usr + krn));
} else {
System.err.println("Could not parse line: " + cpuItem.getLine());
}
}
} else {
System.err.println("Could not parse line: " + s);
}
}
}
} else if (line.startsWith("Kernel Wake lock")) {
if (!line.contains("(nothing executed)")) {
Matcher m = pKWL.matcher(line);
if (m.find()) {
String name = m.group(1);
String sTime = m.group(2);
String sCount = m.group(3);
long ts = readTs(sTime.replace(" ", ""));
tgKWL.setNextRowStyle(colorizeTime(ts));
tgKWL.addData(name);
tgKWL.addData(sCount);
tgKWL.addData(sTime);
tgKWL.addData(new ShadedValue(ts));
if (ts > WAKE_LOG_BUG_THRESHHOLD) {
bug = createBug(br, bug);
bug.list.add("Kernel Wake lock: " + name);
}
} else {
System.err.println("Could not parse line: " + line);
}
}
} else {
if (item.getChildCount() == 0) {
pre.add(line);
}
}
}
if (!tgKWL.isEmpty()) {
tgKWL.end();
ch.addChapter(kernelWakeLock);
}
if (!tgWL.isEmpty()) {
tgWL.end();
ch.addChapter(wakeLock);
}
if (!cpuPerUidStats.isEmpty()) {
for (String sUid : cpuPerUidStats.keySet()) {
CpuPerUid cpu = cpuPerUidStats.get(sUid);
tgCU.addData(cpu.uidName, new Link(cpu.uidLink, sUid));
tgCU.addData(new ShadedValue(cpu.usr));
tgCU.addData(new ShadedValue(cpu.krn));
tgCU.addData(new ShadedValue(cpu.usr + cpu.krn));
tgCU.addData(Long.toString(cpu.usr / MIN));
tgCU.addData(Long.toString(cpu.krn / MIN));
tgCU.addData(Long.toString((cpu.usr + cpu.krn) / MIN));
}
tgCU.end();
ch.addChapter(cpuPerUid);
}
if (!tgCP.isEmpty()) {
tgCP.end();
ch.addChapter(cpuPerProc);
}
if (!tgNet.isEmpty()) {
tgNet.addSeparator();
tgNet.addData("TOTAL:");
tgNet.addData(new ShadedValue(sumRecv));
tgNet.addData(new ShadedValue(sumSent));
tgNet.addData(new ShadedValue(sumRecv + sumSent));
tgNet.end();
ch.addChapter(net);
}
if (detectBugs && bug != null) {
bug.bug.add(new Link(ch.getAnchor(), "Click here for more information"));
br.addBug(bug.bug);
}
}
|
private void genStats(BugReportModule br, Chapter ch, Node node, boolean detectBugs, String csvPrefix) {
PackageInfoPlugin pkgInfo = (PackageInfoPlugin) br.getPlugin("PackageInfoPlugin");
BugState bug = null;
PreText pre = new PreText(ch);
Chapter kernelWakeLock = new Chapter(br, "Kernel Wake locks");
Pattern pKWL = Pattern.compile(".*?\"(.*?)\": (.*?) \\((.*?) times\\)");
Table tgKWL = new Table(Table.FLAG_SORT, kernelWakeLock);
tgKWL.setCSVOutput(br, "battery_" + csvPrefix + "_kernel_wakelocks");
tgKWL.setTableName(br, "battery_" + csvPrefix + "_kernel_wakelocks");
tgKWL.addColumn("Kernel Wakelock", null, Table.FLAG_NONE, "kernel_wakelock varchar");
tgKWL.addColumn("Count", null, Table.FLAG_ALIGN_RIGHT, "count int");
tgKWL.addColumn("Time", null, Table.FLAG_ALIGN_RIGHT, "time varchar");
tgKWL.addColumn("Time(ms)", null, Table.FLAG_ALIGN_RIGHT, "time_ms int");
tgKWL.begin();
Chapter wakeLock = new Chapter(br, "Wake locks");
new Hint(wakeLock).add("Hint: hover over the UID to see it's name.");
Pattern pWL = Pattern.compile("Wake lock (.*?): (.*?) ([a-z]+) \\((.*?) times\\)");
Table tgWL = new Table(Table.FLAG_SORT, wakeLock);
tgWL.setCSVOutput(br, "battery_" + csvPrefix + "_wakelocks");
tgWL.setTableName(br, "battery_" + csvPrefix + "_wakelocks");
tgWL.addColumn("UID", null, Table.FLAG_ALIGN_RIGHT, "uid int");
tgWL.addColumn("Wake lock", null, Table.FLAG_NONE, "wakelock varchar");
tgWL.addColumn("Type", null, Table.FLAG_NONE, "type varchar");
tgWL.addColumn("Count", null, Table.FLAG_ALIGN_RIGHT, "count int");
tgWL.addColumn("Time", null, Table.FLAG_ALIGN_RIGHT, "time varchar");
tgWL.addColumn("Time(ms)", null, Table.FLAG_ALIGN_RIGHT, "time_ms int");
tgWL.begin();
Chapter cpuPerUid = new Chapter(br, "CPU usage per UID");
new Hint(cpuPerUid).add("Hint: hover over the UID to see it's name.");
Pattern pProc = Pattern.compile("Proc (.*?):");
Pattern pCPU = Pattern.compile("CPU: (.*?) usr \\+ (.*?) krn");
Table tgCU = new Table(Table.FLAG_SORT, cpuPerUid);
tgCU.setCSVOutput(br, "battery_" + csvPrefix + "_cpu_per_uid");
tgCU.setTableName(br, "battery_" + csvPrefix + "_cpu_per_uid");
tgCU.addColumn("UID", null, Table.FLAG_ALIGN_RIGHT, "uid int");
tgCU.addColumn("Usr (ms)", null, Table.FLAG_ALIGN_RIGHT, "usr_ms int");
tgCU.addColumn("Krn (ms)", null, Table.FLAG_ALIGN_RIGHT, "krn_ms int");
tgCU.addColumn("Total (ms)", null, Table.FLAG_ALIGN_RIGHT, "total_ms int");
tgCU.addColumn("Usr (min)", null, Table.FLAG_ALIGN_RIGHT, "usr_min int");
tgCU.addColumn("Krn (min)", null, Table.FLAG_ALIGN_RIGHT, "krn_min int");
tgCU.addColumn("Total (min)", null, Table.FLAG_ALIGN_RIGHT, "total_min int");
tgCU.begin();
Chapter cpuPerProc = new Chapter(br, "CPU usage per Proc");
new Hint(cpuPerUid).add("Hint: hover over the UID to see it's name.");
Table tgCP = new Table(Table.FLAG_SORT, cpuPerProc);
tgCP.setCSVOutput(br, "battery_" + csvPrefix + "_cpu_per_proc");
tgCP.setTableName(br, "battery_" + csvPrefix + "_cpu_per_proc");
tgCP.addColumn("UID", null, Table.FLAG_ALIGN_RIGHT, "uid int");
tgCP.addColumn("Proc", null, Table.FLAG_NONE, "proc varchar");
tgCP.addColumn("Usr", null, Table.FLAG_ALIGN_RIGHT, "usr int");
tgCP.addColumn("Usr (ms)", null, Table.FLAG_ALIGN_RIGHT, "usr_ms int");
tgCP.addColumn("Krn", null, Table.FLAG_ALIGN_RIGHT, "krn int");
tgCP.addColumn("Krn (ms)", null, Table.FLAG_ALIGN_RIGHT, "krn_ms int");
tgCP.addColumn("Total (ms)", null, Table.FLAG_ALIGN_RIGHT, "total_ms int");
tgCP.begin();
Chapter net = new Chapter(br, "Network traffic");
new Hint(cpuPerUid).add("Hint: hover over the UID to see it's name.");
Pattern pNet = Pattern.compile("Network: (.*?) received, (.*?) sent");
Table tgNet = new Table(Table.FLAG_SORT, net);
tgNet.setCSVOutput(br, "battery_" + csvPrefix + "_net");
tgNet.setTableName(br, "battery_" + csvPrefix + "_net");
tgNet.addColumn("UID", null, Table.FLAG_ALIGN_RIGHT, "uid int");
tgNet.addColumn("Received (B)", null, Table.FLAG_ALIGN_RIGHT, "received_b int");
tgNet.addColumn("Sent (B)", null, Table.FLAG_ALIGN_RIGHT, "sent_b int");
tgNet.addColumn("Total (B)", null, Table.FLAG_ALIGN_RIGHT, "total_b int");
tgNet.begin();
long sumRecv = 0, sumSent = 0;
HashMap<String, CpuPerUid> cpuPerUidStats = new HashMap<String, CpuPerUid>();
for (Node item : node) {
String line = item.getLine();
if (line.startsWith("#")) {
String sUID = line.substring(1, line.length() - 1);
PackageInfoPlugin.UID uid = null;
String uidName = sUID;
Anchor uidLink = null;
if (pkgInfo != null) {
int uidInt = Integer.parseInt(sUID);
uid = pkgInfo.getUID(uidInt);
if (uid != null) {
uidName = uid.getFullName();
uidLink = pkgInfo.getAnchorToUid(uid);
}
}
for (Node subNode : item) {
String s = subNode.getLine();
if (s.startsWith("Wake lock") && !s.contains("(nothing executed)")) {
Matcher m = pWL.matcher(s);
if (m.find()) {
String name = m.group(1);
String sTime = m.group(2);
String type = m.group(3);
String sCount = m.group(4);
long ts = readTs(sTime.replace(" ", ""));
tgWL.setNextRowStyle(colorizeTime(ts));
tgWL.addData(uidName, new Link(uidLink, sUID));
tgWL.addData(name);
tgWL.addData(type);
tgWL.addData(sCount);
tgWL.addData(sTime);
tgWL.addData(new ShadedValue(ts));
if (ts > WAKE_LOG_BUG_THRESHHOLD) {
bug = createBug(br, bug);
bug.list.add("Wake lock: " + name);
}
} else {
System.err.println("Could not parse line: " + s);
}
} else if (s.startsWith("Network: ")) {
Matcher m = pNet.matcher(s);
if (m.find()) {
long recv = parseBytes(m.group(1));
long sent = parseBytes(m.group(2));
sumRecv += recv;
sumSent += sent;
tgNet.addData(uidName, new Link(uidLink, sUID));
tgNet.addData(new ShadedValue(recv));
tgNet.addData(new ShadedValue(sent));
tgNet.addData(new ShadedValue(recv + sent));
} else {
System.err.println("Could not parse line: " + s);
}
} else if (s.startsWith("Proc ")) {
Matcher mProc = pProc.matcher(s);
if (mProc.find()) {
String procName = mProc.group(1);
Node cpuItem = subNode.findChildStartsWith("CPU:");
if (cpuItem != null) {
Matcher m = pCPU.matcher(cpuItem.getLine());
if (m.find()) {
String sUsr = m.group(1);
long usr = readTs(sUsr.replace(" ", ""));
String sKrn = m.group(2);
long krn = readTs(sKrn.replace(" ", ""));
CpuPerUid cpu = cpuPerUidStats.get(sUID);
if (cpu == null) {
cpu = new CpuPerUid();
cpu.uidLink = uidLink;
cpu.uidName = uidName;
cpuPerUidStats.put(sUID, cpu);
}
cpu.usr += usr;
cpu.krn += krn;
tgCP.addData(uidName, new Link(uidLink, sUID));
tgCP.addData(procName);
tgCP.addData(sUsr);
tgCP.addData(new ShadedValue(usr));
tgCP.addData(sKrn);
tgCP.addData(new ShadedValue(krn));
tgCP.addData(new ShadedValue(usr + krn));
} else {
System.err.println("Could not parse line: " + cpuItem.getLine());
}
}
} else {
System.err.println("Could not parse line: " + s);
}
}
}
} else if (line.startsWith("Kernel Wake lock")) {
if (!line.contains("(nothing executed)")) {
Matcher m = pKWL.matcher(line);
if (m.find()) {
String name = m.group(1);
String sTime = m.group(2);
String sCount = m.group(3);
long ts = readTs(sTime.replace(" ", ""));
tgKWL.setNextRowStyle(colorizeTime(ts));
tgKWL.addData(name);
tgKWL.addData(sCount);
tgKWL.addData(sTime);
tgKWL.addData(new ShadedValue(ts));
if (ts > WAKE_LOG_BUG_THRESHHOLD) {
bug = createBug(br, bug);
bug.list.add("Kernel Wake lock: " + name);
}
} else {
System.err.println("Could not parse line: " + line);
}
}
} else {
if (item.getChildCount() == 0) {
pre.addln(line);
}
}
}
if (!tgKWL.isEmpty()) {
tgKWL.end();
ch.addChapter(kernelWakeLock);
}
if (!tgWL.isEmpty()) {
tgWL.end();
ch.addChapter(wakeLock);
}
if (!cpuPerUidStats.isEmpty()) {
for (String sUid : cpuPerUidStats.keySet()) {
CpuPerUid cpu = cpuPerUidStats.get(sUid);
tgCU.addData(cpu.uidName, new Link(cpu.uidLink, sUid));
tgCU.addData(new ShadedValue(cpu.usr));
tgCU.addData(new ShadedValue(cpu.krn));
tgCU.addData(new ShadedValue(cpu.usr + cpu.krn));
tgCU.addData(Long.toString(cpu.usr / MIN));
tgCU.addData(Long.toString(cpu.krn / MIN));
tgCU.addData(Long.toString((cpu.usr + cpu.krn) / MIN));
}
tgCU.end();
ch.addChapter(cpuPerUid);
}
if (!tgCP.isEmpty()) {
tgCP.end();
ch.addChapter(cpuPerProc);
}
if (!tgNet.isEmpty()) {
tgNet.addSeparator();
tgNet.addData("TOTAL:");
tgNet.addData(new ShadedValue(sumRecv));
tgNet.addData(new ShadedValue(sumSent));
tgNet.addData(new ShadedValue(sumRecv + sumSent));
tgNet.end();
ch.addChapter(net);
}
if (detectBugs && bug != null) {
bug.bug.add(new Link(ch.getAnchor(), "Click here for more information"));
br.addBug(bug.bug);
}
}
|
public void analyse(Project project, SensorContext context) {
for (String language : moduleLanguages.keys()) {
ModuleQProfiles.QProfile qProfile = moduleQProfiles.findByLanguage(language);
if (qProfile != null) {
dao.updateUsedColumn(qProfile.id(), true);
}
}
if (moduleLanguages.keys().size() == 1) {
String language = moduleLanguages.keys().iterator().next();
ModuleQProfiles.QProfile qProfile = moduleQProfiles.findByLanguage(language);
if (qProfile != null) {
Measure measure = new Measure(CoreMetrics.PROFILE, qProfile.name());
Measure measureVersion = new Measure(CoreMetrics.PROFILE_VERSION, qProfile.version().doubleValue());
context.saveMeasure(measure);
context.saveMeasure(measureVersion);
}
}
}
|
public void analyse(Project project, SensorContext context) {
for (String language : moduleLanguages.keys()) {
ModuleQProfiles.QProfile qProfile = moduleQProfiles.findByLanguage(language);
if (qProfile != null) {
dao.updateUsedColumn(qProfile.id(), true);
}
}
if (moduleLanguages.keys().size() == 1) {
String language = moduleLanguages.keys().iterator().next();
ModuleQProfiles.QProfile qProfile = moduleQProfiles.findByLanguage(language);
if (qProfile != null) {
Measure measure = new Measure(CoreMetrics.PROFILE, qProfile.name()).setValue((double)qProfile.id());
Measure measureVersion = new Measure(CoreMetrics.PROFILE_VERSION, qProfile.version().doubleValue());
context.saveMeasure(measure);
context.saveMeasure(measureVersion);
}
}
}
|
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
thisActivity = this;
setContentView(R.layout.picasa);
usernameEditText = (EditText)findViewById(R.id.usernameEditText);
albumList = (ListView)findViewById(R.id.albumList);
Button loadAlbumsButton = (Button)findViewById(R.id.loadAlbumsButton);
loadAlbumsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
List<String> albums = new PicasaApi("" + usernameEditText.getText()).getAlbums();
String[] items;
if (albums != null) {
items = albums.toArray(new String[] {"dummy array to get correct type"});
} else {
items = new String[] { "no albums found" };
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
thisActivity,
android.R.layout.simple_list_item_1,
android.R.id.text1,
items);
albumList.setAdapter(adapter);
}
});
}
|
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
thisActivity = this;
setContentView(R.layout.picasa);
usernameEditText = (EditText)findViewById(R.id.usernameEditText);
albumList = (ListView)findViewById(R.id.albumList);
Button loadAlbumsButton = (Button)findViewById(R.id.loadAlbumsButton);
loadAlbumsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
List<String> albums = new PicasaApi("" + usernameEditText.getText()).getAlbums();
String[] items;
if (albums != null) {
items = albums.toArray(new String[] {"dummy array to get correct type"});
} else {
items = new String[] { "No albums found" };
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
thisActivity,
android.R.layout.simple_list_item_1,
android.R.id.text1,
items);
albumList.setAdapter(adapter);
}
});
}
|
public void migrate(String csvDir, String outputDir) {
CSVFileReader csvFileReader = null;
BufferedWriter volunteersWriter = null;
BufferedWriter volunteerAddressesWriter = null;
BufferedWriter volunteerContactInfoWriter = null;
BufferedWriter volunteerContactTelephonesWriter = null;
BufferedWriter volunteerContactEmailsWriter = null;
BufferedWriter volunteerGeoAreaLookupsWriter = null;
BufferedWriter volunteerTypeOfActivityLookupsWriter = null;
BufferedWriter volunteerCausesIntsLookupsWriter = null;
BufferedWriter volunteerTagsLookupsWriter = null;
BufferedWriter addressesWriter = null;
try {
csvFileReader = new CSVFileReader(new FileReader(csvDir + "tblVol.csv"));
volunteersWriter = new BufferedWriter(new FileWriter(outputDir + "Volunteers.csv"));
volunteerAddressesWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerAddresses.csv"));
volunteerContactInfoWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerContactInfo.csv"));
volunteerContactTelephonesWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerContactTelephones.csv"));
volunteerContactEmailsWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerContactEmails.csv"));
volunteerGeoAreaLookupsWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerGeoAreaLookups.csv"));
volunteerTypeOfActivityLookupsWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerTypeOfActivityLookups.csv"));
volunteerCausesIntsLookupsWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerCausesIntsLookups.csv"));
volunteerTagsLookupsWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerTagsLookups.csv"));
addressesWriter = new BufferedWriter(new FileWriter(outputDir + "Addresses.csv"));
Map<Long, List<TblVolTime>> tblVolTimes = CSVUtil.createVidMap(csvDir + "tblVolTime.csv", TblVolTime.class);
Map<Long, List<TblVolTypeOfActivity>> tblVolTypeOfActivities =
CSVUtil.createVidMap(csvDir + "tblVolTypeOfActivity.csv", TblVolTypeOfActivity.class);
Map<Long, List<TblVolAreasOfInterest>> tblVolAreasOfInterests =
CSVUtil.createVidMap(csvDir + "tblVolAreasOfInterest.csv", TblVolAreasOfInterest.class);
Map<Long, List<TblVolSpecial>> tblVolSpecials =
CSVUtil.createVidMap(csvDir + "tblVolSpecial.csv", TblVolSpecial.class);
TblVol tblVol = null;
Volunteers volunteers = null;
VolunteerContactInfo dayTimeContactInfo = null;
VolunteerContactTelephones dayTimeTelephone = null;
VolunteerContactInfo eveningContactInfo = null;
VolunteerContactTelephones eveningTelephone = null;
VolunteerContactInfo faxContactInfo = null;
VolunteerContactTelephones faxTelephone = null;
VolunteerContactInfo mobileContactInfo = null;
VolunteerContactTelephones mobileTelephone = null;
VolunteerContactInfo emailContactInfo = null;
VolunteerContactEmails email = null;
VolunteerGeoAreaLookups volunteerGeoAreas = null;
List<VolunteerTypeOfActivityLookups> volunteerTypeOfActivities = null;
List<VolunteerCausesIntsLookups> volunteerCausesInts = null;
List<VolunteerTagsLookups> volunteerTags = null;
VolunteerAddresses volunteerAddresses = null;
Addresses addresses = null;
String record = "";
while ((record = csvFileReader.readRecord()) != null) {
tblVol = new TblVol(record);
volunteers = new Volunteers();
dayTimeContactInfo = null;
dayTimeTelephone = null;
eveningContactInfo = null;
eveningTelephone = null;
faxContactInfo = null;
faxTelephone = null;
mobileContactInfo = null;
mobileTelephone = null;
emailContactInfo = null;
email = null;
volunteerGeoAreas = null;
volunteerTypeOfActivities = null;
volunteerCausesInts = null;
volunteerTags = null;
volunteerAddresses = null;
addresses = null;
volunteers.setId(UUID.randomUUID());
volunteers.setVbase2Id(tblVol.getVid());
volunteers.setIsActive(true);
volunteers.setTitleId(MigrationUtil.getLookupId(lookupsMap, "title", tblVol.getTitle().toLowerCase(),
"-"));
volunteers.setFirstName(tblVol.getFirstname());
volunteers.setLastName(tblVol.getLastname());
volunteers.setPreferredName(tblVol.getSalutation() != null &&
!tblVol.getSalutation().trim().equals("") ? tblVol.getSalutation() : tblVol.getFirstname());
volunteers.setAgreesToBeContacted(tblVol.getContactable());
volunteers.setDisabilityDetails(tblVol.getDisabilitystatus());
volunteers.setDateOfBirth(tblVol.getDob());
volunteers.setGenderId(MigrationUtil.getLookupId(lookupsMap, "gender", tblVol.getGender().toLowerCase()));
volunteers.setAgeRangeId(MigrationUtil.getLookupId(lookupsMap, "agerange",
tblVol.getAgerange().toLowerCase()));
volunteers.setEmploymentStatusId(MigrationUtil.getLookupId(lookupsMap, "employmentstatus",
tblVol.getEmploymentstatus().toLowerCase()));
volunteers.setEthnicityId(MigrationUtil.getLookupId(lookupsMap, "ethnicity",
tblVol.getEthnicity().toLowerCase()));
volunteers.setDrivingLicenceId(MigrationUtil.getLookupId(lookupsMap, "drivinglicence",
tblVol.getTypeofdrivinglicence().toLowerCase()));
volunteers.setNationalityId(MigrationUtil.getLookupId(lookupsMap, "nationality",
tblVol.getNationality().toLowerCase()));
volunteers.setReligionId(MigrationUtil.getLookupId(lookupsMap, "religion",
tblVol.getReligion().toLowerCase()));
volunteers.setDisabilityStatusId(MigrationUtil.getLookupId(lookupsMap, "disabilityStatus",
tblVol.getDisabilitystatus().toLowerCase()));
volunteers.setTransportId(MigrationUtil.getLookupId(lookupsMap, "transport",
tblVol.getDriving().toLowerCase()));
volunteers.setQualificationsAndExperience(tblVol.getPreviouswork());
volunteers.setAmCommitment(createCommitment(tblVolTimes.get(volunteers.getVbase2Id()), "AM"));
volunteers.setPmCommitment(createCommitment(tblVolTimes.get(volunteers.getVbase2Id()), "PM"));
volunteers.setEveCommitment(createCommitment(tblVolTimes.get(volunteers.getVbase2Id()), "EVE"));
volunteers.setAvailabilityStatusId(availabilityStatusMap.get(tblVol.getStatus().toLowerCase()));
volunteers.setPlacementStatusId(MigrationUtil.getLookupId(lookupsMap, "placementstatus",
tblVol.getStatus().toLowerCase(), "unknown"));
volunteers.setHowHeardId(MigrationUtil.getLookupId(lookupsMap, "howheard",
tblVol.getHowheard().toLowerCase()));
if (tblVol.getAddress1() != null && !tblVol.getAddress1().equals("")) {
addresses = new Addresses();
volunteerAddresses = new VolunteerAddresses();
addresses.setId(UUID.randomUUID());
addresses.setVbase2Id(volunteers.getVbase2Id());
addresses.setAddress1(tblVol.getAddress1());
addresses.setAddress2(tblVol.getAddress2());
addresses.setTown(tblVol.getTown());
addresses.setCountryId(MigrationUtil.getLookupId(lookupsMap, "country", "uk"));
addresses.setCountyId(MigrationUtil.getLookupId(lookupsMap, "county",
tblVol.getCounty().toLowerCase()));
addresses.setPostCode(tblVol.getPostcode());
volunteerAddresses.setVolunteerId(volunteers.getId());
volunteerAddresses.setName("Unspecified");
volunteerAddresses.setAddressId(addresses.getId());
volunteerAddresses.setIsActive(true);
volunteerAddresses.setIsDefaultAddress(true);
}
if (tblVol.getTelday() != null && !tblVol.getTelday().equals("")) {
dayTimeContactInfo = new VolunteerContactInfo();
dayTimeTelephone = new VolunteerContactTelephones();
dayTimeContactInfo.setId(UUID.randomUUID());
dayTimeContactInfo.setIsActive(true);
dayTimeContactInfo.setIsDefault(false);
dayTimeContactInfo.setNotes("Daytime");
dayTimeTelephone.setVolunteerId(volunteers.getId());
dayTimeTelephone.setVolunteerContactInfoId(dayTimeContactInfo.getId());
dayTimeTelephone.setTelephoneTypeId(MigrationUtil.getLookupId(lookupsMap, "telephonetype",
"unspecified"));
dayTimeTelephone.setTel_number(tblVol.getTelday());
}
if (tblVol.getTelevening() != null && !tblVol.getTelevening().equals("")) {
eveningContactInfo = new VolunteerContactInfo();
eveningTelephone = new VolunteerContactTelephones();
eveningContactInfo.setId(UUID.randomUUID());
eveningContactInfo.setIsActive(true);
eveningContactInfo.setIsDefault(false);
eveningContactInfo.setNotes("Evening");
eveningTelephone.setVolunteerId(volunteers.getId());
eveningTelephone.setVolunteerContactInfoId(eveningContactInfo.getId());
eveningTelephone.setTelephoneTypeId(MigrationUtil.getLookupId(lookupsMap, "telephonetype",
"unspecified"));
eveningTelephone.setTel_number(tblVol.getTelevening());
}
if (tblVol.getFax() != null && !tblVol.getFax().equals("")) {
faxContactInfo = new VolunteerContactInfo();
faxTelephone = new VolunteerContactTelephones();
faxContactInfo.setId(UUID.randomUUID());
faxContactInfo.setIsActive(true);
faxContactInfo.setIsDefault(false);
faxContactInfo.setNotes("");
faxTelephone.setVolunteerId(volunteers.getId());
faxTelephone.setVolunteerContactInfoId(faxContactInfo.getId());
faxTelephone.setTelephoneTypeId(MigrationUtil.getLookupId(lookupsMap, "telephonetype", "fax"));
faxTelephone.setTel_number(tblVol.getFax());
}
if (tblVol.getMobile() != null && !tblVol.getMobile().equals("")) {
mobileContactInfo = new VolunteerContactInfo();
mobileTelephone = new VolunteerContactTelephones();
mobileContactInfo.setId(UUID.randomUUID());
mobileContactInfo.setIsActive(true);
mobileContactInfo.setIsDefault(false);
mobileContactInfo.setNotes("");
mobileTelephone.setVolunteerId(volunteers.getId());
mobileTelephone.setVolunteerContactInfoId(mobileContactInfo.getId());
mobileTelephone.setTelephoneTypeId(MigrationUtil.getLookupId(lookupsMap, "telephonetype", "mobile"));
mobileTelephone.setTel_number(tblVol.getMobile());
}
if (tblVol.getEmail() != null && !tblVol.getEmail().equals("")) {
emailContactInfo = new VolunteerContactInfo();
email = new VolunteerContactEmails();
emailContactInfo.setId(UUID.randomUUID());
emailContactInfo.setIsActive(true);
emailContactInfo.setIsDefault(true);
emailContactInfo.setNotes("");
email.setVolunteerId(volunteers.getId());
email.setVolunteerContactInfoId(emailContactInfo.getId());
email.setTelephoneTypeId(MigrationUtil.getLookupId(lookupsMap, "emailtype", "unspecified"));
email.setEmail(tblVol.getEmail());
}
if (tblVol.getGeographicalarea() != null && !tblVol.getGeographicalarea().equals("")) {
volunteerGeoAreas = new VolunteerGeoAreaLookups();
volunteerGeoAreas.setVolunteerId(volunteers.getId());
volunteerGeoAreas.setLookupId(MigrationUtil.getLookupId(lookupsMap, "geographicalarea",
tblVol.getGeographicalarea().toLowerCase()));
}
if (tblVolTypeOfActivities.get(tblVol.getVid()) != null) {
volunteerTypeOfActivities = new ArrayList<VolunteerTypeOfActivityLookups>();
VolunteerTypeOfActivityLookups volunteerTypeOfActivity = null;
for (TblVolTypeOfActivity activity : tblVolTypeOfActivities.get(tblVol.getVid())) {
volunteerTypeOfActivity = new VolunteerTypeOfActivityLookups();
volunteerTypeOfActivity.setVolunteerId(volunteers.getId());
volunteerTypeOfActivity.setLookupId(MigrationUtil.getLookupId(lookupsMap, "typeofactivity",
activity.getTypeofactivity().toLowerCase()));
if(volunteerTypeOfActivity.getLookupId() != null) {
volunteerTypeOfActivities.add(volunteerTypeOfActivity);
} else {
System.out.println("Opportunity type of activity " + activity.getTypeofactivity()
+ " has no matching type of activity lookup.");
}
}
}
if (tblVolAreasOfInterests.get(tblVol.getVid()) != null) {
volunteerCausesInts = new ArrayList<VolunteerCausesIntsLookups>();
VolunteerCausesIntsLookups volunteerCausesInt = null;
for (TblVolAreasOfInterest areasOfInterest : tblVolAreasOfInterests.get(tblVol.getVid())) {
volunteerCausesInt = new VolunteerCausesIntsLookups();
volunteerCausesInt.setVolunteerId(volunteers.getId());
volunteerCausesInt.setLookupId(MigrationUtil.getLookupId(lookupsMap, "causeinterest",
areasOfInterest.getAreasofinterest().toLowerCase()));
if(volunteerCausesInt.getLookupId() != null) {
volunteerCausesInts.add(volunteerCausesInt);
} else {
System.out.println("Opportunity area of interest " + areasOfInterest.getAreasofinterest()
+ " has no matching cause of interest lookup.");
}
}
}
if (tblVolSpecials.get(tblVol.getVid()) != null) {
volunteerTags = new ArrayList<VolunteerTagsLookups>();
VolunteerTagsLookups volunteerTag = null;
for (TblVolSpecial special : tblVolSpecials.get(tblVol.getVid())) {
volunteerTag = new VolunteerTagsLookups();
volunteerTag.setVolunteerId(volunteers.getId());
volunteerTag.setLookupId(MigrationUtil.getLookupId(lookupsMap, "taggeddata",
special.getSpecial().toLowerCase()));
if(volunteerTag.getLookupId() != null) {
volunteerTags.add(volunteerTag);
} else {
System.out.println("Opportunity special " + special.getSpecial()
+ " has no matching target lookup.");
}
}
}
volunteersWriter.write(volunteers.getRecord() + "\n");
if (volunteerAddresses != null) volunteerAddressesWriter.write(volunteerAddresses.getRecord() + "\n");
if (dayTimeContactInfo != null) volunteerContactInfoWriter.write(dayTimeContactInfo.getRecord() + "\n");
if (eveningContactInfo != null) volunteerContactInfoWriter.write(eveningContactInfo.getRecord() + "\n");
if (faxContactInfo != null) volunteerContactInfoWriter.write(faxContactInfo.getRecord() + "\n");
if (mobileContactInfo != null) volunteerContactInfoWriter.write(mobileContactInfo.getRecord() + "\n");
if (emailContactInfo != null) volunteerContactInfoWriter.write(emailContactInfo.getRecord() + "\n");
if (dayTimeTelephone != null)
volunteerContactTelephonesWriter.write(dayTimeTelephone.getRecord() + "\n");
if (eveningTelephone != null)
volunteerContactTelephonesWriter.write(eveningTelephone.getRecord() + "\n");
if (faxTelephone != null) volunteerContactTelephonesWriter.write(faxTelephone.getRecord() + "\n");
if (mobileTelephone != null) volunteerContactTelephonesWriter.write(mobileTelephone.getRecord() + "\n");
if (email != null) volunteerContactEmailsWriter.write(email.getRecord() + "\n");
if (volunteerGeoAreas != null)
volunteerGeoAreaLookupsWriter.write(volunteerGeoAreas.getRecord() + "\n");
if (volunteerTypeOfActivities != null) {
for (VolunteerTypeOfActivityLookups activity : volunteerTypeOfActivities) {
volunteerTypeOfActivityLookupsWriter.write(activity.getRecord() + "\n");
}
}
if (volunteerCausesInts != null) {
for (VolunteerCausesIntsLookups causesInt : volunteerCausesInts) {
volunteerCausesIntsLookupsWriter.write(causesInt.getRecord() + "\n");
}
}
if (volunteerTags != null) {
for (VolunteerTagsLookups tag : volunteerTags) {
volunteerTagsLookupsWriter.write(tag.getRecord() + "\n");
}
}
if (addresses != null) addressesWriter.write(addresses.getRecord() + "\n");
}
} catch (IOException e) {
System.out.println("Error while migrating volunteers. Error:" + e.getMessage());
} finally {
try {
if (csvFileReader != null) {
csvFileReader.close();
}
if (volunteersWriter != null) {
volunteersWriter.flush();
volunteersWriter.close();
}
if (volunteerAddressesWriter != null) {
volunteerAddressesWriter.flush();
volunteerAddressesWriter.close();
}
if (volunteerContactInfoWriter != null) {
volunteerContactInfoWriter.flush();
volunteerContactInfoWriter.close();
}
if (volunteerContactTelephonesWriter != null) {
volunteerContactTelephonesWriter.flush();
volunteerContactTelephonesWriter.close();
}
if (volunteerContactEmailsWriter != null) {
volunteerContactEmailsWriter.flush();
volunteerContactEmailsWriter.close();
}
if (volunteerGeoAreaLookupsWriter != null) {
volunteerGeoAreaLookupsWriter.flush();
volunteerGeoAreaLookupsWriter.close();
}
if (volunteerTypeOfActivityLookupsWriter != null) {
volunteerTypeOfActivityLookupsWriter.flush();
volunteerTypeOfActivityLookupsWriter.close();
}
if (volunteerCausesIntsLookupsWriter != null) {
volunteerCausesIntsLookupsWriter.flush();
volunteerCausesIntsLookupsWriter.close();
}
if (volunteerTagsLookupsWriter != null) {
volunteerTagsLookupsWriter.flush();
volunteerTagsLookupsWriter.close();
}
if (addressesWriter != null) {
addressesWriter.flush();
addressesWriter.close();
}
} catch (IOException e) {
System.out.println("Error closing volunteers streams. Error:" + e.getMessage());
}
}
}
|
public void migrate(String csvDir, String outputDir) {
CSVFileReader csvFileReader = null;
BufferedWriter volunteersWriter = null;
BufferedWriter volunteerAddressesWriter = null;
BufferedWriter volunteerContactInfoWriter = null;
BufferedWriter volunteerContactTelephonesWriter = null;
BufferedWriter volunteerContactEmailsWriter = null;
BufferedWriter volunteerGeoAreaLookupsWriter = null;
BufferedWriter volunteerTypeOfActivityLookupsWriter = null;
BufferedWriter volunteerCausesIntsLookupsWriter = null;
BufferedWriter volunteerTagsLookupsWriter = null;
BufferedWriter addressesWriter = null;
try {
csvFileReader = new CSVFileReader(new FileReader(csvDir + "tblVol.csv"));
volunteersWriter = new BufferedWriter(new FileWriter(outputDir + "Volunteers.csv"));
volunteerAddressesWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerAddresses.csv"));
volunteerContactInfoWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerContactInfo.csv"));
volunteerContactTelephonesWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerContactTelephones.csv"));
volunteerContactEmailsWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerContactEmails.csv"));
volunteerGeoAreaLookupsWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerGeoAreaLookups.csv"));
volunteerTypeOfActivityLookupsWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerTypeOfActivityLookups.csv"));
volunteerCausesIntsLookupsWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerCausesIntsLookups.csv"));
volunteerTagsLookupsWriter = new BufferedWriter(new FileWriter(outputDir + "VolunteerTagsLookups.csv"));
addressesWriter = new BufferedWriter(new FileWriter(outputDir + "Addresses.csv"));
Map<Long, List<TblVolTime>> tblVolTimes = CSVUtil.createVidMap(csvDir + "tblVolTime.csv", TblVolTime.class);
Map<Long, List<TblVolTypeOfActivity>> tblVolTypeOfActivities =
CSVUtil.createVidMap(csvDir + "tblVolTypeOfActivity.csv", TblVolTypeOfActivity.class);
Map<Long, List<TblVolAreasOfInterest>> tblVolAreasOfInterests =
CSVUtil.createVidMap(csvDir + "tblVolAreasOfInterest.csv", TblVolAreasOfInterest.class);
Map<Long, List<TblVolSpecial>> tblVolSpecials =
CSVUtil.createVidMap(csvDir + "tblVolSpecial.csv", TblVolSpecial.class);
TblVol tblVol = null;
Volunteers volunteers = null;
VolunteerContactInfo dayTimeContactInfo = null;
VolunteerContactTelephones dayTimeTelephone = null;
VolunteerContactInfo eveningContactInfo = null;
VolunteerContactTelephones eveningTelephone = null;
VolunteerContactInfo faxContactInfo = null;
VolunteerContactTelephones faxTelephone = null;
VolunteerContactInfo mobileContactInfo = null;
VolunteerContactTelephones mobileTelephone = null;
VolunteerContactInfo emailContactInfo = null;
VolunteerContactEmails email = null;
VolunteerGeoAreaLookups volunteerGeoAreas = null;
List<VolunteerTypeOfActivityLookups> volunteerTypeOfActivities = null;
List<VolunteerCausesIntsLookups> volunteerCausesInts = null;
List<VolunteerTagsLookups> volunteerTags = null;
VolunteerAddresses volunteerAddresses = null;
Addresses addresses = null;
String record = "";
while ((record = csvFileReader.readRecord()) != null) {
tblVol = new TblVol(record);
volunteers = new Volunteers();
dayTimeContactInfo = null;
dayTimeTelephone = null;
eveningContactInfo = null;
eveningTelephone = null;
faxContactInfo = null;
faxTelephone = null;
mobileContactInfo = null;
mobileTelephone = null;
emailContactInfo = null;
email = null;
volunteerGeoAreas = null;
volunteerTypeOfActivities = null;
volunteerCausesInts = null;
volunteerTags = null;
volunteerAddresses = null;
addresses = null;
volunteers.setId(UUID.randomUUID());
volunteers.setVbase2Id(tblVol.getVid());
volunteers.setIsActive(true);
volunteers.setTitleId(MigrationUtil.getLookupId(lookupsMap, "title", tblVol.getTitle().toLowerCase(),
"-"));
volunteers.setFirstName(tblVol.getFirstname());
volunteers.setLastName(tblVol.getLastname());
volunteers.setPreferredName(tblVol.getSalutation() != null &&
!tblVol.getSalutation().trim().equals("") ? tblVol.getSalutation() : tblVol.getFirstname());
volunteers.setAgreesToBeContacted(tblVol.getContactable());
volunteers.setDisabilityDetails(tblVol.getDisabilitystatus());
volunteers.setDateOfBirth(tblVol.getDob());
volunteers.setGenderId(MigrationUtil.getLookupId(lookupsMap, "gender", tblVol.getGender().toLowerCase()));
volunteers.setAgeRangeId(MigrationUtil.getLookupId(lookupsMap, "agerange",
tblVol.getAgerange().toLowerCase()));
volunteers.setEmploymentStatusId(MigrationUtil.getLookupId(lookupsMap, "employmentstatus",
tblVol.getEmploymentstatus().toLowerCase()));
volunteers.setEthnicityId(MigrationUtil.getLookupId(lookupsMap, "ethnicity",
tblVol.getEthnicity().toLowerCase()));
volunteers.setDrivingLicenceId(MigrationUtil.getLookupId(lookupsMap, "drivinglicence",
tblVol.getTypeofdrivinglicence().toLowerCase()));
volunteers.setNationalityId(MigrationUtil.getLookupId(lookupsMap, "nationality",
tblVol.getNationality().toLowerCase()));
volunteers.setReligionId(MigrationUtil.getLookupId(lookupsMap, "religion",
tblVol.getReligion().toLowerCase()));
volunteers.setDisabilityStatusId(MigrationUtil.getLookupId(lookupsMap, "disabilityStatus",
tblVol.getDisabilitystatus().toLowerCase()));
volunteers.setTransportId(MigrationUtil.getLookupId(lookupsMap, "transport",
tblVol.getDriving().toLowerCase()));
volunteers.setQualificationsAndExperience(tblVol.getPreviouswork());
volunteers.setAmCommitment(createCommitment(tblVolTimes.get(volunteers.getVbase2Id()), "AM"));
volunteers.setPmCommitment(createCommitment(tblVolTimes.get(volunteers.getVbase2Id()), "PM"));
volunteers.setEveCommitment(createCommitment(tblVolTimes.get(volunteers.getVbase2Id()), "EVE"));
volunteers.setAvailabilityStatusId(availabilityStatusMap.get(tblVol.getStatus().toLowerCase()));
volunteers.setPlacementStatusId(MigrationUtil.getLookupId(lookupsMap, "placementstatus",
tblVol.getStatus().toLowerCase(), "unknown"));
volunteers.setHowHeardId(MigrationUtil.getLookupId(lookupsMap, "howheard",
tblVol.getHowheard().toLowerCase()));
if (tblVol.getAddress1() != null && !tblVol.getAddress1().equals("")) {
addresses = new Addresses();
volunteerAddresses = new VolunteerAddresses();
addresses.setId(UUID.randomUUID());
addresses.setVbase2Id(volunteers.getVbase2Id());
addresses.setAddress1(tblVol.getAddress1());
addresses.setAddress2(tblVol.getAddress2());
addresses.setTown(tblVol.getTown());
addresses.setCountryId(MigrationUtil.getLookupId(lookupsMap, "country", "uk"));
addresses.setCountyId(MigrationUtil.getLookupId(lookupsMap, "county",
tblVol.getCounty().toLowerCase()));
addresses.setPostCode(tblVol.getPostcode());
volunteerAddresses.setVolunteerId(volunteers.getId());
volunteerAddresses.setName("Unspecified");
volunteerAddresses.setAddressId(addresses.getId());
volunteerAddresses.setIsActive(true);
volunteerAddresses.setIsDefaultAddress(true);
}
if (tblVol.getTelday() != null && !tblVol.getTelday().equals("")) {
dayTimeContactInfo = new VolunteerContactInfo();
dayTimeTelephone = new VolunteerContactTelephones();
dayTimeContactInfo.setId(UUID.randomUUID());
dayTimeContactInfo.setIsActive(true);
dayTimeContactInfo.setIsDefault(false);
dayTimeContactInfo.setNotes("Daytime");
dayTimeTelephone.setVolunteerId(volunteers.getId());
dayTimeTelephone.setVolunteerContactInfoId(dayTimeContactInfo.getId());
dayTimeTelephone.setTelephoneTypeId(MigrationUtil.getLookupId(lookupsMap, "telephonetype",
"unspecified"));
dayTimeTelephone.setTel_number(tblVol.getTelday());
}
if (tblVol.getTelevening() != null && !tblVol.getTelevening().equals("")) {
eveningContactInfo = new VolunteerContactInfo();
eveningTelephone = new VolunteerContactTelephones();
eveningContactInfo.setId(UUID.randomUUID());
eveningContactInfo.setIsActive(true);
eveningContactInfo.setIsDefault(false);
eveningContactInfo.setNotes("Evening");
eveningTelephone.setVolunteerId(volunteers.getId());
eveningTelephone.setVolunteerContactInfoId(eveningContactInfo.getId());
eveningTelephone.setTelephoneTypeId(MigrationUtil.getLookupId(lookupsMap, "telephonetype",
"unspecified"));
eveningTelephone.setTel_number(tblVol.getTelevening());
}
if (tblVol.getFax() != null && !tblVol.getFax().equals("")) {
faxContactInfo = new VolunteerContactInfo();
faxTelephone = new VolunteerContactTelephones();
faxContactInfo.setId(UUID.randomUUID());
faxContactInfo.setIsActive(true);
faxContactInfo.setIsDefault(false);
faxContactInfo.setNotes("");
faxTelephone.setVolunteerId(volunteers.getId());
faxTelephone.setVolunteerContactInfoId(faxContactInfo.getId());
faxTelephone.setTelephoneTypeId(MigrationUtil.getLookupId(lookupsMap, "telephonetype", "fax"));
faxTelephone.setTel_number(tblVol.getFax());
}
if (tblVol.getMobile() != null && !tblVol.getMobile().equals("")) {
mobileContactInfo = new VolunteerContactInfo();
mobileTelephone = new VolunteerContactTelephones();
mobileContactInfo.setId(UUID.randomUUID());
mobileContactInfo.setIsActive(true);
mobileContactInfo.setIsDefault(false);
mobileContactInfo.setNotes("");
mobileTelephone.setVolunteerId(volunteers.getId());
mobileTelephone.setVolunteerContactInfoId(mobileContactInfo.getId());
mobileTelephone.setTelephoneTypeId(MigrationUtil.getLookupId(lookupsMap, "telephonetype", "mobile"));
mobileTelephone.setTel_number(tblVol.getMobile());
}
if (tblVol.getEmail() != null && !tblVol.getEmail().equals("")) {
emailContactInfo = new VolunteerContactInfo();
email = new VolunteerContactEmails();
emailContactInfo.setId(UUID.randomUUID());
emailContactInfo.setIsActive(true);
emailContactInfo.setIsDefault(true);
emailContactInfo.setNotes("");
email.setVolunteerId(volunteers.getId());
email.setVolunteerContactInfoId(emailContactInfo.getId());
email.setTelephoneTypeId(MigrationUtil.getLookupId(lookupsMap, "emailtype", "unspecified"));
email.setEmail(tblVol.getEmail());
}
if (tblVol.getGeographicalarea() != null && !tblVol.getGeographicalarea().equals("")) {
volunteerGeoAreas = new VolunteerGeoAreaLookups();
volunteerGeoAreas.setVolunteerId(volunteers.getId());
volunteerGeoAreas.setLookupId(MigrationUtil.getLookupId(lookupsMap, "geographicalarea",
tblVol.getGeographicalarea().toLowerCase()));
}
if (tblVolTypeOfActivities.get(tblVol.getVid()) != null) {
volunteerTypeOfActivities = new ArrayList<VolunteerTypeOfActivityLookups>();
VolunteerTypeOfActivityLookups volunteerTypeOfActivity = null;
for (TblVolTypeOfActivity activity : tblVolTypeOfActivities.get(tblVol.getVid())) {
volunteerTypeOfActivity = new VolunteerTypeOfActivityLookups();
volunteerTypeOfActivity.setVolunteerId(volunteers.getId());
volunteerTypeOfActivity.setLookupId(MigrationUtil.getLookupId(lookupsMap, "typeofactivity",
activity.getTypeofactivity().toLowerCase()));
if(volunteerTypeOfActivity.getLookupId() != null) {
volunteerTypeOfActivities.add(volunteerTypeOfActivity);
} else {
System.out.println("Volunteer type of activity " + activity.getTypeofactivity()
+ " has no matching type of activity lookup.");
}
}
}
if (tblVolAreasOfInterests.get(tblVol.getVid()) != null) {
volunteerCausesInts = new ArrayList<VolunteerCausesIntsLookups>();
VolunteerCausesIntsLookups volunteerCausesInt = null;
for (TblVolAreasOfInterest areasOfInterest : tblVolAreasOfInterests.get(tblVol.getVid())) {
volunteerCausesInt = new VolunteerCausesIntsLookups();
volunteerCausesInt.setVolunteerId(volunteers.getId());
volunteerCausesInt.setLookupId(MigrationUtil.getLookupId(lookupsMap, "causeinterest",
areasOfInterest.getAreasofinterest().toLowerCase()));
if(volunteerCausesInt.getLookupId() != null) {
volunteerCausesInts.add(volunteerCausesInt);
} else {
System.out.println("Volunteer area of interest " + areasOfInterest.getAreasofinterest()
+ " has no matching cause of interest lookup.");
}
}
}
if (tblVolSpecials.get(tblVol.getVid()) != null) {
volunteerTags = new ArrayList<VolunteerTagsLookups>();
VolunteerTagsLookups volunteerTag = null;
for (TblVolSpecial special : tblVolSpecials.get(tblVol.getVid())) {
volunteerTag = new VolunteerTagsLookups();
volunteerTag.setVolunteerId(volunteers.getId());
volunteerTag.setLookupId(MigrationUtil.getLookupId(lookupsMap, "taggeddata",
special.getSpecial().toLowerCase()));
if(volunteerTag.getLookupId() != null) {
volunteerTags.add(volunteerTag);
} else {
System.out.println("Volunteer special " + special.getSpecial()
+ " has no matching target lookup.");
}
}
}
volunteersWriter.write(volunteers.getRecord() + "\n");
if (volunteerAddresses != null) volunteerAddressesWriter.write(volunteerAddresses.getRecord() + "\n");
if (dayTimeContactInfo != null) volunteerContactInfoWriter.write(dayTimeContactInfo.getRecord() + "\n");
if (eveningContactInfo != null) volunteerContactInfoWriter.write(eveningContactInfo.getRecord() + "\n");
if (faxContactInfo != null) volunteerContactInfoWriter.write(faxContactInfo.getRecord() + "\n");
if (mobileContactInfo != null) volunteerContactInfoWriter.write(mobileContactInfo.getRecord() + "\n");
if (emailContactInfo != null) volunteerContactInfoWriter.write(emailContactInfo.getRecord() + "\n");
if (dayTimeTelephone != null)
volunteerContactTelephonesWriter.write(dayTimeTelephone.getRecord() + "\n");
if (eveningTelephone != null)
volunteerContactTelephonesWriter.write(eveningTelephone.getRecord() + "\n");
if (faxTelephone != null) volunteerContactTelephonesWriter.write(faxTelephone.getRecord() + "\n");
if (mobileTelephone != null) volunteerContactTelephonesWriter.write(mobileTelephone.getRecord() + "\n");
if (email != null) volunteerContactEmailsWriter.write(email.getRecord() + "\n");
if (volunteerGeoAreas != null)
volunteerGeoAreaLookupsWriter.write(volunteerGeoAreas.getRecord() + "\n");
if (volunteerTypeOfActivities != null) {
for (VolunteerTypeOfActivityLookups activity : volunteerTypeOfActivities) {
volunteerTypeOfActivityLookupsWriter.write(activity.getRecord() + "\n");
}
}
if (volunteerCausesInts != null) {
for (VolunteerCausesIntsLookups causesInt : volunteerCausesInts) {
volunteerCausesIntsLookupsWriter.write(causesInt.getRecord() + "\n");
}
}
if (volunteerTags != null) {
for (VolunteerTagsLookups tag : volunteerTags) {
volunteerTagsLookupsWriter.write(tag.getRecord() + "\n");
}
}
if (addresses != null) addressesWriter.write(addresses.getRecord() + "\n");
}
} catch (IOException e) {
System.out.println("Error while migrating volunteers. Error:" + e.getMessage());
} finally {
try {
if (csvFileReader != null) {
csvFileReader.close();
}
if (volunteersWriter != null) {
volunteersWriter.flush();
volunteersWriter.close();
}
if (volunteerAddressesWriter != null) {
volunteerAddressesWriter.flush();
volunteerAddressesWriter.close();
}
if (volunteerContactInfoWriter != null) {
volunteerContactInfoWriter.flush();
volunteerContactInfoWriter.close();
}
if (volunteerContactTelephonesWriter != null) {
volunteerContactTelephonesWriter.flush();
volunteerContactTelephonesWriter.close();
}
if (volunteerContactEmailsWriter != null) {
volunteerContactEmailsWriter.flush();
volunteerContactEmailsWriter.close();
}
if (volunteerGeoAreaLookupsWriter != null) {
volunteerGeoAreaLookupsWriter.flush();
volunteerGeoAreaLookupsWriter.close();
}
if (volunteerTypeOfActivityLookupsWriter != null) {
volunteerTypeOfActivityLookupsWriter.flush();
volunteerTypeOfActivityLookupsWriter.close();
}
if (volunteerCausesIntsLookupsWriter != null) {
volunteerCausesIntsLookupsWriter.flush();
volunteerCausesIntsLookupsWriter.close();
}
if (volunteerTagsLookupsWriter != null) {
volunteerTagsLookupsWriter.flush();
volunteerTagsLookupsWriter.close();
}
if (addressesWriter != null) {
addressesWriter.flush();
addressesWriter.close();
}
} catch (IOException e) {
System.out.println("Error closing volunteers streams. Error:" + e.getMessage());
}
}
}
|
public boolean launchChunky(Component parentComponent, LauncherSettings settings, VersionInfo version) {
List<String> command = buildCommandLine(version, settings);
if (System.getProperty("log4j.logLevel", "WARN").equals("INFO")) {
System.out.println(commandString(command));
}
ProcessBuilder procBuilder = new ProcessBuilder(command);
try {
final Process proc = procBuilder.start();
final Logger logger;
if (!settings.headless && settings.debugConsole) {
DebugConsole console = new DebugConsole(null, settings.closeConsoleOnExit);
console.setVisible(true);
logger = console;
} else {
logger = new ConsoleLogger();
}
final Scanner stdout = new Scanner(proc.getInputStream());
final Scanner stderr = new Scanner(proc.getErrorStream());
final Thread outputScanner = new Thread("Output Logger") {
@Override
public void run() {
while (!isInterrupted() && stdout.hasNextLine()) {
String line = stdout.nextLine();
logger.appendLine(line);
}
}
};
outputScanner.start();
final Thread errorScanner = new Thread("Error Logger") {
@Override
public void run() {
while (!isInterrupted() && stderr.hasNextLine()) {
String line = stderr.nextLine();
logger.appendErrorLine(line);
}
}
};
errorScanner.start();
ShutdownThread shutdownThread = new ShutdownThread(proc, logger, outputScanner, errorScanner);
shutdownThread.start();
try {
Thread.sleep(200);
int exitValue = shutdownThread.exitValue;
if (exitValue != 0) {
return false;
}
} catch (InterruptedException e) {
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
|
public boolean launchChunky(Component parentComponent, LauncherSettings settings, VersionInfo version) {
List<String> command = buildCommandLine(version, settings);
if (System.getProperty("log4j.logLevel", "WARN").equals("INFO")) {
System.out.println(commandString(command));
}
ProcessBuilder procBuilder = new ProcessBuilder(command);
final Logger logger;
if (!settings.headless && settings.debugConsole) {
DebugConsole console = new DebugConsole(null, settings.closeConsoleOnExit);
console.setVisible(true);
logger = console;
} else {
logger = new ConsoleLogger();
}
try {
final Process proc = procBuilder.start();
final Scanner stdout = new Scanner(proc.getInputStream());
final Scanner stderr = new Scanner(proc.getErrorStream());
final Thread outputScanner = new Thread("Output Logger") {
@Override
public void run() {
while (!isInterrupted() && stdout.hasNextLine()) {
String line = stdout.nextLine();
logger.appendLine(line);
}
}
};
outputScanner.start();
final Thread errorScanner = new Thread("Error Logger") {
@Override
public void run() {
while (!isInterrupted() && stderr.hasNextLine()) {
String line = stderr.nextLine();
logger.appendErrorLine(line);
}
}
};
errorScanner.start();
ShutdownThread shutdownThread = new ShutdownThread(proc, logger, outputScanner, errorScanner);
shutdownThread.start();
try {
Thread.sleep(200);
int exitValue = shutdownThread.exitValue;
if (exitValue != 0) {
return false;
}
} catch (InterruptedException e) {
}
return true;
} catch (IOException e) {
logger.appendErrorLine(e.getMessage());
return false;
}
}
|
public boolean notify(final IEclipseContext notifyContext, final String name,
final int eventType, final Object[] args) {
if (eventType == IRunAndTrack.DISPOSE) {
for (Iterator it = userObjects.iterator(); it.hasNext();) {
WeakReference ref = (WeakReference) it.next();
Object referent = ref.get();
if (referent != null)
findAndCallDispose(referent, referent.getClass(), new ProcessMethodsResult());
}
}
boolean isSetter = (eventType == IRunAndTrack.ADDED || eventType == IRunAndTrack.INITIAL);
Processor processor = new Processor(isSetter) {
void processField(final Field field, String injectName, boolean optional) {
switch (eventType) {
case IRunAndTrack.INITIAL:
String key = findKey(injectName, field.getType());
if (key != null) {
setField(args[0], field, notifyContext.get(key));
} else {
if (!optional) {
throw new IllegalStateException("Could not set " + field
+ " because of missing: " + injectName);
}
}
break;
case IRunAndTrack.ADDED:
String injectKey = findKey(name, field.getType());
if (injectKey != null)
setField(userObject, field, notifyContext.get(injectKey));
break;
case IRunAndTrack.REMOVED:
if (keyMatches(name, injectName) || field.getType().getName().equals(name))
setField(userObject, field, null);
break;
case IRunAndTrack.DISPOSE:
break;
default:
logWarning(userObject, new IllegalArgumentException("Unknown event type: "
+ eventType));
}
}
void processMethod(final Method method, boolean optional) {
String candidateName = method.getName();
if (candidateName.length() <= setMethodPrefix.length())
return;
candidateName = candidateName.substring(setMethodPrefix.length());
Class[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 1)
return;
switch (eventType) {
case IRunAndTrack.INITIAL:
String key = findKey(candidateName, parameterTypes[0]);
if (key != null) {
setMethod(userObject, method, notifyContext.get(key, parameterTypes));
} else {
if (!optional) {
throw new IllegalStateException("Could not invoke " + method
+ " because of missing: " + candidateName);
}
}
break;
case IRunAndTrack.ADDED:
if (keyMatches(name, candidateName)) {
key = findKey(name, parameterTypes[0]);
setMethod(userObject, method, notifyContext.get(key, parameterTypes));
}
break;
case IRunAndTrack.REMOVED:
if (keyMatches(name, candidateName))
setMethod(userObject, method, null);
break;
case IRunAndTrack.DISPOSE:
break;
default:
logWarning(userObject, new IllegalArgumentException("Unknown event type: "
+ eventType));
}
}
void processPostConstructMethod(Method m) {
if (eventType == IRunAndTrack.INITIAL) {
Object[] methodArgs = null;
if (m.getParameterTypes().length == 1)
methodArgs = new Object[] { context };
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
m.invoke(userObject, methodArgs);
} finally {
m.setAccessible(false);
}
} else {
m.invoke(userObject, methodArgs);
}
} catch (Exception e) {
logWarning(userObject, e);
}
}
}
public void processOutMethod(Method m, final String name) {
final IEclipseContext outputContext = (IEclipseContext) notifyContext
.get("outputs");
if (outputContext == null) {
throw new IllegalStateException("No output context available for @Out " + m
+ " in " + userObject);
}
if (eventType == IRunAndTrack.INITIAL) {
Object value;
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
value = m.invoke(userObject, new Object[0]);
} finally {
m.setAccessible(false);
}
} else {
value = m.invoke(userObject, new Object[0]);
}
outputContext.set(name, value);
userObject.getClass().getMethod("addPropertyChangeListener",
new Class[] { String.class, PropertyChangeListener.class }).invoke(
userObject,
new Object[] {
name,
new PropertyChangeListenerImplementation(name,
outputContext) });
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
};
if (eventType == IRunAndTrack.INITIAL) {
if (args == null || args.length == 0 || args[0] == null)
throw new IllegalArgumentException();
Object userObject = args[0];
processor.setObject(userObject);
processClassHierarchy(userObject.getClass(), processor);
WeakReference ref = new WeakReference(userObject);
synchronized (userObjects) {
userObjects.add(ref);
}
} else {
Object[] objectsCopy = safeObjectsCopy();
for (int i = 0; i < objectsCopy.length; i++) {
Object userObject = objectsCopy[i];
processor.setObject(userObject);
processClassHierarchy(userObject.getClass(), processor);
}
}
return (!userObjects.isEmpty());
}
|
public boolean notify(final IEclipseContext notifyContext, final String name,
final int eventType, final Object[] args) {
if (eventType == IRunAndTrack.DISPOSE) {
for (Iterator it = userObjects.iterator(); it.hasNext();) {
WeakReference ref = (WeakReference) it.next();
Object referent = ref.get();
if (referent != null)
findAndCallDispose(referent, referent.getClass(), new ProcessMethodsResult());
}
}
boolean isSetter = (eventType == IRunAndTrack.ADDED || eventType == IRunAndTrack.INITIAL);
Processor processor = new Processor(isSetter) {
void processField(final Field field, String injectName, boolean optional) {
switch (eventType) {
case IRunAndTrack.INITIAL:
String key = findKey(injectName, field.getType());
if (key != null) {
setField(args[0], field, notifyContext.get(key));
} else {
if (!optional) {
throw new IllegalStateException("Could not set " + field
+ " because of missing: " + injectName);
}
}
break;
case IRunAndTrack.ADDED:
String injectKey = findKey(name, field.getType());
if (injectKey != null
&& (keyMatches(name, injectName) || field.getType().getName().equals(
name)))
setField(userObject, field, notifyContext.get(injectKey));
break;
case IRunAndTrack.REMOVED:
if (keyMatches(name, injectName) || field.getType().getName().equals(name))
setField(userObject, field, null);
break;
case IRunAndTrack.DISPOSE:
break;
default:
logWarning(userObject, new IllegalArgumentException("Unknown event type: "
+ eventType));
}
}
void processMethod(final Method method, boolean optional) {
String candidateName = method.getName();
if (candidateName.length() <= setMethodPrefix.length())
return;
candidateName = candidateName.substring(setMethodPrefix.length());
Class[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 1)
return;
switch (eventType) {
case IRunAndTrack.INITIAL:
String key = findKey(candidateName, parameterTypes[0]);
if (key != null) {
setMethod(userObject, method, notifyContext.get(key, parameterTypes));
} else {
if (!optional) {
throw new IllegalStateException("Could not invoke " + method
+ " because of missing: " + candidateName);
}
}
break;
case IRunAndTrack.ADDED:
if (keyMatches(name, candidateName)) {
key = findKey(name, parameterTypes[0]);
setMethod(userObject, method, notifyContext.get(key, parameterTypes));
}
break;
case IRunAndTrack.REMOVED:
if (keyMatches(name, candidateName))
setMethod(userObject, method, null);
break;
case IRunAndTrack.DISPOSE:
break;
default:
logWarning(userObject, new IllegalArgumentException("Unknown event type: "
+ eventType));
}
}
void processPostConstructMethod(Method m) {
if (eventType == IRunAndTrack.INITIAL) {
Object[] methodArgs = null;
if (m.getParameterTypes().length == 1)
methodArgs = new Object[] { context };
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
m.invoke(userObject, methodArgs);
} finally {
m.setAccessible(false);
}
} else {
m.invoke(userObject, methodArgs);
}
} catch (Exception e) {
logWarning(userObject, e);
}
}
}
public void processOutMethod(Method m, final String name) {
final IEclipseContext outputContext = (IEclipseContext) notifyContext
.get("outputs");
if (outputContext == null) {
throw new IllegalStateException("No output context available for @Out " + m
+ " in " + userObject);
}
if (eventType == IRunAndTrack.INITIAL) {
Object value;
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
value = m.invoke(userObject, new Object[0]);
} finally {
m.setAccessible(false);
}
} else {
value = m.invoke(userObject, new Object[0]);
}
outputContext.set(name, value);
userObject.getClass().getMethod("addPropertyChangeListener",
new Class[] { String.class, PropertyChangeListener.class }).invoke(
userObject,
new Object[] {
name,
new PropertyChangeListenerImplementation(name,
outputContext) });
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
};
if (eventType == IRunAndTrack.INITIAL) {
if (args == null || args.length == 0 || args[0] == null)
throw new IllegalArgumentException();
Object userObject = args[0];
processor.setObject(userObject);
processClassHierarchy(userObject.getClass(), processor);
WeakReference ref = new WeakReference(userObject);
synchronized (userObjects) {
userObjects.add(ref);
}
} else {
Object[] objectsCopy = safeObjectsCopy();
for (int i = 0; i < objectsCopy.length; i++) {
Object userObject = objectsCopy[i];
processor.setObject(userObject);
processClassHierarchy(userObject.getClass(), processor);
}
}
return (!userObjects.isEmpty());
}
|
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
switch (type) {
case TYPE_ROW:
v = vi.inflate(R.layout.task_row, null);
break;
case TYPE_ROW_CLICKED:
v = vi.inflate(R.layout.task_row_clicked, null);
}
holder = new ViewHolder();
holder.taskDescription = (TextView) v
.findViewById(R.id.tvRowTaskDescription);
holder.taskProject = (TextView) v
.findViewById(R.id.tvRowTaskProject);
holder.taskDueDate = (TextView) v
.findViewById(R.id.tvRowTaskDueDate);
holder.taskRelLayout = (RelativeLayout) v
.findViewById(R.id.taskRelLayout);
holder.taskPriorityView = (View) v
.findViewById(R.id.horizontal_line_priority);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Task task = entries.get(position);
if (task != null) {
holder.taskDescription.setText(task.getDescription());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String textAppearance = prefs.getString("pref_appearance_descriptionTextSize", context.getResources().getString(R.string.pref_appearance_descriptionTextSize_small));
if (textAppearance.equals(context.getResources().getString(R.string.pref_appearance_descriptionTextSize_small))) {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_small));
} else if (textAppearance.equals(context.getResources().getString(R.string.pref_appearance_descriptionTextSize_medium))) {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_medium));
} else {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_large));
}
holder.taskProject.setText(task.getProject());
if (task.getDue() != null && !(task.getDue().getTime() == 0)) {
if (!DateFormat.getTimeInstance().format(task.getDue())
.equals("00:00:00")) {
holder.taskDueDate.setText(DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(
task.getDue()));
} else {
holder.taskDueDate.setText(DateFormat.getDateInstance()
.format(task.getDue()));
}
} else {
holder.taskDueDate.setText(null);
}
if (!TextUtils.isEmpty(task.getPriority())) {
if (task.getPriority().equals("H")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_red));
} else if (task.getPriority().equals("M")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_yellow));
} else if (task.getPriority().equals("L")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_green));
}
} else {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(android.R.color.transparent));
}
if (task.getStatus().equals("completed")
|| task.getStatus().equals("deleted")) {
if (getItemViewType(position) == TYPE_ROW_CLICKED) {
LinearLayout llButtonLayout = (LinearLayout) v
.findViewById(R.id.taskLinLayout);
llButtonLayout.setVisibility(View.GONE);
View horizBar = v.findViewById(R.id.horizontal_line);
horizBar.setVisibility(View.GONE);
}
}
}
return v;
}
|
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
switch (type) {
case TYPE_ROW:
v = vi.inflate(R.layout.task_row, null);
break;
case TYPE_ROW_CLICKED:
v = vi.inflate(R.layout.task_row_clicked, null);
}
holder = new ViewHolder();
holder.taskDescription = (TextView) v
.findViewById(R.id.tvRowTaskDescription);
holder.taskProject = (TextView) v
.findViewById(R.id.tvRowTaskProject);
holder.taskDueDate = (TextView) v
.findViewById(R.id.tvRowTaskDueDate);
holder.taskRelLayout = (RelativeLayout) v
.findViewById(R.id.taskRelLayout);
holder.taskPriorityView = (View) v
.findViewById(R.id.horizontal_line_priority);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Task task = entries.get(position);
if (task != null) {
holder.taskDescription.setText(task.getDescription());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String textAppearance = prefs.getString("pref_appearance_descriptionTextSize", context.getResources().getString(R.string.pref_appearance_descriptionTextSize_small));
if (textAppearance.equals(context.getResources().getString(R.string.pref_appearance_descriptionTextSize_small))) {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_small));
} else if (textAppearance.equals(context.getResources().getString(R.string.pref_appearance_descriptionTextSize_medium))) {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_medium));
} else {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_large));
}
if(task.getProject() != null) {
holder.taskProject.setText(task.getProject());
} else {
holder.taskProject.setVisibility(View.GONE);
}
if (task.getDue() != null && !(task.getDue().getTime() == 0)) {
if (!DateFormat.getTimeInstance().format(task.getDue())
.equals("00:00:00")) {
holder.taskDueDate.setText(DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(
task.getDue()));
} else {
holder.taskDueDate.setText(DateFormat.getDateInstance()
.format(task.getDue()));
}
} else {
holder.taskDueDate.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(task.getPriority())) {
if (task.getPriority().equals("H")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_red));
} else if (task.getPriority().equals("M")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_yellow));
} else if (task.getPriority().equals("L")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_green));
}
} else {
holder.taskPriorityView.setVisibility(View.GONE);
}
if (task.getStatus().equals("completed")
|| task.getStatus().equals("deleted")) {
if (getItemViewType(position) == TYPE_ROW_CLICKED) {
LinearLayout llButtonLayout = (LinearLayout) v
.findViewById(R.id.taskLinLayout);
llButtonLayout.setVisibility(View.GONE);
View horizBar = v.findViewById(R.id.horizontal_line);
horizBar.setVisibility(View.GONE);
}
}
}
return v;
}
|
public static void main(String[] args)
{
if (args.length < 4)
{
System.err.printf("*** Usage: %s string n k kTolerance", Fragmentizer.class.getCanonicalName());
System.exit(1);
}
String string = args[0];
int n = Integer.parseInt(args[1]);
int k = Integer.parseInt(args[2]);
int kTolerance = Integer.parseInt(args[3]);
FragmentPositionSource source = FragmentPositionSource.ORIGINAL_SEQUENCE;
List<Fragment> fragments = Fragmentizer.fragmentizeForShotgun(string, n, k, kTolerance);
for (Fragment fragment : fragments)
{
System.out.printf("%5d: %s%n", fragment.getPosition(source), fragment.string);
}
System.out.println();
System.out.println(string);
List<List<Fragment>> grouped = Fragmentizer.groupByLine(fragments, source);
for (List<Fragment> list : grouped)
{
int begin = 0;
for (Fragment fragment : list)
{
for (int i = 0; i < fragment.getPosition(source) - begin; i++)
{
System.out.print(" ");
}
System.out.print(fragment.string);
begin = fragment.getPosition(source) + fragment.string.length();
}
System.out.println();
}
FragmentDisplay display = new FragmentDisplay(getFragmentGroupImage(string, grouped,
FragmentPositionSource.ORIGINAL_SEQUENCE));
}
|
public static void main(String[] args)
{
if (args.length < 4)
{
System.err.printf("*** Usage: %s string n k kTolerance", FragmentDisplay.class.getCanonicalName());
System.exit(1);
}
String string = args[0];
int n = Integer.parseInt(args[1]);
int k = Integer.parseInt(args[2]);
int kTolerance = Integer.parseInt(args[3]);
FragmentPositionSource source = FragmentPositionSource.ORIGINAL_SEQUENCE;
List<Fragment> fragments = Fragmentizer.fragmentizeForShotgun(string, n, k, kTolerance);
for (Fragment fragment : fragments)
{
System.out.printf("%5d: %s%n", fragment.getPosition(source), fragment.string);
}
System.out.println();
System.out.println(string);
List<List<Fragment>> grouped = Fragmentizer.groupByLine(fragments, source);
for (List<Fragment> list : grouped)
{
int begin = 0;
for (Fragment fragment : list)
{
for (int i = 0; i < fragment.getPosition(source) - begin; i++)
{
System.out.print(" ");
}
System.out.print(fragment.string);
begin = fragment.getPosition(source) + fragment.string.length();
}
System.out.println();
}
FragmentDisplay display = new FragmentDisplay(getFragmentGroupImage(string, grouped,
FragmentPositionSource.ORIGINAL_SEQUENCE));
}
|
private void processInput()
{
if(player.getState() == Player.State.IDLE)
{
if(keys.get(Keys.LEFT))
{
player.setFacingDirection(Player.FacingDirection.LEFT);
if(canMoveTo(-1,0))
{
movePlayer(-1,0);
}
}
else if(keys.get(Keys.RIGHT))
{
player.setFacingDirection(Player.FacingDirection.RIGHT);
if(canMoveTo(1,0))
{
movePlayer(1,0);
}
}
else if(keys.get(Keys.UP))
{
player.setFacingDirection(Player.FacingDirection.UP);
if(canMoveTo(0,1))
{
movePlayer(0,1);
}
}
else if(keys.get(Keys.DOWN))
{
player.setFacingDirection(Player.FacingDirection.DOWN);
if(canMoveTo(0,-1))
{
movePlayer(0,-1);
}
}
}
if(player.getState() != State.IDLE)
{
if ((player.getPosition().x - startXpos) > 1)
{
stopPlayer(1,0);
rightReleased();
doBlockLogic();
}
else if ((player.getPosition().y - startYpos) > 1)
{
stopPlayer(0,1);
upReleased();
doBlockLogic();
}
else if (Math.abs((player.getPosition().x - startXpos)) > 1)
{
stopPlayer(-1,0);
leftReleased();
doBlockLogic();
}
else if (Math.abs((player.getPosition().y - startYpos)) > 1)
{
stopPlayer(0,-1);
downReleased();
doBlockLogic();
}
}
if(actionBlock != null)
{
if ((actionBlock.getPosition().x - actionBlockStartXpos) > 1)
{
if(pushBlockToLiquid(1,0)==false){
actionBlock.getVelocity().x = 0;
switchCollisionBlocks((int) actionBlockStartXpos,(int) actionBlockStartYpos,(int) (actionBlockStartXpos + 1),(int) actionBlockStartYpos);
actionBlock.getPosition().set(actionBlockStartXpos + 1, actionBlockStartYpos);
}
actionBlock = null;
}
else if ((actionBlock.getPosition().y - actionBlockStartYpos) > 1)
{
if(pushBlockToLiquid(0,1)==false){
actionBlock.getVelocity().y = 0;
switchCollisionBlocks((int) actionBlockStartXpos,(int) actionBlockStartYpos,(int) (actionBlockStartXpos ),(int) actionBlockStartYpos + 1);
actionBlock.getPosition().set(actionBlockStartXpos , actionBlockStartYpos + 1);
}
actionBlock = null;
}
else if (Math.abs((actionBlock.getPosition().y - actionBlockStartYpos)) > 1)
{
if(pushBlockToLiquid(0,-1)==false){
actionBlock.getVelocity().y = 0;
switchCollisionBlocks((int) actionBlockStartXpos,(int) actionBlockStartYpos,(int) (actionBlockStartXpos ),(int) actionBlockStartYpos - 1);
actionBlock.getPosition().set(actionBlockStartXpos , actionBlockStartYpos - 1);
}
actionBlock = null;
}
else if (Math.abs((actionBlock.getPosition().x - actionBlockStartXpos)) > 1)
{
if(pushBlockToLiquid(-1,0)==false){
actionBlock.getVelocity().x = 0;
switchCollisionBlocks((int) actionBlockStartXpos,(int) actionBlockStartYpos,(int) (actionBlockStartXpos - 1),(int) actionBlockStartYpos);
actionBlock.getPosition().set(actionBlockStartXpos - 1 , actionBlockStartYpos);
}
actionBlock = null;
}
}
}
|
private void processInput()
{
if(player.getState() == Player.State.IDLE)
{
if(keys.get(Keys.LEFT))
{
player.setFacingDirection(Player.FacingDirection.LEFT);
if(canMoveTo(-1,0))
{
movePlayer(-1,0);
}
}
else if(keys.get(Keys.RIGHT))
{
player.setFacingDirection(Player.FacingDirection.RIGHT);
if(canMoveTo(1,0))
{
movePlayer(1,0);
}
}
else if(keys.get(Keys.UP))
{
player.setFacingDirection(Player.FacingDirection.UP);
if(canMoveTo(0,1))
{
movePlayer(0,1);
}
}
else if(keys.get(Keys.DOWN))
{
player.setFacingDirection(Player.FacingDirection.DOWN);
if(canMoveTo(0,-1))
{
movePlayer(0,-1);
}
}
}
if(player.getState() != State.IDLE)
{
if ((player.getPosition().x - startXpos) > 1)
{
stopPlayer(1,0);
doBlockLogic();
}
else if ((player.getPosition().y - startYpos) > 1)
{
stopPlayer(0,1);
doBlockLogic();
}
else if (Math.abs((player.getPosition().x - startXpos)) > 1)
{
stopPlayer(-1,0);
doBlockLogic();
}
else if (Math.abs((player.getPosition().y - startYpos)) > 1)
{
stopPlayer(0,-1);
doBlockLogic();
}
}
if(actionBlock != null)
{
if ((actionBlock.getPosition().x - actionBlockStartXpos) > 1)
{
if(pushBlockToLiquid(1,0)==false){
actionBlock.getVelocity().x = 0;
switchCollisionBlocks((int) actionBlockStartXpos,(int) actionBlockStartYpos,(int) (actionBlockStartXpos + 1),(int) actionBlockStartYpos);
actionBlock.getPosition().set(actionBlockStartXpos + 1, actionBlockStartYpos);
}
actionBlock = null;
}
else if ((actionBlock.getPosition().y - actionBlockStartYpos) > 1)
{
if(pushBlockToLiquid(0,1)==false){
actionBlock.getVelocity().y = 0;
switchCollisionBlocks((int) actionBlockStartXpos,(int) actionBlockStartYpos,(int) (actionBlockStartXpos ),(int) actionBlockStartYpos + 1);
actionBlock.getPosition().set(actionBlockStartXpos , actionBlockStartYpos + 1);
}
actionBlock = null;
}
else if (Math.abs((actionBlock.getPosition().y - actionBlockStartYpos)) > 1)
{
if(pushBlockToLiquid(0,-1)==false){
actionBlock.getVelocity().y = 0;
switchCollisionBlocks((int) actionBlockStartXpos,(int) actionBlockStartYpos,(int) (actionBlockStartXpos ),(int) actionBlockStartYpos - 1);
actionBlock.getPosition().set(actionBlockStartXpos , actionBlockStartYpos - 1);
}
actionBlock = null;
}
else if (Math.abs((actionBlock.getPosition().x - actionBlockStartXpos)) > 1)
{
if(pushBlockToLiquid(-1,0)==false){
actionBlock.getVelocity().x = 0;
switchCollisionBlocks((int) actionBlockStartXpos,(int) actionBlockStartYpos,(int) (actionBlockStartXpos - 1),(int) actionBlockStartYpos);
actionBlock.getPosition().set(actionBlockStartXpos - 1 , actionBlockStartYpos);
}
actionBlock = null;
}
}
}
|
private void sendSubscriptions( Event event )
{
String from = Manager.getStorageInstance().getGlobalConfiguration().getSmtpHost();
if ( StringUtil.isEmpty( from ) )
{
from = "[email protected]";
}
Session session = HibernateUtil.getCurrentSession();
for ( User user : Manager.getSecurityInstance().getUsers() )
{
user = (User) session.load( StoredUser.class, user.getUsername() );
if ( !user.isDisabled() )
{
continue;
}
if ( ( event.getUsername() == null || !event.getUsername().equals( user.getUsername() ) ) &&
event.shouldNotify( user ) && !user.isDisabled() )
{
if ( !StringUtil.isEmpty( user.getEmail() ) )
{
getLoggerForComponent( getClass().getName() ).info( "Emailing event to user " + user.getUsername() + " at " + user.getEmail() );
try
{
( (EmailNotifier) getNotifierList().get( "email" ).newInstance() ).sendEventEmail( event, user.getEmail(), from, EmailNotifier.FooterType.Subscription );
}
catch ( Exception e )
{
getLoggerForComponent( getClass().getName() ).error( "Problem found sending email subscriptions", e );
}
}
else
{
getLoggerForComponent( getClass().getName() ).warn( "No email for user " + user.getUsername() );
}
}
}
}
|
private void sendSubscriptions( Event event )
{
String from = Manager.getStorageInstance().getGlobalConfiguration().getSmtpHost();
if ( StringUtil.isEmpty( from ) )
{
from = "[email protected]";
}
Session session = HibernateUtil.getCurrentSession();
for ( User user : Manager.getSecurityInstance().getUsers() )
{
user = (User) session.load( StoredUser.class, user.getUsername() );
if ( user.isDisabled() )
{
continue;
}
if ( ( event.getUsername() == null || !event.getUsername().equals( user.getUsername() ) ) &&
event.shouldNotify( user ) )
{
if ( !StringUtil.isEmpty( user.getEmail() ) )
{
getLoggerForComponent( getClass().getName() ).info( "Emailing event to user " + user.getUsername() + " at " + user.getEmail() );
try
{
( (EmailNotifier) getNotifierList().get( "email" ).newInstance() ).sendEventEmail( event, user.getEmail(), from, EmailNotifier.FooterType.Subscription );
}
catch ( Exception e )
{
getLoggerForComponent( getClass().getName() ).error( "Problem found sending email subscriptions", e );
}
}
else
{
getLoggerForComponent( getClass().getName() ).warn( "No email for user " + user.getUsername() );
}
}
}
}
|
public String toString(){
String currencyChar = "";
switch (getCurrency()) {
case EUR: currencyChar+= " �"; break;
case PLN: currencyChar+= " zl";
}
String s = DECIMAL_FORMAT.format(value) + currencyChar;
return s;
}
|
public String toString(){
String currencyChar = "";
switch (getCurrency()) {
case EUR: currencyChar+= " \u20ac"; break;
case PLN: currencyChar+= " zl";
}
String s = DECIMAL_FORMAT.format(value) + currencyChar;
return s;
}
|
public Object createElement(final Object parent, final String tag, final XMLElement attributes) {
if (attributes == null) {
return null;
}
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
if (typeAttribute == null || NodeTextBuilder.XML_NODE_XHTML_TYPE_NODE.equals(typeAttribute)) {
return null;
}
return parent;
}
|
public Object createElement(final Object parent, final String tag, final XMLElement attributes) {
if (attributes == null) {
return null;
}
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
if (! NodeTextBuilder.XML_NODE_XHTML_TYPE_NOTE.equals(typeAttribute)) {
return null;
}
return parent;
}
|
public static List<Activity> getRecentActivity(List<RepositoryModel> models, int daysBack,
String objectId) {
Date thresholdDate = new Date(System.currentTimeMillis() - daysBack * TimeUtils.ONEDAY);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
Map<String, Activity> activity = new HashMap<String, Activity>();
for (RepositoryModel model : models) {
if (model.hasCommits && model.lastChange.after(thresholdDate)) {
Repository repository = GitBlit.self().getRepository(model.name);
List<RevCommit> commits = JGitUtils.getRevLog(repository, objectId, thresholdDate);
Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository);
repository.close();
String branch = objectId;
if (StringUtils.isEmpty(branch)) {
List<RefModel> headRefs = allRefs.get(commits.get(0).getId());
List<String> localBranches = new ArrayList<String>();
for (RefModel ref : headRefs) {
if (ref.getName().startsWith(Constants.R_HEADS)) {
localBranches.add(ref.getName().substring(Constants.R_HEADS.length()));
}
}
if (localBranches.size() == 1) {
branch = localBranches.get(0);
} else if (localBranches.size() > 1) {
if (localBranches.contains("master")) {
branch = "master";
} else {
branch = localBranches.get(0);
}
}
}
for (RevCommit commit : commits) {
Date date = JGitUtils.getCommitDate(commit);
String dateStr = df.format(date);
if (!activity.containsKey(dateStr)) {
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
activity.put(dateStr, new Activity(cal.getTime()));
}
RepositoryCommit commitModel = activity.get(dateStr).addCommit(model.name,
branch, commit);
commitModel.setRefs(allRefs.get(commit.getId()));
}
}
}
List<Activity> recentActivity = new ArrayList<Activity>(activity.values());
for (Activity daily : recentActivity) {
Collections.sort(daily.commits);
}
return recentActivity;
}
|
public static List<Activity> getRecentActivity(List<RepositoryModel> models, int daysBack,
String objectId) {
Date thresholdDate = new Date(System.currentTimeMillis() - daysBack * TimeUtils.ONEDAY);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
Map<String, Activity> activity = new HashMap<String, Activity>();
for (RepositoryModel model : models) {
if (model.hasCommits && model.lastChange.after(thresholdDate)) {
Repository repository = GitBlit.self().getRepository(model.name);
List<RevCommit> commits = JGitUtils.getRevLog(repository, objectId, thresholdDate);
Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository);
repository.close();
String branch = objectId;
if (StringUtils.isEmpty(branch) && !commits.isEmpty()) {
List<RefModel> headRefs = allRefs.get(commits.get(0).getId());
List<String> localBranches = new ArrayList<String>();
for (RefModel ref : headRefs) {
if (ref.getName().startsWith(Constants.R_HEADS)) {
localBranches.add(ref.getName().substring(Constants.R_HEADS.length()));
}
}
if (localBranches.size() == 1) {
branch = localBranches.get(0);
} else if (localBranches.size() > 1) {
if (localBranches.contains("master")) {
branch = "master";
} else {
branch = localBranches.get(0);
}
}
}
for (RevCommit commit : commits) {
Date date = JGitUtils.getCommitDate(commit);
String dateStr = df.format(date);
if (!activity.containsKey(dateStr)) {
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
activity.put(dateStr, new Activity(cal.getTime()));
}
RepositoryCommit commitModel = activity.get(dateStr).addCommit(model.name,
branch, commit);
commitModel.setRefs(allRefs.get(commit.getId()));
}
}
}
List<Activity> recentActivity = new ArrayList<Activity>(activity.values());
for (Activity daily : recentActivity) {
Collections.sort(daily.commits);
}
return recentActivity;
}
|
private void search(Block block) {
switch (block.getType()) {
case AIR:
break;
case WALL_SIGN:
BlockState state = block.getState();
org.bukkit.block.Sign signState = (Sign) state;
if (plugin.config.isValidWallSign(signState)) {
search(Util.getSignAttached(signState));
}
break;
case WOODEN_DOOR:
case IRON_DOOR_BLOCK:
searchDoor(block, true, true);
break;
case FENCE_GATE:
searchFenceGate(block, true, true);
break;
case TRAP_DOOR:
searchTrapDoor(block, true, plugin.config.vertical_trapdoors);
break;
case DISPENSER:
searchSimpleBlock(block, plugin.config.group_dispensers, plugin.config.group_dispensers);
break;
case BREWING_STAND:
searchSimpleBlock(block, plugin.config.group_brewing_stands, plugin.config.group_brewing_stands);
break;
case ENCHANTMENT_TABLE:
searchSimpleBlock(block, plugin.config.group_enchantment_tables, plugin.config.group_enchantment_tables);
break;
case CAULDRON:
searchSimpleBlock(block, plugin.config.group_cauldrons, plugin.config.group_cauldrons);
break;
case FURNACE:
case BURNING_FURNACE:
searchFurnace(block, plugin.config.group_furnaces, plugin.config.group_furnaces);
break;
case CHEST:
searchChest(block, true, true);
break;
default:
for (BlockFace bf : plugin.config.CARDINAL_FACES) {
Block adjacent = block.getRelative(bf);
if (adjacent.getState().getData() instanceof TrapDoor) {
Block hinge = adjacent.getRelative(((TrapDoor) adjacent.getState().getData()).getAttachedFace());
if (hinge.equals(block)) {
search(adjacent);
}
}
}
Block adjacentUp = block.getRelative(BlockFace.UP);
if (adjacentUp.getState().getData() instanceof Door) {
search(adjacentUp);
}
Block adjacentDown = block.getRelative(BlockFace.DOWN);
if (adjacentDown.getState().getData() instanceof Door) {
search(adjacentDown);
}
}
}
|
private void search(Block block) {
switch (block.getType()) {
case AIR:
break;
case WALL_SIGN:
BlockState state = block.getState();
org.bukkit.block.Sign signState = (Sign) state;
if (plugin.config.isValidWallSign(signState)) {
search(Util.getSignAttached(signState));
}
break;
case WOODEN_DOOR:
case IRON_DOOR_BLOCK:
searchDoor(block, true, true);
break;
case FENCE_GATE:
searchFenceGate(block, true, true);
break;
case TRAP_DOOR:
searchTrapDoor(block, true, plugin.config.vertical_trapdoors);
break;
case DISPENSER:
searchSimpleBlock(block, plugin.config.group_dispensers, plugin.config.group_dispensers);
break;
case BREWING_STAND:
searchSimpleBlock(block, plugin.config.group_brewing_stands, plugin.config.group_brewing_stands);
break;
case ENCHANTMENT_TABLE:
searchSimpleBlock(block, plugin.config.group_enchantment_tables, plugin.config.group_enchantment_tables);
break;
case CAULDRON:
searchSimpleBlock(block, plugin.config.group_cauldrons, plugin.config.group_cauldrons);
break;
case FURNACE:
case BURNING_FURNACE:
searchFurnace(block, plugin.config.group_furnaces, plugin.config.group_furnaces);
break;
case CHEST:
searchChest(block, true, false);
break;
default:
for (BlockFace bf : plugin.config.CARDINAL_FACES) {
Block adjacent = block.getRelative(bf);
if (adjacent.getState().getData() instanceof TrapDoor) {
Block hinge = adjacent.getRelative(((TrapDoor) adjacent.getState().getData()).getAttachedFace());
if (hinge.equals(block)) {
search(adjacent);
}
}
}
Block adjacentUp = block.getRelative(BlockFace.UP);
if (adjacentUp.getState().getData() instanceof Door) {
search(adjacentUp);
}
Block adjacentDown = block.getRelative(BlockFace.DOWN);
if (adjacentDown.getState().getData() instanceof Door) {
search(adjacentDown);
}
}
}
|
public void execute() throws BuildException {
try {
prepareSourceRepos();
application.initializeRepos(null);
List ius = prepareIUs();
if (ius == null || ius.size() == 0)
throw new BuildException("Need to specify either a non-empty source metadata repository or a valid list of IUs.");
application.setSourceIUs(ius);
IStatus result = application.run(null);
if (result.matches(IStatus.ERROR))
throw new ProvisionException(result);
} catch (ProvisionException e) {
throw new BuildException("Error occurred while transforming repository.", e);
}
}
|
public void execute() throws BuildException {
try {
prepareSourceRepos();
application.initializeRepos(null);
List ius = prepareIUs();
if ((ius == null || ius.size() == 0) && (sourceRepos == null || sourceRepos.isEmpty()))
throw new BuildException("Need to specify either a non-empty source metadata repository or a valid list of IUs.");
application.setSourceIUs(ius);
IStatus result = application.run(null);
if (result.matches(IStatus.ERROR))
throw new ProvisionException(result);
} catch (ProvisionException e) {
throw new BuildException("Error occurred while transforming repository.", e);
}
}
|
public AddTestCasePage(final PageParameters params) {
super(params);
if (!params.containsKey("idReq")) {
error("Parametro idReq non trovato");
setResponsePage(ProjectPage.class);
}
RequirementMapper reqMapper = SqlConnection.getMapper(RequirementMapper.class);
Requirement req = reqMapper.get(BigInteger.valueOf(params.getInt("idReq")));
BookmarkablePageLink<String>requirementLnk=new BookmarkablePageLink<String>("requirementLnk",RequirementPage.class,params);
requirementLnk.add(new Label("requirementName", req.getName()));
add(requirementLnk);
testCase.setId_requirement(req.getId());
Form<TestCase> addForm = new Form<TestCase>("addForm");
addForm.add(new TextField<String>("nameFld", new PropertyModel<String>(testCase, "name")));
addForm.add(new TextArea<String>("descriptionFld", new PropertyModel<String>(testCase, "description")));
addForm.add(new TextArea<String>("expectedResultFld", new PropertyModel<String>(testCase, "expected_result")));
SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class);
List<TestCase> allTests=sesTestMapper.getMapper().getAll(new TestCaseSelectSort(req.getId(), "name", true));
sesTestMapper.close();
addForm.add(new ListMultipleChoice<TestCase>("dependencyFld",new Model<ArrayList<TestCase>>(dependencies),allTests));
addForm.add(new Button("addBtn"){
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
if(addTestCase()){
setResponsePage(AddTestCasePage.class, params);
}
}
});
addForm.add(new Button("addUpdBtn"){
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
if(addTestCase()){
setResponsePage(UpdateTestCasePage.class, new PageParameters("idTest="+testCase.getId()));
}
}
});
addForm.add(new Button("addAndStepBtn"){
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
if(addTestCase()){
setResponsePage(AddStepPage.class, new PageParameters("idTest="+testCase.getId()));
}
}
});
add(addForm);
}
|
public AddTestCasePage(final PageParameters params) {
super(params);
if (!params.containsKey("idReq")) {
error("Parametro idReq non trovato");
setResponsePage(ProjectPage.class);
}
RequirementMapper reqMapper = SqlConnection.getMapper(RequirementMapper.class);
Requirement req = reqMapper.get(BigInteger.valueOf(params.getInt("idReq")));
BookmarkablePageLink<String>requirementLnk=new BookmarkablePageLink<String>("requirementLnk",RequirementPage.class,params);
requirementLnk.add(new Label("requirementName", req.getName()));
add(requirementLnk);
testCase.setId_requirement(req.getId());
Form<TestCase> addForm = new Form<TestCase>("addForm");
addForm.add(new TextField<String>("nameFld", new PropertyModel<String>(testCase, "name")).setRequired(true));
addForm.add(new TextArea<String>("descriptionFld", new PropertyModel<String>(testCase, "description")));
addForm.add(new TextArea<String>("expectedResultFld", new PropertyModel<String>(testCase, "expected_result")));
SqlSessionMapper<TestCaseMapper> sesTestMapper = SqlConnection.getSessionMapper(TestCaseMapper.class);
List<TestCase> allTests=sesTestMapper.getMapper().getAll(new TestCaseSelectSort(req.getId(), "name", true));
sesTestMapper.close();
addForm.add(new ListMultipleChoice<TestCase>("dependencyFld",new Model<ArrayList<TestCase>>(dependencies),allTests));
addForm.add(new Button("addBtn"){
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
if(addTestCase()){
setResponsePage(AddTestCasePage.class, params);
}
}
});
addForm.add(new Button("addUpdBtn"){
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
if(addTestCase()){
setResponsePage(UpdateTestCasePage.class, new PageParameters("idTest="+testCase.getId()));
}
}
});
addForm.add(new Button("addAndStepBtn"){
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
if(addTestCase()){
setResponsePage(AddStepPage.class, new PageParameters("idTest="+testCase.getId()));
}
}
});
add(addForm);
}
|
static public ReconConfig reconstruct(JSONObject obj) throws Exception {
try {
String mode = obj.getString("mode");
if ("extend".equals(mode) || "strict".equals("mode")) {
mode = "freebase/" + mode;
} else if ("heuristic".equals(mode)) {
mode = "core/standard-service";
} else if (!mode.contains("/")) {
mode = "core/" + mode;
}
List<Class<? extends ReconConfig>> classes = s_opNameToClass.get(mode);
if (classes != null && classes.size() > 0) {
Class<? extends ReconConfig> klass = classes.get(classes.size() - 1);
Method reconstruct = klass.getMethod("reconstruct", JSONObject.class);
if (reconstruct != null) {
return (ReconConfig) reconstruct.invoke(null, obj);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
static public ReconConfig reconstruct(JSONObject obj) throws Exception {
try {
String mode = obj.getString("mode");
if ("extend".equals(mode) || "strict".equals(mode)) {
mode = "freebase/" + mode;
} else if ("heuristic".equals(mode)) {
mode = "core/standard-service";
} else if (!mode.contains("/")) {
mode = "core/" + mode;
}
List<Class<? extends ReconConfig>> classes = s_opNameToClass.get(mode);
if (classes != null && classes.size() > 0) {
Class<? extends ReconConfig> klass = classes.get(classes.size() - 1);
Method reconstruct = klass.getMethod("reconstruct", JSONObject.class);
if (reconstruct != null) {
return (ReconConfig) reconstruct.invoke(null, obj);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
protected int countNeg() {
int count = 0;
for (int i = 1; i <= size; i++) {
if (mapsto(i) < 0) count ++;
}
return count;
}
|
protected int countNeg() {
int count = 0;
for (int i = 1; i <= size; i++) {
if (mapsTo(i) < 0) count ++;
}
return count;
}
|
public static String calculateBreakEvenTime (SystemConfiguration system, LocationDetails location) {
double cost = calculateSystemCost(system);
double savings = 0;
int year = 0;
int month = 0;
int finalMonth = 1;
boolean never = false;
while (savings < cost) {
while (month < 12 && savings < cost) {
savings = savings + calculateAverageMonthlySavings(system, location, year);
data.add(savings);
month = month + 1;
finalMonth = month;
}
month = 0;
year = year + 1;
if (year > 200) {
never = true;
savings = cost;
}
}
if (never == true) {
return ("Never!");
} else {
return (year-1 + " years, " + finalMonth + " months");
}
}
|
public static String calculateBreakEvenTime (SystemConfiguration system, LocationDetails location) {
double cost = calculateSystemCost(system);
double savings = 0;
int year = 0;
int month = 0;
int finalMonth = 1;
boolean never = false;
while (savings < cost) {
while (month < 12 && savings < cost) {
savings = savings + calculateAverageMonthlySavings(system, location, year);
month = month + 1;
finalMonth = month;
}
month = 0;
year = year + 1;
if (year > 200) {
never = true;
savings = cost;
}
}
if (never == true) {
return ("Never!");
} else {
return (year-1 + " years, " + finalMonth + " months");
}
}
|
public void updateLayer(List<DAG.Node> layer, DAG.Direction direction) {
List<InvariantList> nodeInvariantList =
new ArrayList<InvariantList>();
for (int i = 0; i < layer.size(); i++) {
DAG.Node layerNode = layer.get(i);
int x = layerNode.vertexIndex;
InvariantList nodeInvariant =
new InvariantList(nodes.indexOf(layerNode));
nodeInvariant.add(this.invariants.getColor(x));
nodeInvariant.add(this.invariants.getVertexInvariant(x));
List<Integer> relativeInvariants = new ArrayList<Integer>();
List<DAG.Node> relatives = (direction == Direction.UP) ?
layerNode.children : layerNode.parents;
for (Node relative : relatives) {
int j = this.nodes.indexOf(relative);
int inv = this.invariants.getNodeInvariant(j);
int edgeColor;
if (direction == Direction.UP) {
edgeColor = relative.edgeColors.get(layerNode.vertexIndex);
} else {
edgeColor = layerNode.edgeColors.get(relative.vertexIndex);
}
relativeInvariants.add(inv * (edgeColor + 1));
}
Collections.sort(relativeInvariants);
nodeInvariant.addAll(relativeInvariants);
nodeInvariantList.add(nodeInvariant);
}
Collections.sort(nodeInvariantList);
int order = 1;
int first = nodeInvariantList.get(0).originalIndex;
this.invariants.setNodeInvariant(first, order);
for (int i = 1; i < nodeInvariantList.size(); i++) {
InvariantList a = nodeInvariantList.get(i - 1);
InvariantList b = nodeInvariantList.get(i);
if (!a.equals(b)) {
order++;
}
this.invariants.setNodeInvariant(b.originalIndex, order);
}
}
|
public void updateLayer(List<DAG.Node> layer, DAG.Direction direction) {
List<InvariantList> nodeInvariantList =
new ArrayList<InvariantList>();
for (int i = 0; i < layer.size(); i++) {
DAG.Node layerNode = layer.get(i);
int x = layerNode.vertexIndex;
InvariantList nodeInvariant =
new InvariantList(nodes.indexOf(layerNode));
nodeInvariant.add(this.invariants.getColor(x));
nodeInvariant.add(this.invariants.getVertexInvariant(x));
List<Integer> relativeInvariants = new ArrayList<Integer>();
List<DAG.Node> relatives = (direction == Direction.UP) ?
layerNode.children : layerNode.parents;
for (Node relative : relatives) {
int j = this.nodes.indexOf(relative);
int inv = this.invariants.getNodeInvariant(j);
int edgeColor;
if (direction == Direction.UP) {
edgeColor = relative.edgeColors.get(layerNode.vertexIndex);
} else {
edgeColor = layerNode.edgeColors.get(relative.vertexIndex);
}
relativeInvariants.add(inv);
relativeInvariants.add(vertexCount + 1 + edgeColor);
}
Collections.sort(relativeInvariants);
nodeInvariant.addAll(relativeInvariants);
nodeInvariantList.add(nodeInvariant);
}
Collections.sort(nodeInvariantList);
int order = 1;
int first = nodeInvariantList.get(0).originalIndex;
this.invariants.setNodeInvariant(first, order);
for (int i = 1; i < nodeInvariantList.size(); i++) {
InvariantList a = nodeInvariantList.get(i - 1);
InvariantList b = nodeInvariantList.get(i);
if (!a.equals(b)) {
order++;
}
this.invariants.setNodeInvariant(b.originalIndex, order);
}
}
|
public PresentationObject getCatalog(ProductCatalog productCatalog, IWContext iwc, List productCategories) throws RemoteException, FinderException {
Table table = new Table();
table.setWidth("100%");
table.setCellspacing(1);
table.setCellpadding(2);
Collection products = productCatalog.getProducts(productCategories);
Iterator iter = products.iterator();
Iterator catIter = productCategories.iterator();
int row = 1;
int column = 1;
int imageColumn = 1;
Hashtable metaDataTypes = new Hashtable();
table.add(productCatalog.getHeader(productCatalog.iwrb.getLocalizedString("product.product", "Product")), column++, row);
List metadataKeys = new Vector();
String[] metadata = new String[10+column];
while (catIter.hasNext()) {
ICCategory element = (ICCategory) catIter.next();
metaDataTypes.putAll(getCategoryService(iwc).getInheritedMetaDataTypes(element.getMetaDataTypes(), element));
}
if (!metaDataTypes.isEmpty()) {
Set set = metaDataTypes.keySet();
Iterator setIter = set.iterator();
while (setIter.hasNext()) {
String key = setIter.next().toString();
if (!metadataKeys.contains(key)) {
metadataKeys.add(key);
metadata[column] = key;
table.add(productCatalog.getHeader(productCatalog.iwrb.getLocalizedString(METADATA + key, key)), column++, row);
}
}
}
imageColumn = column;
table.add(productCatalog.getHeader(productCatalog.iwrb.getLocalizedString("product.images", "Images")), column++, row);
table.setRowColor(row, productCatalog.getHeaderBackgroundColor());
Product product;
String key;
String meta;
Locale locale = iwc.getCurrentLocale();
while ( iter.hasNext() ) {
++row;
product = (Product) iter.next();
if (productCatalog.hasEditPermission()) {
table.add(productCatalog.getProductEditorLink(product), 1, row);
}
if (productCatalog._productIsLink && productCatalog._productLinkPage != null) {
Link link = new Link(productCatalog.getText(product.getProductName(iwc.getCurrentLocaleId())));
link.setPage(productCatalog._productLinkPage);
table.add(link, 1, row);
} else {
table.add(productCatalog.getText(product.getProductName(iwc.getCurrentLocaleId())) ,1, row);
}
for (int i = 0; i < metadata.length; i++) {
key = metadata[i];
if (key != null) {
meta = product.getMetaData(METADATA + key + "_" + locale.toString());
if (meta != null) {
table.add(productCatalog.getText(meta), i, row);
}
}
}
Collection coll = getEditorBusiness(iwc).getFiles(product);
Iterator images = coll.iterator();
Image image;
int counter = 0;
while (images.hasNext()) {
++counter;
try {
image = new Image( new Integer(( (ICFile) images.next()).getPrimaryKey().toString()).intValue() );
Window window = new Window(image);
Link link = new Link(productCatalog.getText(Integer.toString(counter)));
link.setWindow(window);
table.add(link, imageColumn, row);
table.add(productCatalog.getText(Text.NON_BREAKING_SPACE), imageColumn, row);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
table.setRowColor(row, productCatalog.getBackgroundColor());
}
return table;
}
|
public PresentationObject getCatalog(ProductCatalog productCatalog, IWContext iwc, List productCategories) throws RemoteException, FinderException {
Table table = new Table();
table.setWidth("100%");
table.setCellspacing(1);
table.setCellpadding(2);
Collection products = productCatalog.getProducts(productCategories);
Iterator iter = products.iterator();
Iterator catIter = productCategories.iterator();
int row = 1;
int column = 1;
int imageColumn = 1;
Hashtable metaDataTypes = new Hashtable();
table.add(productCatalog.getHeader(productCatalog.iwrb.getLocalizedString("product.product", "Product")), column++, row);
List metadataKeys = new Vector();
String[] metadata = new String[10+column];
while (catIter.hasNext()) {
ICCategory element = (ICCategory) catIter.next();
metaDataTypes.putAll(getCategoryService(iwc).getInheritedMetaDataTypes(element.getMetaDataTypes(), element));
}
if (!metaDataTypes.isEmpty()) {
Set set = metaDataTypes.keySet();
Iterator setIter = set.iterator();
while (setIter.hasNext()) {
String key = setIter.next().toString();
if (!metadataKeys.contains(key)) {
metadataKeys.add(key);
metadata[column] = key;
table.add(productCatalog.getHeader(productCatalog.iwrb.getLocalizedString(METADATA + key, key)), column++, row);
}
}
}
imageColumn = column;
table.add(productCatalog.getHeader(productCatalog.iwrb.getLocalizedString("product.images", "Images")), column++, row);
table.setRowColor(row, productCatalog.getHeaderBackgroundColor());
Product product;
String key;
String meta;
Locale locale = iwc.getCurrentLocale();
while ( iter.hasNext() ) {
++row;
product = (Product) iter.next();
if (productCatalog.hasEditPermission()) {
table.add(productCatalog.getProductEditorLink(product), 1, row);
}
table.add(productCatalog.getNamePresentationObject(product), 1, row);
for (int i = 0; i < metadata.length; i++) {
key = metadata[i];
if (key != null) {
meta = product.getMetaData(METADATA + key + "_" + locale.toString());
if (meta != null) {
table.add(productCatalog.getText(meta), i, row);
}
}
}
Collection coll = getEditorBusiness(iwc).getFiles(product);
Iterator images = coll.iterator();
Image image;
int counter = 0;
while (images.hasNext()) {
++counter;
try {
image = new Image( new Integer(( (ICFile) images.next()).getPrimaryKey().toString()).intValue() );
Window window = new Window(image);
Link link = new Link(productCatalog.getText(Integer.toString(counter)));
link.setWindow(window);
table.add(link, imageColumn, row);
table.add(productCatalog.getText(Text.NON_BREAKING_SPACE), imageColumn, row);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
table.setRowColor(row, productCatalog.getBackgroundColor());
}
return table;
}
|
Token nextToken(){
Token res = null ;
String temp = new String() ;
for (int i =indexInput; i < Input.length(); i++) {
indexInput++ ;
res = new Token();
nodeNFA nextNode = CurrentState.getNextNode(Input.charAt(i));
if (nextNode == null){
throw new RuntimeException("Error in Alphabetic of language");
}else if (nextNode == nfa.loopState){
temp += Input.charAt(i);
res.type = typeToken.Num ;
int index = i+1 ;
while(nextNode.getNextNode(Input.charAt(index)) ==nfa.loopState )
{
nextNode = nextNode.getNextNode(Input.charAt(index));
temp += Input.charAt(index);
index++;
i++;
}
indexInput = index ;
res.s = temp;
CurrentState = nextNode ;
break;
}else if (nextNode.isFiniteState()){
temp += Input.charAt(i);
switch(Input.charAt(i))
{
case '(':
res.type = typeToken.openBrace ;
break;
case ')':
res.type = typeToken.closeBrace ;
break;
case '<':
res.type = typeToken.openTok_brace ;
break;
case '>':
res.type = typeToken.closeTok_brace ;
break;
case '.':
res.type = typeToken.dot;
break;
case '&':
res.type = typeToken.ParallelSign ;
break;
case ',':
res.type = typeToken.comma ;
break;
}
res.s = temp;
CurrentState = nextNode ;
break;
}else{
CurrentState = nextNode ;
}
}
if (res !=null)
mCurrentToken = res ;
return res ;
}
|
Token nextToken(){
Token res = null ;
String temp = new String() ;
for (int i =indexInput; i < Input.length(); i++) {
indexInput++ ;
res = new Token();
nodeNFA nextNode = CurrentState.getNextNode(Input.charAt(i));
if (nextNode == null){
throw new RuntimeException("Error in Alphabetic of language");
}else if (nextNode == nfa.loopState){
temp += Input.charAt(i);
res.type = typeToken.Num ;
int index = i+1 ;
while( index < Input.length() && nextNode.getNextNode(Input.charAt(index)) ==nfa.loopState )
{
nextNode = nextNode.getNextNode(Input.charAt(index));
temp += Input.charAt(index);
index++;
i++;
}
indexInput = index ;
res.s = temp;
CurrentState = nextNode ;
break;
}else if (nextNode.isFiniteState()){
temp += Input.charAt(i);
switch(Input.charAt(i))
{
case '(':
res.type = typeToken.openBrace ;
break;
case ')':
res.type = typeToken.closeBrace ;
break;
case '<':
res.type = typeToken.openTok_brace ;
break;
case '>':
res.type = typeToken.closeTok_brace ;
break;
case '.':
res.type = typeToken.dot;
break;
case '&':
res.type = typeToken.ParallelSign ;
break;
case ',':
res.type = typeToken.comma ;
break;
}
res.s = temp;
CurrentState = nextNode ;
break;
}else{
CurrentState = nextNode ;
}
}
if (res !=null)
mCurrentToken = res ;
return res ;
}
|
public Cursor loadInBackground() {
if (BuildConfig.DEBUG) {
Log.d(TAG, "loadInBackground");
}
if (sessionId == 0 || !TextUtils.isEmpty(more)) {
Bundle extras = createSession(sessionId, more);
if (extras != null) {
sessionId = extras.getLong(ThingProvider.EXTRA_SESSION_ID);
setSelectionArgs(Array.of(sessionId));
} else {
return null;
}
}
Bundle extras = new Bundle(1);
extras.putLong(ThingProvider.EXTRA_SESSION_ID, sessionId);
return new CursorExtrasWrapper(super.loadInBackground(), extras);
}
|
public Cursor loadInBackground() {
if (BuildConfig.DEBUG) {
Log.d(TAG, "loadInBackground");
}
if (sessionId == 0 || !TextUtils.isEmpty(more)) {
Bundle extras = createSession(sessionId, more);
if (extras == null) {
return null;
}
sessionId = extras.getLong(ThingProvider.EXTRA_SESSION_ID);
}
Bundle extras = new Bundle(1);
extras.putLong(ThingProvider.EXTRA_SESSION_ID, sessionId);
setSelectionArgs(Array.of(sessionId));
return new CursorExtrasWrapper(super.loadInBackground(), extras);
}
|
public boolean open(final Track track) {
if (track == null)
return false;
this.inputFile = track;
try {
URI location = track.getLocation();
InputStream fis;
if (location.getScheme().equals("file")) {
logger.info("Opening file: " + location);
streaming = false;
fis = new FileInputStream(inputFile.getFile());
streamSize = inputFile.getFile().length();
} else {
logger.info("Opening stream: " + location);
streaming = true;
URLConnection urlConnection = location.toURL().openConnection();
urlConnection.setRequestProperty("Icy-MetaData", "1");
fis = urlConnection.getInputStream();
String metaIntString = null;
String contentType = urlConnection.getContentType();
if (!contentType.equals("audio/mpeg")) {
if (contentType.equals("unknown/unknown")) {
logger.fine("Reading SHOUTCast response");
String s = readLine(fis);
if (!s.equals("ICY 200 OK")) {
logger.warning("SHOUTCast invalid response: " + s);
return false;
}
while (true) {
s = readLine(fis);
if (s.isEmpty()) {
break;
}
String[] ss = s.split(":");
if (ss[0].equals("icy-metaint")) {
metaIntString = ss[1];
} else if (ss[0].equals("icy-genre")) {
track.setGenre(ss[1]);
} else if (ss[0].equals("icy-name")) {
track.setAlbum(ss[1]);
}
}
} else {
return false;
}
} else {
metaIntString = urlConnection.getHeaderField("icy-metaint");
track.setGenre(urlConnection.getHeaderField("icy-genre"));
track.setAlbum(urlConnection.getHeaderField("icy-name"));
}
if (Util.isEmpty(metaIntString))
metaIntString = "0";
final int metaInt = Integer.valueOf(metaIntString);
if (metaInt > 0) {
fis = new FilterInputStream(fis) {
private int count = 0;
@Override
public int read(byte[] b, int off, int len) throws IOException {
int bytesToMeta = metaInt - count;
if (bytesToMeta == 0) {
int size = read() * 16;
if (size > 1) {
byte[] meta = new byte[size];
int i = super.read(meta, 0, size);
String metaString = new String(meta, 0, i, "UTF-8");
String title = "StreamTitle='";
if (metaString.startsWith(title)) {
String[] ss = metaString.substring(title.length(), metaString.indexOf(";") - 1).split(" - ");
if (ss.length > 0) {
if (ss.length > 1) {
track.setArtist(ss[0]);
track.setTitle(ss[1]);
} else {
track.setTitle(ss[0]);
}
}
}
}
count = 0;
}
if (bytesToMeta > 0 && bytesToMeta < len)
len = bytesToMeta;
int read = super.read(b, off, len);
count += read;
return read;
}
};
}
decoder = new Decoder();
}
bitstream = new Bitstream(fis);
Header header = bitstream.readFrame();
encDelay = header.getEncDelay();
int encPadding = header.getEncPadding();
int sampleRate = header.frequency();
int channels = header.mode() == Header.SINGLE_CHANNEL ? 1 : 2;
track.setSampleRate(sampleRate);
track.setChannels(channels);
samplesPerFrame = (int) (header.ms_per_frame() * header.frequency() / 1000);
audioFormat = new AudioFormat(sampleRate, 16, channels, true, false);
if (!streaming) {
totalSamples = samplesPerFrame * (header.max_number_of_frames(streamSize) + header.min_number_of_frames(streamSize)) / 2;
if (encPadding < totalSamples) {
totalSamples -= encPadding;
}
totalSamples -= encDelay;
bitstream.close();
fis.close();
createBitstream(0);
}
currentSample = 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
|
public boolean open(final Track track) {
if (track == null)
return false;
this.inputFile = track;
try {
URI location = track.getLocation();
InputStream fis;
if (location.getScheme().equals("file")) {
logger.info("Opening file: " + location);
streaming = false;
fis = new FileInputStream(inputFile.getFile());
streamSize = inputFile.getFile().length();
} else {
logger.info("Opening stream: " + location);
streaming = true;
URLConnection urlConnection = location.toURL().openConnection();
urlConnection.setRequestProperty("Icy-MetaData", "1");
fis = urlConnection.getInputStream();
String metaIntString = null;
String contentType = urlConnection.getContentType();
if (!contentType.equals("audio/mpeg")) {
if (contentType.equals("unknown/unknown")) {
logger.fine("Reading SHOUTCast response");
String s = readLine(fis);
if (!s.equals("ICY 200 OK")) {
logger.warning("SHOUTCast invalid response: " + s);
return false;
}
while (true) {
s = readLine(fis);
if (s.isEmpty()) {
break;
}
String[] ss = s.split(":");
if (ss[0].equals("icy-metaint")) {
metaIntString = ss[1];
} else if (ss[0].equals("icy-genre")) {
track.setGenre(ss[1]);
} else if (ss[0].equals("icy-name")) {
track.setAlbum(ss[1]);
}
}
} else {
return false;
}
} else {
metaIntString = urlConnection.getHeaderField("icy-metaint");
track.setGenre(urlConnection.getHeaderField("icy-genre"));
track.setAlbum(urlConnection.getHeaderField("icy-name"));
}
if (Util.isEmpty(metaIntString))
metaIntString = "0";
final int metaInt = Integer.valueOf(metaIntString);
if (metaInt > 0) {
fis = new FilterInputStream(fis) {
private int count = 0;
@Override
public int read(byte[] b, int off, int len) throws IOException {
int bytesToMeta = metaInt - count;
if (bytesToMeta == 0) {
int size = read() * 16;
if (size > 1) {
byte[] meta = new byte[size];
int i = super.read(meta, 0, size);
String metaString = new String(meta, 0, i, "UTF-8");
String title = "StreamTitle='";
if (metaString.startsWith(title)) {
String[] ss = metaString.substring(title.length(), metaString.indexOf(";") - 1).split(" - ");
if (ss.length > 0) {
if (ss.length > 1) {
track.setArtist(ss[0]);
track.setTitle(ss[1]);
} else {
track.setTitle(ss[0]);
}
}
}
}
count = 0;
}
if (bytesToMeta >= 0 && bytesToMeta < len)
len = bytesToMeta;
int read = super.read(b, off, len);
count += read;
return read;
}
};
}
decoder = new Decoder();
}
bitstream = new Bitstream(fis);
Header header = bitstream.readFrame();
encDelay = header.getEncDelay();
int encPadding = header.getEncPadding();
int sampleRate = header.frequency();
int channels = header.mode() == Header.SINGLE_CHANNEL ? 1 : 2;
track.setSampleRate(sampleRate);
track.setChannels(channels);
samplesPerFrame = (int) (header.ms_per_frame() * header.frequency() / 1000);
audioFormat = new AudioFormat(sampleRate, 16, channels, true, false);
if (!streaming) {
totalSamples = samplesPerFrame * (header.max_number_of_frames(streamSize) + header.min_number_of_frames(streamSize)) / 2;
if (encPadding < totalSamples) {
totalSamples -= encPadding;
}
totalSamples -= encDelay;
bitstream.close();
fis.close();
createBitstream(0);
}
currentSample = 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
|
public void refresh(Calendar timestamp) {
ArrayList<Alert> _Alerts = new ArrayList<Alert>();
ArrayList<Vessel> removeVessels = new ArrayList<Vessel>();
for(int i=0; i< _Vessels.size(); i++){
Vessel v1;
v1 = _Vessels.get(i);
try {
Coord v1Coords = v1.getCoord(timestamp);
if(v1Coords.isInRange(range)){
for(int j=i+1; j<_Vessels.size(); j++){
String risk = "none";
Alert newAlert;
Vessel v2;
v2 = _Vessels.get(j);
Coord v2Coords = v2.getCoord(timestamp);
double deltaX = v1Coords.x() - v2Coords.x();
double deltaY = v1Coords.y() - v2Coords.y();
double distance = Math.sqrt(Math.pow(deltaX, 2.0) + Math.pow(deltaY, 2.0));
if (distance < 50){
risk = "high";
newAlert = createAlert(AlertType.HIGHRISK, v1, v2);
_Alerts.add(newAlert);
}
else if (distance < 200 && risk != "high"){
risk = "low";
newAlert = createAlert(AlertType.LOWRISK, v1, v2);
_Alerts.add(newAlert);
}
else {
risk = "none";
newAlert = createAlert(AlertType.NONE, v1, v2);
_Alerts.add(newAlert);
}
}
}
else{
removeVessels.add(v1);
}
}
catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
for(int i = 0; i < removeVessels.size(); i++){
_Vessels.remove(removeVessels.get(i));
}
for (int i=0; i < _Observers.size(); i++) {
_Observers.get(i).refresh(_Alerts,_Vessels);
}
}
|
public void refresh(Calendar timestamp) {
ArrayList<Alert> _Alerts = new ArrayList<Alert>();
ArrayList<Vessel> removeVessels = new ArrayList<Vessel>();
for(int i=0; i< _Vessels.size(); i++){
Vessel v1;
v1 = _Vessels.get(i);
try {
Coord v1Coords = v1.getCoord(timestamp);
if(v1Coords.isInRange(range)){
for(int j=i+1; j<_Vessels.size(); j++){
String risk = "none";
Alert newAlert;
Vessel v2;
v2 = _Vessels.get(j);
Coord v2Coords = v2.getCoord(timestamp);
double deltaX = v1Coords.x() - v2Coords.x();
double deltaY = v1Coords.y() - v2Coords.y();
double distance = Math.sqrt(Math.pow(deltaX, 2.0) + Math.pow(deltaY, 2.0));
if (distance < 50){
risk = "high";
newAlert = createAlert(AlertType.HIGHRISK, v1, v2);
_Alerts.add(newAlert);
}
else if (distance < 200 && risk != "high"){
risk = "low";
newAlert = createAlert(AlertType.LOWRISK, v1, v2);
_Alerts.add(newAlert);
}
}
}
else{
removeVessels.add(v1);
}
}
catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
for(int i = 0; i < removeVessels.size(); i++){
_Vessels.remove(removeVessels.get(i));
}
for (int i=0; i < _Observers.size(); i++) {
_Observers.get(i).refresh(_Alerts,_Vessels);
}
}
|
public Token nextToken() {
Token token = null;
CoffeeSymbol symbol = null;
Exception problem = null;
try {
symbol = aptanaScanner.nextToken();
if (symbol == null) {
token = CommonToken.INVALID_TOKEN;
} else if (symbol.getId() == Terminals.EOF) {
token = new CommonToken(CommonToken.EOF);
} else {
token = new BeaverToken(symbol);
}
} catch (IOException e) {
problem = e;
} catch (beaver.Scanner.Exception e) {
problem = e;
} catch (ArrayIndexOutOfBoundsException e) {
token = new CommonToken(RULE_OUTDENT);
}
if (problem != null) {
logger.warn("Cannot get next token ", problem);
token = CommonToken.INVALID_TOKEN;
}
logger.debug("token: " + token);
return token;
}
|
public Token nextToken() {
Token token = null;
CoffeeSymbol symbol = null;
Exception problem = null;
try {
symbol = aptanaScanner.nextToken();
if (symbol == null) {
token = CommonToken.INVALID_TOKEN;
} else if (symbol.getId() == Terminals.EOF) {
token = new CommonToken(CommonToken.EOF);
} else {
token = new BeaverToken(symbol);
}
} catch (IOException e) {
problem = e;
} catch (beaver.Scanner.Exception e) {
problem = e;
}
if (problem != null) {
logger.warn("Cannot get next token ", problem);
token = CommonToken.INVALID_TOKEN;
}
logger.debug("token: " + token);
return token;
}
|
public void testDeleteDirectory() throws Exception {
final String TEST_DIR = getApplicationContext().getCacheDir().getAbsolutePath() +
"-testDeleteDirectory-" + System.currentTimeMillis();
final File nonexistent = new File("nonexistentDirectory");
assertFalse(nonexistent.exists());
try {
deleteDirectoryRecursively(nonexistent);
fail("deleteDirectoryRecursively(null) should throw Exception");
} catch (IllegalStateException e) { }
File dir = mkdir(TEST_DIR);
deleteDirectoryRecursively(dir);
assertFalse(dir.exists());
dir = mkdir(TEST_DIR);
populateDir(dir);
deleteDirectoryRecursively(dir);
assertFalse(dir.exists());
dir = mkdir(TEST_DIR);
populateDir(dir);
File subDir = new File(TEST_DIR + File.separator + "subDir");
assertTrue(subDir.mkdir());
deleteDirectoryRecursively(dir);
assertFalse(subDir.exists());
assertFalse(dir.exists());
dir = mkdir(TEST_DIR);
populateDir(dir);
subDir = new File(TEST_DIR + File.separator + "subDir");
assertTrue(subDir.mkdir());
populateDir(subDir);
deleteDirectoryRecursively(dir);
assertFalse(subDir.exists());
assertFalse(dir.exists());
}
|
public void testDeleteDirectory() throws Exception {
final String TEST_DIR = getApplicationContext().getCacheDir().getAbsolutePath() +
"-testDeleteDirectory-" + System.currentTimeMillis();
final File nonexistent = new File("nonexistentDirectory");
assertFalse(nonexistent.exists());
try {
deleteDirectoryRecursively(nonexistent);
fail("deleteDirectoryRecursively on a nonexistent directory should throw Exception");
} catch (IllegalStateException e) { }
File dir = mkdir(TEST_DIR);
deleteDirectoryRecursively(dir);
assertFalse(dir.exists());
dir = mkdir(TEST_DIR);
populateDir(dir);
deleteDirectoryRecursively(dir);
assertFalse(dir.exists());
dir = mkdir(TEST_DIR);
populateDir(dir);
File subDir = new File(TEST_DIR + File.separator + "subDir");
assertTrue(subDir.mkdir());
deleteDirectoryRecursively(dir);
assertFalse(subDir.exists());
assertFalse(dir.exists());
dir = mkdir(TEST_DIR);
populateDir(dir);
subDir = new File(TEST_DIR + File.separator + "subDir");
assertTrue(subDir.mkdir());
populateDir(subDir);
deleteDirectoryRecursively(dir);
assertFalse(subDir.exists());
assertFalse(dir.exists());
}
|
public void read( DataInputStream in ) throws IOException
{
int validCount = IOUtil.readInt( in );
for ( int i = 0; i < validCount; i++ )
{
String propertyName = IOUtil.readString( in );
int index = getPropertyIndex( propertyName );
if ( index == -1 )
{
String propertyCssText = IOUtil.readString( in );
if ( IStyle.BIRT_DATE_TIME_FORMAT_PROPERTY
.equalsIgnoreCase( propertyName ) )
{
this.setStringFormat( propertyCssText );
}
else if ( IStyle.BIRT_NUMBER_FORMAT_PROPERTY
.equalsIgnoreCase( propertyName ) )
{
this.setNumberFormat( propertyCssText );
}
else if ( IStyle.BIRT_DATE_FORMAT_PROPERTY
.equalsIgnoreCase( propertyName ) )
{
this.setDateFormat( propertyCssText );
}
else if ( IStyle.BIRT_TIME_FORMAT_PROPERTY
.equalsIgnoreCase( propertyName ) )
{
this.setTimeFormat( propertyCssText );
}
else if ( IStyle.BIRT_DATE_TIME_FORMAT_PROPERTY
.equalsIgnoreCase( propertyName ) )
{
this.setDateTimeFormat( propertyCssText );
}
else
{
throw new IOException( propertyName + " not valid" );
}
}
else
{
if ( index == StyleConstants.STYLE_DATA_FORMAT )
{
CSSValue value = DataFormatValue.read( in );
setProperty( index, value );
}
else
{
String propertyCssText = IOUtil.readString( in );
setCssText( index, propertyCssText );
}
}
}
}
|
public void read( DataInputStream in ) throws IOException
{
int validCount = IOUtil.readInt( in );
for ( int i = 0; i < validCount; i++ )
{
String propertyName = IOUtil.readString( in );
int index = getPropertyIndex( propertyName );
if ( index == -1 )
{
String propertyCssText = IOUtil.readString( in );
if ( IStyle.BIRT_STRING_FORMAT_PROPERTY
.equalsIgnoreCase( propertyName ) )
{
this.setStringFormat( propertyCssText );
}
else if ( IStyle.BIRT_NUMBER_FORMAT_PROPERTY
.equalsIgnoreCase( propertyName ) )
{
this.setNumberFormat( propertyCssText );
}
else if ( IStyle.BIRT_DATE_FORMAT_PROPERTY
.equalsIgnoreCase( propertyName ) )
{
this.setDateFormat( propertyCssText );
}
else if ( IStyle.BIRT_TIME_FORMAT_PROPERTY
.equalsIgnoreCase( propertyName ) )
{
this.setTimeFormat( propertyCssText );
}
else if ( IStyle.BIRT_DATE_TIME_FORMAT_PROPERTY
.equalsIgnoreCase( propertyName ) )
{
this.setDateTimeFormat( propertyCssText );
}
else
{
throw new IOException( propertyName + " not valid" );
}
}
else
{
if ( index == StyleConstants.STYLE_DATA_FORMAT )
{
CSSValue value = DataFormatValue.read( in );
setProperty( index, value );
}
else
{
String propertyCssText = IOUtil.readString( in );
setCssText( index, propertyCssText );
}
}
}
}
|
public void use(Board board, UsageParam param) throws WeblaboraException {
Player player = board.getPlayer(board.getActivePlayer());
double energy = param.getEnergy();
if(energy >= 9) {
player.addNickel(2);
}
else if(energy >= 6) {
player.addNickel(1);
player.addPenny(3);
}
else if(energy >= 3) {
player.addNickel(1);
}
else return;
player.subtractAll(param);
}
|
public void use(Board board, UsageParam param) throws WeblaboraException {
Player player = board.getPlayer(board.getActivePlayer());
double energy = param.getEnergy();
if(energy >= 9) {
player.addNickel(2);
}
else if(energy >= 6) {
player.addNickel(1);
player.addPenny(3);
}
else if(energy >= 3) {
player.addNickel(1);
}
else return;
player.subtractEnergy(param);
}
|
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, HeadsetService.class));
if (WM8994.isSupported(context)) {
WM8994.restore(context);
}
if (SoundControlHelper.getSoundControlHelper(context).isSupported()) {
SoundControlHelper.getSoundControlHelper(context).applyValues();
}
if (BoefflaSoundControlHelper.getBoefflaSoundControlHelper(context).getBoefflaSound()) {
BoefflaSoundControlHelper.getBoefflaSoundControlHelper(context).applyValues();
}
}
|
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, HeadsetService.class));
if (WM8994.isSupported(context)) {
WM8994.restore(context);
}
if (SoundControlHelper.getSoundControlHelper(context).isSupported()) {
SoundControlHelper.getSoundControlHelper(context).applyValues();
}
if (BoefflaSoundControlHelper.getBoefflaSoundControlHelper(context).getBoefflaSound() && BoefflaSoundControlHelper.getBoefflaSoundControlHelper(context).readBoefflaSound() != 1) {
BoefflaSoundControlHelper.getBoefflaSoundControlHelper(context).applyValues();
}
}
|
public FigNode makePresentation(Layer lay) {
Fig obj1 = new FigRect(-5, -5, 30, 30, Color.black, Color.green);
Vector temp_list = new Vector();
temp_list.addElement(obj1);
FigClass fn = new FigClass(this, temp_list);
fn.bindPort(north, obj1);
return fn;
}
|
public FigNode makePresentation(Layer lay) {
Fig obj1 = new FigRect(0, 0, 100, 70, Color.black, Color.green);
Vector temp_list = new Vector();
temp_list.addElement(obj1);
FigClass fn = new FigClass(this, temp_list);
fn.bindPort(north, obj1);
return fn;
}
|
private void InitProtocol() {
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_INIT", CONNECTION_TYPES.NULL) {
@Override
public String exec(String args) {
String[] parsedArgs = args.split(",");
if (CURR_TYPE == CONNECTION_TYPES.NULL) {
if (parsedArgs[1].equals(STR_VERSION)) {
try {
CURR_TYPE = CONNECTION_TYPES.valueOf(parsedArgs[0]);
if (!parsedArgs[2].equals(System.getProperty("file.encoding"))) {
RibbonServer.logAppend(LOG_ID, 2, "мережева сесія вимогає іншої кодової сторінки:" + parsedArgs[2]);
CURR_SESSION.setReaderEncoding(parsedArgs[2]);
}
return "OK:\nRIBBON_GCTL_FORCE_LOGIN:";
} catch (IllegalArgumentException ex) {
return "RIBBON_ERROR:Невідомий тип з'єднання!";
}
} else {
return "RIBBON_ERROR:Невідомий ідентефікатор протокола.";
}
} else {
return "RIBBON_WARNING:З'єднання вже ініціьовано!";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_LOGIN", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 2);
if (!RibbonServer.ACCESS_ALLOW_MULTIPLIE_LOGIN && SessionManager.isAlreadyLogined(parsedArgs[0])) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " вже увійшов до системи!\nRIBBON_GCTL_FORCE_LOGIN:";
}
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && (!AccessHandler.isUserAdmin(parsedArgs[0]))) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " не є адміністратором системи.\nRIBBON_GCTL_FORCE_LOGIN:";
}
String returned = AccessHandler.PROC_LOGIN_USER(parsedArgs[0], parsedArgs[1]);
if (returned == null) {
if (CURR_TYPE == CONNECTION_TYPES.CLIENT) {
RibbonServer.logAppend(LOG_ID, 3, "користувач " + parsedArgs[0] + " увійшов до системи.");
} else if (CURR_TYPE == CONNECTION_TYPES.CONTROL) {
RibbonServer.logAppend(LOG_ID, 3, "адміністратор " + parsedArgs[0] + " увійшов до системи.");
if (RibbonServer.CONTROL_IS_PRESENT == false) {
RibbonServer.logAppend(RibbonServer.LOG_ID, 2, "ініційовано контроль системи!");
RibbonServer.CONTROL_IS_PRESENT = true;
}
}
CURR_SESSION.USER_NAME = parsedArgs[0];
CURR_SESSION.CURR_ENTRY = SessionManager.createSessionEntry(parsedArgs[0]);
CURR_SESSION.setSessionName();
return "OK:" + CURR_SESSION.CURR_ENTRY.SESSION_HASH_ID;
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_GET_ID", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.CURR_ENTRY != null) {
return "RIBBON_ERROR:Вхід не виконано!\nRIBBON_GCTL_FORCE_LOGIN:";
} else {
return CURR_SESSION.CURR_ENTRY.SESSION_HASH_ID;
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_RESUME", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
SessionManager.SessionEntry exicted = SessionManager.getUserBySessionEntry(args);
if (exicted == null) {
return "RIBBON_GCTL_FORCE_LOGIN:";
} else {
String returned = AccessHandler.PROC_RESUME_USER(exicted);
if (returned == null) {
SessionManager.reniewEntry(exicted);
CURR_SESSION.USER_NAME = exicted.SESSION_USER_NAME;
CURR_SESSION.CURR_ENTRY = exicted;
CURR_SESSION.setSessionName();
return "OK:";
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_REM_LOGIN", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!IS_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
} else if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
} else if (!AccessHandler.isUserAdmin(CURR_SESSION.USER_NAME)) {
return "RIBBON_ERROR:Ця сессія не може використовувати видалений режим!";
}
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 2);
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && (!AccessHandler.isUserAdmin(parsedArgs[0]))) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " не є адміністратором системи.\nRIBBON_GCTL_FORCE_LOGIN:";
}
String returned = AccessHandler.PROC_LOGIN_USER(parsedArgs[0], parsedArgs[1]);
if (returned == null) {
if (CURR_TYPE == CONNECTION_TYPES.CLIENT) {
RibbonServer.logAppend(LOG_ID, 3, "користувач " + parsedArgs[0] + " видалено увійшов до системи.");
} else if (CURR_TYPE == CONNECTION_TYPES.CONTROL) {
RibbonServer.logAppend(LOG_ID, 3, "адміністратор " + parsedArgs[0] + " видалено увійшов до системи.");
}
return "OK:";
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_GET_USERNAME", CONNECTION_TYPES.ANY) {
public String exec(String args) {
if (CURR_SESSION.USER_NAME != null) {
return "OK:" + CURR_SESSION.USER_NAME;
} else {
return "RIBBON_ERROR:Вхід до системи не виконано!";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_SET_REMOTE_MODE", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
} else if (!AccessHandler.isUserAdmin(CURR_SESSION.USER_NAME)) {
return "RIBBON_ERROR:Ця сессія не може використовувати видалений режим!";
}
IS_REMOTE = "1".equals(args) ? true : false;
return "OK:" + (IS_REMOTE ? "1" : "0");
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_ACCESS_CONTEXT", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
} else if (!AccessHandler.isUserAdmin(CURR_SESSION.USER_NAME)) {
return "RIBBON_ERROR:Ця сессія не може використовувати видалений режим!";
}
UserClasses.UserEntry overUser = AccessHandler.getEntryByName(Generic.CsvFormat.commonParseLine(args, 1)[0]);
if (overUser == null) {
return "RIBBON_ERROR:Користувача не знайдено!";
} else if (!overUser.IS_ENABLED) {
return "RIBBON_ERROR:Користувача заблоковано!";
}
String oldUserName = CURR_SESSION.USER_NAME;
CURR_SESSION.USER_NAME = overUser.USER_NAME;
CURR_SESSION.outStream.println("PROCEED:");
String subResult = null;
try {
subResult = process(CURR_SESSION.inStream.readLine());
} catch (java.io.IOException ex) {
RibbonServer.logAppend(LOG_ID, 1, "неможливо прочитати дані з сокету!");
SessionManager.closeSession(CURR_SESSION);
}
CURR_SESSION.USER_NAME = oldUserName;
return subResult;
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_CLOSE", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && SessionManager.hasOtherControl(CURR_SESSION) == false) {
RibbonServer.logAppend(RibbonServer.LOG_ID, 2, "контроль над системою завершено!");
RibbonServer.CONTROL_IS_PRESENT = false;
}
return "COMMIT_CLOSE:";
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_DIRS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Directories.PROC_GET_DIRS();
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_TAGS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Messenger.PROC_GET_TAGS();
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_LOAD_BASE_FROM_INDEX", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Messenger.PROC_LOAD_BASE_FROM_INDEX(args);
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_POST_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
MessageClasses.Message recievedMessage = new MessageClasses.Message();
recievedMessage.createMessageForPost(args);
recievedMessage.AUTHOR = CURR_SESSION.USER_NAME;
Boolean collectMessage = true;
StringBuffer messageBuffer = new StringBuffer();
String inLine;
while (collectMessage) {
try {
inLine = CURR_SESSION.inStream.readLine();
if (!inLine.equals("END:")) {
messageBuffer.append(inLine);
messageBuffer.append("\n");
} else {
collectMessage = false;
}
} catch (java.io.IOException ex) {
return "RIBBON_ERROR:Неможливо прочитати повідомлення з сокету!";
}
}
recievedMessage.CONTENT = messageBuffer.toString();
String answer = Procedures.PROC_POST_MESSAGE(recievedMessage);
if (answer.equals("OK:")) {
BROADCAST_TAIL = "RIBBON_UCTL_LOAD_INDEX:" + recievedMessage.returnEntry().toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
}
return answer;
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = args.split(",");
String givenDir = parsedArgs[0];
String givenIndex = parsedArgs[1];
StringBuffer returnedMessage = new StringBuffer();
if (AccessHandler.checkAccess(CURR_SESSION.USER_NAME, givenDir, 0) == false) {
return "RIBBON_ERROR:Помилка доступу до напрямку " + givenDir;
}
String dirPath = Directories.getDirPath(givenDir);
if (dirPath == null) {
return "RIBBON_ERROR:Напрямок " + givenDir + " не існує!";
} else {
try {
java.io.BufferedReader messageReader = new java.io.BufferedReader(new java.io.FileReader(dirPath + givenIndex));
while (messageReader.ready()) {
returnedMessage.append(messageReader.readLine());
returnedMessage.append("\n");
}
return returnedMessage.append("END:").toString();
} catch (java.io.FileNotFoundException ex) {
return "RIBBON_ERROR:Повідмолення не існує!";
} catch (java.io.IOException ex) {
RibbonServer.logAppend(LOG_ID, 1, "помилка зчитування повідомлення " + givenDir + ":" + givenIndex);
return "RIBBON_ERROR:Помилка виконання команди!";
}
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_MODIFY_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
StringBuffer messageBuffer = new StringBuffer();
String inLine;
Boolean collectMessage = true;
String[] parsedArgs = Generic.CsvFormat.splitCsv(args);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
MessageClasses.Message modTemplate = new MessageClasses.Message();
modTemplate.createMessageForModify(parsedArgs[1]);
while (collectMessage) {
try {
inLine = CURR_SESSION.inStream.readLine();
if (!inLine.equals("END:")) {
messageBuffer.append(inLine);
messageBuffer.append("\n");
} else {
collectMessage = false;
}
} catch (java.io.IOException ex) {
return "RIBBON_ERROR:Неможливо прочитати повідомлення з сокету!";
}
}
modTemplate.CONTENT = messageBuffer.toString();
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
Integer oldIntFlag = AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2);
Integer newIntFlag = AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, modTemplate.DIRS, 1);
if ((CURR_SESSION.USER_NAME.equals(matchedEntry.AUTHOR) && (newIntFlag == null)) || ((oldIntFlag == null) && (newIntFlag == null))) {
for (Integer dirIndex = 0; dirIndex < matchedEntry.DIRS.length; dirIndex++) {
if (AccessHandler.checkAccess(CURR_SESSION.USER_NAME, matchedEntry.DIRS[dirIndex], 1) == true) {
continue;
} else {
return "RIBBON_ERROR:Помилка доступу до напрямку " + matchedEntry.DIRS[dirIndex] + ".";
}
}
Procedures.PROC_MODIFY_MESSAGE(matchedEntry, modTemplate);
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
if (oldIntFlag != null) {
return "RIBBON_ERROR:Помилка доступу до напрямку " + matchedEntry.DIRS[oldIntFlag] + ".";
} else {
return "RIBBON_ERROR:Помилка доступу до напрямку " + modTemplate.DIRS[newIntFlag] + ".";
}
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_DELETE_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(args);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
} else {
if (matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) == null)) {
Procedures.PROC_DELETE_MESSAGE(matchedEntry);
BROADCAST_TAIL = "RIBBON_UCTL_DELETE_INDEX:" + matchedEntry.INDEX;
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_ADD_MESSAGE_PROPERTY", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 3);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
if ((matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) != null))) {
MessageClasses.MessageProperty newProp = new MessageClasses.MessageProperty(parsedArgs[1], CURR_SESSION.USER_NAME, parsedArgs[2], RibbonServer.getCurrentDate());
newProp.TYPE = parsedArgs[1];
newProp.TEXT_MESSAGE = parsedArgs[2];
newProp.DATE = RibbonServer.getCurrentDate();
newProp.USER = CURR_SESSION.USER_NAME;
matchedEntry.PROPERTIES.add(newProp);
IndexReader.updateBaseIndex();
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_DEL_MESSAGE_PROPERTY", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 3);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
if ((matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) != null))) {
MessageClasses.MessageProperty findedProp = null;
java.util.ListIterator<MessageClasses.MessageProperty> propIter = matchedEntry.PROPERTIES.listIterator();
while (propIter.hasNext()) {
MessageClasses.MessageProperty currProp = propIter.next();
if (currProp.TYPE.equals(parsedArgs[1]) && currProp.DATE.equals(parsedArgs[2])) {
findedProp = currProp;
break;
}
}
if (findedProp != null) {
matchedEntry.PROPERTIES.remove(findedProp);
IndexReader.updateBaseIndex();
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Системної ознаки не існує!";
}
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_USERS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return AccessHandler.PROC_GET_USERS_UNI(false);
}
});
}
|
private void InitProtocol() {
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_INIT", CONNECTION_TYPES.NULL) {
@Override
public String exec(String args) {
String[] parsedArgs = args.split(",");
if (CURR_TYPE == CONNECTION_TYPES.NULL) {
if (parsedArgs[1].equals(STR_VERSION)) {
try {
CURR_TYPE = CONNECTION_TYPES.valueOf(parsedArgs[0]);
if (!parsedArgs[2].equals(System.getProperty("file.encoding"))) {
RibbonServer.logAppend(LOG_ID, 2, "мережева сесія вимогає іншої кодової сторінки:" + parsedArgs[2]);
CURR_SESSION.setReaderEncoding(parsedArgs[2]);
}
return "OK:\nRIBBON_GCTL_FORCE_LOGIN:";
} catch (IllegalArgumentException ex) {
return "RIBBON_ERROR:Невідомий тип з'єднання!";
}
} else {
return "RIBBON_ERROR:Невідомий ідентефікатор протокола.";
}
} else {
return "RIBBON_WARNING:З'єднання вже ініціьовано!";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_LOGIN", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 2);
if (!RibbonServer.ACCESS_ALLOW_MULTIPLIE_LOGIN && SessionManager.isAlreadyLogined(parsedArgs[0])) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " вже увійшов до системи!\nRIBBON_GCTL_FORCE_LOGIN:";
}
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && (!AccessHandler.isUserAdmin(parsedArgs[0]))) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " не є адміністратором системи.\nRIBBON_GCTL_FORCE_LOGIN:";
}
String returned = AccessHandler.PROC_LOGIN_USER(parsedArgs[0], parsedArgs[1]);
if (returned == null) {
if (CURR_TYPE == CONNECTION_TYPES.CLIENT) {
RibbonServer.logAppend(LOG_ID, 3, "користувач " + parsedArgs[0] + " увійшов до системи.");
} else if (CURR_TYPE == CONNECTION_TYPES.CONTROL) {
RibbonServer.logAppend(LOG_ID, 3, "адміністратор " + parsedArgs[0] + " увійшов до системи.");
if (RibbonServer.CONTROL_IS_PRESENT == false) {
RibbonServer.logAppend(RibbonServer.LOG_ID, 2, "ініційовано контроль системи!");
RibbonServer.CONTROL_IS_PRESENT = true;
}
}
CURR_SESSION.USER_NAME = parsedArgs[0];
CURR_SESSION.CURR_ENTRY = SessionManager.createSessionEntry(parsedArgs[0]);
CURR_SESSION.setSessionName();
return "OK:" + CURR_SESSION.CURR_ENTRY.SESSION_HASH_ID;
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_GET_ID", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.CURR_ENTRY != null) {
return "RIBBON_ERROR:Вхід не виконано!\nRIBBON_GCTL_FORCE_LOGIN:";
} else {
return CURR_SESSION.CURR_ENTRY.SESSION_HASH_ID;
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_RESUME", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
SessionManager.SessionEntry exicted = SessionManager.getUserBySessionEntry(args);
if (exicted == null) {
return "RIBBON_GCTL_FORCE_LOGIN:";
} else {
String returned = AccessHandler.PROC_RESUME_USER(exicted);
if (returned == null) {
SessionManager.reniewEntry(exicted);
CURR_SESSION.USER_NAME = exicted.SESSION_USER_NAME;
CURR_SESSION.CURR_ENTRY = exicted;
CURR_SESSION.setSessionName();
return "OK:";
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_REM_LOGIN", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!IS_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
} else if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
}
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 2);
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && (!AccessHandler.isUserAdmin(parsedArgs[0]))) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " не є адміністратором системи.\nRIBBON_GCTL_FORCE_LOGIN:";
}
String returned = AccessHandler.PROC_LOGIN_USER(parsedArgs[0], parsedArgs[1]);
if (returned == null) {
if (CURR_TYPE == CONNECTION_TYPES.CLIENT) {
RibbonServer.logAppend(LOG_ID, 3, "користувач " + parsedArgs[0] + " видалено увійшов до системи.");
} else if (CURR_TYPE == CONNECTION_TYPES.CONTROL) {
RibbonServer.logAppend(LOG_ID, 3, "адміністратор " + parsedArgs[0] + " видалено увійшов до системи.");
}
return "OK:";
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_GET_USERNAME", CONNECTION_TYPES.ANY) {
public String exec(String args) {
if (CURR_SESSION.USER_NAME != null) {
return "OK:" + CURR_SESSION.USER_NAME;
} else {
return "RIBBON_ERROR:Вхід до системи не виконано!";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_SET_REMOTE_MODE", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
} else if (!AccessHandler.isUserAdmin(CURR_SESSION.USER_NAME)) {
return "RIBBON_ERROR:Ця сессія не може використовувати видалений режим!";
}
IS_REMOTE = "1".equals(args) ? true : false;
return "OK:" + (IS_REMOTE ? "1" : "0");
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_ACCESS_CONTEXT", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
} else if (!IS_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
}
UserClasses.UserEntry overUser = AccessHandler.getEntryByName(Generic.CsvFormat.commonParseLine(args, 1)[0]);
if (overUser == null) {
return "RIBBON_ERROR:Користувача не знайдено!";
} else if (!overUser.IS_ENABLED) {
return "RIBBON_ERROR:Користувача заблоковано!";
}
String oldUserName = CURR_SESSION.USER_NAME;
CURR_SESSION.USER_NAME = overUser.USER_NAME;
CURR_SESSION.outStream.println("PROCEED:");
String subResult = null;
try {
subResult = process(CURR_SESSION.inStream.readLine());
} catch (java.io.IOException ex) {
RibbonServer.logAppend(LOG_ID, 1, "неможливо прочитати дані з сокету!");
SessionManager.closeSession(CURR_SESSION);
}
CURR_SESSION.USER_NAME = oldUserName;
return subResult;
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_CLOSE", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && SessionManager.hasOtherControl(CURR_SESSION) == false) {
RibbonServer.logAppend(RibbonServer.LOG_ID, 2, "контроль над системою завершено!");
RibbonServer.CONTROL_IS_PRESENT = false;
}
return "COMMIT_CLOSE:";
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_DIRS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Directories.PROC_GET_DIRS();
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_TAGS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Messenger.PROC_GET_TAGS();
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_LOAD_BASE_FROM_INDEX", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Messenger.PROC_LOAD_BASE_FROM_INDEX(args);
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_POST_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
MessageClasses.Message recievedMessage = new MessageClasses.Message();
recievedMessage.createMessageForPost(args);
recievedMessage.AUTHOR = CURR_SESSION.USER_NAME;
Boolean collectMessage = true;
StringBuffer messageBuffer = new StringBuffer();
String inLine;
while (collectMessage) {
try {
inLine = CURR_SESSION.inStream.readLine();
if (!inLine.equals("END:")) {
messageBuffer.append(inLine);
messageBuffer.append("\n");
} else {
collectMessage = false;
}
} catch (java.io.IOException ex) {
return "RIBBON_ERROR:Неможливо прочитати повідомлення з сокету!";
}
}
recievedMessage.CONTENT = messageBuffer.toString();
String answer = Procedures.PROC_POST_MESSAGE(recievedMessage);
if (answer.equals("OK:")) {
BROADCAST_TAIL = "RIBBON_UCTL_LOAD_INDEX:" + recievedMessage.returnEntry().toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
}
return answer;
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = args.split(",");
String givenDir = parsedArgs[0];
String givenIndex = parsedArgs[1];
StringBuffer returnedMessage = new StringBuffer();
if (AccessHandler.checkAccess(CURR_SESSION.USER_NAME, givenDir, 0) == false) {
return "RIBBON_ERROR:Помилка доступу до напрямку " + givenDir;
}
String dirPath = Directories.getDirPath(givenDir);
if (dirPath == null) {
return "RIBBON_ERROR:Напрямок " + givenDir + " не існує!";
} else {
try {
java.io.BufferedReader messageReader = new java.io.BufferedReader(new java.io.FileReader(dirPath + givenIndex));
while (messageReader.ready()) {
returnedMessage.append(messageReader.readLine());
returnedMessage.append("\n");
}
return returnedMessage.append("END:").toString();
} catch (java.io.FileNotFoundException ex) {
return "RIBBON_ERROR:Повідмолення не існує!";
} catch (java.io.IOException ex) {
RibbonServer.logAppend(LOG_ID, 1, "помилка зчитування повідомлення " + givenDir + ":" + givenIndex);
return "RIBBON_ERROR:Помилка виконання команди!";
}
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_MODIFY_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
StringBuffer messageBuffer = new StringBuffer();
String inLine;
Boolean collectMessage = true;
String[] parsedArgs = Generic.CsvFormat.splitCsv(args);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
MessageClasses.Message modTemplate = new MessageClasses.Message();
modTemplate.createMessageForModify(parsedArgs[1]);
while (collectMessage) {
try {
inLine = CURR_SESSION.inStream.readLine();
if (!inLine.equals("END:")) {
messageBuffer.append(inLine);
messageBuffer.append("\n");
} else {
collectMessage = false;
}
} catch (java.io.IOException ex) {
return "RIBBON_ERROR:Неможливо прочитати повідомлення з сокету!";
}
}
modTemplate.CONTENT = messageBuffer.toString();
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
Integer oldIntFlag = AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2);
Integer newIntFlag = AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, modTemplate.DIRS, 1);
if ((CURR_SESSION.USER_NAME.equals(matchedEntry.AUTHOR) && (newIntFlag == null)) || ((oldIntFlag == null) && (newIntFlag == null))) {
for (Integer dirIndex = 0; dirIndex < matchedEntry.DIRS.length; dirIndex++) {
if (AccessHandler.checkAccess(CURR_SESSION.USER_NAME, matchedEntry.DIRS[dirIndex], 1) == true) {
continue;
} else {
return "RIBBON_ERROR:Помилка доступу до напрямку " + matchedEntry.DIRS[dirIndex] + ".";
}
}
Procedures.PROC_MODIFY_MESSAGE(matchedEntry, modTemplate);
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
if (oldIntFlag != null) {
return "RIBBON_ERROR:Помилка доступу до напрямку " + matchedEntry.DIRS[oldIntFlag] + ".";
} else {
return "RIBBON_ERROR:Помилка доступу до напрямку " + modTemplate.DIRS[newIntFlag] + ".";
}
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_DELETE_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(args);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
} else {
if (matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) == null)) {
Procedures.PROC_DELETE_MESSAGE(matchedEntry);
BROADCAST_TAIL = "RIBBON_UCTL_DELETE_INDEX:" + matchedEntry.INDEX;
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_ADD_MESSAGE_PROPERTY", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 3);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
if ((matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) != null))) {
MessageClasses.MessageProperty newProp = new MessageClasses.MessageProperty(parsedArgs[1], CURR_SESSION.USER_NAME, parsedArgs[2], RibbonServer.getCurrentDate());
newProp.TYPE = parsedArgs[1];
newProp.TEXT_MESSAGE = parsedArgs[2];
newProp.DATE = RibbonServer.getCurrentDate();
newProp.USER = CURR_SESSION.USER_NAME;
matchedEntry.PROPERTIES.add(newProp);
IndexReader.updateBaseIndex();
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_DEL_MESSAGE_PROPERTY", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 3);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
if ((matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) != null))) {
MessageClasses.MessageProperty findedProp = null;
java.util.ListIterator<MessageClasses.MessageProperty> propIter = matchedEntry.PROPERTIES.listIterator();
while (propIter.hasNext()) {
MessageClasses.MessageProperty currProp = propIter.next();
if (currProp.TYPE.equals(parsedArgs[1]) && currProp.DATE.equals(parsedArgs[2])) {
findedProp = currProp;
break;
}
}
if (findedProp != null) {
matchedEntry.PROPERTIES.remove(findedProp);
IndexReader.updateBaseIndex();
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Системної ознаки не існує!";
}
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
});
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_USERS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return AccessHandler.PROC_GET_USERS_UNI(false);
}
});
}
|
protected String doTemplateRequest(Melati melati, ServletTemplateContext context)
throws Exception {
ContactsDatabase db = (ContactsDatabase)melati.getDatabase();
Contact contact = (Contact)melati.getObject();
if (melati.getMethod().equals("Insert")) {
contact = (Contact)db.getContactTable().newPersistent();
}
else if (melati.getMethod().equals("Update")) {
if (contact == null) {
contact = (Contact) db.getContactTable().newPersistent();
Form.extractFields(melati.getServletTemplateContext(),contact);
db.getContactTable().create(contact);
} else {
Form.extractFields(melati.getServletTemplateContext(),contact);
}
deleteCategories(db,contact);
String[] categories = melati.getRequest().
getParameterValues("field_category");
if (categories != null) {
for (int i=0; i< categories.length; i++) {
ContactCategory cat =
(ContactCategory)db.getContactCategoryTable().newPersistent();
cat.setContact(contact);
cat.setCategoryTroid(new Integer(categories[i]));
db.getContactCategoryTable().create(cat);
}
}
try {
melati.getResponse().sendRedirect
("/melati/org.melati.example.contacts.Search/contacts");
} catch (IOException e) {
throw new Exception(e.toString());
}
return null;
}
else if (melati.getMethod().equals("Delete")) {
deleteCategories(db,contact);
contact.deleteAndCommit();
try {
melati.getResponse().sendRedirect
("/melati/org.melati.example.contacts.Search/contacts");
} catch (IOException e) {
throw new Exception(e.toString());
}
return null;
}
else if (melati.getMethod().equals("View")) {
return "org/melati/example/contacts/ContactView";
}
else {
throw new Exception("Invalid Method");
}
context.put("contact",contact);
context.put("categories",db.getCategoryTable().selection());
return "org/melati/example/contacts/ContactView";
}
|
protected String doTemplateRequest(Melati melati, ServletTemplateContext context)
throws Exception {
ContactsDatabase db = (ContactsDatabase)melati.getDatabase();
Contact contact = (Contact)melati.getObject();
if (melati.getMethod().equals("Insert")) {
contact = (Contact)db.getContactTable().newPersistent();
}
else if (melati.getMethod().equals("Update")) {
if (contact == null) {
contact = (Contact) db.getContactTable().newPersistent();
Form.extractFields(melati.getServletTemplateContext(),contact);
db.getContactTable().create(contact);
} else {
Form.extractFields(melati.getServletTemplateContext(),contact);
}
deleteCategories(db,contact);
String[] categories = melati.getRequest().
getParameterValues("field_category");
if (categories != null) {
for (int i=0; i< categories.length; i++) {
ContactCategory cat =
(ContactCategory)db.getContactCategoryTable().newPersistent();
cat.setContact(contact);
cat.setCategoryTroid(new Integer(categories[i]));
db.getContactCategoryTable().create(cat);
}
}
try {
melati.getResponse().sendRedirect
("/melati/org.melati.example.contacts.Search/contacts");
} catch (IOException e) {
throw new Exception(e.toString());
}
return null;
}
else if (melati.getMethod().equals("Delete")) {
deleteCategories(db,contact);
contact.deleteAndCommit();
try {
melati.getResponse().sendRedirect
("/melati/org.melati.example.contacts.Search/contacts");
} catch (IOException e) {
throw new Exception(e.toString());
}
return null;
}
else if (melati.getMethod().equals("View")) {
}
else {
throw new Exception("Invalid Method");
}
context.put("contact",contact);
context.put("categories",db.getCategoryTable().selection());
return "org/melati/example/contacts/ContactView";
}
|
public @Override void keyTyped(char _char, int _code) {
this.waitingOnPlayerNames = false;
if(_code == Keyboard.KEY_TAB) this.completePlayerName();
else this.playerNamesFound = false;
if(_code != Keyboard.KEY_TAB) this.playerNamesFound = false;
switch (_code) {
case Keyboard.KEY_TAB:
if(GuiScreen.isCtrlKeyDown()) {
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
tc.activatePrev();
} else tc.activateNext();
break;
}
this.completePlayerName();
break;
case Keyboard.KEY_ESCAPE:
this.mc.displayGuiScreen((GuiScreen)null);
break;
case Keyboard.KEY_RETURN:
StringBuilder _msg = new StringBuilder(1500);
for(int i=this.inputList.size()-1; i>=0; i--) _msg.append(this.inputList.get(i).getText());
if(_msg.toString().length() > 0) {
TabbyChatUtils.writeLargeChat(_msg.toString());
for(int i=1; i<this.inputList.size(); i++) {
this.inputList.get(i).setText("");
this.inputList.get(i).setVisible(false);
}
}
this.mc.displayGuiScreen((GuiScreen)null);
break;
case Keyboard.KEY_UP:
if(GuiScreen.isCtrlKeyDown()) this.getSentHistory(-1);
else {
int foc = this.getFocusedFieldInd();
if(foc+1 < this.inputList.size() && this.inputList.get(foc+1).getVisible()) {
int gcp = this.inputList.get(foc).getCursorPosition();
int lng = this.inputList.get(foc+1).getText().length();
int newPos = Math.min(gcp, lng);
this.inputList.get(foc).setFocused(false);
this.inputList.get(foc+1).setFocused(true);
this.inputList.get(foc+1).setCursorPosition(newPos);
} else this.getSentHistory(-1);
}
break;
case Keyboard.KEY_DOWN:
if(GuiScreen.isCtrlKeyDown()) this.getSentHistory(1);
else {
int foc = this.getFocusedFieldInd();
if(foc-1 >= 0 && this.inputList.get(foc-1).getVisible()) {
int gcp = this.inputList.get(foc).getCursorPosition();
int lng = this.inputList.get(foc-1).getText().length();
int newPos = Math.min(gcp, lng);
this.inputList.get(foc).setFocused(false);
this.inputList.get(foc-1).setFocused(true);
this.inputList.get(foc-1).setCursorPosition(newPos);
} else this.getSentHistory(1);
}
break;
case Keyboard.KEY_PRIOR:
this.gnc.scroll(19);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
break;
case Keyboard.KEY_NEXT:
this.gnc.scroll(-19);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
break;
case Keyboard.KEY_BACK:
if(this.inputField.isFocused() && this.inputField.getCursorPosition() > 0) this.inputField.textboxKeyTyped(_char, _code);
else this.removeCharsAtCursor(-1);
break;
case Keyboard.KEY_DELETE:
if(this.inputField.isFocused()) this.inputField.textboxKeyTyped(_char, _code);
else this.removeCharsAtCursor(1);
break;
case Keyboard.KEY_LEFT:
case Keyboard.KEY_RIGHT:
this.inputList.get(this.getFocusedFieldInd()).textboxKeyTyped(_char, _code);
break;
default:
if(GuiScreen.isCtrlKeyDown()) {
if(_code > 1 && _code < 12) {
tc.activateIndex(_code-1);
} else if(_code == Keyboard.KEY_O) {
this.mc.displayGuiScreen(this.tc.generalSettings);
} else {
this.inputField.textboxKeyTyped(_char, _code);
}
} else if(this.inputField.isFocused() && this.fontRenderer.getStringWidth(this.inputField.getText()) < sr.getScaledWidth()-20) {
this.inputField.textboxKeyTyped(_char, _code);
} else {
this.insertCharsAtCursor(Character.toString(_char));
}
}
}
|
public @Override void keyTyped(char _char, int _code) {
this.waitingOnPlayerNames = false;
if(_code != Keyboard.KEY_TAB) this.playerNamesFound = false;
switch (_code) {
case Keyboard.KEY_TAB:
if(GuiScreen.isCtrlKeyDown()) {
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
tc.activatePrev();
} else tc.activateNext();
break;
}
this.completePlayerName();
break;
case Keyboard.KEY_ESCAPE:
this.mc.displayGuiScreen((GuiScreen)null);
break;
case Keyboard.KEY_RETURN:
StringBuilder _msg = new StringBuilder(1500);
for(int i=this.inputList.size()-1; i>=0; i--) _msg.append(this.inputList.get(i).getText());
if(_msg.toString().length() > 0) {
TabbyChatUtils.writeLargeChat(_msg.toString());
for(int i=1; i<this.inputList.size(); i++) {
this.inputList.get(i).setText("");
this.inputList.get(i).setVisible(false);
}
}
this.mc.displayGuiScreen((GuiScreen)null);
break;
case Keyboard.KEY_UP:
if(GuiScreen.isCtrlKeyDown()) this.getSentHistory(-1);
else {
int foc = this.getFocusedFieldInd();
if(foc+1 < this.inputList.size() && this.inputList.get(foc+1).getVisible()) {
int gcp = this.inputList.get(foc).getCursorPosition();
int lng = this.inputList.get(foc+1).getText().length();
int newPos = Math.min(gcp, lng);
this.inputList.get(foc).setFocused(false);
this.inputList.get(foc+1).setFocused(true);
this.inputList.get(foc+1).setCursorPosition(newPos);
} else this.getSentHistory(-1);
}
break;
case Keyboard.KEY_DOWN:
if(GuiScreen.isCtrlKeyDown()) this.getSentHistory(1);
else {
int foc = this.getFocusedFieldInd();
if(foc-1 >= 0 && this.inputList.get(foc-1).getVisible()) {
int gcp = this.inputList.get(foc).getCursorPosition();
int lng = this.inputList.get(foc-1).getText().length();
int newPos = Math.min(gcp, lng);
this.inputList.get(foc).setFocused(false);
this.inputList.get(foc-1).setFocused(true);
this.inputList.get(foc-1).setCursorPosition(newPos);
} else this.getSentHistory(1);
}
break;
case Keyboard.KEY_PRIOR:
this.gnc.scroll(19);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
break;
case Keyboard.KEY_NEXT:
this.gnc.scroll(-19);
if(this.tc.enabled()) this.scrollBar.scrollBarMouseWheel();
break;
case Keyboard.KEY_BACK:
if(this.inputField.isFocused() && this.inputField.getCursorPosition() > 0) this.inputField.textboxKeyTyped(_char, _code);
else this.removeCharsAtCursor(-1);
break;
case Keyboard.KEY_DELETE:
if(this.inputField.isFocused()) this.inputField.textboxKeyTyped(_char, _code);
else this.removeCharsAtCursor(1);
break;
case Keyboard.KEY_LEFT:
case Keyboard.KEY_RIGHT:
this.inputList.get(this.getFocusedFieldInd()).textboxKeyTyped(_char, _code);
break;
default:
if(GuiScreen.isCtrlKeyDown()) {
if(_code > 1 && _code < 12) {
tc.activateIndex(_code-1);
} else if(_code == Keyboard.KEY_O) {
this.mc.displayGuiScreen(this.tc.generalSettings);
} else {
this.inputField.textboxKeyTyped(_char, _code);
}
} else if(this.inputField.isFocused() && this.fontRenderer.getStringWidth(this.inputField.getText()) < sr.getScaledWidth()-20) {
this.inputField.textboxKeyTyped(_char, _code);
} else {
this.insertCharsAtCursor(Character.toString(_char));
}
}
}
|
private void initComponents() {
jFrame1 = new javax.swing.JFrame();
jButton1 = new javax.swing.JButton();
jSpinner1 = new javax.swing.JSpinner(new SpinnerNumberModel(10, 4, 15, 1));
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jComboBox2 = new javax.swing.JComboBox();
jDialog1 = new javax.swing.JDialog();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jButton2 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton1.setText("OK !");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jSpinner1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jSpinner1MousePressed(evt);
}
});
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Human", "Random AI", "Select AI" }));
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Human", "Random AI", "Select AI" }));
jLabel1.setText("size of map");
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addGroup(jFrame1Layout.createSequentialGroup()
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))))))
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
jFileChooser1.setName("");
javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
jDialog1.getContentPane().setLayout(jDialog1Layout);
jDialog1Layout.setHorizontalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog1Layout.setVerticalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Hex Game");
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 324, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 445, Short.MAX_VALUE)
);
jButton2.setText("New Game");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton4.setText("Undo");
jButton4.setEnabled(false);
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton3.setText("Exit");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addContainerGap(226, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(12, 12, 12))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}
|
private void initComponents() {
jFrame1 = new javax.swing.JFrame();
jButton1 = new javax.swing.JButton();
jSpinner1 = new javax.swing.JSpinner(new SpinnerNumberModel(10, 4, 15, 1));
jFileChooser1 = new JFileChooser();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jComboBox2 = new javax.swing.JComboBox();
jDialog1 = new javax.swing.JDialog();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jButton2 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton1.setText("OK !");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jSpinner1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jSpinner1MousePressed(evt);
}
});
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Human", "Random AI", "Select AI" }));
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Human", "Random AI", "Select AI" }));
jLabel1.setText("size of map");
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addGroup(jFrame1Layout.createSequentialGroup()
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))))))
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
jFileChooser1.setName("");
javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
jDialog1.getContentPane().setLayout(jDialog1Layout);
jDialog1Layout.setHorizontalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog1Layout.setVerticalGroup(
jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Hex Game");
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 324, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 445, Short.MAX_VALUE)
);
jButton2.setText("New Game");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton4.setText("Undo");
jButton4.setEnabled(false);
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton3.setText("Exit");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addContainerGap(226, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(12, 12, 12))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}
|
public SearchPage(final PageParameters parameters)
{
add( new BookmarkablePageLink<Void>( "playground", PlaygroundPage.class ) );
Form<Query> searchForm = new Form<Query>( "search", new CompoundPropertyModel<Query>(query) );
searchForm.add( new DropDownChoice<String>("source",
Arrays.asList( "(all)",
"world-cities-points.txt",
"countries-poly.txt",
"countries-bbox.txt",
"states-poly.txt",
"states-bbox.txt" ) ));
searchForm.add( new TextField<String>( "fq" ) );
searchForm.add( new DropDownChoice<String>("field",
Arrays.asList( "geo", "ptvector", "bbox", "quad", "geohash" ) ));
searchForm.add( new DropDownChoice<SpatialOperation>("op",
SpatialOperation.values() ));
searchForm.add( new TextField<String>( "geo" ) );
searchForm.add( new IndicatingAjaxButton( "submit" ) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
target.addComponent( results );
}
});
searchForm.add( new CheckBox( "score" ) );
searchForm.add( new TextField<String>( "distErrPct" ) );
searchForm.add( new TextField<String>( "sort" ) );
add( searchForm );
queryResponse = new LoadableDetachableModel<QueryResponse>() {
@Override
protected QueryResponse load() {
long now = System.currentTimeMillis();
QueryResponse rsp = null;
error.setObject( null );
try {
rsp = solr.query( query.getObject().toSolrQuery( 100 ) );
}
catch (SolrServerException ex) {
Throwable t = ex.getCause();
if( t == null ) {
t = ex;
}
log.warn( "unable to execute query", ex );
error.setObject( Throwables.getStackTraceAsString(t) );
}
catch (Throwable ex) {
log.warn( "unable to execute query", ex );
error.setObject( Throwables.getStackTraceAsString(ex) );
}
elapsed.setObject( System.currentTimeMillis()-now );
return rsp;
}
};
results = new WebMarkupContainer( "results", queryResponse ) {
@Override
protected void onBeforeRender()
{
RepeatingView rv = new RepeatingView( "item" );
replace( rv );
QueryResponse rsp = queryResponse.getObject();
if( rsp != null ) {
for( SolrDocument doc : rsp.getResults() ) {
final String id = (String)doc.getFieldValue( "id" );
WebMarkupContainer row = new WebMarkupContainer( rv.newChildId() );
row.add( new Label( "name", doc.getFieldValue( "id" ) + " - " + doc.getFieldValue( "name" ) ) );
row.add( new Label( "source", (String)doc.getFieldValue( "source" ) ));
row.add( new Label( "score", doc.getFieldValue( "score" )+"" ));
row.add( new ExternalLink( "link", "/solr/select?q=id:"+ClientUtils.escapeQueryChars(id) ));
row.add( addKmlLink( "kml", id, "geohash" ));
rv.add( row );
}
}
super.onBeforeRender();
}
};
results.setOutputMarkupId( true );
results.add( new WebMarkupContainer( "item" ) );
results.add( new Label("count", new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
QueryResponse rsp = queryResponse.getObject();
String v = null;
if( rsp == null ) {
v = "unable to execute query";
}
else {
SolrDocumentList docs = rsp.getResults();
v = docs.getStart() + " - " + (docs.getStart()+docs.size()) + " of " + docs.getNumFound();
}
v += " ["+DurationFormatUtils.formatDurationHMS(elapsed.getObject())+"]";
return v;
}
}));
results.add( new Label( "solr", new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
SolrParams params = query.getObject().toSolrQuery( 10 );
return params.get( "q" );
}
}).add( new AttributeModifier( "href", true, new AbstractReadOnlyModel<CharSequence>() {
@Override
public CharSequence getObject() {
StringBuilder url = new StringBuilder();
url.append( "http://localhost:8080/solr/select?debugQuery=true" );
SolrParams params = query.getObject().toSolrQuery( 10 );
for(Iterator<String> it=params.getParameterNamesIterator(); it.hasNext(); ) {
final String name = it.next();
try {
final String [] values = params.getParams(name);
if( values.length > 0 ) {
for( String v : values ) {
url.append( "&"+URLEncoder.encode( name, "UTF-8" ) );
url.append( '=' );
url.append( URLEncoder.encode( v, "UTF-8" ) );
}
}
else {
url.append( "&"+URLEncoder.encode( name, "UTF-8" ) );
}
}
catch( Exception ex ) {
ex.printStackTrace();
}
}
return url;
}
})));
results.add( new Label( "error", error ) {
@Override
public boolean isVisible() {
return error.getObject() != null;
}
});
add( results );
final WebMarkupContainer load = new WebMarkupContainer( "load" );
load.setOutputMarkupId( true );
load.add( new IndicatingAjaxLink<Void>( "link" ) {
@Override
public void onClick(AjaxRequestTarget target) {
pool.execute( new Runnable() {
@Override
public void run() {
try {
File data = WicketApplication.getDataDir();
SolrServer sss = new ConcurrentUpdateSolrServer(
"http://localhost:8080/solr", 20, 3 );
if(false) {
sss = solr;
}
loader.loadSampleData( data, sss );
}
catch (Exception e) {
e.printStackTrace();
}
}
});
load.add( new AbstractAjaxTimerBehavior( Duration.seconds(1) ) {
@Override
protected void onTimer(AjaxRequestTarget target) {
System.out.println( "running: "+loader.status );
if( !loader.running ) {
this.stop();
setResponsePage( getPage() );
}
target.addComponent( load );
}
});
try {
Thread.sleep( 100 );
} catch (InterruptedException e) {
return;
}
target.addComponent( load );
}
@Override
public boolean isVisible() {
return !loader.running;
}
});
WebMarkupContainer status = new WebMarkupContainer( "status" ) {
@Override
public boolean isVisible() {
return loader.running;
}
};
load.add( status );
status.add( new Label( "history", new AbstractReadOnlyModel<CharSequence>() {
@Override
public CharSequence getObject() {
StringBuilder str = new StringBuilder();
for( String line : loader.history ) {
str.append( line ).append( "\n" );
}
return str;
}
}));
status.add( new Label( "status", new AbstractReadOnlyModel<CharSequence>() {
@Override
public CharSequence getObject() {
return "Loading: "+loader.name+" ("+loader.count + ") " + loader.status;
}
}));
add( load );
}
|
public SearchPage(final PageParameters parameters)
{
add( new BookmarkablePageLink<Void>( "playground", PlaygroundPage.class ) );
Form<Query> searchForm = new Form<Query>( "search", new CompoundPropertyModel<Query>(query) );
searchForm.add( new DropDownChoice<String>("source",
Arrays.asList( "(all)",
"world-cities-points.txt",
"countries-poly.txt",
"countries-bbox.txt",
"states-poly.txt",
"states-bbox.txt" ) ));
searchForm.add( new TextField<String>( "fq" ) );
searchForm.add( new DropDownChoice<String>("field",
Arrays.asList( "geo", "ptvector", "bbox", "quad", "geohash" ) ));
searchForm.add( new DropDownChoice<SpatialOperation>("op",
SpatialOperation.values() ));
searchForm.add( new TextField<String>( "geo" ) );
searchForm.add( new IndicatingAjaxButton( "submit" ) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
target.addComponent( results );
}
});
searchForm.add( new CheckBox( "score" ) );
searchForm.add( new TextField<String>( "distErrPct" ) );
searchForm.add( new TextField<String>( "sort" ) );
add( searchForm );
queryResponse = new LoadableDetachableModel<QueryResponse>() {
@Override
protected QueryResponse load() {
long now = System.currentTimeMillis();
QueryResponse rsp = null;
error.setObject( null );
try {
rsp = solr.query( query.getObject().toSolrQuery( 100 ) );
}
catch (SolrServerException ex) {
Throwable t = ex.getCause();
if( t == null ) {
t = ex;
}
log.warn( "unable to execute query", ex );
error.setObject( Throwables.getStackTraceAsString(t) );
}
catch (Throwable ex) {
log.warn( "unable to execute query", ex );
error.setObject( Throwables.getStackTraceAsString(ex) );
}
elapsed.setObject( System.currentTimeMillis()-now );
return rsp;
}
};
results = new WebMarkupContainer( "results", queryResponse ) {
@Override
protected void onBeforeRender()
{
RepeatingView rv = new RepeatingView( "item" );
replace( rv );
QueryResponse rsp = queryResponse.getObject();
if( rsp != null ) {
for( SolrDocument doc : rsp.getResults() ) {
final String id = (String)doc.getFieldValue( "id" );
WebMarkupContainer row = new WebMarkupContainer( rv.newChildId() );
row.add( new Label( "name", doc.getFieldValue( "id" ) + " - " + doc.getFieldValue( "name" ) ) );
row.add( new Label( "source", (String)doc.getFieldValue( "source" ) ));
row.add( new Label( "score", doc.getFieldValue( "score" )+"" ));
row.add( new ExternalLink( "link", "/solr/select?q=id:"+ClientUtils.escapeQueryChars(id) ));
row.add( addKmlLink( "kml", id, "shape" ));
rv.add( row );
}
}
super.onBeforeRender();
}
};
results.setOutputMarkupId( true );
results.add( new WebMarkupContainer( "item" ) );
results.add( new Label("count", new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
QueryResponse rsp = queryResponse.getObject();
String v = null;
if( rsp == null ) {
v = "unable to execute query";
}
else {
SolrDocumentList docs = rsp.getResults();
v = docs.getStart() + " - " + (docs.getStart()+docs.size()) + " of " + docs.getNumFound();
}
v += " ["+DurationFormatUtils.formatDurationHMS(elapsed.getObject())+"]";
return v;
}
}));
results.add( new Label( "solr", new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
SolrParams params = query.getObject().toSolrQuery( 10 );
return params.get( "q" );
}
}).add( new AttributeModifier( "href", true, new AbstractReadOnlyModel<CharSequence>() {
@Override
public CharSequence getObject() {
StringBuilder url = new StringBuilder();
url.append( "http://localhost:8080/solr/select?debugQuery=true" );
SolrParams params = query.getObject().toSolrQuery( 10 );
for(Iterator<String> it=params.getParameterNamesIterator(); it.hasNext(); ) {
final String name = it.next();
try {
final String [] values = params.getParams(name);
if( values.length > 0 ) {
for( String v : values ) {
url.append( "&"+URLEncoder.encode( name, "UTF-8" ) );
url.append( '=' );
url.append( URLEncoder.encode( v, "UTF-8" ) );
}
}
else {
url.append( "&"+URLEncoder.encode( name, "UTF-8" ) );
}
}
catch( Exception ex ) {
ex.printStackTrace();
}
}
return url;
}
})));
results.add( new Label( "error", error ) {
@Override
public boolean isVisible() {
return error.getObject() != null;
}
});
add( results );
final WebMarkupContainer load = new WebMarkupContainer( "load" );
load.setOutputMarkupId( true );
load.add( new IndicatingAjaxLink<Void>( "link" ) {
@Override
public void onClick(AjaxRequestTarget target) {
pool.execute( new Runnable() {
@Override
public void run() {
try {
File data = WicketApplication.getDataDir();
SolrServer sss = new ConcurrentUpdateSolrServer(
"http://localhost:8080/solr", 20, 3 );
if(false) {
sss = solr;
}
loader.loadSampleData( data, sss );
}
catch (Exception e) {
e.printStackTrace();
}
}
});
load.add( new AbstractAjaxTimerBehavior( Duration.seconds(1) ) {
@Override
protected void onTimer(AjaxRequestTarget target) {
System.out.println( "running: "+loader.status );
if( !loader.running ) {
this.stop();
setResponsePage( getPage() );
}
target.addComponent( load );
}
});
try {
Thread.sleep( 100 );
} catch (InterruptedException e) {
return;
}
target.addComponent( load );
}
@Override
public boolean isVisible() {
return !loader.running;
}
});
WebMarkupContainer status = new WebMarkupContainer( "status" ) {
@Override
public boolean isVisible() {
return loader.running;
}
};
load.add( status );
status.add( new Label( "history", new AbstractReadOnlyModel<CharSequence>() {
@Override
public CharSequence getObject() {
StringBuilder str = new StringBuilder();
for( String line : loader.history ) {
str.append( line ).append( "\n" );
}
return str;
}
}));
status.add( new Label( "status", new AbstractReadOnlyModel<CharSequence>() {
@Override
public CharSequence getObject() {
return "Loading: "+loader.name+" ("+loader.count + ") " + loader.status;
}
}));
add( load );
}
|
private void addExecuteMethod(JavaComposite sc) {
sc.add("public Object execute(" + EXECUTION_EVENT(sc) + " event) throws " + EXECUTION_EXCEPTION(sc) + " {");
sc.add(I_EDITOR_PART(sc) + " editorPart = " + HANDLER_UTIL(sc) + ".getActiveEditor(event);");
sc.add(editorClassName + " editor = null;");
sc.addLineBreak();
sc.add("if (editorPart instanceof " + editorClassName + ") {");
sc.add("editor = (" + editorClassName + ") editorPart;");
sc.add("operationTarget = (" + I_TEXT_OPERATION_TARGET(sc) + ") editorPart.getAdapter(" + I_TEXT_OPERATION_TARGET(sc) + ".class);");
sc.add("document = editor.getDocumentProvider().getDocument(editor.getEditorInput());");
sc.add("}");
sc.add("if (editor == null || operationTarget == null || document == null) {");
sc.add("return null;");
sc.add("}");
sc.addLineBreak();
sc.add("prefixesMap = new " + LINKED_HASH_MAP + "<String, String[]>();");
sc.add("prefixesMap.put(" + I_DOCUMENT(sc) + ".DEFAULT_CONTENT_TYPE, COMMENT_PREFIXES);");
sc.addLineBreak();
sc.add(I_SELECTION(sc) + " currentSelection = " + HANDLER_UTIL(sc) + ".getCurrentSelection(event);");
sc.add("final int operationCode;");
sc.add("if (isSelectionCommented(currentSelection)) {");
sc.add("operationCode = " + I_TEXT_OPERATION_TARGET(sc) + ".STRIP_PREFIX;");
sc.add("} else {");
sc.add("operationCode = " + I_TEXT_OPERATION_TARGET(sc) + ".PREFIX;");
sc.add("}");
sc.addLineBreak();
sc.add("if (!operationTarget.canDoOperation(operationCode)) {");
sc.add("return null;");
sc.add("}");
sc.addLineBreak();
sc.add(SHELL(sc) + " shell = editorPart.getSite().getShell();");
sc.add(DISPLAY(sc) + " display = null;");
sc.add("if (shell != null && !shell.isDisposed()) {");
sc.add("display = shell.getDisplay();");
sc.add("}");
sc.addLineBreak();
sc.add(BUSY_INDICATOR(sc) + ".showWhile(display, new Runnable() {");
sc.add("public void run() {");
sc.add("operationTarget.doOperation(operationCode);");
sc.add("}");
sc.add("});");
sc.addLineBreak();
sc.add("return null;");
sc.add("}");
sc.addLineBreak();
}
|
private void addExecuteMethod(JavaComposite sc) {
sc.add("public Object execute(" + EXECUTION_EVENT(sc) + " event) throws " + EXECUTION_EXCEPTION(sc) + " {");
sc.add(I_EDITOR_PART(sc) + " editorPart = " + HANDLER_UTIL(sc) + ".getActiveEditor(event);");
sc.add(editorClassName + " editor = null;");
sc.addLineBreak();
sc.add("if (editorPart instanceof " + editorClassName + ") {");
sc.add("editor = (" + editorClassName + ") editorPart;");
sc.add("operationTarget = (" + I_TEXT_OPERATION_TARGET(sc) + ") editorPart.getAdapter(" + I_TEXT_OPERATION_TARGET(sc) + ".class);");
sc.add("document = editor.getDocumentProvider().getDocument(editor.getEditorInput());");
sc.add("}");
sc.add("if (editor == null || operationTarget == null || document == null) {");
sc.add("return null;");
sc.add("}");
sc.addLineBreak();
sc.add("prefixesMap = new " + LINKED_HASH_MAP + "<String, String[]>();");
sc.add("prefixesMap.put(" + I_DOCUMENT(sc) + ".DEFAULT_CONTENT_TYPE, COMMENT_PREFIXES);");
sc.addLineBreak();
sc.add(I_SELECTION(sc) + " currentSelection = editor.getSelectionProvider().getSelection();");
sc.add("final int operationCode;");
sc.add("if (isSelectionCommented(currentSelection)) {");
sc.add("operationCode = " + I_TEXT_OPERATION_TARGET(sc) + ".STRIP_PREFIX;");
sc.add("} else {");
sc.add("operationCode = " + I_TEXT_OPERATION_TARGET(sc) + ".PREFIX;");
sc.add("}");
sc.addLineBreak();
sc.add("if (!operationTarget.canDoOperation(operationCode)) {");
sc.add("return null;");
sc.add("}");
sc.addLineBreak();
sc.add(SHELL(sc) + " shell = editorPart.getSite().getShell();");
sc.add(DISPLAY(sc) + " display = null;");
sc.add("if (shell != null && !shell.isDisposed()) {");
sc.add("display = shell.getDisplay();");
sc.add("}");
sc.addLineBreak();
sc.add(BUSY_INDICATOR(sc) + ".showWhile(display, new Runnable() {");
sc.add("public void run() {");
sc.add("operationTarget.doOperation(operationCode);");
sc.add("}");
sc.add("});");
sc.addLineBreak();
sc.add("return null;");
sc.add("}");
sc.addLineBreak();
}
|
private void createAppletApplication() {
try {
Class sweetHome3DAppletClass = SweetHome3DApplet.class;
List java3DFiles = new ArrayList(Arrays.asList(new String [] {
"j3dcore.jar",
"vecmath.jar",
"j3dutils.jar",
"macosx/gluegen-rt.jar",
"macosx/jogl.jar",
"macosx/libgluegen-rt.jnilib",
"macosx/libjogl.jnilib",
"macosx/libjogl_awt.jnilib",
"macosx/libjogl_cg.jnilib"}));
if ("64".equals(System.getProperty("sun.arch.data.model"))) {
java3DFiles.add("linux/x64/libj3dcore-ogl.so");
java3DFiles.add("windows/x64/j3dcore-ogl.dll");
} else {
java3DFiles.add("linux/i386/libj3dcore-ogl.so");
java3DFiles.add("linux/i386/libj3dcore-ogl-cg.so");
java3DFiles.add("windows/i386/j3dcore-d3d.dll");
java3DFiles.add("windows/i386/j3dcore-ogl.dll");
java3DFiles.add("windows/i386/j3dcore-ogl-cg.dll");
java3DFiles.add("windows/i386/j3dcore-ogl-chk.dll");
}
List applicationPackages = new ArrayList(Arrays.asList(new String [] {
"com.eteks.sweethome3d",
"javax.media",
"javax.vecmath",
"com.sun.j3d",
"com.sun.opengl",
"com.sun.gluegen.runtime",
"javax.media.opengl",
"com.sun.media",
"com.ibm.media",
"jmpapps.util",
"com.microcrowd.loader.java3d",
"org.sunflow"}));
applicationPackages.addAll(getPluginsPackages());
String applicationClassName = getApplicationClassName();
if (!applicationClassName.startsWith((String)applicationPackages.get(0))) {
String [] applicationClassParts = applicationClassName.split("\\.");
String applicationClassPackageBase = "";
for (int i = 0, n = Math.min(applicationClassParts.length - 1, 2); i < n; i++) {
if (i > 0) {
applicationClassPackageBase += ".";
}
applicationClassPackageBase += applicationClassParts [i];
}
applicationPackages.add(applicationClassPackageBase);
}
ClassLoader extensionsClassLoader = new ExtensionsClassLoader(
sweetHome3DAppletClass.getClassLoader(), sweetHome3DAppletClass.getProtectionDomain(),
(String [])java3DFiles.toArray(new String [java3DFiles.size()]),
(String [])applicationPackages.toArray(new String [applicationPackages.size()]));
Class applicationClass = extensionsClassLoader.loadClass(applicationClassName);
Constructor applicationConstructor =
applicationClass.getConstructor(new Class [] {JApplet.class});
this.appletApplication = applicationConstructor.newInstance(new Object [] {this});
} catch (Throwable ex) {
if (ex instanceof AccessControlException) {
showError(getLocalizedString("signatureError"));
} else {
showError("<html>" + getLocalizedString("startError")
+ "<br>Exception" + ex.getClass().getName() + " " + ex.getMessage());
ex.printStackTrace();
}
}
}
|
private void createAppletApplication() {
try {
Class sweetHome3DAppletClass = SweetHome3DApplet.class;
List java3DFiles = new ArrayList(Arrays.asList(new String [] {
"j3dcore.jar",
"vecmath.jar",
"j3dutils.jar",
"macosx/gluegen-rt.jar",
"macosx/jogl.jar",
"macosx/libgluegen-rt.jnilib",
"macosx/libjogl.jnilib",
"macosx/libjogl_awt.jnilib",
"macosx/libjogl_cg.jnilib"}));
if ("64".equals(System.getProperty("sun.arch.data.model"))) {
java3DFiles.add("linux/x64/libj3dcore-ogl.so");
java3DFiles.add("windows/x64/j3dcore-ogl.dll");
} else {
java3DFiles.add("linux/i386/libj3dcore-ogl.so");
java3DFiles.add("linux/i386/libj3dcore-ogl-cg.so");
java3DFiles.add("windows/i386/j3dcore-d3d.dll");
java3DFiles.add("windows/i386/j3dcore-ogl.dll");
java3DFiles.add("windows/i386/j3dcore-ogl-cg.dll");
java3DFiles.add("windows/i386/j3dcore-ogl-chk.dll");
}
List applicationPackages = new ArrayList(Arrays.asList(new String [] {
"com.eteks.sweethome3d",
"javax.media",
"javax.vecmath",
"com.sun.j3d",
"com.sun.opengl",
"com.sun.gluegen.runtime",
"javax.media.opengl",
"com.sun.media",
"com.ibm.media",
"jmpapps.util",
"com.microcrowd.loader.java3d",
"org.sunflow"}));
applicationPackages.addAll(getPluginsPackages());
String applicationClassName = getApplicationClassName();
if (!applicationClassName.startsWith((String)applicationPackages.get(0))) {
String [] applicationClassParts = applicationClassName.split("\\.");
String applicationClassPackageBase = "";
for (int i = 0, n = Math.min(applicationClassParts.length - 1, 2); i < n; i++) {
if (i > 0) {
applicationClassPackageBase += ".";
}
applicationClassPackageBase += applicationClassParts [i];
}
applicationPackages.add(applicationClassPackageBase);
}
ClassLoader extensionsClassLoader = new ExtensionsClassLoader(
sweetHome3DAppletClass.getClassLoader(), sweetHome3DAppletClass.getProtectionDomain(),
(String [])java3DFiles.toArray(new String [java3DFiles.size()]),
(String [])applicationPackages.toArray(new String [applicationPackages.size()]));
Class applicationClass = extensionsClassLoader.loadClass(applicationClassName);
Constructor applicationConstructor =
applicationClass.getConstructor(new Class [] {JApplet.class});
this.appletApplication = applicationConstructor.newInstance(new Object [] {this});
} catch (Throwable ex) {
if (ex instanceof AccessControlException) {
showError(getLocalizedString("signatureError"));
} else {
showError("<html>" + getLocalizedString("startError")
+ "<br>Exception " + ex.getClass().getName()
+ (ex.getMessage() != null ? " " + ex.getMessage() : ""));
ex.printStackTrace();
}
}
}
|
private String getCommonPattern(String message1, String message2) {
if (message1.equals(message2)) {
return PatternUtils.simpleToRegexp(message1);
}
if (message1.isEmpty() || message2.isEmpty()) {
return null;
}
int noMatchStart = -1;
int separatorPosition = 0;
boolean doMatch = true;
boolean oneStartsWithOther = false;
while (doMatch) {
noMatchStart++;
if (noMatchStart >= message1.length() || noMatchStart >= message2.length()) {
oneStartsWithOther = true;
doMatch = false;
} else {
if (isSeparator(message1, noMatchStart)) {
separatorPosition = noMatchStart;
}
if (message1.charAt(noMatchStart) != message2.charAt(noMatchStart)) {
doMatch = false;
}
}
}
noMatchStart = separatorPosition;
int noMatchEnd = 0;
boolean sameEnd = false;
if (!oneStartsWithOther) {
doMatch = true;
while (doMatch) {
noMatchEnd++;
int pos1 = message1.length() - noMatchEnd;
int pos2 = message2.length() - noMatchEnd;
if (pos1 > 0 && pos2 > 0) {
if (isSeparator(message1, pos1)) {
separatorPosition = noMatchEnd;
}
if (message1.charAt(pos1) != message2.charAt(pos2)) {
doMatch = false;
}
} else {
doMatch = false;
sameEnd = true;
}
}
if (!sameEnd) {
noMatchEnd = separatorPosition;
}
} else {
String longMsg = message2;
String shortMsg = message1;
if (message1.length() > message2.length()) {
longMsg = message1;
shortMsg = message2;
}
int matchingLength = shortMsg.length();
int notMatchLength = longMsg.length() - shortMsg.length();
if (matchingLength / notMatchLength > MATCHING_INDEX) {
return PatternUtils.simpleToRegexp(shortMsg) + ANY_STR_PATTERN;
}
return null;
}
int matchingLength = 2 * noMatchStart + 2 * noMatchEnd;
int notMatchLength = message1.length() + message2.length() - 2 * noMatchStart - 2 * noMatchEnd;
if (matchingLength / notMatchLength > MATCHING_INDEX) {
return PatternUtils.simpleToRegexp(message1.substring(0, noMatchStart)) + ANY_STR_PATTERN +
PatternUtils.simpleToRegexp(message1.substring(message1.length() - noMatchEnd));
}
return null;
}
|
private String getCommonPattern(String message1, String message2) {
if (message1.equals(message2)) {
return PatternUtils.simpleToRegexp(message1);
}
if (message1.isEmpty() || message2.isEmpty()) {
return null;
}
int noMatchStart = -1;
int separatorPosition = 0;
boolean doMatch = true;
boolean oneStartsWithOther = false;
while (doMatch) {
noMatchStart++;
if (noMatchStart >= message1.length() || noMatchStart >= message2.length()) {
oneStartsWithOther = true;
doMatch = false;
} else {
if (isSeparator(message1, noMatchStart)) {
separatorPosition = noMatchStart + 1;
}
if (message1.charAt(noMatchStart) != message2.charAt(noMatchStart)) {
doMatch = false;
}
}
}
noMatchStart = separatorPosition;
int noMatchEnd = 0;
boolean sameEnd = false;
if (!oneStartsWithOther) {
doMatch = true;
while (doMatch) {
noMatchEnd++;
int pos1 = message1.length() - noMatchEnd;
int pos2 = message2.length() - noMatchEnd;
if (pos1 > 0 && pos2 > 0) {
if (isSeparator(message1, pos1)) {
separatorPosition = noMatchEnd;
}
if (message1.charAt(pos1) != message2.charAt(pos2)) {
doMatch = false;
}
} else {
doMatch = false;
sameEnd = true;
}
}
if (!sameEnd) {
noMatchEnd = separatorPosition;
}
} else {
String longMsg = message2;
String shortMsg = message1;
if (message1.length() > message2.length()) {
longMsg = message1;
shortMsg = message2;
}
int matchingLength = shortMsg.length();
int notMatchLength = longMsg.length() - shortMsg.length();
if (matchingLength / notMatchLength > MATCHING_INDEX) {
return PatternUtils.simpleToRegexp(shortMsg) + ANY_STR_PATTERN;
}
return null;
}
int matchingLength = 2 * noMatchStart + 2 * noMatchEnd;
int notMatchLength = message1.length() + message2.length() - 2 * noMatchStart - 2 * noMatchEnd;
if (matchingLength / notMatchLength > MATCHING_INDEX) {
return PatternUtils.simpleToRegexp(message1.substring(0, noMatchStart)) + ANY_STR_PATTERN +
PatternUtils.simpleToRegexp(message1.substring(message1.length() - noMatchEnd));
}
return null;
}
|
public Form<T> bind(Map<String,String> data, String... allowedFields) {
DataBinder dataBinder = null;
Map<String, String> objectData = data;
if(rootName == null) {
dataBinder = new DataBinder(blankInstance());
} else {
dataBinder = new DataBinder(blankInstance(), rootName);
objectData = new HashMap<String,String>();
for(String key: data.keySet()) {
if(key.startsWith(rootName + ".")) {
objectData.put(key.substring(rootName.length() + 1), data.get(key));
}
}
}
if(allowedFields.length > 0) {
dataBinder.setAllowedFields(allowedFields);
}
SpringValidatorAdapter validator = new SpringValidatorAdapter(play.data.validation.Validation.getValidator());
dataBinder.setValidator(validator);
dataBinder.setConversionService(play.data.format.Formatters.conversion);
dataBinder.setAutoGrowNestedPaths(true);
dataBinder.bind(new MutablePropertyValues(objectData));
Set<ConstraintViolation<Object>> validationErrors;
if (groups != null) {
validationErrors = validator.validate(dataBinder.getTarget(), groups);
} else {
validationErrors = validator.validate(dataBinder.getTarget());
}
BindingResult result = dataBinder.getBindingResult();
for (ConstraintViolation<Object> violation : validationErrors) {
String field = violation.getPropertyPath().toString();
FieldError fieldError = result.getFieldError(field);
if (fieldError == null || !fieldError.isBindingFailure()) {
try {
result.rejectValue(field,
violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
getArgumentsForConstraint(result.getObjectName(), field, violation.getConstraintDescriptor()),
violation.getMessage());
}
catch (NotReadablePropertyException ex) {
throw new IllegalStateException("JSR-303 validated property '" + field +
"' does not have a corresponding accessor for data binding - " +
"check your DataBinder's configuration (bean property versus direct field access)", ex);
}
}
}
if(result.hasErrors()) {
Map<String,List<ValidationError>> errors = new HashMap<String,List<ValidationError>>();
for(FieldError error: result.getFieldErrors()) {
String key = error.getObjectName() + "." + error.getField();
if(key.startsWith("target.") && rootName == null) {
key = key.substring(7);
}
List<Object> arguments = new ArrayList<Object>();
for(Object arg: error.getArguments()) {
if(!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) {
arguments.add(arg);
}
}
if(!errors.containsKey(key)) {
errors.put(key, new ArrayList<ValidationError>());
}
errors.get(key).add(new ValidationError(key, error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments));
}
return new Form(rootName, backedType, data, errors, None(), groups);
} else {
Object globalError = null;
if(result.getTarget() != null) {
try {
java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
globalError = v.invoke(result.getTarget());
} catch(NoSuchMethodException e) {
} catch(Throwable e) {
throw new RuntimeException(e);
}
}
if(globalError != null) {
Map<String,List<ValidationError>> errors = new HashMap<String,List<ValidationError>>();
if(globalError instanceof String) {
errors.put("", new ArrayList<ValidationError>());
errors.get("").add(new ValidationError("", (String)globalError, new ArrayList()));
} else if(globalError instanceof List) {
errors.put("", (List<ValidationError>)globalError);
} else if(globalError instanceof Map) {
errors = (Map<String,List<ValidationError>>)globalError;
}
return new Form(rootName, backedType, data, errors, None(), groups);
}
return new Form(rootName, backedType, new HashMap<String,String>(data), new HashMap<String,List<ValidationError>>(errors), Some((T)result.getTarget()), groups);
}
}
|
public Form<T> bind(Map<String,String> data, String... allowedFields) {
DataBinder dataBinder = null;
Map<String, String> objectData = data;
if(rootName == null) {
dataBinder = new DataBinder(blankInstance());
} else {
dataBinder = new DataBinder(blankInstance(), rootName);
objectData = new HashMap<String,String>();
for(String key: data.keySet()) {
if(key.startsWith(rootName + ".")) {
objectData.put(key.substring(rootName.length() + 1), data.get(key));
}
}
}
if(allowedFields.length > 0) {
dataBinder.setAllowedFields(allowedFields);
}
SpringValidatorAdapter validator = new SpringValidatorAdapter(play.data.validation.Validation.getValidator());
dataBinder.setValidator(validator);
dataBinder.setConversionService(play.data.format.Formatters.conversion);
dataBinder.setAutoGrowNestedPaths(true);
dataBinder.bind(new MutablePropertyValues(objectData));
Set<ConstraintViolation<Object>> validationErrors;
if (groups != null) {
validationErrors = validator.validate(dataBinder.getTarget(), groups);
} else {
validationErrors = validator.validate(dataBinder.getTarget());
}
BindingResult result = dataBinder.getBindingResult();
for (ConstraintViolation<Object> violation : validationErrors) {
String field = violation.getPropertyPath().toString();
FieldError fieldError = result.getFieldError(field);
if (fieldError == null || !fieldError.isBindingFailure()) {
try {
result.rejectValue(field,
violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
getArgumentsForConstraint(result.getObjectName(), field, violation.getConstraintDescriptor()),
violation.getMessage());
}
catch (NotReadablePropertyException ex) {
throw new IllegalStateException("JSR-303 validated property '" + field +
"' does not have a corresponding accessor for data binding - " +
"check your DataBinder's configuration (bean property versus direct field access)", ex);
}
}
}
if(result.hasErrors()) {
Map<String,List<ValidationError>> errors = new HashMap<String,List<ValidationError>>();
for(FieldError error: result.getFieldErrors()) {
String key = error.getObjectName() + "." + error.getField();
if(key.startsWith("target.") && rootName == null) {
key = key.substring(7);
}
List<Object> arguments = new ArrayList<Object>();
for(Object arg: error.getArguments()) {
if(!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) {
arguments.add(arg);
}
}
if(!errors.containsKey(key)) {
errors.put(key, new ArrayList<ValidationError>());
}
errors.get(key).add(new ValidationError(key, error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments));
}
return new Form(rootName, backedType, data, errors, None(), groups);
} else {
Object globalError = null;
if(result.getTarget() != null) {
try {
java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
globalError = v.invoke(result.getTarget());
} catch(NoSuchMethodException e) {
} catch(Throwable e) {
throw new RuntimeException(e);
}
}
if(globalError != null) {
Map<String,List<ValidationError>> errors = new HashMap<String,List<ValidationError>>();
if(globalError instanceof String) {
errors.put("", new ArrayList<ValidationError>());
errors.get("").add(new ValidationError("", (String)globalError, new ArrayList()));
} else if(globalError instanceof List) {
for (ValidationError error : (List<ValidationError>) globalError) {
List<ValidationError> errorsForKey = errors.get(error.key());
if (errorsForKey == null) {
errors.put(error.key(), errorsForKey = new ArrayList<ValidationError>());
}
errorsForKey.add(error);
}
} else if(globalError instanceof Map) {
errors = (Map<String,List<ValidationError>>)globalError;
}
return new Form(rootName, backedType, data, errors, None(), groups);
}
return new Form(rootName, backedType, new HashMap<String,String>(data), new HashMap<String,List<ValidationError>>(errors), Some((T)result.getTarget()), groups);
}
}
|
private MainFrame() {
setTitle("Wombat - Build " + Wombat.VERSION);
setSize(Options.DisplayWidth, Options.DisplayHeight);
setLocation(Options.DisplayLeft, Options.DisplayTop);
setLayout(new BorderLayout(5, 5));
try {
setIconImage(IconManager.icon("Wombat.png").getImage());
} catch(NullPointerException ex) {
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Documents.CloseAll();
Options.DisplayTop = Math.max(0, e.getWindow().getLocation().y);
Options.DisplayLeft = Math.max(0, e.getWindow().getLocation().x);
Options.DisplayWidth = Math.max(400, e.getWindow().getWidth());
Options.DisplayHeight = Math.max(400, e.getWindow().getHeight());
Options.save();
System.exit(0);
}
});
setJMenuBar(MenuManager.menu());
TabWindow documents = new TabWindow();
StringViewMap viewMap = new StringViewMap();
Documents = new DocumentManager(viewMap, documents);
Documents.New();
History = new HistoryTextArea();
REPL = new REPLTextArea();
viewMap.addView("REPL - Execute", new View("REPL - Execute", null, REPL));
viewMap.addView("REPL - History", new View("REPL - History", null, History));
SplitWindow replSplit = new SplitWindow(false, viewMap.getView("REPL - Execute"), viewMap.getView("REPL - History"));
viewMap.getView("REPL - Execute").getWindowProperties().setCloseEnabled(false);
viewMap.getView("REPL - History").getWindowProperties().setCloseEnabled(false);
SplitWindow fullSplit = new SplitWindow(false, 0.6f, documents, replSplit);
Root = DockingUtil.createRootWindow(new ViewMap(), true);
Root.setWindow(fullSplit);
add(Root);
kawa = new KawaWrap();
Thread t = new Thread(new Runnable() {
public void run() {
while (true) {
if (OutputIntercept.hasContent())
History.append(OutputIntercept.getContent() + "\n");
try { Thread.sleep(50); } catch(Exception e) {}
}
}
});
t.setDaemon(true);
t.start();
ToolBar = new JToolBar();
ToolBar.setFloatable(false);
for (Action a : new Action[]{new actions.New(), new actions.Open(), new actions.Save(), new actions.Close()})
ToolBar.add(a);
ToolBar.addSeparator();
for (Action a : new Action[]{new actions.Run(), new actions.Format(), new actions.Reset()})
ToolBar.add(a);
add(ToolBar, BorderLayout.PAGE_START);
ToolBar.setVisible(Options.DisplayToolbar);
}
|
private MainFrame() {
setTitle("Wombat - Build " + Wombat.VERSION);
setSize(Options.DisplayWidth, Options.DisplayHeight);
setLocation(Options.DisplayLeft, Options.DisplayTop);
setLayout(new BorderLayout(5, 5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
setIconImage(IconManager.icon("Wombat.png").getImage());
} catch(NullPointerException ex) {
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Documents.CloseAll();
Options.DisplayTop = Math.max(0, e.getWindow().getLocation().y);
Options.DisplayLeft = Math.max(0, e.getWindow().getLocation().x);
Options.DisplayWidth = Math.max(400, e.getWindow().getWidth());
Options.DisplayHeight = Math.max(400, e.getWindow().getHeight());
Options.save();
}
});
setJMenuBar(MenuManager.menu());
TabWindow documents = new TabWindow();
StringViewMap viewMap = new StringViewMap();
Documents = new DocumentManager(viewMap, documents);
Documents.New();
History = new HistoryTextArea();
REPL = new REPLTextArea();
viewMap.addView("REPL - Execute", new View("REPL - Execute", null, REPL));
viewMap.addView("REPL - History", new View("REPL - History", null, History));
SplitWindow replSplit = new SplitWindow(false, viewMap.getView("REPL - Execute"), viewMap.getView("REPL - History"));
viewMap.getView("REPL - Execute").getWindowProperties().setCloseEnabled(false);
viewMap.getView("REPL - History").getWindowProperties().setCloseEnabled(false);
SplitWindow fullSplit = new SplitWindow(false, 0.6f, documents, replSplit);
Root = DockingUtil.createRootWindow(new ViewMap(), true);
Root.setWindow(fullSplit);
add(Root);
kawa = new KawaWrap();
Thread t = new Thread(new Runnable() {
public void run() {
while (true) {
if (OutputIntercept.hasContent())
History.append(OutputIntercept.getContent() + "\n");
try { Thread.sleep(50); } catch(Exception e) {}
}
}
});
t.setDaemon(true);
t.start();
ToolBar = new JToolBar();
ToolBar.setFloatable(false);
for (Action a : new Action[]{new actions.New(), new actions.Open(), new actions.Save(), new actions.Close()})
ToolBar.add(a);
ToolBar.addSeparator();
for (Action a : new Action[]{new actions.Run(), new actions.Format(), new actions.Reset()})
ToolBar.add(a);
add(ToolBar, BorderLayout.PAGE_START);
ToolBar.setVisible(Options.DisplayToolbar);
}
|
public Runnable create() {
return new Runnable() {
@Override
public void run() {
try {
start();
} catch (IOException e) {
getHandler().postException(e);
}
}
};
}
|
public Runnable create() {
return new Runnable() {
@Override
public void run() {
try {
start();
} catch (IOException e) {
getHandler().postException(e);
}
}
};
}
|
public Dialog onCreateDialog(Bundle savedInstanceState) {
Fragment targetFragment = getTargetFragment();
if (targetFragment != null && targetFragment instanceof Callbacks) {
callbacks = (Callbacks) targetFragment;
} else if (getActivity() instanceof Callbacks) {
callbacks = (Callbacks) getActivity();
} else {
callbacks = new AlertDialogFragment.Callbacks() {
@Override
public void onDialogClicked(DialogInterface dialog, int which) {}
@Override
public void onDialogCancelled(DialogInterface dialog) {}
};
}
DialogInterface.OnClickListener listener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callbacks.onDialogClicked(dialog, which);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Bundle args = new Bundle();
if (args.containsKey(KEY_ICON)) builder.setIcon(args.getInt(KEY_ICON));
if (args.containsKey(KEY_TITLE_ID))
builder.setTitle(args.getInt(KEY_TITLE_ID));
else if (args.containsKey(KEY_TITLE))
builder.setTitle(args.getString(KEY_TITLE));
if (args.containsKey(KEY_MESSAGE_ID))
builder.setMessage(args.getInt(KEY_MESSAGE_ID));
else if (args.containsKey(KEY_MESSAGE))
builder.setMessage(args.getString(KEY_MESSAGE));
if (args.containsKey(KEY_NEGATIVE_TEXT_ID))
builder.setNegativeButton(args.getInt(KEY_NEGATIVE_TEXT_ID), listener);
else if (args.containsKey(KEY_NEGATIVE_TEXT))
builder.setNegativeButton(args.getString(KEY_NEGATIVE_TEXT), listener);
if (args.containsKey(KEY_NEUTRAL_TEXT_ID))
builder.setNeutralButton(args.getInt(KEY_NEUTRAL_TEXT_ID), listener);
else if (args.containsKey(KEY_NEGATIVE_TEXT))
builder.setNeutralButton(args.getString(KEY_NEUTRAL_TEXT), listener);
if (args.containsKey(KEY_POSITIVE_TEXT_ID))
builder.setPositiveButton(args.getInt(KEY_POSITIVE_TEXT_ID), listener);
else if (args.containsKey(KEY_POSITIVE_TEXT))
builder.setPositiveButton(args.getString(KEY_POSITIVE_TEXT), listener);
if (args.containsKey(KEY_CANCELABLE))
builder.setCancelable(args.getBoolean(KEY_CANCELABLE));
return builder.create();
}
|
public Dialog onCreateDialog(Bundle savedInstanceState) {
Fragment targetFragment = getTargetFragment();
if (targetFragment != null && targetFragment instanceof Callbacks) {
callbacks = (Callbacks) targetFragment;
} else if (getActivity() instanceof Callbacks) {
callbacks = (Callbacks) getActivity();
} else {
callbacks = new AlertDialogFragment.Callbacks() {
@Override
public void onDialogClicked(DialogInterface dialog, int which) {}
@Override
public void onDialogCanceled(DialogInterface dialog) {}
};
}
DialogInterface.OnClickListener listener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callbacks.onDialogClicked(dialog, which);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Bundle args = new Bundle();
if (args.containsKey(KEY_ICON)) builder.setIcon(args.getInt(KEY_ICON));
if (args.containsKey(KEY_TITLE_ID))
builder.setTitle(args.getInt(KEY_TITLE_ID));
else if (args.containsKey(KEY_TITLE))
builder.setTitle(args.getString(KEY_TITLE));
if (args.containsKey(KEY_MESSAGE_ID))
builder.setMessage(args.getInt(KEY_MESSAGE_ID));
else if (args.containsKey(KEY_MESSAGE))
builder.setMessage(args.getString(KEY_MESSAGE));
if (args.containsKey(KEY_NEGATIVE_TEXT_ID))
builder.setNegativeButton(args.getInt(KEY_NEGATIVE_TEXT_ID), listener);
else if (args.containsKey(KEY_NEGATIVE_TEXT))
builder.setNegativeButton(args.getString(KEY_NEGATIVE_TEXT), listener);
if (args.containsKey(KEY_NEUTRAL_TEXT_ID))
builder.setNeutralButton(args.getInt(KEY_NEUTRAL_TEXT_ID), listener);
else if (args.containsKey(KEY_NEGATIVE_TEXT))
builder.setNeutralButton(args.getString(KEY_NEUTRAL_TEXT), listener);
if (args.containsKey(KEY_POSITIVE_TEXT_ID))
builder.setPositiveButton(args.getInt(KEY_POSITIVE_TEXT_ID), listener);
else if (args.containsKey(KEY_POSITIVE_TEXT))
builder.setPositiveButton(args.getString(KEY_POSITIVE_TEXT), listener);
if (args.containsKey(KEY_CANCELABLE))
builder.setCancelable(args.getBoolean(KEY_CANCELABLE));
return builder.create();
}
|
public static void setFirstRunParameters(PreferencesWrapper preferencesWrapper) {
preferencesWrapper.setCodecPriority("iLBC/8000/1",
getCpuAbi().equalsIgnoreCase("armeabi-v7a")?"189":"0");
preferencesWrapper.setCodecPriority("PCMU/8000/1", "240");
preferencesWrapper.setCodecPriority("PCMA/8000/1", "230");
preferencesWrapper.setCodecPriority("speex/8000/1", "190");
preferencesWrapper.setCodecPriority("speex/16000/1", "180");
preferencesWrapper.setCodecPriority("speex/32000/1", "0");
preferencesWrapper.setCodecPriority("GSM/8000/1", "100");
preferencesWrapper.setCodecPriority("G722/16000/1", "0");
preferencesWrapper.setPreferenceStringValue(PreferencesWrapper.SND_AUTO_CLOSE_TIME, isCompatible(4)?"1":"5");
preferencesWrapper.setPreferenceStringValue(PreferencesWrapper.SND_CLOCK_RATE, isCompatible(4)?"16000":"8000");
preferencesWrapper.setPreferenceBooleanValue(PreferencesWrapper.ECHO_CANCELLATION, isCompatible(4)?true:false);
preferencesWrapper.setPreferenceBooleanValue(PreferencesWrapper.KEEP_AWAKE_IN_CALL,
android.os.Build.BRAND.equalsIgnoreCase("google")?true:false);
}
|
public static void setFirstRunParameters(PreferencesWrapper preferencesWrapper) {
preferencesWrapper.setCodecPriority("iLBC/8000/1",
getCpuAbi().equalsIgnoreCase("armeabi-v7a")?"189":"0");
preferencesWrapper.setCodecPriority("PCMU/8000/1", "240");
preferencesWrapper.setCodecPriority("PCMA/8000/1", "230");
preferencesWrapper.setCodecPriority("speex/8000/1", "190");
preferencesWrapper.setCodecPriority("speex/16000/1", "180");
preferencesWrapper.setCodecPriority("speex/32000/1", "0");
preferencesWrapper.setCodecPriority("GSM/8000/1", "100");
preferencesWrapper.setCodecPriority("G722/16000/1", "0");
preferencesWrapper.setPreferenceStringValue(PreferencesWrapper.SND_AUTO_CLOSE_TIME, isCompatible(4)?"1":"5");
preferencesWrapper.setPreferenceStringValue(PreferencesWrapper.SND_CLOCK_RATE, isCompatible(4)?"16000":"8000");
preferencesWrapper.setPreferenceBooleanValue(PreferencesWrapper.ECHO_CANCELLATION, isCompatible(4)?true:false);
preferencesWrapper.setPreferenceBooleanValue(PreferencesWrapper.KEEP_AWAKE_IN_CALL,
( android.os.Build.DEVICE.equalsIgnoreCase("passion") ||
android.os.Build.DEVICE.equalsIgnoreCase("bravo") )?true:false);
}
|
public static String resolveIdGetterName(JavaClass<?> entity)
{
String result = null;
for (Member<?> member : entity.getMembers())
{
if (member.hasAnnotation(Id.class))
{
String name = member.getName();
String type = null;
if (member instanceof Method)
{
type = ((Method<?, ?>) member).getReturnType().getName();
if (name.startsWith("get"))
{
name = name.substring(2);
}
}
else if (member instanceof Field)
{
type = ((Field<?>) member).getType().getName();
}
if (type != null)
{
for (Method<?, ?> method : entity.getMethods())
{
if (method.getParameters().size() == 0 && type.equals(method.getReturnType()))
{
if (method.getName().toLowerCase().contains(name.toLowerCase()))
{
result = method.getName() + "()";
break;
}
}
}
}
if (result != null)
{
break;
}
else if (type != null && member.isPublic())
{
String memberName = member.getName();
if (member instanceof Method && memberName.startsWith("get"))
{
memberName = memberName.substring(3);
memberName = Strings.uncapitalize(memberName);
}
result = memberName;
}
}
}
if (result == null)
{
throw new RuntimeException("Could not determine @Id field and getter method for @Entity ["
+ entity.getQualifiedName()
+ "]. Aborting.");
}
return result;
}
|
public static String resolveIdGetterName(JavaClass<?> entity)
{
String result = null;
for (Member<?> member : entity.getMembers())
{
if (member.hasAnnotation(Id.class))
{
String name = member.getName();
String type = null;
if (member instanceof Method)
{
type = ((Method<?, ?>) member).getReturnType().getQualifiedName();
if (name.startsWith("get"))
{
name = name.substring(2);
}
}
else if (member instanceof Field)
{
type = ((Field<?>) member).getType().getQualifiedName();
}
if (type != null)
{
for (Method<?, ?> method : entity.getMethods())
{
if (method.getParameters().size() == 0 && type.equals(method.getReturnType().getQualifiedName()))
{
if (method.getName().toLowerCase().contains(name.toLowerCase()))
{
result = method.getName() + "()";
break;
}
}
}
}
if (result != null)
{
break;
}
else if (type != null && member.isPublic())
{
String memberName = member.getName();
if (member instanceof Method && memberName.startsWith("get"))
{
memberName = memberName.substring(3);
memberName = Strings.uncapitalize(memberName);
}
result = memberName;
}
}
}
if (result == null)
{
throw new RuntimeException("Could not determine @Id field and getter method for @Entity ["
+ entity.getQualifiedName()
+ "]. Aborting.");
}
return result;
}
|
private Comparable[][] getBounds( int tIndex )
throws IOException, InterruptedException {
StarTable table = tables[ tIndex ];
int ncol = table.getColumnCount();
if ( ! engine.canBoundMatch() ) {
return new Comparable[ 2 ][ ncol ];
}
boolean[] isComparable = new boolean[ ncol ];
int ncomp = 0;
for ( int icol = 0; icol < ncol; icol++ ) {
if ( Comparable.class.isAssignableFrom( table.getColumnInfo( icol )
.getContentClass() ) ) {
isComparable[ icol ] = true;
ncomp++;
}
}
if ( ncomp == 0 ) {
return new Comparable[ 2 ][ ncol ];
}
Comparable[] mins = new Comparable[ ncol ];
Comparable[] maxs = new Comparable[ ncol ];
ProgressRowSequence rseq =
new ProgressRowSequence( table, indicator,
"Assessing range of coordinates " +
"from table " + ( tIndex + 1 ) );
try {
for ( long lrow = 0; rseq.nextProgress(); lrow++ ) {
Object[] row = rseq.getRow();
for ( int icol = 0; icol < ncol; icol++ ) {
if ( isComparable[ icol ] ) {
Object cell = row[ icol ];
if ( cell instanceof Comparable ) {
Comparable val = (Comparable) cell;
if ( mins[ icol ] == null ||
mins[ icol ].compareTo( val ) > 0 ) {
mins[ icol ] = val;
}
if ( maxs[ icol ] == null ||
maxs[ icol ].compareTo( val ) < 0 ) {
maxs[ icol ] = val;
}
}
}
}
}
}
finally {
rseq.close();
}
logTupleBounds( "Limits are: ", mins, maxs );
return engine.getMatchBounds( mins, maxs );
}
|
private Comparable[][] getBounds( int tIndex )
throws IOException, InterruptedException {
StarTable table = tables[ tIndex ];
int ncol = table.getColumnCount();
if ( ! engine.canBoundMatch() ) {
return new Comparable[ 2 ][ ncol ];
}
boolean[] isComparable = new boolean[ ncol ];
int ncomp = 0;
for ( int icol = 0; icol < ncol; icol++ ) {
if ( Comparable.class.isAssignableFrom( table.getColumnInfo( icol )
.getContentClass() ) ) {
isComparable[ icol ] = true;
ncomp++;
}
}
if ( ncomp == 0 ) {
return new Comparable[ 2 ][ ncol ];
}
Comparable[] mins = new Comparable[ ncol ];
Comparable[] maxs = new Comparable[ ncol ];
ProgressRowSequence rseq =
new ProgressRowSequence( table, indicator,
"Assessing range of coordinates " +
"from table " + ( tIndex + 1 ) );
try {
for ( long lrow = 0; rseq.nextProgress(); lrow++ ) {
Object[] row = rseq.getRow();
for ( int icol = 0; icol < ncol; icol++ ) {
if ( isComparable[ icol ] ) {
Object cell = row[ icol ];
if ( cell instanceof Comparable &&
! Tables.isBlank( cell ) ) {
Comparable val = (Comparable) cell;
if ( mins[ icol ] == null ||
mins[ icol ].compareTo( val ) > 0 ) {
mins[ icol ] = val;
}
if ( maxs[ icol ] == null ||
maxs[ icol ].compareTo( val ) < 0 ) {
maxs[ icol ] = val;
}
}
}
}
}
}
finally {
rseq.close();
}
logTupleBounds( "Limits are: ", mins, maxs );
return engine.getMatchBounds( mins, maxs );
}
|
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args){
if (command.getName().equalsIgnoreCase("vision")){
if (sender.hasPermission("visionflow.vision") || sender.isOp()){
Player player = Bukkit.getPlayer(sender.getName());
if (args.length >= 1){
String argtwo = args[0].trim();
if (argtwo.equalsIgnoreCase("on")){
player.removePotionEffect(PotionEffectType.NIGHT_VISION);
player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 1));
sender.sendMessage(ChatColor.YELLOW + "Turned vision " + ChatColor.GOLD + "on");
} else if(argtwo.equalsIgnoreCase("off")){
sender.sendMessage(ChatColor.YELLOW + "Turned vision " + ChatColor.RED + "off");
player.removePotionEffect(PotionEffectType.NIGHT_VISION);
}
} else {
sender.sendMessage(ChatColor.YELLOW + "You need to type /vision <on/off> !");
}
} else {
sender.sendMessage(ChatColor.RED + "You don't have permission to do that!");
}
return true;
}
return false;
}
|
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args){
if (command.getName().equalsIgnoreCase("vision")){
if (sender.hasPermission("visionflow.vision") || sender.isOp()){
Player player = Bukkit.getPlayer(sender.getName());
if (args.length >= 1){
String argtwo = args[0].trim();
if (argtwo.equalsIgnoreCase("on")){
player.removePotionEffect(PotionEffectType.NIGHT_VISION);
player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, Integer.MAX_VALUE, 1));
sender.sendMessage(ChatColor.YELLOW + "Turned vision " + ChatColor.GOLD + "on");
} else if(argtwo.equalsIgnoreCase("off")){
sender.sendMessage(ChatColor.YELLOW + "Turned vision " + ChatColor.RED + "off");
player.removePotionEffect(PotionEffectType.NIGHT_VISION);
}
} else {
sender.sendMessage(ChatColor.YELLOW + "You need to type /vision <on/off> !");
}
return true;
}
return false;
} return false;
}
|
public static void getDirectory(final String... args) {
final CommandLineParser cliParser = new CommandLineParser(null, null, null);
final BaseDirectoryLocator locator = new BaseDirectoryLocator();
cliParser.parse(args);
final String configDirectory = cliParser.getConfigDirectory();
setDirectory(configDirectory == null ? configDirectory : locator.getDefaultBaseDirectory());
}
|
public static void getDirectory(final String... args) {
final CommandLineParser cliParser = new CommandLineParser(null, null, null);
final BaseDirectoryLocator locator = new BaseDirectoryLocator();
cliParser.parse(args);
final String configDirectory = cliParser.getConfigDirectory();
setDirectory(configDirectory == null ? locator.getDefaultBaseDirectory() : configDirectory);
}
|
public static void main(String[] args) throws Exception {
String username = args[0];
char[] password = args[1].toCharArray();
LoginParams loginParams = new LoginParams(
"Local", username, password, "myproxy2.arcs.org.au", "7512");
ServiceInterface si = null;
try {
si = ServiceInterfaceFactory.createInterface(loginParams);
si.login(username, password);
} catch (Exception e) {
throw new LoginException(e.getLocalizedMessage());
}
JobSubmissionObjectImpl jso = new JobSubmissionObjectImpl();
jso.setApplication("java");
jso.setCommandline("java -version");
String jobname = si.createJob(jso.getStringJobPropertyMap(), "/APAC/VPAC", "force-name");
si.submitJob(jobname);
}
|
public static void main(String[] args) throws Exception {
String username = args[0];
char[] password = args[1].toCharArray();
LoginParams loginParams = new LoginParams(
"Local", username, password, "myproxy2.arcs.org.au", "7512");
ServiceInterface si = null;
try {
si = ServiceInterfaceFactory.createInterface(loginParams);
si.login(username, password);
} catch (Exception e) {
throw new LoginException(e.getLocalizedMessage());
}
JobSubmissionObjectImpl jso = new JobSubmissionObjectImpl();
jso.setApplication("java");
jso.setCommandline("java -version");
}
|
public Token extract(String response)
{
Preconditions.checkEmptyString(response, "Cant extract a token from null object or an empty string.");
Matcher matcher = Pattern.compile(TOKEN_REGEX).matcher(response);
if (matcher.matches())
{
String token = URLUtils.percentDecode(matcher.group(1));
String secret = URLUtils.percentDecode(matcher.group(2));
return new Token(token, secret);
} else
{
throw new OAuthException("Could not find request token or secret in response: " + response, null);
}
}
|
public Token extract(String response)
{
Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");
Matcher matcher = Pattern.compile(TOKEN_REGEX).matcher(response);
if (matcher.matches())
{
String token = URLUtils.percentDecode(matcher.group(1));
String secret = URLUtils.percentDecode(matcher.group(2));
return new Token(token, secret);
} else
{
throw new OAuthException("Response body is incorrect. Can't extract a token from this: '" + response + "'", null);
}
}
|
public static void SystemPropertys() throws Exception
{
String Java_Version = System.getProperty("java.version");
String SystemOS = System.getProperty("os.name");
String SystemType = System.getProperty("os.arch");
String SystemVersion = System.getProperty("os.version");
String UserName = System.getProperty("user.name");
String UserDir = System.getProperty("user.home");
System.out.println("/*************************************************************\\");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println("| Java Version: "+ Java_Version + " |");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println("| Operating System: "+ SystemOS + " " + SystemType + " Version: " + SystemVersion + " |");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println("| User: " + UserName + " |");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println("| Home: " + UserDir +" |");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println(" ************************************************************* ");
}
|
public static void SystemPropertys() throws Exception
{
String Java_Version = System.getProperty("java.version");
String SystemOS = System.getProperty("os.name");
String SystemType = System.getProperty("os.arch");
String SystemVersion = System.getProperty("os.version");
String UserName = System.getProperty("user.name");
String UserDir = System.getProperty("user.home");
System.out.println("/*************************************************************\\");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println("| System Information: |");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println("| Java Version: "+ Java_Version + " |");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println("| Operating System: "+ SystemOS + " " + SystemType + " Version: " + SystemVersion + " |");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println("| User: " + UserName + " |");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println("| Home: " + UserDir +" |");
Thread.sleep(500);
System.out.println("| |");
Thread.sleep(500);
System.out.println(" ************************************************************* ");
}
|
public Color colorize(double start, double stop, double value) {
Color returnColor = Color.BLACK;
if (value > 0.0) {
if (value >= start && value <= stop) {
double range = stop - start;
value -= start;
if (value < (range / 2.0)) {
returnColor = interpolateColor(m_color1, m_color2, 2.0 * value / range);
}
else {
returnColor = interpolateColor(m_color2, m_color3, 2.0 * (value - (range / 2.0)) / range);
}
}
}
return returnColor;
}
|
public Color colorize(double start, double stop, double value) {
Color returnColor = Color.BLACK;
if (value > 0.0) {
if (value >= start && value <= stop) {
double range = stop - start;
if (0.0 == range) {
returnColor = m_color2;
}
else {
value -= start;
if (value < (range / 2.0)) {
returnColor = interpolateColor(m_color1, m_color2, 2.0 * value / range);
}
else {
returnColor = interpolateColor(m_color2, m_color3, 2.0 * (value - (range / 2.0)) / range);
}
}
}
}
return returnColor;
}
|
public String parseSaveSettings(final HttpServletRequest request) {
String[] issueSelectValue = request.getParameterValues("issueSelect");
String[] collectorIssueSelectValue = request.getParameterValues("issueSelect_collector");
String[] excludeDatesValue = request.getParameterValues("excludedates");
String[] includeDatesValue = request.getParameterValues("includedates");
if (issueSelectValue == null) {
issuesPatterns = new ArrayList<Pattern>();
} else {
issuesPatterns = new ArrayList<Pattern>();
for (String filteredIssueKey : issueSelectValue) {
issuesPatterns.add(Pattern.compile(filteredIssueKey));
}
}
if (collectorIssueSelectValue == null) {
collectorIssuePatterns = new ArrayList<Pattern>();
} else {
collectorIssuePatterns = new ArrayList<Pattern>();
for (String filteredIssueKey : collectorIssueSelectValue) {
collectorIssuePatterns.add(Pattern.compile(filteredIssueKey));
}
}
boolean parseExcludeException = false;
boolean parseIncludeException = false;
if (excludeDatesValue == null) {
excludeDates = "";
} else {
String excludeDatesValueString = excludeDatesValue[0];
if (!excludeDatesValueString.isEmpty()) {
for (String dateString : excludeDatesValueString.split(",")) {
try {
DateTimeConverterUtil.stringToDate(dateString);
} catch (ParseException e) {
parseExcludeException = true;
messageExclude = "plugin.parse.exception.exclude";
if (messageParameterExclude.isEmpty()) {
messageParameterExclude += dateString;
} else {
messageParameterExclude += ", " + dateString;
}
}
}
}
excludeDates = excludeDatesValueString;
}
if (includeDatesValue == null) {
includeDates = "";
} else {
String includeDatesValueString = includeDatesValue[0];
if (!includeDatesValueString.isEmpty()) {
for (String dateString : includeDatesValueString.split(",")) {
try {
DateTimeConverterUtil.stringToDate(dateString);
} catch (ParseException e) {
parseIncludeException = true;
messageInclude = "plugin.parse.exception.include";
if (messageParameterInclude.isEmpty()) {
messageParameterInclude += dateString;
} else {
messageParameterInclude += ", " + dateString;
}
}
}
}
includeDates = includeDatesValueString;
}
if (parseExcludeException || parseIncludeException) {
return SUCCESS;
}
return null;
}
|
public String parseSaveSettings(final HttpServletRequest request) {
String[] issueSelectValue = request.getParameterValues("issueSelect");
String[] collectorIssueSelectValue = request.getParameterValues("issueSelect_collector");
String[] excludeDatesValue = request.getParameterValues("excludedates");
String[] includeDatesValue = request.getParameterValues("includedates");
if (issueSelectValue == null) {
issuesPatterns = new ArrayList<Pattern>();
} else {
issuesPatterns = new ArrayList<Pattern>();
for (String filteredIssueKey : issueSelectValue) {
issuesPatterns.add(Pattern.compile(filteredIssueKey));
}
}
if (collectorIssueSelectValue == null) {
collectorIssuePatterns = new ArrayList<Pattern>();
} else {
collectorIssuePatterns = new ArrayList<Pattern>();
for (String filteredIssueKey : collectorIssueSelectValue) {
collectorIssuePatterns.add(Pattern.compile(filteredIssueKey));
}
}
boolean parseExcludeException = false;
boolean parseIncludeException = false;
if (excludeDatesValue == null) {
excludeDates = "";
} else {
String excludeDatesValueString = excludeDatesValue[0];
if (!excludeDatesValueString.isEmpty()) {
excludeDatesValueString = excludeDatesValueString.replace(" ", "").replace("\r", "").replace("\n", "");
for (String dateString : excludeDatesValueString.split(",")) {
try {
DateTimeConverterUtil.stringToDate(dateString);
} catch (ParseException e) {
parseExcludeException = true;
messageExclude = "plugin.parse.exception.exclude";
if (messageParameterExclude.isEmpty()) {
messageParameterExclude += dateString;
} else {
messageParameterExclude += ", " + dateString;
}
}
}
}
excludeDates = excludeDatesValueString;
}
if (includeDatesValue == null) {
includeDates = "";
} else {
String includeDatesValueString = includeDatesValue[0];
if (!includeDatesValueString.isEmpty()) {
includeDatesValueString = includeDatesValueString.replace(" ", "").replace("\r", "").replace("\n", "");
for (String dateString : includeDatesValueString.split(",")) {
try {
DateTimeConverterUtil.stringToDate(dateString);
} catch (ParseException e) {
parseIncludeException = true;
messageInclude = "plugin.parse.exception.include";
if (messageParameterInclude.isEmpty()) {
messageParameterInclude += dateString;
} else {
messageParameterInclude += ", " + dateString;
}
}
}
}
includeDates = includeDatesValueString;
}
if (parseExcludeException || parseIncludeException) {
return SUCCESS;
}
return null;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.