answer
stringlengths 17
10.2M
|
|---|
package org.odk.collect.android.tasks;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import org.commcare.android.crypt.EncryptionIO;
import org.commcare.android.logging.AndroidLogger;
import org.commcare.android.tasks.templates.CommCareTask;
import org.commcare.dalvik.odk.provider.FormsProviderAPI.FormsColumns;
import org.commcare.dalvik.odk.provider.InstanceProviderAPI;
import org.commcare.dalvik.odk.provider.InstanceProviderAPI.InstanceColumns;
import org.commcare.dalvik.preferences.DeveloperPreferences;
import org.javarosa.core.io.StreamsUtil;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.transport.payload.ByteArrayPayload;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.model.xform.XFormSerializingVisitor;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.utilities.EncryptionUtils;
import org.odk.collect.android.utilities.EncryptionUtils.EncryptedFormInformation;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.crypto.spec.SecretKeySpec;
/**
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class SaveToDiskTask extends CommCareTask<Void, String, SaveToDiskTask.SaveStatus, FormEntryActivity> {
// callback to run upon saving
private FormSavedListener mSavedListener;
private final Boolean exitAfterSave;
private final Boolean mMarkCompleted;
// URI to the thing we are saving
private Uri mUri;
// The name of the form we are saving
private final String mInstanceName;
private final Context context;
// URI to the table we are saving to
private final Uri instanceContentUri;
private final SecretKeySpec symetricKey;
public enum SaveStatus {
SAVED_COMPLETE,
SAVED_INCOMPLETE,
INVALID_ANSWER,
SAVED_AND_EXIT
}
public static final int SAVING_TASK_ID = 17;
public SaveToDiskTask(Uri mUri, Boolean saveAndExit, Boolean markCompleted, String updatedName, Context context, Uri instanceContentUri, SecretKeySpec symetricKey, boolean headless) {
TAG = SaveToDiskTask.class.getSimpleName();
this.mUri = mUri;
exitAfterSave = saveAndExit;
mMarkCompleted = markCompleted;
mInstanceName = updatedName;
this.context = context;
this.instanceContentUri = instanceContentUri;
this.symetricKey = symetricKey;
if (headless) {
this.taskId = -1;
} else {
this.taskId = SAVING_TASK_ID;
}
}
/**
* Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
* an instance, it will be used to fill the {@link FormDef}.
*/
@Override
protected SaveStatus doTaskBackground(Void... nothing) {
if (hasInvalidAnswers(mMarkCompleted, DeveloperPreferences.shouldFireTriggersOnSave())) {
return SaveStatus.INVALID_ANSWER;
}
FormEntryActivity.mFormController.postProcessInstance();
exportData(mMarkCompleted);
if (exitAfterSave) {
return SaveStatus.SAVED_AND_EXIT;
} else if (mMarkCompleted) {
return SaveStatus.SAVED_COMPLETE;
} else {
return SaveStatus.SAVED_INCOMPLETE;
}
}
/**
* Update or create a new entry in the form table for the
*/
private void updateInstanceDatabase(boolean incomplete, boolean canEditAfterCompleted) {
ContentValues values = new ContentValues();
if (mInstanceName != null) {
values.put(InstanceColumns.DISPLAY_NAME, mInstanceName);
}
if (incomplete || !mMarkCompleted) {
values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE);
} else {
values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_COMPLETE);
}
// update this whether or not the status is complete.
values.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, Boolean.toString(canEditAfterCompleted));
// Insert or update the form instance into the database.
String resolverType = context.getContentResolver().getType(mUri);
if (InstanceColumns.CONTENT_ITEM_TYPE.equals(resolverType)) {
// Started with a concrete instance (e.i. by editing an existing
// form), so just update it.
context.getContentResolver().update(mUri, values, null, null);
} else if (FormsColumns.CONTENT_ITEM_TYPE.equals(resolverType)) {
// Started with an empty form or possibly a manually saved form.
// Try updating, and create a new instance if that fails.
String[] whereArgs = {FormEntryActivity.mInstancePath};
int rowsUpdated = context.getContentResolver().update(instanceContentUri, values,
InstanceColumns.INSTANCE_FILE_PATH + "=?", whereArgs);
if (rowsUpdated == 0) {
// Form instance didn't exist in the table, so create it.
Log.e(TAG, "No instance found, creating");
Cursor c = null;
try {
// grab the first entry in the instance table for the form
c = context.getContentResolver().query(mUri, null, null, null, null);
c.moveToFirst();
// copy data out of that entry, into the entry we are creating
values.put(InstanceColumns.JR_FORM_ID,
c.getString(c.getColumnIndex(FormsColumns.JR_FORM_ID)));
values.put(InstanceColumns.SUBMISSION_URI,
c.getString(c.getColumnIndex(FormsColumns.SUBMISSION_URI)));
if (mInstanceName == null) {
values.put(InstanceColumns.DISPLAY_NAME,
c.getString(c.getColumnIndex(FormsColumns.DISPLAY_NAME)));
}
} finally {
if (c != null) {
c.close();
}
}
values.put(InstanceColumns.INSTANCE_FILE_PATH, FormEntryActivity.mInstancePath);
try {
mUri = context.getContentResolver().insert(instanceContentUri, values);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
}
} else if (rowsUpdated == 1) {
Log.i(TAG, "Instance already exists, updating");
} else{
Log.w(TAG, "Updated more than one entry, that's not good");
}
}
}
private void exportData(boolean markCompleted) {
ByteArrayPayload payload;
try {
// assume no binary data inside the model.
FormInstance datamodel = FormEntryActivity.mFormController.getInstance();
XFormSerializingVisitor serializer = new XFormSerializingVisitor(markCompleted);
payload = (ByteArrayPayload)serializer.createSerializedPayload(datamodel);
writeXmlToStream(payload,
EncryptionIO.createFileOutputStream(FormEntryActivity.mInstancePath, symetricKey));
} catch (IOException e) {
throw new RuntimeException("Unable to serialize form save payload.");
}
// update the mUri. We've saved the reloadable instance, so update status...
updateInstanceDatabase(true, true);
if ( markCompleted ) {
// now see if it is to be finalized and perhaps update everything...
boolean canEditAfterCompleted = FormEntryActivity.mFormController.isSubmissionEntireForm();
boolean isEncrypted = false;
// build a submission.xml to hold the data being submitted
// and (if appropriate) encrypt the files on the side
// pay attention to the ref attribute of the submission profile...
try {
payload = FormEntryActivity.mFormController.getSubmissionXml();
} catch (IOException e) {
throw new RuntimeException("Unable to serialize form save payload.");
}
File instanceXml = new File(FormEntryActivity.mInstancePath);
File submissionXml = new File(instanceXml.getParentFile(), "submission.xml");
// write out submission.xml -- the data to actually submit to aggregate
try {
writeXmlToStream(payload,
EncryptionIO.createFileOutputStream(submissionXml.getAbsolutePath(), symetricKey));
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Something is blocking acesss to the file at " + submissionXml.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Unable to write xml to " + submissionXml.getAbsolutePath());
}
// see if the form is encrypted and we can encrypt it...
EncryptedFormInformation formInfo = EncryptionUtils.getEncryptedFormInformation(mUri, FormEntryActivity.mFormController.getSubmissionMetadata(), context, instanceContentUri);
if ( formInfo != null ) {
// if we are encrypting, the form cannot be reopened afterward
canEditAfterCompleted = false;
// and encrypt the submission (this is a one-way operation)...
if (!EncryptionUtils.generateEncryptedSubmission(instanceXml, submissionXml, formInfo)) {
throw new RuntimeException("Unable to encrypt form submission.");
}
isEncrypted = true;
}
// At this point, we have:
// 1. the saved original instanceXml,
// 2. all the plaintext attachments
// 2. the submission.xml that is the completed xml (whether encrypting or not)
// 3. all the encrypted attachments if encrypting (isEncrypted = true).
// NEXT:
// 1. Update the instance database (with status complete).
// 2. Overwrite the instanceXml with the submission.xml
// and remove the plaintext attachments if encrypting
updateInstanceDatabase(false, canEditAfterCompleted);
if ( !canEditAfterCompleted ) {
// AT THIS POINT, there is no going back. We are committed
// to returning "success" (true) whether or not we can
// rename "submission.xml" to instanceXml and whether or
// not we can delete the plaintext media files.
// Handle the fall-out for a failed "submission.xml" rename
// in the InstanceUploader task. Leftover plaintext media
// files are handled during form deletion.
// delete the restore Xml file.
if ( !instanceXml.delete() ) {
Log.e(TAG, "Error deleting " + instanceXml.getAbsolutePath()
+ " prior to renaming submission.xml");
return;
}
// rename the submission.xml to be the instanceXml
if ( !submissionXml.renameTo(instanceXml) ) {
Log.e(TAG, "Error renaming submission.xml to " + instanceXml.getAbsolutePath());
return;
}
// if encrypted, delete all plaintext files
// (anything not named instanceXml or anything not ending in .enc)
if ( isEncrypted ) {
if ( !EncryptionUtils.deletePlaintextFiles(instanceXml) ) {
Log.e(TAG, "Error deleting plaintext files for " + instanceXml.getAbsolutePath());
}
}
}
}
}
private void writeXmlToStream(ByteArrayPayload payload, OutputStream output) throws IOException {
// create data stream
InputStream is = payload.getPayloadStream();
StreamsUtil.writeFromInputToOutput(is, output);
output.close();
}
@Override
protected void onPostExecute(SaveStatus result) {
super.onPostExecute(result);
synchronized (this) {
if (mSavedListener != null)
mSavedListener.savingComplete(result);
}
}
@Override
protected void deliverResult(FormEntryActivity receiver, SaveStatus result) {
}
@Override
protected void deliverUpdate(FormEntryActivity receiver, String... update) {
}
@Override
protected void deliverError(FormEntryActivity receiver, Exception e) {
receiver.handleFormSaveError(e);
}
public void setFormSavedListener(FormSavedListener fsl) {
synchronized (this) {
mSavedListener = fsl;
}
}
/**
* Goes through the entire form to make sure all entered answers comply
* with their constraints. Constraints are ignored on 'jump to', so
* answers can be outside of constraints. We don't allow saving to disk,
* though, until all answers conform to their constraints/requirements.
* @param fireTriggerables re-fire the triggers associated with the
* question when checking its constraints?
*/
private boolean hasInvalidAnswers(boolean markCompleted, boolean fireTriggerables) {
FormIndex i = FormEntryActivity.mFormController.getFormIndex();
FormEntryActivity.mFormController.jumpToIndex(FormIndex.createBeginningOfFormIndex());
int event;
if (!fireTriggerables) {
Logger.log(AndroidLogger.TYPE_FORM_ENTRY, "Saving form without firing triggers.");
}
while ((event =
FormEntryActivity.mFormController.stepToNextEvent(FormController.STEP_INTO_GROUP)) != FormEntryController.EVENT_END_OF_FORM) {
if (event == FormEntryController.EVENT_QUESTION) {
int saveStatus;
if (fireTriggerables) {
saveStatus =
FormEntryActivity.mFormController
.answerQuestion(FormEntryActivity.mFormController.getQuestionPrompt()
.getAnswerValue());
} else {
saveStatus =
FormEntryActivity.mFormController.checkCurrentQuestionConstraint();
}
if (markCompleted &&
(saveStatus == FormEntryController.ANSWER_REQUIRED_BUT_EMPTY ||
saveStatus == FormEntryController.ANSWER_CONSTRAINT_VIOLATED)) {
return true;
}
}
}
FormEntryActivity.mFormController.jumpToIndex(i);
return false;
}
}
|
package org.reactfx;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import org.reactfx.util.MapHelper;
class OnRecurseAccumulateStream<T, A> extends LazilyBoundStream<T> {
private final EventStream<T> source;
private final Function<? super T, ? extends A> initialTransformation;
private final BiFunction<? super A, ? super T, ? extends A> reduction;
private final ToIntFunction<? super A> size;
private final Function<? super A, ? extends T> head;
private final Function<? super A, ? extends A> tail;
private MapHelper<Subscriber<? super T>, A> pendingEvents = null;
public OnRecurseAccumulateStream(
EventStream<T> source,
Function<? super T, ? extends A> initialTransformation,
BiFunction<? super A, ? super T, ? extends A> reduction,
ToIntFunction<? super A> size,
Function<? super A, ? extends T> head,
Function<? super A, ? extends A> tail) {
this.source = source;
this.initialTransformation = initialTransformation;
this.reduction = reduction;
this.size = size;
this.head = head;
this.tail = tail;
}
@Override
protected Subscription subscribeToInputs() {
return subscribeTo(source, this::emitValue);
}
private void emitValue(T value) {
if(MapHelper.isEmpty(pendingEvents) && getObserverCount() == 1) {
emit(value);
} else {
forEachObserver(s -> {
if(MapHelper.containsKey(pendingEvents, s)) {
A accum = MapHelper.get(pendingEvents, s);
accum = reduction.apply(accum, value);
if(size.applyAsInt(accum) > 0) {
pendingEvents = MapHelper.put(pendingEvents, s, accum);
} else {
pendingEvents = MapHelper.remove(pendingEvents, s);
}
} else {
A accum = initialTransformation.apply(value);
if(size.applyAsInt(accum) > 0) {
pendingEvents = MapHelper.put(pendingEvents, s, accum);
}
}
});
while(!MapHelper.isEmpty(pendingEvents)) {
Subscriber<? super T> subscriber = MapHelper.chooseKey(pendingEvents);
A accum = MapHelper.get(pendingEvents, subscriber);
int n = size.applyAsInt(accum);
assert n > 0;
T first = head.apply(accum);
if(n == 1) {
pendingEvents = MapHelper.remove(pendingEvents, subscriber);
} else {
accum = tail.apply(accum);
if(size.applyAsInt(accum) > 0) { // always true if size() and tail() fulfill their contract
pendingEvents = MapHelper.put(pendingEvents, subscriber, accum);
}
}
runUnsafeAction(() -> subscriber.onEvent(first));
}
}
}
}
|
package com.dpanayotov.gameoflife.life;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.SurfaceHolder;
import com.dpanayotov.gameoflife.preferences.Preferences;
import com.dpanayotov.gameoflife.util.Resolution;
import java.util.ArrayList;
import java.util.List;
public class Life {
private List<Grid> queue;
private Grid grid;
private Grid previousGrid;
public Grid summedGrid;
private int screenWidth;
private int screenHeight;
private SurfaceHolder surfaceHolder;
private Resolution resolution;
private int halfCell;
private int tickRate;
private boolean isometricProjection;
private boolean highlife;
private int initialPopulationDensity;
private int minPopulationDensity;
private int minPopulationCount;
private boolean isRunning = false;
private HandlerThread ht;
private Handler handler;
private final Runnable drawRunner = new Runnable() {
@Override
public void run() {
update();
handler.postDelayed(drawRunner, tickRate);
}
};
private Paint primaryPaint = new Paint(),
secondaryPaint = new Paint(),
backgroundPaint = new Paint();
public Life(int screenWidth, int screenHeight, SurfaceHolder surfaceHolder) {
initPaint(Preferences.getColor(Preferences.Colors.PRIMARY), primaryPaint);
initPaint(Preferences.getColor(Preferences.Colors.SECONDARY), secondaryPaint);
initPaint(Preferences.getColor(Preferences.Colors.BACKGROUND), backgroundPaint);
getPreferences();
this.screenWidth = (int) ceil(screenWidth, resolution.cellSize);
this.screenHeight = (int) ceil(screenHeight, resolution.cellSize);
this.surfaceHolder = surfaceHolder;
resolution.gridWidth = this.screenWidth / resolution.cellSize;
resolution.gridHeight = this.screenHeight / resolution.cellSize;
minPopulationCount = Math.round(resolution.gridWidth * resolution.gridHeight *
(minPopulationDensity / 100f));
reset();
}
private void initPaint(int color, Paint paint) {
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
}
public void update() {
Grid nextGrid = grid.deriveNextState(highlife);
if (nextGrid.populationCount < minPopulationCount || previousGrid.equals(nextGrid)) {
reset();
drawRestart();
} else {
queue.add(0, new Grid(grid));
queue.remove(queue.size() - 1);
previousGrid = grid;
grid = new Grid(nextGrid);
summedGrid = new Grid(grid);
for (int i = 0; i < resolution.gridWidth; i++) {
for (int j = 0; j < resolution.gridHeight; j++) {
if (summedGrid.cells[i][j] == 0) {
for (int k = 0; k < Constants.QUEUE_SIZE; k++) {
if (queue.get(k).cells[i][j] == 1) {
summedGrid.cells[i][j] = k + 2;
break;
}
}
}
}
}
draw();
}
}
private void resetQueue() {
queue = new ArrayList<>();
for (int i = 0; i < Constants.QUEUE_SIZE; i++) {
queue.add(new Grid(resolution.gridWidth, resolution.gridHeight, 0));
}
}
private void reset() {
previousGrid = new Grid(resolution.gridWidth, resolution.gridHeight, 0);
grid = new Grid(resolution.gridWidth, resolution.gridHeight, initialPopulationDensity);
resetQueue();
}
private void getPreferences() {
resolution = Preferences.getResolutions().get(Preferences.getResolution());
halfCell = resolution.cellSize / 2;
tickRate = Preferences.getTickRates().get(Preferences.getTickRate());
isometricProjection = Preferences.getIsometricProjection();
highlife = Preferences.getHighlife();
minPopulationDensity = Preferences.getMinPopulationDensityOptions().get(Preferences
.getMinPopulationDensity());
initialPopulationDensity = Preferences.getInitialPopulationDensityOptions().get
(Preferences.getInitialPopulationDensity());
}
private void drawRestart() {
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
if (canvas != null) {
canvas.drawRect(0, 0, screenWidth, screenHeight, backgroundPaint);
}
} finally {
if (canvas != null) surfaceHolder.unlockCanvasAndPost(canvas);
}
}
private void draw() {
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
if (canvas != null) {
canvas.drawRect(0, 0, screenWidth, screenHeight, backgroundPaint);
for (int i = 0; i < resolution.gridWidth; i++) {
for (int j = 0; j < resolution.gridHeight; j++) {
if (summedGrid.cells[i][j] > 0) {
int cellX = i * resolution.cellSize + halfCell;
int cellY = j * resolution.cellSize + halfCell;
if (isometricProjection) {
cellY = (cellY + i * halfCell) % screenHeight;
}
drawCell(cellX, cellY, summedGrid.cells[i][j], canvas);
}
}
}
int j, value;
for (int i = 1; i < resolution.gridWidth; i += 2) {
j = resolution.gridHeight - 1 - ((i - 1) / 2);
value = summedGrid.cells[i][j];
if (value > 0) {
int cellX = i * resolution.cellSize + halfCell;
int cellY = j * resolution.cellSize + halfCell;
cellY = (cellY + i * halfCell);
drawCell(cellX, cellY, value, canvas);
}
}
}
} finally {
if (canvas != null) surfaceHolder.unlockCanvasAndPost(canvas);
}
}
private void drawCell(int x, int y, int value, Canvas canvas) {
secondaryPaint.setAlpha((int) (255 * (1 / (float) value)));
int radius = (halfCell - Constants.CELL_PADDING) - Constants
.RADIUS_STEP * (value - 1);
if (value > 1) {
canvas.drawCircle(x, y, radius, secondaryPaint);
} else {
canvas.drawCircle(x, y, radius, primaryPaint);
}
}
public void start() {
if (!isRunning) {
isRunning = true;
ht = new HandlerThread("");
ht.start();
handler = new Handler(ht.getLooper());
handler.post(drawRunner);
}
}
public void stop() {
if (isRunning) {
handler.removeCallbacks(drawRunner);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
ht.quitSafely();
}else{
ht.quit();
}
isRunning = false;
}
}
public static double ceil(double input, double step) {
return Math.ceil(input / step) * step;
}
}
|
package com.dpanayotov.gameoflife.life;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import com.dpanayotov.gameoflife.preferences.Preferences;
import com.dpanayotov.gameoflife.util.Resolution;
import com.dpanayotov.gameoflife.util.ScreenUtil;
import java.util.ArrayList;
import java.util.List;
public class Life {
private List<Grid> queue;
private Grid grid;
private Grid previousGrid;
public Grid summedGrid;
private int screenWidth;
private int screenHeight;
private SurfaceHolder surfaceHolder;
private Resolution resolution;
private int halfCell;
private int tickRate;
private boolean isometricProjection;
private boolean highlife;
private int minPopulationCount;
private boolean isRunning = false;
private Paint primaryPaint = new Paint(),
secondaryPaint = new Paint(),
backgroundPaint = new Paint();
public Life(int screenWidth, int screenHeight, int customGridWidth, int customGridHeight,
SurfaceHolder surfaceHolder) {
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.surfaceHolder = surfaceHolder;
initPaint(Preferences.getColor(Preferences.Colors.PRIMARY), primaryPaint);
initPaint(Preferences.getColor(Preferences.Colors.SECONDARY), secondaryPaint);
initPaint(Preferences.getColor(Preferences.Colors.BACKGROUND), backgroundPaint);
getPreferences();
if (customGridWidth != 0) {
resolution.gridWidth = customGridWidth;
}
if (customGridHeight != 0) {
resolution.gridHeight = customGridHeight;
}
reset();
}
public Life(int screenWidth, int screenHeight, SurfaceHolder surfaceHolder) {
this(screenWidth, screenHeight, 0, 0, surfaceHolder);
}
public Life(SurfaceHolder surfaceHolder) {
this(ScreenUtil.getScreenSize().x, ScreenUtil.getScreenSize().y, surfaceHolder);
}
private void initPaint(int color, Paint paint) {
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
}
public void update() {
Grid nextGrid = grid.deriveNextState(highlife);
if (nextGrid.populationCount < minPopulationCount || previousGrid.equals(nextGrid)) {
reset();
update();
} else {
queue.add(0, new Grid(grid));
queue.remove(queue.size() - 1);
previousGrid = grid;
grid = new Grid(nextGrid);
summedGrid = new Grid(grid);
for (int i = 0; i < resolution.gridWidth; i++) {
for (int j = 0; j < resolution.gridHeight; j++) {
if (summedGrid.cells[i][j] == 0) {
for (int k = 0; k < Constants.QUEUE_SIZE; k++) {
if (queue.get(k).cells[i][j] == 1) {
summedGrid.cells[i][j] = k + 2;
break;
}
}
}
}
}
draw();
}
}
private void resetQueue() {
queue = new ArrayList<>();
for (int i = 0; i < Constants.QUEUE_SIZE; i++) {
queue.add(new Grid(resolution.gridWidth, resolution.gridHeight, false));
}
}
private void reset() {
previousGrid = new Grid(resolution.gridWidth, resolution.gridHeight, false);
grid = new Grid(resolution.gridWidth, resolution.gridHeight, true);
resetQueue();
}
private void getPreferences() {
resolution = Preferences.getResolutions().get(Preferences.getResolution());
halfCell = resolution.cellSize / 2;
tickRate = Preferences.getTickRates().get(Preferences.getTickRate());
isometricProjection = Preferences.getIsometricProjection();
highlife = Preferences.getHighlife();
int populationPercentage = Preferences.getPopulationPercentages().get(Preferences
.getPopulationPercentage());
minPopulationCount = Math.round(((resolution.gridWidth * resolution.gridWidth) / 100f) *
populationPercentage);
}
private void draw() {
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
if (canvas != null) {
canvas.drawRect(0, 0, screenWidth, screenHeight, backgroundPaint);
for (int i = 0; i < resolution.gridWidth; i++) {
for (int j = 0; j < resolution.gridHeight; j++) {
if (summedGrid.cells[i][j] > 0) {
int cellX = i * resolution.cellSize + halfCell;
int cellY = j * resolution.cellSize + halfCell;
if (isometricProjection) {
cellY = (cellY + i * halfCell) % screenHeight;
}
secondaryPaint.setAlpha((int) (255 * (1 / (float) summedGrid
.cells[i][j])));
int radius = (halfCell - Constants.CELL_PADDING) - Constants
.RADIUS_STEP * (summedGrid.cells[i][j] - 1);
if (summedGrid.cells[i][j] > 1) {
canvas.drawCircle(cellX, cellY, radius, secondaryPaint);
} else {
canvas.drawCircle(cellX, cellY, radius, primaryPaint);
}
}
}
}
}
} finally {
if (canvas != null) surfaceHolder.unlockCanvasAndPost(canvas);
}
}
private final Handler handler = new Handler();
private final Runnable drawRunner = new Runnable() {
@Override
public void run() {
update();
handler.postDelayed(drawRunner, tickRate);
}
};
public void start() {
if (!isRunning) {
isRunning = true;
handler.post(drawRunner);
}
}
public void stop() {
if (isRunning) {
handler.removeCallbacks(drawRunner);
isRunning = false;
}
}
}
|
package com.example.tinyl.care4old;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class Care4Old extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"mail42@reponse.uni:84422448"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_care4_old);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login /*|| id == EditorInfo.IME_NULL*/) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
getLoaderManager().initLoader(0, null, this);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
/* if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}*/
// Check for a valid email address.
if (TextUtils.isEmpty(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
} else if (!isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(Care4Old.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
doHttpRequest();
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return doHttpRequest();
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
if (success) {
//Intent intent = new Intent(Care4Old.this, PatientPage.class);
openMainPage();
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
}
}
private void openMainPage(){
Intent intent = new Intent(Care4Old.this, MainPagePro.class);
startActivity(intent);
}
boolean doHttpRequest() {
return false;
}
}
|
package com.grayfox.android.client;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.grayfox.android.R;
import com.grayfox.android.client.model.AccessToken;
import com.grayfox.android.client.model.ApiResponse;
import com.grayfox.android.client.model.User;
import com.grayfox.android.http.Charset;
import com.grayfox.android.http.ContentType;
import com.grayfox.android.http.Header;
import com.grayfox.android.http.Method;
import com.grayfox.android.http.RequestBuilder;
import javax.inject.Inject;
public class UsersApi extends BaseApi {
private static final String TAG = UsersApi.class.getSimpleName();
@Inject
public UsersApi(Context context) {
super(context);
}
public String awaitAccessToken(String foursquareAuthorizationCode) {
String url = new Uri.Builder().scheme(getString(R.string.gf_api_host_scheme))
.encodedAuthority(getString(R.string.gf_api_host))
.appendEncodedPath(getString(R.string.gf_api_path))
.appendEncodedPath(getString(R.string.gf_api_app_users_path))
.appendEncodedPath(getString(R.string.gf_api_app_users_register_with_foursquare_path))
.appendQueryParameter("authorization-code", foursquareAuthorizationCode)
.build().toString();
String json = RequestBuilder.newInstance(url).setMethod(Method.GET)
.setHeader(Header.ACCEPT, ContentType.APPLICATION_JSON.getMimeType())
.setHeader(Header.ACCEPT_LANGUAGE, getClientAcceptLanguage())
.setHeader(Header.ACCEPT_CHARSET, Charset.UTF_8.getValue())
.makeForResult();
if (json != null) {
ApiResponse<AccessToken> apiResponse = parse(json, AccessToken.class);
if (apiResponse.getError() == null) return apiResponse.getResponse().getToken();
else {
Log.e(TAG, "Response error ->" + apiResponse.getError());
throw new ApiException(apiResponse.getError().getErrorMessage());
}
} else {
Log.e(TAG, "Null response");
throw new ApiException(getString(R.string.grayfox_api_request_error));
}
}
public User awaitSelfUser(String accessToken) {
String url = new Uri.Builder().scheme(getString(R.string.gf_api_host_scheme))
.encodedAuthority(getString(R.string.gf_api_host))
.appendEncodedPath(getString(R.string.gf_api_path))
.appendEncodedPath(getString(R.string.gf_api_app_users_path))
.appendEncodedPath(getString(R.string.gf_api_app_users_self_path))
.appendQueryParameter("access-token", accessToken)
.build().toString();
String json = RequestBuilder.newInstance(url).setMethod(Method.GET)
.setHeader(Header.ACCEPT, ContentType.APPLICATION_JSON.getMimeType())
.setHeader(Header.ACCEPT_LANGUAGE, getClientAcceptLanguage())
.setHeader(Header.ACCEPT_CHARSET, Charset.UTF_8.getValue())
.makeForResult();
if (json != null) {
ApiResponse<User> apiResponse = parse(json, User.class);
if (apiResponse.getError() == null) return apiResponse.getResponse();
else {
Log.e(TAG, "Response error ->" + apiResponse.getError());
throw new ApiException(apiResponse.getError().getErrorMessage());
}
} else {
Log.e(TAG, "Null response");
throw new ApiException(getString(R.string.grayfox_api_request_error));
}
}
}
|
package com.germancoding.packetapi;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.logging.Logger;
import com.germancoding.packetapi.Process.ActionType;
import com.germancoding.packetapi.defaultpackets.ClosePacket;
import com.germancoding.packetapi.defaultpackets.DefaultPacket;
import com.germancoding.packetapi.defaultpackets.HandshakePacket;
public class PacketHandler {
/** Applications can change this value if they want **/
public static int PROTOCOL_VERSION = 1;
/** Handshake ID used in the sendHandshake() method. The other side will respond to that packet. **/
public static int HANDSHAKE_ID_REQUEST = 0;
/** Handshake ID used when replying to a handshake packet. The other side will not respond to that packet. **/
public static int HANDSHAKE_ID_RESPONSE = 1;
public Logger logger = Logger.getLogger("PacketHandler");
public InputStream in; // Public for direct access (Yes, that's not encapsulated...)
public OutputStream out;
private DataSender sender;
private DataReader reader;
private PacketListener listener;
private DefaultPacketListener defaultPacketListener = new DefaultPacketListener(this);
// State attributes
private String connectionName;
private boolean closed;
private boolean versionApproved;
private boolean handshakeSend;
private boolean closeListenerNotified;
private int remoteProtocolVersion = -1;
private HashMap<Short, Class<? extends Packet>> packetMap = new HashMap<Short, Class<? extends Packet>>(); // TODO: What about a static packet map? (The local packet map could be optional)
private static boolean hasExternalThread;
private static int numberOfHandlers;
private static LinkedList<Process> processingQueue = new LinkedList<Process>();
/**
* Creates a new PacketHandler instance. The instance will use the given I/O streams to send and receive data.
*
* @param in
* The InputStream to read data from.
* @param out
* The OutputStream to send data to.
* @param connectionName
* Optional: Give the connection a name to identify it. Can be <code>null</code>.
* @param listener
* A listener which is notified when something happens (A packet arrived, the connection failed...). Can be <code>null</code> if the application does not want to listen to
* incoming data.
*/
public PacketHandler(InputStream in, OutputStream out, String connectionName, PacketListener listener) {
if (in == null || out == null) {
throw new IllegalArgumentException("InputStream or OutputStream can not be null");
}
if (connectionName == null)
connectionName = "";
this.in = in;
this.out = out;
this.setConnectionName(connectionName);
if (listener != null) // Could be null, if the application doesn't want to listen to incoming packets
{
this.setListener(listener);
} else {
this.setListener(new PacketListener() { // Setup an empty listener for the application
@Override
public void onPacketReceived(PacketHandler handler, Packet packet) {
; // Do nothing
}
@Override
public void onConnectionFailed(PacketHandler handler) {
;
}
@Override
public void onUnknownPacketReceived(PacketHandler handler, short id) {
;
}
@Override
public void onConnectionClosed(PacketHandler handler, String message, boolean expected) {
;
}
});
}
registerPacketDefaults();
sender = new DataSender(this);
reader = new DataReader(this);
numberOfHandlers++;
}
private void registerPacketDefaults() {
try {
registerPacket(HandshakePacket.class);
registerPacket(ClosePacket.class);
} catch (Exception e) {
logger.severe("Failed to register default packets! " + e);
}
}
/**
* Registers a new packet. After registering the packet type can be send and received.
*
* @param packetClass
* The class of the new packet.
* @throws Exception
* If reflection fails, like when there is no nullary constructor.
*/
public void registerPacket(Class<? extends Packet> packetClass) throws Exception {
if (packetClass == null)
throw new IllegalArgumentException("packetClass can not be null");
// If this call fails (e.g when there is no nullary constructor), an exception will be thrown.
int id = packetClass.newInstance().getId();
packetMap.put((short) id, packetClass);
}
public Packet getNewPacketInstance(short id) {
Class<? extends Packet> packetClass = packetMap.get(id);
if (packetClass == null) {
logger.warning("Packet with id=" + id + " not found");
return null;
}
try {
return packetClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
logger.severe("Failed to instantiate a new packet class instance. " + e);
}
return null;
}
/**
* Sends the given packet by adding it to the sending queue.
*
* @param p
* The packet to send.
*/
public void sendPacket(Packet p) {
getSender().sendPacket(p);
}
/**
* Notifies this instance that the connection has failed. This method notifies the listeners and closes the connection
*
* @param e
* A exception describing why the connection has failed.
*/
public void onConnectionFail(Exception e) {
if (closed) // Abort if the connection was already closed (A closed connection can not fail)
return;
logger.severe("Connection '" + getConnectionName() + "' failed! " + e);
getDefaultPacketListener().onConnectionFailed(this);
getListener().onConnectionFailed(this);
close();
}
/**
* Notifies this instance that the connection is closed.
*
* @param message
* Message why the connection was closed.
* @param expected
* Whether this was expected (like there was a close packet) or not (like when the underlying socket is closed without notification)
*/
public void onConnectionClosed(String message, boolean expected) {
getDefaultPacketListener().onConnectionClosed(this, message, expected);
getListener().onConnectionClosed(this, message, expected);
closeListenerNotified = true;
close();
}
/**
* Closes the connection, the I/O streams and notfies the other side that we are closing this connection.
*/
public void close() {
if (closed)
return;
if (!closeListenerNotified) {
// Someone is calling close() directly so we assume that the connection was closed expectly
getDefaultPacketListener().onConnectionClosed(this, "Connection closed locally", true);
getListener().onConnectionClosed(this, "Connection closed locally", true);
}
closed = true;
ClosePacket close = new ClosePacket();
sendPacket(close);
long timeout = System.currentTimeMillis() + 5000;
do {
synchronized (this) {
try {
this.wait(500);
if (System.currentTimeMillis() >= timeout) {
break;
}
} catch (InterruptedException e) {
break;
}
}
} while (!sender.queueEmpty());
sender.interrupt();
reader.interrupt();
try {
in.close();
out.close();
} catch (IOException e) {
;
}
numberOfHandlers
synchronized (processingQueue) {
processingQueue.notify(); // Wake up an waiting external thread (if there is one) to update itself.
}
dispose();
}
private void dispose() {
sender = null;
reader = null;
packetMap = null;
in = null;
out = null;
connectionName = null;
logger = null;
listener = null;
defaultPacketListener = null;
}
/**
* @return The name of this connection.
*/
public String getConnectionName() {
return connectionName;
}
public void setConnectionName(String connectionName) {
this.connectionName = connectionName;
}
/**
* @return The reader which is reading data from the InputStream.
*/
public DataReader getReader() {
return reader;
}
/**
* @return The sender which is sending data to the OutputStream.
*/
public DataSender getSender() {
return sender;
}
/**
* @return The application/user listener.
*/
public PacketListener getListener() {
return listener;
}
public void setListener(PacketListener listener) {
this.listener = listener;
}
/**
* @return The listener used by the PacketAPI for default packets.
*/
public DefaultPacketListener getDefaultPacketListener() {
return defaultPacketListener;
}
public void setDefaultPacketListener(DefaultPacketListener defaultPacketListener) {
this.defaultPacketListener = defaultPacketListener;
}
/**
* Called when a new packet was received.
*
* @param packet
* The packet just received.
*/
public void onPacketReceived(Packet packet) {
if (hasExternalThread) {
// Processing is done by the external thread
Process process = new Process(ActionType.RECEIVED, packet.getId(), packet, this);
addToQueue(process);
} else {
// Directly pass the packet to the listener
processPacket(packet);
}
}
public void onUnknownPacketReceived(short id) {
if (hasExternalThread) {
Process process = new Process(ActionType.UNKN_RECEIVED, id, null, this);
addToQueue(process);
} else {
processUnknownPacket(id);
}
}
private void processUnknownPacket(short id) {
getDefaultPacketListener().onUnknownPacketReceived(this, id);
getListener().onUnknownPacketReceived(this, id);
}
private void processPacket(Packet packet) {
if (packet instanceof DefaultPacket) {
getDefaultPacketListener().onPacketReceived(this, packet);
} else {
getListener().onPacketReceived(this, packet);
}
}
/**
* Whether the connection was closed (using the close() function of this class) or not.
*
* @return
*/
public boolean isClosed() {
return closed;
}
private void addToQueue(Process process) {
synchronized (processingQueue) {
processingQueue.add(process);
processingQueue.notify();
}
}
/**
* Sends a handshake to exchange version numbers. You have to call this method if you want to use state attributes like isVersionApproved().
*/
public void sendHandshake() {
sendHandshake(HANDSHAKE_ID_REQUEST);
}
/**
* Sends a handshake using the given id as the handshake id.
*
* @param id
* The handshake id.
*/
public void sendHandshake(int id) {
HandshakePacket handshake = new HandshakePacket();
handshake.setHandshakeID(id);
handshake.setProtocolVersion(PROTOCOL_VERSION);
sendPacket(handshake);
setHandshakeSend(true);
}
public static boolean hasExternalThread() {
return hasExternalThread;
}
public static void threadJoin() {
if (hasExternalThread) {
throw new IllegalAccessError("There is already an external thread");
}
hasExternalThread = true;
while (numberOfHandlers > 0) {
try {
Process proc = null;
synchronized (processingQueue) {
if (!processingQueue.isEmpty()) {
proc = processingQueue.removeFirst();
}
}
if (proc != null) {
switch (proc.getType()) {
case RECEIVED:
proc.getHandler().processPacket(proc.getPacket());
break;
case UNKN_RECEIVED:
proc.getHandler().processUnknownPacket(proc.getPacketID());
break;
default:
break;
}
} else // No more elements in the queue, wait for a notify
{
synchronized (processingQueue) {
try {
processingQueue.wait();
} catch (InterruptedException e) {
;
}
}
}
} catch (Throwable e) {
System.err.println("Exception in external processing thread: " + e);
}
}
hasExternalThread = false;
}
/**
* @return Whether the protocol version is approved. The protocol version is approved when both peers have the same protocol version.<br>
* To request a version check, simply send a handshake packet by calling <code>sendHandshake()</code>. After receiving the response from the other side and comparing the version numbers, the version will
* be approved.
*/
public boolean isVersionApproved() {
return versionApproved;
}
public void setVersionApproved(boolean versionApproved) {
this.versionApproved = versionApproved;
}
/**
* @return Whether this side has send a handshake packet.<br>
* Note: Handshake packets are not send automatically, you have to call <code>sendHandshake()</code>.
*/
public boolean isHandshakeSend() {
return handshakeSend;
}
public void setHandshakeSend(boolean handshakeSend) {
this.handshakeSend = handshakeSend;
}
/**
* @return The protocol version of the other peer or -1 if the version used by the other peer is unknown (e.g no handshake was send)
*/
public int getRemoteProtocolVersion() {
return remoteProtocolVersion;
}
public void setRemoteProtocolVersion(int remoteProtocolVersion) {
this.remoteProtocolVersion = remoteProtocolVersion;
}
}
|
package com.slidingmenu.lib;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.view.KeyEventCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.util.Log;
import android.util.TypedValue;
import android.view.FocusFinder;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.Scroller;
import com.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.slidingmenu.lib.SlidingMenu.OnOpenedListener;
//import com.slidingmenu.lib.SlidingMenu.OnCloseListener;
//import com.slidingmenu.lib.SlidingMenu.OnOpenListener;
public class CustomViewAbove extends ViewGroup {
private static final String TAG = "CustomViewAbove";
private static final boolean DEBUG = false;
private static final boolean USE_CACHE = false;
private static final int MAX_SETTLE_DURATION = 600;
private static final int MIN_DISTANCE_FOR_FLING = 25; // dips
private static final Interpolator sInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
private View mContent;
private int mCurItem;
private Scroller mScroller;
private boolean mScrollingCacheEnabled;
private boolean mScrolling;
private boolean mIsBeingDragged;
private boolean mIsUnableToDrag;
private int mTouchSlop;
private float mInitialMotionX;
/**
* Position of the last motion event.
*/
private float mLastMotionX;
private float mLastMotionY;
/**
* ID of the active pointer. This is used to retain consistency during
* drags/flings if multiple pointers are used.
*/
protected int mActivePointerId = INVALID_POINTER;
/**
* Sentinel value for no current active pointer.
* Used by {@link #mActivePointerId}.
*/
private static final int INVALID_POINTER = -1;
/**
* Determines speed during touch scrolling
*/
protected VelocityTracker mVelocityTracker;
private int mMinimumVelocity;
protected int mMaximumVelocity;
private int mFlingDistance;
private CustomViewBehind mCustomViewBehind;
// private int mMode;
private boolean mEnabled = true;
private OnPageChangeListener mOnPageChangeListener;
private OnPageChangeListener mInternalPageChangeListener;
// private OnCloseListener mCloseListener;
// private OnOpenListener mOpenListener;
private OnClosedListener mClosedListener;
private OnOpenedListener mOpenedListener;
// private int mScrollState = SCROLL_STATE_IDLE;
/**
* Callback interface for responding to changing state of the selected page.
*/
public interface OnPageChangeListener {
/**
* This method will be invoked when the current page is scrolled, either as part
* of a programmatically initiated smooth scroll or a user initiated touch scroll.
*
* @param position Position index of the first page currently being displayed.
* Page position+1 will be visible if positionOffset is nonzero.
* @param positionOffset Value from [0, 1) indicating the offset from the page at position.
* @param positionOffsetPixels Value in pixels indicating the offset from position.
*/
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
/**
* This method will be invoked when a new page becomes selected. Animation is not
* necessarily complete.
*
* @param position Position index of the new selected page.
*/
public void onPageSelected(int position);
}
/**
* Simple implementation of the {@link OnPageChangeListener} interface with stub
* implementations of each method. Extend this if you do not intend to override
* every method of {@link OnPageChangeListener}.
*/
public static class SimpleOnPageChangeListener implements OnPageChangeListener {
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// This space for rent
}
public void onPageSelected(int position) {
// This space for rent
}
public void onPageScrollStateChanged(int state) {
// This space for rent
}
}
public CustomViewAbove(Context context) {
this(context, null);
}
public CustomViewAbove(Context context, AttributeSet attrs) {
this(context, attrs, true);
}
public CustomViewAbove(Context context, AttributeSet attrs, boolean isAbove) {
super(context, attrs);
initCustomViewAbove();
}
void initCustomViewAbove() {
setWillNotDraw(false);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setFocusable(true);
final Context context = getContext();
mScroller = new Scroller(context, sInterpolator);
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
setInternalPageChangeListener(new SimpleOnPageChangeListener() {
public void onPageSelected(int position) {
if (mCustomViewBehind != null) {
switch (position) {
case 0:
case 2:
mCustomViewBehind.setChildrenEnabled(true);
break;
case 1:
mCustomViewBehind.setChildrenEnabled(false);
break;
}
}
}
});
final float density = context.getResources().getDisplayMetrics().density;
mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);
}
/**
* Set the currently selected page. If the CustomViewPager has already been through its first
* layout there will be a smooth animated transition between the current item and the
* specified item.
*
* @param item Item index to select
*/
public void setCurrentItem(int item) {
setCurrentItemInternal(item, true, false);
}
/**
* Set the currently selected page.
*
* @param item Item index to select
* @param smoothScroll True to smoothly scroll to the new item, false to transition immediately
*/
public void setCurrentItem(int item, boolean smoothScroll) {
setCurrentItemInternal(item, smoothScroll, false);
}
public int getCurrentItem() {
return mCurItem;
}
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) {
setCurrentItemInternal(item, smoothScroll, always, 0);
}
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) {
// if (!always && mCurItem == item && mMenu != null && mContent != null) {
if (!always && mCurItem == item && mContent != null) {
setScrollingCacheEnabled(false);
return;
}
item = mCustomViewBehind.getMenuPage(item);
final boolean dispatchSelected = mCurItem != item;
mCurItem = item;
final int destX = getDestScrollX(mCurItem);
if (dispatchSelected && mOnPageChangeListener != null) {
mOnPageChangeListener.onPageSelected(item);
}
if (dispatchSelected && mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageSelected(item);
}
if (smoothScroll) {
smoothScrollTo(destX, 0, velocity);
} else {
completeScroll();
scrollTo(destX, 0);
}
}
/**
* Set a listener that will be invoked whenever the page changes or is incrementally
* scrolled. See {@link OnPageChangeListener}.
*
* @param listener Listener to set
*/
public void setOnPageChangeListener(OnPageChangeListener listener) {
mOnPageChangeListener = listener;
}
/*
public void setOnOpenListener(OnOpenListener l) {
mOpenListener = l;
}
public void setOnCloseListener(OnCloseListener l) {
mCloseListener = l;
}
*/
public void setOnOpenedListener(OnOpenedListener l) {
mOpenedListener = l;
}
public void setOnClosedListener(OnClosedListener l) {
mClosedListener = l;
}
/**
* Set a separate OnPageChangeListener for internal use by the support library.
*
* @param listener Listener to set
* @return The old listener that was set, if any.
*/
OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) {
OnPageChangeListener oldListener = mInternalPageChangeListener;
mInternalPageChangeListener = listener;
return oldListener;
}
// We want the duration of the page snap animation to be influenced by the distance that
// the screen has to travel, however, we don't want this duration to be effected in a
// purely linear fashion. Instead, we use this method to moderate the effect that the distance
// of travel has on the overall snap duration.
float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
return (float) FloatMath.sin(f);
}
public int getDestScrollX(int page) {
switch (page) {
case 0:
case 2:
return mCustomViewBehind.getMenuLeft(mContent, page);
case 1:
return mContent.getLeft();
}
return 0;
}
private int getLeftBound() {
return mCustomViewBehind.getAbsLeftBound(mContent);
}
private int getRightBound() {
return mCustomViewBehind.getAbsRightBound(mContent);
}
public int getContentLeft() {
return mContent.getLeft() + mContent.getPaddingLeft();
}
public boolean isMenuOpen() {
return mCurItem == 0 || mCurItem == 2;
}
public int getBehindWidth() {
if (mCustomViewBehind == null) {
return 0;
} else {
return mCustomViewBehind.getBehindWidth();
}
}
public int getChildWidth(int i) {
switch (i) {
case 0:
return getBehindWidth();
case 1:
return mContent.getWidth();
default:
return 0;
}
}
public boolean isSlidingEnabled() {
return mEnabled;
}
public void setSlidingEnabled(boolean b) {
mEnabled = b;
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x the number of pixels to scroll by on the X axis
* @param y the number of pixels to scroll by on the Y axis
*/
void smoothScrollTo(int x, int y) {
smoothScrollTo(x, y, 0);
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x the number of pixels to scroll by on the X axis
* @param y the number of pixels to scroll by on the Y axis
* @param velocity the velocity associated with a fling, if applicable. (0 otherwise)
*/
void smoothScrollTo(int x, int y, int velocity) {
if (getChildCount() == 0) {
// Nothing to do.
setScrollingCacheEnabled(false);
return;
}
int sx = getScrollX();
int sy = getScrollY();
int dx = x - sx;
int dy = y - sy;
if (dx == 0 && dy == 0) {
completeScroll();
if (isMenuOpen()) {
if (mOpenedListener != null)
mOpenedListener.onOpened();
} else {
if (mClosedListener != null)
mClosedListener.onClosed();
}
return;
}
setScrollingCacheEnabled(true);
mScrolling = true;
final int width = getBehindWidth();
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth *
distanceInfluenceForSnapDuration(distanceRatio);
int duration = 0;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
final float pageDelta = (float) Math.abs(dx) / width;
duration = (int) ((pageDelta + 1) * 100);
duration = MAX_SETTLE_DURATION;
}
duration = Math.min(duration, MAX_SETTLE_DURATION);
mScroller.startScroll(sx, sy, dx, dy, duration);
invalidate();
}
public void setContent(View v) {
if (mContent != null)
this.removeView(mContent);
mContent = v;
addView(mContent);
}
public View getContent() {
return mContent;
}
public void setCustomViewBehind(CustomViewBehind cvb) {
mCustomViewBehind = cvb;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = getDefaultSize(0, widthMeasureSpec);
int height = getDefaultSize(0, heightMeasureSpec);
setMeasuredDimension(width, height);
final int contentWidth = getChildMeasureSpec(widthMeasureSpec, 0, width);
final int contentHeight = getChildMeasureSpec(heightMeasureSpec, 0, height);
mContent.measure(contentWidth, contentHeight);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Make sure scroll position is set correctly.
if (w != oldw) {
// [ChrisJ] - This fixes the onConfiguration change for orientation issue..
// maybe worth having a look why the recomputeScroll pos is screwing
completeScroll();
scrollTo(getDestScrollX(mCurItem), getScrollY());
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int width = r - l;
final int height = b - t;
mContent.layout(0, 0, width, height);
}
public void setAboveOffset(int i) {
// RelativeLayout.LayoutParams params = ((RelativeLayout.LayoutParams)mContent.getLayoutParams());
// params.setMargins(i, params.topMargin, params.rightMargin, params.bottomMargin);
mContent.setPadding(i, mContent.getPaddingTop(),
mContent.getPaddingRight(), mContent.getPaddingBottom());
}
@Override
public void computeScroll() {
if (!mScroller.isFinished()) {
if (mScroller.computeScrollOffset()) {
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
pageScrolled(x);
}
// Keep on drawing until the animation has finished.
invalidate();
return;
}
}
// Done with scroll, clean up state.
completeScroll();
}
private void pageScrolled(int xpos) {
final int widthWithMargin = getWidth();
final int position = xpos / widthWithMargin;
final int offsetPixels = xpos % widthWithMargin;
final float offset = (float) offsetPixels / widthWithMargin;
onPageScrolled(position, offset, offsetPixels);
}
/**
* This method will be invoked when the current page is scrolled, either as part
* of a programmatically initiated smooth scroll or a user initiated touch scroll.
* If you override this method you must call through to the superclass implementation
* (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled
* returns.
*
* @param position Position index of the first page currently being displayed.
* Page position+1 will be visible if positionOffset is nonzero.
* @param offset Value from [0, 1) indicating the offset from the page at position.
* @param offsetPixels Value in pixels indicating the offset from position.
*/
protected void onPageScrolled(int position, float offset, int offsetPixels) {
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels);
}
if (mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels);
}
}
private void completeScroll() {
boolean needPopulate = mScrolling;
if (needPopulate) {
// Done with scroll, no longer want to cache view drawing.
setScrollingCacheEnabled(false);
mScroller.abortAnimation();
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
}
if (isMenuOpen()) {
if (mOpenedListener != null)
mOpenedListener.onOpened();
} else {
if (mClosedListener != null)
mClosedListener.onClosed();
}
}
mScrolling = false;
}
protected int mTouchMode = SlidingMenu.TOUCHMODE_MARGIN;
public void setTouchMode(int i) {
mTouchMode = i;
}
public int getTouchMode() {
return mTouchMode;
}
private boolean thisTouchAllowed(MotionEvent ev) {
int x = (int) (ev.getX() + mScrollX);
if (isMenuOpen()) {
return mCustomViewBehind.menuOpenTouchAllowed(mContent, mCurItem, x);
} else {
switch (mTouchMode) {
case SlidingMenu.TOUCHMODE_FULLSCREEN:
return true;
case SlidingMenu.TOUCHMODE_NONE:
return false;
case SlidingMenu.TOUCHMODE_MARGIN:
return mCustomViewBehind.marginTouchAllowed(mContent, x);
}
}
return false;
}
private boolean thisSlideAllowed(float dx) {
boolean allowed = false;
if (isMenuOpen()) {
allowed = mCustomViewBehind.menuOpenSlideAllowed(dx);
} else {
allowed = mCustomViewBehind.menuClosedSlideAllowed(dx);
}
if (DEBUG)
Log.v(TAG, "this slide allowed " + allowed + " dx: " + dx);
return allowed;
}
private int getPointerIndex(MotionEvent ev, int id) {
int activePointerIndex = MotionEventCompat.findPointerIndex(ev, id);
if (activePointerIndex == -1)
mActivePointerId = INVALID_POINTER;
return activePointerIndex;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (!mEnabled)
return false;
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
if (action == MotionEvent.ACTION_DOWN && DEBUG)
Log.v(TAG, "Received ACTION_DOWN");
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP
|| (action != MotionEvent.ACTION_DOWN && mIsUnableToDrag)) {
endDrag();
return false;
}
switch (action) {
case MotionEvent.ACTION_MOVE:
final int activePointerId = mActivePointerId;
if (activePointerId == INVALID_POINTER)
break;
final int pointerIndex = this.getPointerIndex(ev, activePointerId);
if (mActivePointerId == INVALID_POINTER)
break;
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float dx = x - mLastMotionX;
final float xDiff = Math.abs(dx);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mLastMotionY);
if (DEBUG) Log.v(TAG, "onInterceptTouch moved to:(" + x + ", " + y + "), diff:(" + xDiff + ", " + yDiff + "), mLastMotionX:" + mLastMotionX);
if (xDiff > mTouchSlop && xDiff > yDiff && thisSlideAllowed(dx)) {
if (DEBUG) Log.v(TAG, "Starting drag! from onInterceptTouch");
mIsBeingDragged = true;
mLastMotionX = x;
setScrollingCacheEnabled(true);
} else if (yDiff > mTouchSlop) {
mIsUnableToDrag = true;
}
break;
case MotionEvent.ACTION_DOWN:
mActivePointerId = ev.getAction() & ((Build.VERSION.SDK_INT >= 8) ? MotionEvent.ACTION_POINTER_INDEX_MASK :
MotionEvent.ACTION_POINTER_INDEX_MASK);
mLastMotionX = mInitialMotionX = MotionEventCompat.getX(ev, mActivePointerId);
mLastMotionY = MotionEventCompat.getY(ev, mActivePointerId);
if (thisTouchAllowed(ev)) {
mIsBeingDragged = false;
mIsUnableToDrag = false;
if (isMenuOpen())
return true;
} else {
mIsUnableToDrag = true;
}
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
if (!mIsBeingDragged) {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
}
return mIsBeingDragged;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!mEnabled)
return false;
if (!mIsBeingDragged && !thisTouchAllowed(ev))
return false;
final int action = ev.getAction();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
/*
* If being flinged and user touches, stop the fling. isFinished
* will be false if being flinged.
*/
completeScroll();
// Remember where the motion event started
mLastMotionX = mInitialMotionX = ev.getX();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
break;
case MotionEvent.ACTION_MOVE:
if (!mIsBeingDragged) {
final int pointerIndex = getPointerIndex(ev, mActivePointerId);
if (mActivePointerId == INVALID_POINTER) {
break;
}
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float dx = x - mLastMotionX;
final float xDiff = Math.abs(dx);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mLastMotionY);
if (DEBUG) Log.v(TAG, "onTouch moved to:(" + x + ", " + y + "), diff:(" + xDiff + ", " + yDiff + "), mLastMotionX:" + mLastMotionX);
if (xDiff > mTouchSlop && xDiff > yDiff && thisSlideAllowed(dx)) {
if (DEBUG) Log.v(TAG, "Starting drag! from onTouch");
mIsBeingDragged = true;
mLastMotionX = x;
setScrollingCacheEnabled(true);
}
}
if (mIsBeingDragged) {
// Scroll to follow the motion event
final int activePointerIndex = getPointerIndex(ev, mActivePointerId);
if (mActivePointerId == INVALID_POINTER) {
break;
}
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final float deltaX = mLastMotionX - x;
mLastMotionX = x;
float oldScrollX = getScrollX();
float scrollX = oldScrollX + deltaX;
final float leftBound = getLeftBound();
final float rightBound = getRightBound();
if (scrollX < leftBound) {
scrollX = leftBound;
} else if (scrollX > rightBound) {
scrollX = rightBound;
}
// Don't lose the rounded component
mLastMotionX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
pageScrolled((int) scrollX);
}
break;
case MotionEvent.ACTION_UP:
if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
velocityTracker, mActivePointerId);
final int scrollX = getScrollX();
// final int widthWithMargin = getWidth();
// final float pageOffset = (float) (scrollX % widthWithMargin) / widthWithMargin;
// TODO test this. should get better flinging behavior
final float pageOffset = (float) (scrollX - getDestScrollX(mCurItem)) / getBehindWidth();
final int activePointerIndex = getPointerIndex(ev, mActivePointerId);
if (mActivePointerId != INVALID_POINTER) {
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final int totalDelta = (int) (x - mInitialMotionX);
int nextPage = determineTargetPage(pageOffset, initialVelocity, totalDelta);
setCurrentItemInternal(nextPage, true, true, initialVelocity);
} else {
setCurrentItemInternal(mCurItem, true, true, initialVelocity);
}
mActivePointerId = INVALID_POINTER;
endDrag();
} else if (isMenuOpen()) {
// close the menu
setCurrentItem(1);
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsBeingDragged) {
setCurrentItemInternal(mCurItem, true, true);
mActivePointerId = INVALID_POINTER;
endDrag();
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
final float x = MotionEventCompat.getX(ev, index);
mLastMotionX = x;
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
int pointerIndex = this.getPointerIndex(ev, mActivePointerId);
if (mActivePointerId == INVALID_POINTER)
break;
mLastMotionX = MotionEventCompat.getX(ev, pointerIndex);
break;
}
return true;
}
@Override
public void scrollTo(int x, int y) {
super.scrollTo(x, y);
mScrollX = x;
if (mEnabled)
mCustomViewBehind.scrollBehindTo(mContent, x, y);
// if (mSelectorDrawable != null)
// invalidate();
}
private int determineTargetPage(float pageOffset, int velocity, int deltaX) {
int targetPage = mCurItem;
if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) {
targetPage += velocity > 0 ? -1: 1;
} else {
targetPage = (int) Math.round(mCurItem + pageOffset);
}
return targetPage;
}
protected float getPercentOpen() {
return Math.abs(mScrollX) / getBehindWidth();
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
// Draw the margin drawable if needed.
mCustomViewBehind.drawShadow(mContent, canvas);
mCustomViewBehind.drawFade(mContent, canvas, getPercentOpen());
// if (mSelectorEnabled)
// onDrawMenuSelector(canvas, getPercentOpen());
}
// variables for drawing
private float mScrollX = 0.0f;
// for the indicator
private boolean mSelectorEnabled = true;
private Bitmap mSelectorDrawable;
private View mSelectedView;
private void onDrawMenuSelector(Canvas canvas, float openPercent) {
if (mSelectorDrawable != null && mSelectedView != null) {
String tag = (String) mSelectedView.getTag(R.id.selected_view);
if (tag.equals(TAG+"SelectedView")) {
int right = getContentLeft();
int left = (int) (right - mSelectorDrawable.getWidth() * openPercent);
canvas.save();
canvas.clipRect(left, 0, right, getHeight());
canvas.drawBitmap(mSelectorDrawable, left, getSelectedTop(), null);
canvas.restore();
}
}
}
public void setSelectorEnabled(boolean b) {
mSelectorEnabled = b;
}
public void setSelectedView(View v) {
if (mSelectedView != null) {
mSelectedView.setTag(R.id.selected_view, null);
mSelectedView = null;
}
if (v.getParent() != null) {
mSelectedView = v;
mSelectedView.setTag(R.id.selected_view, TAG+"SelectedView");
invalidate();
}
}
private int getSelectedTop() {
int y = mSelectedView.getTop();
y += (mSelectedView.getHeight() - mSelectorDrawable.getHeight()) / 2;
return y;
}
public void setSelectorBitmap(Bitmap b) {
mSelectorDrawable = b;
refreshDrawableState();
}
private void onSecondaryPointerUp(MotionEvent ev) {
if (DEBUG) Log.v(TAG, "onSecondaryPointerUp called");
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
private void endDrag() {
mIsBeingDragged = false;
mIsUnableToDrag = false;
mActivePointerId = INVALID_POINTER;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
private void setScrollingCacheEnabled(boolean enabled) {
if (mScrollingCacheEnabled != enabled) {
mScrollingCacheEnabled = enabled;
if (USE_CACHE) {
final int size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(enabled);
}
}
}
}
}
/**
* Tests scrollability within child views of v given a delta of dx.
*
* @param v View to test for horizontal scrollability
* @param checkV Whether the view v passed should itself be checked for scrollability (true),
* or just its children (false).
* @param dx Delta scrolled in pixels
* @param x X coordinate of the active touch point
* @param y Y coordinate of the active touch point
* @return true if child views of v can be scrolled by delta of dx.
*/
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
final int scrollY = v.getScrollY();
final int count = group.getChildCount();
// Count backwards - let topmost views consume scroll distance first.
for (int i = count - 1; i >= 0; i
final View child = group.getChildAt(i);
if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() &&
y + scrollY >= child.getTop() && y + scrollY < child.getBottom() &&
canScroll(child, true, dx, x + scrollX - child.getLeft(),
y + scrollY - child.getTop())) {
return true;
}
}
}
return checkV && ViewCompat.canScrollHorizontally(v, -dx);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// Let the focused view and/or our descendants get the key first
return super.dispatchKeyEvent(event) || executeKeyEvent(event);
}
/**
* You can call this function yourself to have the scroll view perform
* scrolling from a key event, just as if the event had been dispatched to
* it by the view hierarchy.
*
* @param event The key event to execute.
* @return Return true if the event was handled, else false.
*/
public boolean executeKeyEvent(KeyEvent event) {
boolean handled = false;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_LEFT:
handled = arrowScroll(FOCUS_LEFT);
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
handled = arrowScroll(FOCUS_RIGHT);
break;
case KeyEvent.KEYCODE_TAB:
if (Build.VERSION.SDK_INT >= 11) {
// The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD
// before Android 3.0. Ignore the tab key on those devices.
if (KeyEventCompat.hasNoModifiers(event)) {
handled = arrowScroll(FOCUS_FORWARD);
} else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
handled = arrowScroll(FOCUS_BACKWARD);
}
}
break;
}
}
return handled;
}
public boolean arrowScroll(int direction) {
View currentFocused = findFocus();
if (currentFocused == this) currentFocused = null;
boolean handled = false;
View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused,
direction);
if (nextFocused != null && nextFocused != currentFocused) {
if (direction == View.FOCUS_LEFT) {
// If there is nothing to the left, or this is causing us to
// jump to the right, then what we really want to do is page left.
if (currentFocused != null && nextFocused.getLeft() >= currentFocused.getLeft()) {
handled = pageLeft();
} else {
handled = nextFocused.requestFocus();
}
} else if (direction == View.FOCUS_RIGHT) {
// If there is nothing to the right, or this is causing us to
// jump to the left, then what we really want to do is page right.
if (currentFocused != null && nextFocused.getLeft() <= currentFocused.getLeft()) {
handled = pageRight();
} else {
handled = nextFocused.requestFocus();
}
}
} else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {
// Trying to move left and nothing there; try to page.
handled = pageLeft();
} else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {
// Trying to move right and nothing there; try to page.
handled = pageRight();
}
if (handled) {
playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
}
return handled;
}
boolean pageLeft() {
if (mCurItem > 0) {
setCurrentItem(mCurItem-1, true);
return true;
}
return false;
}
boolean pageRight() {
if (mCurItem < 1) {
setCurrentItem(mCurItem+1, true);
return true;
}
return false;
}
}
|
package com.james.status.data.icon;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.preference.PreferenceManager;
import android.support.annotation.ColorInt;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import com.james.status.R;
import com.james.status.data.IconStyleData;
import com.james.status.data.PreferenceData;
import com.james.status.data.preference.BasePreferenceData;
import com.james.status.data.preference.BooleanPreferenceData;
import com.james.status.data.preference.ColorPreferenceData;
import com.james.status.data.preference.FontPreferenceData;
import com.james.status.data.preference.IconPreferenceData;
import com.james.status.data.preference.IntegerPreferenceData;
import com.james.status.data.preference.ListPreferenceData;
import com.james.status.receivers.IconUpdateReceiver;
import com.james.status.utils.ColorUtils;
import com.james.status.utils.StaticUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class IconData<T extends IconUpdateReceiver> {
public static final int LEFT_GRAVITY = -1, CENTER_GRAVITY = 0, RIGHT_GRAVITY = 1;
private Context context;
private ReDrawListener reDrawListener;
private Typeface typeface;
private T receiver;
private int backgroundColor;
private List<IconStyleData> styles;
private IconStyleData style;
private int level;
private Bitmap bitmap;
Paint iconPaint;
Paint textPaint;
private String text;
int defaultTextColor;
int defaultTextDarkColor;
int defaultIconColor;
int defaultIconDarkColor;
int drawnTextColor;
int drawnTextSize;
int drawnTextAlpha;
int drawnIconColor;
int drawnIconSize;
int drawnIconAlpha;
int drawnPadding;
int targetTextColor;
int targetTextSize;
int targetTextAlpha;
int targetIconColor;
int targetIconSize;
int targetIconAlpha;
int targetPadding;
boolean isAnimations;
public IconData(Context context) {
this.context = context;
iconPaint = new Paint();
iconPaint.setAntiAlias(true);
iconPaint.setDither(true);
textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setDither(true);
styles = getIconStyles();
level = 0;
init();
drawnIconColor = defaultIconColor;
drawnTextColor = defaultTextColor;
}
public void init() {
defaultIconColor = targetIconColor = (int) PreferenceData.ICON_ICON_COLOR.getSpecificOverriddenValue(
getContext(), PreferenceData.STATUS_ICON_COLOR.getValue(getContext()), getIdentifierArgs());
defaultIconDarkColor = PreferenceData.STATUS_DARK_ICON_COLOR.getValue(getContext());
defaultTextColor = targetTextColor = (int) PreferenceData.ICON_TEXT_COLOR.getSpecificOverriddenValue(
getContext(), PreferenceData.STATUS_ICON_TEXT_COLOR.getValue(getContext()), getIdentifierArgs());
defaultTextDarkColor = PreferenceData.STATUS_DARK_ICON_TEXT_COLOR.getValue(getContext());
targetIconSize = (int) StaticUtils.getPixelsFromDp((int) PreferenceData.ICON_ICON_SCALE.getSpecificValue(getContext(), getIdentifierArgs()));
targetTextSize = StaticUtils.getPixelsFromSp(getContext(), (float) (int) PreferenceData.ICON_TEXT_SIZE.getSpecificValue(getContext(), getIdentifierArgs()));
targetPadding = (int) StaticUtils.getPixelsFromDp((int) PreferenceData.ICON_ICON_PADDING.getSpecificValue(getContext(), getIdentifierArgs()));
backgroundColor = PreferenceData.STATUS_COLOR.getValue(getContext());
Typeface typefaceFont = Typeface.DEFAULT;
String typefaceName = PreferenceData.ICON_TEXT_TYPEFACE.getSpecificOverriddenValue(getContext(), null, getIdentifierArgs());
if (typefaceName != null) {
try {
typefaceFont = Typeface.createFromAsset(getContext().getAssets(), typefaceName);
} catch (Exception ignored) {
}
}
typeface = Typeface.create(typefaceFont, (int) PreferenceData.ICON_TEXT_EFFECT.getSpecificValue(getContext(), getIdentifierArgs()));
drawnTextAlpha = 0;
targetTextAlpha = 255;
drawnIconAlpha = 0;
targetIconAlpha = 255;
isAnimations = PreferenceData.STATUS_ICON_ANIMATIONS.getValue(getContext());
if (styles.size() > 0) {
String name = PreferenceData.ICON_ICON_STYLE.getSpecificOverriddenValue(context, styles.get(0).name, getIdentifierArgs());
if (name != null) {
for (IconStyleData style : styles) {
if (style.name.equals(name)) {
this.style = style;
break;
}
}
}
if (style == null) style = styles.get(0);
}
}
public final Context getContext() {
return context;
}
public final void setReDrawListener(ReDrawListener listener) {
reDrawListener = listener;
}
public final void onIconUpdate(int level) {
this.level = level;
if (hasIcon()) {
bitmap = style.getBitmap(context, level);
if (reDrawListener != null)
reDrawListener.onRequestReDraw();
}
}
public final void onTextUpdate(@Nullable String text) {
if (hasText()) {
this.text = text;
if (reDrawListener != null)
reDrawListener.onRequestReDraw();
}
}
public final void requestReDraw() {
if (reDrawListener != null)
reDrawListener.onRequestReDraw();
}
public final boolean isVisible() {
return PreferenceData.ICON_VISIBILITY.getSpecificOverriddenValue(getContext(), isDefaultVisible(), getIdentifierArgs()) && StaticUtils.isPermissionsGranted(getContext(), getPermissions());
}
boolean isDefaultVisible() {
return true;
}
public boolean canHazIcon() {
//i can haz drawable resource
return true;
}
public boolean hasIcon() {
return canHazIcon() && PreferenceData.ICON_ICON_VISIBILITY.getSpecificOverriddenValue(getContext(), true, getIdentifierArgs()) && style != null;
}
public boolean canHazText() {
//u can not haz text tho
return false;
}
public boolean hasText() {
return canHazText() && PreferenceData.ICON_TEXT_VISIBILITY.getSpecificOverriddenValue(getContext(), !canHazIcon(), getIdentifierArgs());
}
public String[] getPermissions() {
return new String[]{};
}
public T getReceiver() {
return null;
}
public IntentFilter getIntentFilter() {
return new IntentFilter();
}
public void register() {
if (receiver == null) receiver = getReceiver();
if (receiver != null) getContext().registerReceiver(receiver, getIntentFilter());
onIconUpdate(-1);
}
public void unregister() {
if (receiver != null) getContext().unregisterReceiver(receiver);
}
public final int getIconPadding() {
return PreferenceData.ICON_ICON_PADDING.getSpecificValue(getContext(), getIdentifierArgs());
}
public final int getIconScale() {
return PreferenceData.ICON_ICON_SCALE.getSpecificValue(getContext(), getIdentifierArgs());
}
public final float getTextSize() {
return (float) (int) PreferenceData.ICON_TEXT_SIZE.getSpecificValue(getContext(), getIdentifierArgs());
}
@ColorInt
public final Integer getTextColor() {
return PreferenceData.ICON_TEXT_COLOR.getSpecificValue(getContext(), getIdentifierArgs());
}
public final int getPosition() {
return PreferenceData.ICON_POSITION.getSpecificValue(getContext(), getIdentifierArgs());
}
public int getDefaultGravity() {
return RIGHT_GRAVITY;
}
public final int getGravity() {
return PreferenceData.ICON_GRAVITY.getSpecificOverriddenValue(getContext(), getDefaultGravity(), getIdentifierArgs());
}
/**
* Determines the color of the icon based on various settings,
* some of which are icon-specific.
*
* @param color the color to be drawn behind the icon
*/
public void setBackgroundColor(@ColorInt int color) {
backgroundColor = color;
if (PreferenceData.STATUS_TINTED_ICONS.getValue(getContext())) {
targetIconColor = color;
targetTextColor = color;
} else {
if ((boolean) PreferenceData.STATUS_DARK_ICONS.getValue(getContext()) && ColorUtils.isColorDark(color)) {
targetIconColor = defaultIconColor;
targetTextColor = defaultTextColor;
} else {
targetIconColor = defaultIconDarkColor;
targetTextColor = defaultTextDarkColor;
}
}
requestReDraw();
}
@Nullable
public Bitmap getBitmap() {
if (hasIcon()) return bitmap;
else return null;
}
@Nullable
public String getText() {
if (hasText()) return text;
else return null;
}
public String getTitle() {
return getClass().getSimpleName();
}
@LayoutRes
public int getIconLayout() {
return R.layout.item_icon;
}
public boolean needsDraw() {
return drawnIconSize != targetIconSize ||
Color.red(drawnIconColor) != Color.red(targetIconColor) ||
Color.green(drawnIconColor) != Color.green(targetIconColor) ||
Color.blue(drawnIconColor) != Color.blue(targetIconColor) ||
drawnTextSize != targetTextSize ||
Color.red(drawnTextColor) != Color.red(drawnTextColor) ||
Color.green(drawnTextColor) != Color.green(drawnTextColor) ||
Color.blue(drawnTextColor) != Color.blue(drawnTextColor) ||
drawnPadding != targetPadding ||
drawnTextAlpha != targetTextAlpha ||
drawnIconAlpha != targetIconAlpha;
}
public void updateAnimatedValues() {
if (isAnimations) {
drawnIconColor = Color.rgb(
StaticUtils.getAnimatedValue(Color.red(drawnIconColor), Color.red(targetIconColor)),
StaticUtils.getAnimatedValue(Color.green(drawnIconColor), Color.green(targetIconColor)),
StaticUtils.getAnimatedValue(Color.blue(drawnIconColor), Color.blue(targetIconColor))
);
drawnIconSize = StaticUtils.getAnimatedValue(drawnIconSize, targetIconSize);
drawnTextColor = Color.rgb(
StaticUtils.getAnimatedValue(Color.red(drawnTextColor), Color.red(targetTextColor)),
StaticUtils.getAnimatedValue(Color.green(drawnTextColor), Color.green(targetTextColor)),
StaticUtils.getAnimatedValue(Color.blue(drawnTextColor), Color.blue(targetTextColor))
);
drawnTextSize = StaticUtils.getAnimatedValue(drawnTextSize, targetTextSize);
drawnPadding = StaticUtils.getAnimatedValue(drawnPadding, targetPadding);
drawnTextAlpha = StaticUtils.getAnimatedValue(drawnTextAlpha, targetTextAlpha);
drawnIconAlpha = StaticUtils.getAnimatedValue(drawnIconAlpha, targetIconAlpha);
} else {
drawnIconColor = targetIconColor;
drawnIconSize = targetIconSize;
drawnTextColor = targetTextColor;
drawnTextSize = targetTextSize;
drawnPadding = targetPadding;
drawnTextAlpha = targetTextAlpha;
drawnIconAlpha = targetIconAlpha;
}
}
/**
* Draws the icon on a canvas.
*
* @param canvas the canvas to draw on
* @param x the x position (LTR px) to start drawing the icon at
* @param width the available width for the icon to be drawn within
*/
public void draw(Canvas canvas, int x, int width) {
updateAnimatedValues();
int iconColor = Color.rgb(
StaticUtils.getMergedValue(Color.red(drawnIconColor), Color.red(backgroundColor), (float) drawnIconAlpha / 255),
StaticUtils.getMergedValue(Color.green(drawnIconColor), Color.green(backgroundColor), (float) drawnIconAlpha / 255),
StaticUtils.getMergedValue(Color.blue(drawnIconColor), Color.blue(backgroundColor), (float) drawnIconAlpha / 255)
);
iconPaint.setColor(iconColor);
iconPaint.setColorFilter(new PorterDuffColorFilter(iconColor, PorterDuff.Mode.SRC_IN));
textPaint.setColor(drawnTextColor);
textPaint.setAlpha(drawnTextAlpha);
textPaint.setTextSize(drawnTextSize);
textPaint.setTypeface(typeface);
x += drawnPadding;
if (hasIcon() && bitmap != null && drawnIconSize > 0) {
if (drawnIconSize == targetIconSize && targetIconSize != bitmap.getWidth()) {
if (bitmap.getWidth() > targetIconSize)
bitmap = Bitmap.createScaledBitmap(bitmap, targetIconSize, targetIconSize, true);
else {
Bitmap bitmap = style.getBitmap(context, level);
if (bitmap != null) {
this.bitmap = bitmap;
if (this.bitmap.getWidth() != targetIconSize)
this.bitmap = Bitmap.createScaledBitmap(bitmap, targetIconSize, targetIconSize, true);
}
}
}
Matrix matrix = new Matrix();
matrix.postScale((float) drawnIconSize / bitmap.getWidth(), (float) drawnIconSize / bitmap.getWidth());
matrix.postTranslate(x, ((float) canvas.getHeight() - drawnIconSize) / 2);
canvas.drawBitmap(bitmap, matrix, iconPaint);
x += drawnIconSize + drawnPadding;
}
if (hasText() && text != null) {
Paint.FontMetrics metrics = textPaint.getFontMetrics();
canvas.drawText(text, x, ((canvas.getHeight() - metrics.descent - metrics.ascent) / 2), textPaint);
}
}
/**
* Returns the estimated width (px) of the icon, or -1
* if the icon needs to know the available space
* first.
*
* @param height the height (px) to scale the icon to
* @param available the available width for the icon, or -1 if not yet calculated
* @return the estimated width (px) of the icon
*/
public int getWidth(int height, int available) {
int width = 0;
if ((hasIcon() && bitmap != null) || (hasText() && text != null))
width += StaticUtils.getAnimatedValue(drawnPadding, targetPadding);
if (hasIcon() && bitmap != null) {
width += StaticUtils.getAnimatedValue(drawnIconSize, targetIconSize);
width += StaticUtils.getAnimatedValue(drawnPadding, targetPadding);
}
if (hasText() && text != null) {
Paint textPaint = new Paint();
textPaint.setTextSize(StaticUtils.getAnimatedValue(drawnTextSize, targetTextSize));
textPaint.setTypeface(typeface);
Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
width += hasText() ? bounds.width() : 0;
width += StaticUtils.getAnimatedValue(drawnPadding, targetPadding);
}
return width;
}
public List<BasePreferenceData> getPreferences() {
List<BasePreferenceData> preferences = new ArrayList<>();
if (canHazIcon() && (hasText() || !hasIcon())) {
preferences.add(new BooleanPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Boolean>(
PreferenceData.ICON_ICON_VISIBILITY,
getContext().getString(R.string.preference_show_drawable),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<Boolean>() {
@Override
public void onPreferenceChange(Boolean preference) {
StaticUtils.updateStatusService(getContext());
}
}
));
}
if (canHazText() && (hasIcon() || !hasText())) {
preferences.add(new BooleanPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Boolean>(
PreferenceData.ICON_TEXT_VISIBILITY,
getContext().getString(R.string.preference_show_text),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<Boolean>() {
@Override
public void onPreferenceChange(Boolean preference) {
StaticUtils.updateStatusService(getContext());
}
}
));
}
preferences.addAll(Arrays.asList(
new ListPreferenceData(
getContext(),
new BasePreferenceData.Identifier<>(
PreferenceData.ICON_GRAVITY,
getContext().getString(R.string.preference_gravity),
getDefaultGravity(),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext());
}
},
new ListPreferenceData.ListPreference(
getContext().getString(R.string.gravity_left),
LEFT_GRAVITY
),
new ListPreferenceData.ListPreference(
getContext().getString(R.string.gravity_center),
CENTER_GRAVITY
),
new ListPreferenceData.ListPreference(
getContext().getString(R.string.gravity_right),
RIGHT_GRAVITY
)
),
new IntegerPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_ICON_PADDING,
getContext().getString(R.string.preference_icon_padding),
getIdentifierArgs()
),
getContext().getString(R.string.unit_dp),
null,
null,
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext());
}
}
)
));
if (hasIcon()) {
preferences.add(new IntegerPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_ICON_SCALE,
getContext().getString(R.string.preference_icon_scale),
getIdentifierArgs()
),
getContext().getString(R.string.unit_dp),
0,
null,
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext());
}
}
));
}
if (hasText()) {
preferences.add(new IntegerPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_TEXT_SIZE,
getContext().getString(R.string.preference_text_size)
),
getContext().getString(R.string.unit_sp),
0,
null,
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext());
}
}
));
preferences.add(new ColorPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_TEXT_COLOR,
getContext().getString(R.string.preference_text_color),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext());
}
}
));
preferences.add(new FontPreferenceData(
getContext(),
new BasePreferenceData.Identifier<String>(
PreferenceData.ICON_TEXT_TYPEFACE,
getContext().getString(R.string.preference_text_font),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<String>() {
@Override
public void onPreferenceChange(String preference) {
StaticUtils.updateStatusService(getContext());
}
},
"Audiowide.ttf",
"BlackOpsOne.ttf",
"HennyPenny.ttf",
"Iceland.ttf",
"Megrim.ttf",
"Monoton.ttf",
"NewRocker.ttf",
"Nosifer.ttf",
"PermanentMarker.ttf",
"Playball.ttf",
"Righteous.ttf",
"Roboto.ttf",
"RobotoCondensed.ttf",
"RobotoSlab.ttf",
"VT323.ttf",
"Wallpoet.ttf"
));
preferences.add(new ListPreferenceData(
getContext(),
new BasePreferenceData.Identifier<Integer>(
PreferenceData.ICON_TEXT_EFFECT,
getContext().getString(R.string.preference_text_effect),
getIdentifierArgs()
),
new BasePreferenceData.OnPreferenceChangeListener<Integer>() {
@Override
public void onPreferenceChange(Integer preference) {
StaticUtils.updateStatusService(getContext());
}
},
new ListPreferenceData.ListPreference(getContext().getString(R.string.text_effect_none), Typeface.NORMAL),
new ListPreferenceData.ListPreference(getContext().getString(R.string.text_effect_bold), Typeface.BOLD),
new ListPreferenceData.ListPreference(getContext().getString(R.string.text_effect_italic), Typeface.ITALIC),
new ListPreferenceData.ListPreference(getContext().getString(R.string.text_effect_bold_italic), Typeface.BOLD_ITALIC)
));
}
if (hasIcon()) {
preferences.add(new IconPreferenceData(
getContext(),
new BasePreferenceData.Identifier<String>(
PreferenceData.ICON_ICON_STYLE,
getContext().getString(R.string.preference_icon_style),
getIdentifierArgs()
),
this,
new BasePreferenceData.OnPreferenceChangeListener<IconStyleData>() {
@Override
public void onPreferenceChange(IconStyleData preference) {
style = preference;
StaticUtils.updateStatusService(getContext());
}
}
));
}
return preferences;
}
public int getIconStyleSize() {
return 0;
}
public String[] getIconNames() {
return new String[]{};
}
public List<IconStyleData> getIconStyles() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
List<IconStyleData> styles = new ArrayList<>();
String[] names = PreferenceData.ICON_ICON_STYLE_NAMES.getSpecificValue(getContext(), getIdentifierArgs());
for (String name : names) {
IconStyleData style = IconStyleData.fromSharedPreferences(prefs, getClass().getName(), name);
if (style != null) styles.add(style);
}
return styles;
}
public final void addIconStyle(IconStyleData style) {
if (style.getSize() == getIconStyleSize()) {
List<String> list = new ArrayList<>(Arrays.asList((String[]) PreferenceData.ICON_ICON_STYLE_NAMES.getSpecificValue(getContext(), getIdentifierArgs())));
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
style.writeToSharedPreferences(editor, getClass().getName());
editor.apply();
list.add(style.name);
PreferenceData.ICON_ICON_STYLE_NAMES.setValue(context, list.toArray(new String[list.size()]), getIdentifierArgs());
}
}
public final void removeIconStyle(IconStyleData style) {
List<String> list = new ArrayList<>(Arrays.asList((String[]) PreferenceData.ICON_ICON_STYLE_NAMES.getSpecificValue(getContext(), getIdentifierArgs())));
list.remove(style.name);
PreferenceData.ICON_ICON_STYLE_NAMES.setValue(context, list.toArray(new String[list.size()]), getIdentifierArgs());
}
public String[] getIdentifierArgs() {
return new String[]{getClass().getName()};
}
public interface ReDrawListener {
void onRequestReDraw();
}
}
|
package com.cube.storm;
import android.content.Context;
import android.support.annotation.NonNull;
import com.cube.storm.ui.controller.downloader.StormSchemeHandler;
import com.cube.storm.ui.data.ContentSize;
import com.cube.storm.ui.lib.factory.FileFactory;
import com.cube.storm.ui.lib.factory.IntentFactory;
import com.cube.storm.ui.lib.factory.ViewFactory;
import com.cube.storm.ui.lib.handler.LinkHandler;
import com.cube.storm.ui.lib.parser.ViewBuilder;
import com.cube.storm.ui.lib.parser.ViewProcessor;
import com.cube.storm.ui.lib.processor.TextProcessor;
import com.cube.storm.ui.lib.resolver.AppResolver;
import com.cube.storm.ui.lib.spec.DividerSpec;
import com.cube.storm.ui.lib.spec.ListDividerSpec;
import com.cube.storm.ui.model.App;
import com.cube.storm.ui.model.Model;
import com.cube.storm.ui.model.list.ListItem;
import com.cube.storm.ui.model.list.collection.CollectionItem;
import com.cube.storm.ui.model.page.Page;
import com.cube.storm.ui.model.property.LinkProperty;
import com.cube.storm.ui.model.property.TextProperty;
import com.cube.storm.util.lib.processor.Processor;
import com.cube.storm.util.lib.resolver.AssetsResolver;
import com.cube.storm.util.lib.resolver.FileResolver;
import com.cube.storm.util.lib.resolver.Resolver;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
/**
* This is the entry point class of the library. To enable the use of the library, you must instantiate
* a new {@link UiSettings.Builder} object in your {@link android.app.Application} singleton class.
*
* This class should not be directly instantiated.
*
* @author Callum Taylor
* @project LightningUi
*/
public class UiSettings
{
/**
* The singleton instance of the settings
*/
private static UiSettings instance;
public static UiSettings getInstance()
{
if (instance == null)
{
throw new IllegalAccessError("You must build the Ui settings object first using UiSettings$Builder");
}
return instance;
}
/**
* Default private constructor
*/
private UiSettings(){}
/**
* App data for the content
*/
@Getter private App app;
/**
* The intent factory instance of the module. This is the instance that will be used to resolve
* every activity/fragment for a storm page/Uri
*/
@Getter @Setter private IntentFactory intentFactory;
/**
* The view factory instance of the module. This is the instance that will be used to resolve
* models and holders for a specific view
*/
@Getter @Setter private ViewFactory viewFactory;
/**
* Factory class responsible for loading a file from disk based on its Uri
*/
@Getter @Setter private FileFactory fileFactory;
/**
* The view processor map used by {@link com.cube.storm.ui.lib.parser.ViewBuilder}. Use {@link com.cube.storm.UiSettings.Builder#registerType(Type, com.cube.storm.ui.lib.parser.ViewProcessor)} to
* override the processor used to match models with json class names
*/
@Getter @Setter private Map<Type, ViewProcessor> viewProcessors = new LinkedHashMap<Type, ViewProcessor>(0);
/**
* Image loader which is used when displaying images in the list
*/
@Getter @Setter private ImageLoader imageLoader = ImageLoader.getInstance();
/**
* The density to use when loading images
*/
@Getter @Setter private ContentSize contentSize;
/**
* The handler used when a link is triggered
*/
@Getter @Setter private LinkHandler linkHandler;
/**
* The gson builder class used to build all of the storm objects from json/string/binary
*/
@Getter @Setter private ViewBuilder viewBuilder;
/**
* Processor class used to process strings as part of {@link com.cube.storm.ui.model.property.TextProperty}
*/
@Getter @Setter private Processor<TextProperty, String> textProcessor;
/**
* Uri resolver used to load a file based on it's protocol. You should not need to use this instance
* directly to load a file, instead use {@link com.cube.storm.ui.lib.factory.FileFactory} which uses this
* to resolve a file and load it. Only use this if you want to load a specific scheme
*/
@Getter @Setter private Map<String, Resolver> uriResolvers = new LinkedHashMap<String, Resolver>(2);
/**
* Default divider spec to use in {@link com.cube.storm.ui.controller.adapter.StormListAdapter}
*/
@Getter @Setter private DividerSpec dividerSpec;
/**
* Sets the app model of the content
*
* @param app The new app model
*/
public void setApp(@NonNull App app)
{
this.app = app;
}
/**
* The builder class for {@link com.cube.storm.UiSettings}. Use this to create a new {@link com.cube.storm.UiSettings} instance
* with the customised properties specific for your project.
*
* Call {@link #build()} to build the settings object.
*/
public static class Builder
{
/**
* The temporary instance of the {@link UiSettings} object.
*/
private UiSettings construct;
private Context context;
/**
* Default constructor
*/
public Builder(Context context)
{
this.construct = new UiSettings();
this.context = context.getApplicationContext();
intentFactory(new IntentFactory(){});
viewFactory(new ViewFactory(){});
fileFactory(new FileFactory(){});
imageLoaderConfiguration(new ImageLoaderConfiguration.Builder(this.context));
linkHandler(new LinkHandler());
textProcessor(new TextProcessor());
contentSize(ContentSize.MEDIUM);
ViewProcessor<? extends Model> baseProcessor = new ViewProcessor<Model>()
{
@Override public Class<? extends Model> getClassFromName(String name)
{
return UiSettings.getInstance().getViewFactory().getModelForView(name);
}
};
registerType(Page.class, baseProcessor);
registerType(ListItem.class, baseProcessor);
registerType(CollectionItem.class, baseProcessor);
registerType(LinkProperty.class, baseProcessor);
registerUriResolver("file", new FileResolver());
registerUriResolver("assets", new AssetsResolver(this.context));
registerUriResolver("app", new AppResolver(this.context));
viewBuilder(new ViewBuilder(){});
dividerSpec(new ListDividerSpec());
}
/**
* Sets the default {@link com.cube.storm.ui.lib.spec.DividerSpec} for the list adapter to use when layout out its children
*
* @param spec The new divider spec to use by default
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder dividerSpec(DividerSpec spec)
{
construct.dividerSpec = spec;
return this;
}
/**
* Sets the default {@link com.cube.storm.ui.lib.factory.IntentFactory} for the module
*
* @param intentFactory The new {@link com.cube.storm.ui.lib.factory.IntentFactory}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder intentFactory(IntentFactory intentFactory)
{
construct.intentFactory = intentFactory;
return this;
}
/**
* Sets the default {@link com.cube.storm.ui.lib.factory.ViewFactory} for the module
*
* @param viewFactory The new {@link com.cube.storm.ui.lib.factory.ViewFactory}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder viewFactory(ViewFactory viewFactory)
{
construct.viewFactory = viewFactory;
return this;
}
/**
* Sets the default {@link com.cube.storm.ui.lib.factory.FileFactory} for the module
*
* @param fileFactory The new {@link com.cube.storm.ui.lib.factory.FileFactory}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder fileFactory(FileFactory fileFactory)
{
construct.fileFactory = fileFactory;
return this;
}
/**
* Sets the default image loader configuration.
*
* Note: The ImageDownloader set in the builder is overriden by this method to allow the use
* of {@link #getUriResolvers()} to resolve the uris for loading images. Use {@link #registerUriResolver(String, com.cube.storm.util.lib.resolver.Resolver)}
* to register any additional custom uris you wish to override.
*
* @param configuration The new configuration for the image loader
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder imageLoaderConfiguration(ImageLoaderConfiguration.Builder configuration)
{
if (construct.imageLoader.isInited())
{
construct.imageLoader.destroy();
}
construct.imageLoader.init(configuration.build());
return this;
}
/**
* Sets the default {@link com.cube.storm.ui.data.ContentSize} for the module
*
* @param contentSize The new {@link com.cube.storm.ui.data.ContentSize}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder contentSize(ContentSize contentSize)
{
construct.contentSize = contentSize;
return this;
}
/**
* Sets the default {@link com.cube.storm.ui.lib.handler.LinkHandler} for the module
*
* @param linkHandler The new {@link com.cube.storm.ui.lib.handler.LinkHandler}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder linkHandler(LinkHandler linkHandler)
{
construct.linkHandler = linkHandler;
return this;
}
/**
* Sets the default {@link com.cube.storm.ui.lib.parser.ViewBuilder} for the module
*
* @param viewBuilder The new {@link com.cube.storm.ui.lib.parser.ViewBuilder}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder viewBuilder(ViewBuilder viewBuilder)
{
construct.viewBuilder = viewBuilder;
return this;
}
/**
* Sets the default {@link com.cube.storm.util.lib.processor.Processor} for the module
*
* @param textProcessor The new {@link com.cube.storm.util.lib.processor.Processor}
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder textProcessor(Processor<TextProperty, String> textProcessor)
{
construct.textProcessor = textProcessor;
return this;
}
/**
* Registers a deserializer type for a class instance. Use this method to override what processor
* gets used for a specific view type.
*
* @param instanceClass The class to register for deserialization
* @param deserializer The processor class
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerType(Type instanceClass, ViewProcessor deserializer)
{
construct.viewProcessors.put(instanceClass, deserializer);
return this;
}
/**
* Registers a uri resolver to use in the {@link com.cube.storm.ui.lib.factory.FileFactory}
*
* @param protocol The string protocol to register
* @param resolver The resolver to use for the registered protocol
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerUriResolver(String protocol, Resolver resolver)
{
construct.uriResolvers.put(protocol, resolver);
if (!ImageLoader.getInstance().getRegisteredSchemeHandlers().containsKey(protocol))
{
ImageLoader.getInstance().registerSchemeHandler(protocol, new StormSchemeHandler());
}
return this;
}
/**
* Registers a uri resolvers
*
* @param resolvers The map of resolvers to register
*
* @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining
*/
public Builder registerUriResolver(Map<String, Resolver> resolvers)
{
construct.uriResolvers.putAll(resolvers);
for (String protocol : resolvers.keySet())
{
if (!ImageLoader.getInstance().getRegisteredSchemeHandlers().containsKey(protocol))
{
ImageLoader.getInstance().registerSchemeHandler(protocol, new StormSchemeHandler());
}
}
return this;
}
/**
* Builds the final settings object and sets its instance. Use {@link #getInstance()} to retrieve the settings
* instance.
*
* @return The newly set {@link com.cube.storm.UiSettings} instance
*/
public UiSettings build()
{
return (UiSettings.instance = construct);
}
}
}
|
package com.pyze.events.ui;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.pyze.android.collections.Values;
import com.pyze.events.Constants.Extras;
import com.pyze.events.EventsManager;
import com.pyze.events.R;
import com.pyze.events.RandomNumberGenerator;
public class MethodDetailActivity extends AppCompatActivity {
private String[] mArgumentsArray = new String[] {"facebook", "twitter", "pyze rocks", "news", "music", "video",
"bitcoin", "content", "account", "activate"};
private TextView mRequiredAttributesTv, mCustomAttributesTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_method_details);
getSupportActionBar().setTitle(getString(R.string.title_methods));
mRequiredAttributesTv = (TextView) findViewById(R.id.textview_required_attributes);
mCustomAttributesTv = (TextView) findViewById(R.id.textview_custom_attributes);
int position = getIntent().getIntExtra(Extras.SELECTED_METHOD_POSITION, 0);
final Method selectedMethod = EventsManager.getInstance().getMethodList().get(position);
RandomNumberGenerator rGen = new RandomNumberGenerator();
Class<?>[] parametersTypeArray = selectedMethod.getParameterTypes();
int parametersCount = parametersTypeArray.length;
final Object[] arguments = new Object[parametersCount];
if(parametersCount > 0) {
for(int index = 0; index < parametersCount; index++) {
String parameterType = parametersTypeArray[index].getName();
if(parameterType.equalsIgnoreCase("java.util.HashMap")) {
mCustomAttributesTv.setVisibility(View.VISIBLE);
HashMap<Object, Object> map = getCustomAttributesMap();
Set<Entry<Object, Object>> keyset = map.entrySet();
Iterator<Entry<Object, Object>> iterator = keyset.iterator();
while(iterator.hasNext()) {
Entry<Object, Object> entry = iterator.next();
mCustomAttributesTv.setText(mCustomAttributesTv.getText() + "\n "
+ entry.getKey() + " : " + entry.getValue());
}
arguments[index] = map;
} else if(parameterType.equalsIgnoreCase("java.lang.String")) {
mRequiredAttributesTv.setVisibility(View.VISIBLE);
String attribute = mArgumentsArray[rGen.getNumber()];
mRequiredAttributesTv.setText(mRequiredAttributesTv.getText() + "\n" + attribute );
arguments[index] = attribute;
} else if(parameterType.equalsIgnoreCase("boolean")) {
mRequiredAttributesTv.setVisibility(View.VISIBLE);
mRequiredAttributesTv.setText(mRequiredAttributesTv.getText() + "\ntrue");
arguments[index] = true;
} else if(parameterType.equalsIgnoreCase("long")) {
mRequiredAttributesTv.setVisibility(View.VISIBLE);
mRequiredAttributesTv.setText(mRequiredAttributesTv.getText() + "\n54834211");
arguments[index] = 54834211;
} else if(parameterType.equalsIgnoreCase("com.pyze.android.events.dto.PyzeGeoPoint")) {
mRequiredAttributesTv.setVisibility(View.VISIBLE);
mRequiredAttributesTv.setText(mRequiredAttributesTv.getText() + "\nLongitude:12, Latitude:24");
arguments[index] = "12,24";
} else if(parameterType.equalsIgnoreCase("com.pyze.android.collections.Values")) {
Values values = new Values();
values.putValue("key1", "value1");
values.putValue("key2", "value2");
values.putValue("key3", "value3");
values.putValue("key4", "value4");
Iterator<Entry<Object, Object>> iterator = values.getAttributes().entrySet().iterator();
while(iterator.hasNext()) {
Entry<Object, Object> entry = iterator.next();
mCustomAttributesTv.setText(mCustomAttributesTv.getText() + "\n "
+ entry.getKey() + " : " + entry.getValue());
}
arguments[index] = values;
}
}
}
((Button) findViewById(R.id.btn_done)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
try {
selectedMethod.invoke(null, arguments);
Toast.makeText(MethodDetailActivity.this, getString(R.string.event_success), Toast.LENGTH_LONG).show();
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
});
}
public HashMap<Object, Object> getCustomAttributesMap() {
HashMap<Object, Object> map = new HashMap<Object, Object>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");
return map;
}
}
|
package net.runelite.api;
import java.util.HashMap;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Enumeration of message types that can be received in the chat.
*/
@AllArgsConstructor
@Getter
public enum ChatMessageType
{
/**
* A message received from the server.
*/
SERVER(0),
/**
* A message in the public chat.
*/
PUBLIC(2),
/**
* A private message from another player.
*/
PRIVATE_MESSAGE_RECEIVED(3),
/**
* A trade request received.
*/
TRADE_RECEIVED(4),
/**
* A message received when a friend logs in or out.
*/
PRIVATE_MESSAGE_INFO(5),
/**
* A private message sent to another player.
*/
PRIVATE_MESSAGE_SENT(6),
/**
* A private message received from a moderator.
*/
PRIVATE_MESSAGE_RECEIVED_MOD(7),
/**
* A message received in clan chat.
*/
CLANCHAT(9),
/**
* A message received with information about the current clan chat.
*/
CLANCHAT_INFO(11),
/**
* A trade request being sent.
*/
TRADE_SENT(12),
/**
* An abuse report submitted.
*/
ABUSE_REPORT(26),
/**
* Examine item description.
*/
EXAMINE_ITEM(27),
/**
* Examine NPC description.
*/
EXAMINE_NPC(28),
/**
* Examine object description.
*/
EXAMINE_OBJECT(29),
/**
* Adding player to friend list.
*/
FRIENDS_LIST_ADD(30),
/**
* Adding player to ignore list.
*/
IGNORE_LIST_ADD(31),
/**
* An autochat message from a player.
*/
AUTOCHAT(90),
/**
* A game message (ie. when a setting is changed).
*/
GAME(99),
/**
* A message received when somebody sends a trade offer.
*/
TRADE(101),
/**
* A message received when somebody sends a duel offer.
*/
DUEL(103),
/**
* A message that was filtered.
*/
FILTERED(105),
/**
* A message about an action.
*/
ACTION(109),
/**
* An unknown message type.
*/
UNKNOWN(-1);
private final int type;
private static final Map<Integer, ChatMessageType> CHAT_MESSAGE_TYPES = new HashMap<>();
static
{
for (ChatMessageType chatMessageType : values())
{
CHAT_MESSAGE_TYPES.put(chatMessageType.type, chatMessageType);
}
}
/**
* Utility method that maps the type value to its respective
* {@link ChatMessageType} value.
*
* @param type the raw type
* @return appropriate message type, or {@link #UNKNOWN}
*/
public static ChatMessageType of(int type)
{
return CHAT_MESSAGE_TYPES.getOrDefault(type, UNKNOWN);
}
}
|
package kaist.cs550_2016.poche;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.media.MediaMetadataRetriever;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import junit.framework.Assert;
import java.io.IOException;
public class MainActivity extends AppCompatActivity
implements BSUI.BSUIEventListener, MediaPlayer.OnCompletionListener {
private TextView titleTextView;
private TextView artistTextView;
private TextView durationTextView;
private TextView positionTextView;
private TextView positionSlashTextView;
private ImageView albumArtImageView;
private ImageView nextAlbumArtImageView;
private ImageView seekBarImageView;
private ImageView playMode;
private RelativeLayout controlLayout;
private Playlist playlist;
private GestureDetector gestureDetector;
private MediaPlayerService.MediaPlayerServiceBinder mediaPlayerServiceBinder;
private AsyncTask tick, albumArtTransition;
private Bitmap nextAlbumArt;
private int defaultAlbumArtAvarageColor;
private boolean isFirstTrack;
private BSUI bsui;
private boolean directionLeft;
private int uiUpdateFrameRate = 1000 / 30;
private int albumArtTransitionFrameRate = 1000 / 60;
/**
* The total length of the track in ms
*/
private int trackDuration;
private int screenWidth, screenHeight;
// private float pxPerDip;
private float pxPerWidthPercentage, pxPerHeightPercentage;
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme_AppBarOverlay);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri playlistUri = getIntent().getData();
Debug.log(this, "Playlist loaded: " + playlistUri.toString());
try {
Debug.stopwatchStart();
playlist = Playlist.parse(this, playlistUri);
Debug.toastStopwatch("Parse()");
} catch (IOException e) {
Toast.makeText(this,
R.string.toast_fail_parseplaylist, Toast.LENGTH_LONG).show();
e.printStackTrace();
finish();
}
isFirstTrack = true;
bindService(new Intent(getBaseContext(), MediaPlayerService.class),
connection, BIND_AUTO_CREATE);
// Start media playback in onServiceConnected
bsui = new BSUI();
bsui.setBSUIEventListener(this);
gestureDetector = new GestureDetector(this, bsui);
View bsuiRegion = findViewById(R.id.main_BSUIRegion);
bsuiRegion.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Debug.log("MotionEvent: " + event);
gestureDetector.onTouchEvent(event);
return true;
}
});
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
if (ConfigHelper.getInstance().isWakeLock()) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
screenHeight = getResources().getDisplayMetrics().heightPixels;
screenWidth = getResources().getDisplayMetrics().widthPixels;
// pxPerDip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics());
pxPerHeightPercentage = ((float) screenHeight) / 100;
pxPerWidthPercentage = ((float) screenWidth) / 100;
// Android does not GC on strongly referenced variables!
titleTextView = (TextView) findViewById(R.id.main_TextTitle);
artistTextView = (TextView) findViewById(R.id.main_TextArtist);
durationTextView = (TextView) findViewById(R.id.main_TextDuration);
positionTextView = (TextView) findViewById(R.id.main_TextPosition);
positionSlashTextView = (TextView) findViewById(R.id.main_TextPositionSlash);
albumArtImageView = (ImageView) findViewById(R.id.main_ImageAlbumArt);
nextAlbumArtImageView = (ImageView) findViewById(R.id.main_NextImageAlbumArt);
seekBarImageView = (ImageView) findViewById(R.id.main_SeekBar);
playMode = (ImageView) findViewById(R.id.main_Mode);
controlLayout = (RelativeLayout) findViewById(R.id.main_Control_Layout);
positionTextView.setText("0:00");
seekBarImageView.setX(-100 * pxPerWidthPercentage);
nextAlbumArtImageView.setX(100 * pxPerWidthPercentage);
defaultAlbumArtAvarageColor =
ContextCompat.getColor(this, R.color.colorDefaultAlbumArtAverage);
if(ConfigHelper.getInstance().getPlayOrder() == ConfigHelper.PlayOrder.SHUFFLE)
playMode.setImageDrawable(getDrawable(R.drawable.shuffle));
tick = new Tick().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, uiUpdateFrameRate);
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mediaPlayerServiceBinder = ((MediaPlayerService.MediaPlayerServiceBinder) service);
mediaPlayerServiceBinder.initialize(MainActivity.this);
PlayTrack();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// Nothing to do
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayerServiceBinder != null) {
unbindService(connection);
mediaPlayerServiceBinder = null;
}
if (tick != null) tick.cancel(true);
}
@Override
public void onBSUIEvent(BSUI.BSUIEvent event) {
Debug.log(this, "BSUI event: " + event);
switch (event) {
case SINGLE_TAP:
pauseResume();
break;
case STROKE_UP:
adjustVolume(AudioManager.ADJUST_RAISE);
break;
case STROKE_DOWN:
adjustVolume(AudioManager.ADJUST_LOWER);
break;
case STROKE_LEFT:
PrevTrack();
break;
case STROKE_RIGHT:
NextTrack();
break;
}
}
public void PlayTrack() {
if (mediaPlayerServiceBinder == null) return;
Uri uri = playlist.GetCurrentTrack();
mediaPlayerServiceBinder.setTrack(uri);
updateMetadata(uri);
directionLeft = false;
if(!mediaPlayerServiceBinder.isPlaying())
mediaPlayerServiceBinder.pauseTrack();
}
private void pauseResume() {
if (mediaPlayerServiceBinder == null) return;
mediaPlayerServiceBinder.pauseTrack();
}
private void NextTrack() {
directionLeft = false;
playlist.NextTrack();
PlayTrack();
}
private void PrevTrack() {
directionLeft = true;
playlist.PrevTrack();
PlayTrack();
}
private void adjustVolume(int volumeAdjustCommand) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
volumeAdjustCommand, AudioManager.FLAG_SHOW_UI);
}
private void SetPlayMode(ConfigHelper.PlayOrder playOrder) {
ConfigHelper.getInstance().setPlayOrder(playOrder);
}
// OnCompletionListener
@Override
public void onCompletion(MediaPlayer mp) {
NextTrack();
}
/**
* Retrieves metadata from the current track and displays them on the UI
* Should be used only once per track
*
* @param uri
*/
private void updateMetadata(Uri uri) {
// Update text
String trackTitle, trackArtist;
Bitmap albumArt;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(this, uri);
try {
trackTitle = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
} catch (Exception e) {
trackTitle = uri.getPath();
}
try {
trackArtist = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
} catch (Exception e) {
trackArtist = getString(R.string.main_noartist);
}
// Android API returns the track length in milliseconds as a String
trackDuration = Integer.parseInt(
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
String trackLength = millisecondsToMinutesAndSeconds(trackDuration);
Debug.log("Title: ", trackTitle);
Debug.log("Artist: ", trackArtist);
Debug.log("Length: ", trackLength);
titleTextView.setText(trackTitle);
artistTextView.setText(trackArtist);
durationTextView.setText(trackLength);
try {
byte[] bytearr = retriever.getEmbeddedPicture();
albumArt = BitmapFactory.decodeByteArray(bytearr, 0, bytearr.length);
} catch (Exception e) {
albumArt = null;
//BitmapFactory.decodeResource(getApplicationContext().getResources(),R.drawable.random_album_art);
}
if (isFirstTrack) {
if (albumArt != null) {
albumArtImageView.setImageBitmap(albumArt);
}
else {
albumArtImageView.setImageResource(R.drawable.random_album_art);
}
isFirstTrack = false;
}
else {
if (albumArtTransition != null) {
albumArtTransition.cancel(true);
if (nextAlbumArt != null) {
albumArtImageView.setImageBitmap(nextAlbumArt);
}
else {
albumArtImageView.setImageResource(R.drawable.random_album_art);
}
}
if (albumArt != null) {
nextAlbumArtImageView.setImageBitmap(albumArt);
}
else {
nextAlbumArtImageView.setImageResource(R.drawable.random_album_art);
}
int direction = directionLeft ? 0 : 1;
albumArtTransition = new AlbumArtTransition().executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR, 500, albumArtTransitionFrameRate, direction);
}
nextAlbumArt = albumArt;
setColorForAlbumArt(albumArt);
}
private void setColorForAlbumArt(@Nullable Bitmap albumArt) {
int color1, color2;
int averageColor = albumArt != null ? getAverageColor(albumArt) : defaultAlbumArtAvarageColor;
View rootLayout = findViewById(R.id.main_Root);
// update colors
rootLayout.setBackgroundColor(0xFF000000 + averageColor);
int r = Color.red(averageColor);
int g = Color.green(averageColor);
int b = Color.blue(averageColor);
int max = Math.max(r, Math.max(g, b));
final float darkerRatio = 0.4f;
final float lighterRatio = 0.6f;
int darkerAvg = 0xFF000000 +
getColorInt((int) (r * darkerRatio), (int) (g * darkerRatio), (int) (b * darkerRatio));
int lightMod = (int)((255 - max) * lighterRatio);
int lighterAvg = averageColor + lightMod * 0x10000 + lightMod * 0x100 + lightMod + 0xFF000000;
double brightnessDelta = (r + g + b) * 0.6;
// if too little difference, boost text color so it's brighter than the background
// arbitrary threshold that felt good enough
if (brightnessDelta < 300) {
color1 = lighterAvg;
float color2Ratio = 1 / darkerRatio;
color2 = 0xFF000000 +
getColorInt((int) (r * color2Ratio), (int) (g * color2Ratio), (int) (b * color2Ratio));
// and if the average color is not dark
} else {
color1 = darkerAvg;
float color2Ratio = darkerRatio * 1.7f;
color2 = 0xFF000000 +
getColorInt((int) (r * color2Ratio), (int) (g * color2Ratio), (int) (b * color2Ratio));
}
titleTextView.setTextColor(color1);
artistTextView.setTextColor(color1);
durationTextView.setTextColor(color1);
positionSlashTextView.setTextColor(color1);
positionTextView.setTextColor(color1);
seekBarImageView.setBackgroundColor(color1);
int color2ReducedOpacacity = color2 - 0xAA000000;
for (int i = 0; i < controlLayout.getChildCount(); i++) {
ImageView iv = (ImageView) controlLayout.getChildAt(i);
if (iv.getTag() == null) {
// not a bracket
iv.setColorFilter(color2, PorterDuff.Mode.SRC_IN);
} else {
// bracket
iv.setColorFilter(color2ReducedOpacacity, PorterDuff.Mode.SRC_IN);
}
}
int somethingInTheMiddle = color2 - 0x77000000;
playMode.setColorFilter(somethingInTheMiddle, PorterDuff.Mode.SRC_IN);
}
/**
* Updates the UI animation during track transition
*
* @param progress assumed to be [0, 1]
* @param direction false is left to right, true is right to left
*/
private void updateAlbumArt(float progress, boolean direction) {
// if next track
// i.e. next album art coming in from the right
if (direction) {
nextAlbumArtImageView.setX(100 * (1 - progress) * pxPerWidthPercentage);
} else {
nextAlbumArtImageView.setX(-100 * (1 - progress) * pxPerWidthPercentage);
}
if (progress >= 1) {
if (nextAlbumArt != null) {
albumArtImageView.setImageBitmap(nextAlbumArt);
}
else {
albumArtImageView.setImageResource(R.drawable.random_album_art);
}
nextAlbumArtImageView.setX(100 * pxPerWidthPercentage);
}
}
/**
* Updates the seek bar and the current time TextView
*/
private void updateTrackTime() {
if (mediaPlayerServiceBinder == null) return;
int seconds = mediaPlayerServiceBinder.getCurrentPosition();
positionTextView.setText(millisecondsToMinutesAndSeconds(seconds));
float percentCurrentPosition = ((float) seconds) / trackDuration * 100;
seekBarImageView.setX((percentCurrentPosition - 100) * pxPerWidthPercentage);
}
/**
* Returns the input time as a String of minutes : seconds
* Rounds up
* e.g. 219921 -> 3:40
*
* @param ms Time in milliseconds
* @return
*/
private String millisecondsToMinutesAndSeconds(int ms) {
float seconds = ((float) (ms % 60000)) / 1000;
int secs = (int) seconds;
if (seconds > secs)
secs++;
String suffix = secs < 10 ? ":0" + secs : ":" + secs;
int mins = ms / 60000;
return "" + mins + suffix;
}
/**
* Uses getColorInt() for finalizing the return value
* If too computationally expensive, just increase the stride
*
* @param bmp
* @return
*/
private int getAverageColor(Bitmap bmp) {
int totalCount = bmp.getWidth() * bmp.getHeight();
int[] pixels = new int[totalCount];
bmp.getPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
// int causes overflow
long totalR = 0;
long totalG = 0;
long totalB = 0;
for (int px : pixels) {
int r = Color.red(px);
int g = Color.green(px);
int b = Color.blue(px);
totalR += r * r;
totalG += g * g;
totalB += b * b;
}
totalR = (int) Math.sqrt(totalR / totalCount);
totalG = (int) Math.sqrt(totalG / totalCount);
totalB = (int) Math.sqrt(totalB / totalCount);
return getColorInt((int) totalR, (int) totalG, (int) totalB);
}
/**
* Returns an int that contains RGB information as 0xRRGGBB
* Might need to add 0xFF000000 if using for ARGB
* Clips input to [0, 255]
*
* @param r
* @param g
* @param b
* @return
*/
private int getColorInt(int r, int g, int b) {
r = Math.max(0, Math.min(255, r));
g = Math.max(0, Math.min(255, g));
b = Math.max(0, Math.min(255, b));
return Color.rgb(r,g,b);
}
/**
* Kind of like an update function
* Except it does not take dt as argument
*/
private class Tick extends AsyncTask<Integer, Integer, Integer> {
/**
* args[0] == tick interval in ms
* e.g. if input is [100] the task is run at most 10Hz
* Just like update(), there is no guarantee of maintaining 10Hz
*
* @param args
* @return
*/
protected Integer doInBackground(Integer... args) {
while (true) {
try {
Thread.sleep(args[0]);
publishProgress(0);
} catch (java.lang.InterruptedException e) {
Assert.assertNotNull(null);
}
}
}
/**
* Does not use any inputs
*
* @param args
*/
protected void onProgressUpdate(Integer... args) {
updateTrackTime();
}
}
/**
* Measures the time since an album art transition was called, and notifies the UI updater
* responsible for the transition on how much time has passed.
*/
private class AlbumArtTransition extends AsyncTask<Integer, Float, Integer> {
/**
* args[0] == total time in ms
* args[1] == tick interval in ms
* args[2] == direction. 0 is Prev, 1 is Next
* Does not guarantee constant tick rate.
*
* @param args
* @return
*/
protected Integer doInBackground(Integer... args) {
long timeBeforeSleep = System.currentTimeMillis();
int timeElapsed = 0;
int timeTarget = args[0];
int timeTick = args[1];
int direction = args[2];
Assert.assertTrue(direction == 0 || direction == 1);
while (timeElapsed < timeTarget) {
try {
Thread.sleep(timeTick);
timeElapsed += System.currentTimeMillis() - timeBeforeSleep;
publishProgress(((float) timeElapsed) / timeTarget, (float) direction);
} catch (java.lang.InterruptedException e) {
Assert.assertNotNull(null);
}
}
publishProgress(1.0f, (float) direction);
return 0;
}
/**
* args[0] == time elapsed as a ratio of time elapsed vs total time
* args[1] == direction. 0 is Left, 1 is Right.
* No error checking
*
* @param args
*/
protected void onProgressUpdate(Float... args) {
updateAlbumArt(args[0], args[1] > 0);
}
}
}
|
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
/**
* The Grand-Daddy of them all!
*
* @author jshmtthwclrk
*
*/
public class MainPanel extends JFrame {
/**
* SerialVersionUID
*/
private static final long serialVersionUID = -7236160691262901215L;
/** Bounding box for panels */
public JFrame frame = new JFrame();
/** Panel that contains all the separate panels */
public JPanel main = new JPanel();
/** Panel that displays the 2-D array */
private JPanel grid = new JPanel();
/** Dis Panel does da choosin */
private JPanel radioBox = new JPanel();
/** The Side Panel of Information!!! */
private JPanel side = new JPanel();
/** Background color */
private Color GOLD = new Color(218,165,32);
/** Grid object */
private Grid grd = new Grid();
/** Panel that shows the visualization */
private JPanel swagPanel = new JPanel();
/** 2-D array for grid panel */
public JPanel[][] pArray;
private JRadioButton union = new JRadioButton("Union Find");
private JRadioButton qUnion = new JRadioButton("Quick Union Find");
private JButton execute = new JButton("Execute");
private JLabel gridSizeLabel = new JLabel("Enter size:");
private JTextField gridSizeText = new JTextField("", 5);
private JLabel numRunsLabel = new JLabel("Number of runs:");
private JTextField numRunsText = new JTextField("1", 5);
private String numRunsString;
private JLabel select = new JLabel("Selection: ");
private String sizeString;
private JLabel currSize = new JLabel("Grid Size: ");
private int theSize = 0;
private JLabel blank1 = new JLabel(" ");
private JLabel blank2 = new JLabel(" ");
private JLabel blank3 = new JLabel(" ");
private JLabel blank4 = new JLabel(" ");
/** Weighted Compression Quick Union object */
public WeightedCompressionQuickUnion qf;
/** Quick Find object */
public QuickFind uf;
private int randRow;
private int randCol;
/** Percolation object */
public Percolation<DynamicConnectivity> perk;
private JLabel percent = new JLabel("Last Percent open: 0%");
private DecimalFormat df = new DecimalFormat("#.000");
private JLabel avgPercent = new JLabel("Avg Percent open: 0%");
private JLabel avgTime = new JLabel("Avg Run Time: ");
private JLabel runs = new JLabel("Number of Runs: ");
private double avgPercentNum;
private long avgTimeNum;
// Timer Stuff
private int timerCount = 0;
private JLabel timerLabel = new JLabel("Last Run Time: " + timerCount + " ms");
//Build Percent List
private String[] percentList;
private JLabel percentListTitle = new JLabel("");
private JLabel percentListLabel0 = new JLabel("");
private JLabel percentListLabel1 = new JLabel("");
private JLabel percentListLabel2 = new JLabel("");
private JLabel percentListLabel3 = new JLabel("");
private JLabel percentListLabel4 = new JLabel("");
private JLabel percentListLabel5 = new JLabel("");
private JLabel percentListLabel6 = new JLabel("");
private JLabel percentListLabel7 = new JLabel("");
private JLabel percentListLabel8 = new JLabel("");
private JLabel percentListLabel9 = new JLabel("");
/** Main method */
public static void main(String [] args) {
@SuppressWarnings("unused")
MainPanel mainPanel = new MainPanel();
} // end main method
/**
* Constructor that sets up the Main Panel for Union Find Visualization.
*/
public MainPanel() {
frame.setSize(800, 700);
frame.setResizable(false);
frame.setTitle("Union Find");
main.setSize(800,700);
main.setLayout(null);
@SuppressWarnings("unused")
RadioBox rdobx = new RadioBox();
@SuppressWarnings("unused")
SidePanel sdpnl = new SidePanel();
main.add(grid);
main.add(radioBox);
main.add(side);
frame.add(main);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} // end constructor
private class Grid {
/**
* Constructor that sets up the Grid Panel.
*/
public Grid() {
GridLayout gridGrid = new GridLayout();
grid.setSize(600, 600);
grid.setLayout(gridGrid);
grid.setBackground(Color.DARK_GRAY);
grid.setLocation(0, 0);
grid.setVisible(true);
} // end constructor
private void initalizeGrid(int size) {
pArray = new JPanel[size][size];
grid.removeAll();
grid.updateUI();
swagPanel.removeAll();
swagPanel.updateUI();
grid.setLayout(new GridLayout());
swagPanel.setBackground(GOLD);
swagPanel.setSize(600, 600);
GridLayout tileGrid = new GridLayout(size, size, 1, 1);
tileGrid.minimumLayoutSize(swagPanel);
swagPanel.setLayout(tileGrid);
swagPanel.setVisible(true);
percentListLabel0.setText("");
percentListLabel1.setText("");
percentListLabel2.setText("");
percentListLabel3.setText("");
percentListLabel4.setText("");
percentListLabel5.setText("");
percentListLabel6.setText("");
percentListLabel7.setText("");
percentListLabel8.setText("");
percentListLabel9.setText("");
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
JPanel panel = new JPanel(/*new GridBagLayout()*/);
panel.setBackground(Color.DARK_GRAY);
//panel.setSize(new Dimension((600/size), (600/size)));
panel.setVisible(true);
swagPanel.add(panel);
pArray[row][col] = panel;
} // end nested for loop
} // end for loop
grid.add(swagPanel);
} // end method initalizeGrid(int)
private void updateGrid() {
// random number stuff
randRow = (int)(Math.random() * ((theSize - 1) + 1));
randCol = (int)(Math.random() * ((theSize - 1) + 1));
if(perk.isOpen(randRow, randCol) == false) {
perk.open(randRow, randCol);
pArray[randRow][randCol].setBackground(Color.BLUE);
} // end if statement
} // end method updateGrid
} // end inner class Grid
/**
* Private Inner Class for User Interaction Panel
* @author Joshua Clark
*
*/
private class RadioBox {
/**
* Constructor
*/
public RadioBox() {
/** Panel that handles interactions with user. */
JPanel subPanel = new JPanel();
radioBox.setSize(800, 100);
radioBox.setBackground(Color.LIGHT_GRAY);
radioBox.setLocation(0, 600);
radioBox.setLayout(new BorderLayout());
union.setSelected(true);
execute.addActionListener(new ActionListener() {
@SuppressWarnings({ "rawtypes", "unchecked" })
public void actionPerformed(ActionEvent e) {
//swagPanel.setBackground(GOLD);
sizeString = gridSizeText.getText();
numRunsString = numRunsText.getText();
if(isNumeric(sizeString) && Integer.parseInt(sizeString) <=60
&& Integer.parseInt(sizeString) >= 2 && isNumeric(numRunsString)
&& Integer.parseInt(numRunsString) >= 1) {
int numRuns = Integer.parseInt(numRunsString);
percentList = new String[numRuns];
int i = 0;
avgPercentNum = 0;
avgTimeNum = 0;
while(numRuns > 0) {
execute.setEnabled(false);
currSize.setText("Grid Size: " + sizeString + " x " + sizeString);
theSize = Integer.parseInt(sizeString);
grd.initalizeGrid(theSize);
if(union.isSelected()) {
select.setText("Selection: Union");
uf = new QuickFind(theSize * theSize + 2);
perk = new Percolation(uf, theSize);
perk.startTimer();
} else if(qUnion.isSelected()) {
select.setText("Selection: Quick Union");
qf = new WeightedCompressionQuickUnion(theSize * theSize + 2);
perk = new Percolation(qf, theSize);
perk.startTimer();
}
while(perk.percolates() == false) {
grd.updateGrid();
}
perk.endTimer();
avgPercentNum = ((perk.percentOn()) + avgPercentNum);
String tempPercent = df.format(perk.percentOn() * 100);
percentList[i] = tempPercent;
avgTimeNum = (perk.calculateTimeTaken() + avgTimeNum);
timerLabel.setText("Last Run Time: " + perk.calculateTimeTaken() + " ms");
percent.setText("Last Percent open: " + df.format(perk.percentOn() * 100) + "%");
execute.setEnabled(true);
numRuns
i++;
//System.out.println(df.format(perk.percentOn() * 100));
}
avgPercentNum = avgPercentNum / Integer.parseInt(numRunsString);
avgTimeNum = avgTimeNum / Integer.parseInt(numRunsString);
avgPercent.setText("Avg Percent open: " + df.format(avgPercentNum * 100) + "%");
avgTime.setText("Avg Run Time: " + avgTimeNum + " ms");
runs.setText("Number of Runs: " + numRunsString);
int k;
if(Integer.parseInt(numRunsString) < 10){
k = Integer.parseInt(numRunsString);
}
else {
k=10;
}
for(int j = i-k; j<i; j++){
if(j == i-k) percentListLabel0.setText(" " +percentList[i-k] + "%");
if(j == i-k+1) percentListLabel1.setText(" " +percentList[i-k+1] + "%");
if(j == i-k+2) percentListLabel2.setText(" " +percentList[i-k+2] + "%");
if(j == i-k+3) percentListLabel3.setText(" " +percentList[i-k+3] + "%");
if(j == i-k+4) percentListLabel4.setText(" " +percentList[i-k+4] + "%");
if(j == i-k+5) percentListLabel5.setText(" " +percentList[i-k+5] + "%");
if(j == i-k+6) percentListLabel6.setText(" " +percentList[i-k+6] + "%");
if(j == i-k+7) percentListLabel7.setText(" " +percentList[i-k+7] + "%");
if(j == i-k+8) percentListLabel8.setText(" " +percentList[i-k+8] + "%");
if(j == i-k+9) percentListLabel9.setText(" " +percentList[i-k+9] + "%");
}
percentListTitle.setText("Last "+ k +" Percentages: ");
repaint();
} else {
JOptionPane.showMessageDialog(frame,
"Please enter a valid number between 2 and 60, then press Execute again.",
"Invalid Input", JOptionPane.WARNING_MESSAGE);
}
}
});
JPanel north = new JPanel();
north.setPreferredSize(new Dimension(800,20));
ButtonGroup bGroup = new ButtonGroup();
bGroup.add(union);
bGroup.add(qUnion);
subPanel.add(union);
subPanel.add(qUnion);
subPanel.add(gridSizeLabel);
subPanel.add(gridSizeText);
subPanel.add(numRunsLabel);
subPanel.add(numRunsText);
subPanel.add(execute);
radioBox.add(north, BorderLayout.NORTH);
radioBox.add(subPanel, BorderLayout.CENTER);
radioBox.setVisible(true);
} // end constructor
/**
* Takes in a string and returns a boolean response depending upon
* whether or not the string is a number.
* @param str
* @return
*/
public boolean isNumeric (String str) {
return str.matches("\\d+");
} // end method isNumeric(String)
} // end inner class RadioBox
/**
* Private Inner Class for Side Information Panel
* @author Joshua Clark
*
*/
private class SidePanel {
/**
* Constructor
*/
public SidePanel() {
side.setSize(200, 600);
side.setLocation(601, 0);
side.setLayout(new BoxLayout(side, BoxLayout.PAGE_AXIS));
//side.setBackground(Color.LIGHT_GRAY);
//JPanel padding = new JPanel();
//padding.setSize(5, 5);
//side.add(padding);
timerLabel.setFont(new Font("San-Serif", Font.PLAIN, 14));
select.setFont(new Font("San-Serif", Font.PLAIN, 14));
currSize.setFont(new Font("San-Serif", Font.PLAIN, 14));
percent.setFont(new Font("San-Serif", Font.PLAIN, 14));
avgPercent.setFont(new Font("San-Serif", Font.PLAIN, 14));
avgTime.setFont(new Font("San-Serif", Font.PLAIN, 14));
runs.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListLabel9.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListLabel8.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListLabel7.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListLabel6.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListLabel5.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListLabel4.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListLabel3.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListLabel2.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListLabel1.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListLabel0.setFont(new Font("San-Serif", Font.PLAIN, 14));
percentListTitle.setFont(new Font("San-Serif", Font.PLAIN, 14));
side.add(select);
side.add(currSize);
side.add(runs);
side.add(blank1);
side.add(timerLabel);
side.add(avgTime);
side.add(blank2);
side.add(percent);
side.add(avgPercent);
side.add(blank3);
side.add(percentListTitle);
side.add(percentListLabel0);
side.add(percentListLabel1);
side.add(percentListLabel2);
side.add(percentListLabel3);
side.add(percentListLabel4);
side.add(percentListLabel5);
side.add(percentListLabel6);
side.add(percentListLabel7);
side.add(percentListLabel8);
side.add(percentListLabel9);
} // end constructor
} // end inner class SidePanel
} // end class
|
package me.cvhc.equationsolver;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;
import com.androidplot.xy.XYStepMode;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.HashMap;
public class PlotActivity extends AppCompatActivity implements OnTouchListener {
private DecimalInputView textUpperBound, textLowerBound;
private XYPlot plot;
private CheckBox checkXLogScale;
private HashMap<Character, String> anotherSide;
private SharedPreferences sharedPreferences;
private FunctionWrapper mainSeries = null;
private double minX, maxX;
private double defaultMinX, defaultMaxX;
private double maxAbsY;
private int nZero = 0;
private static double SCALE_YAXIS = 1.12;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plot);
// load preferences
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int prefPlot = sharedPreferences.getInt("pref_plot_samples", 200);
// initialize View objects
Button buttonApply = (Button)findViewById(R.id.buttonApply);
Button buttonReset = (Button)findViewById(R.id.buttonReset);
textLowerBound = (DecimalInputView)findViewById(R.id.textLowerBound);
textUpperBound = (DecimalInputView)findViewById(R.id.textUpperBound);
checkXLogScale = (CheckBox)findViewById(R.id.checkXLogScale);
plot = (XYPlot)findViewById(R.id.plot);
assert buttonApply != null;
assert buttonReset != null;
assert textLowerBound != null;
assert textUpperBound != null;
assert checkXLogScale != null;
assert plot != null;
// read data from Intent object
Intent intent = getIntent();
final ExpressionCalculator eval = new ExpressionCalculator();
anotherSide = (HashMap<Character, String>)intent.getSerializableExtra("EXPRESSION");
for (Character c: anotherSide.keySet()) {
eval.setVariable(c, anotherSide.get(c));
}
double[] threshold = intent.getDoubleArrayExtra("THRESHOLD");
if (threshold.length == 2) {
// Bisection mode
java.util.Arrays.sort(threshold);
defaultMinX = minX = threshold[0];
defaultMaxX = maxX = threshold[1];
} else {
// find an appropriate range
double[] range = findBingoRange(threshold[0], eval);
defaultMinX = minX = range[0];
defaultMaxX = maxX = range[1];
}
// auto enable Log scale
if (minX > 0 && maxX > 0 && Math.log10(maxX / minX) > 6) {
checkXLogScale.setChecked(true);
}
DecimalInputView.OnValueChangedListener valueChangedListener = new DecimalInputView.OnValueChangedListener() {
@Override
public void onValueChanged(Number val) {
double[] tmp = { textLowerBound.getValue(), textUpperBound.getValue() };
java.util.Arrays.sort(tmp);
minX = checkXLogScale.isChecked() ? logScale(tmp[0]) : tmp[0];
maxX = checkXLogScale.isChecked() ? logScale(tmp[1]) : tmp[1];
resetY();
updatePlotBound();
}
};
textLowerBound.setDialogTitle(getString(R.string.lower_bound_of_roi));
textLowerBound.setDefaultValue(minX);
textLowerBound.setOnValueChangedListener(valueChangedListener);
textUpperBound.setDialogTitle(getString(R.string.upper_bound_of_roi));
textUpperBound.setDefaultValue(maxX);
textUpperBound.setOnValueChangedListener(valueChangedListener);
// listeners
buttonApply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String warning = null;
if (nZero == 0) {
warning = "Probably no zero point in select range.";
} else if (nZero > 1) {
warning = "It seems there are multiple zero points in select range.";
}
if (warning != null) {
new AlertDialog.Builder(PlotActivity.this)
.setTitle(android.R.string.dialog_alert_title)
.setMessage(warning)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
submitSelectRange();
}
})
.setNegativeButton(android.R.string.no, null)
.setIconAttribute(android.R.attr.alertDialogIcon)
.show();
} else {
submitSelectRange();
}
}
});
buttonReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
minX = checkXLogScale.isChecked() ? logScale(defaultMinX) : defaultMinX;
maxX = checkXLogScale.isChecked() ? logScale(defaultMaxX) : defaultMaxX;
if (minX >= maxX || !isNormal(minX) || !isNormal(maxX)) {
minX = checkXLogScale.isChecked() ? logScale(1e-14) : 0.0;
maxX = checkXLogScale.isChecked() ? 0.0 : 1.0;
}
resetY();
updatePlotBound();
}
});
abstract class CustomFormat extends NumberFormat {
@Override
abstract public StringBuffer format(double v, StringBuffer b, FieldPosition f);
@Override
public StringBuffer format(long v, StringBuffer b, FieldPosition f) { return null; }
@Override
public Number parse(String s, ParsePosition p) { return null; }
}
checkXLogScale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
minX = logScale(minX);
maxX = logScale(maxX);
if (!isNormal(minX) || !isNormal(maxX)) {
minX = logScale(Math.pow(10, -14.0));
maxX = 0.0;
}
} else {
minX = logScaleRecover(minX);
maxX = logScaleRecover(maxX);
}
mainSeries.resetCache();
resetY();
updatePlotBound();
}
});
// plot UI settings
plot.setOnTouchListener(this);
plot.setDomainStep(XYStepMode.SUBDIVIDE, 5);
plot.setDomainValueFormat(new CustomFormat() {
@Override
public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) {
double output = checkXLogScale.isChecked() ? logScaleRecover(value) : value;
return new StringBuffer(String.format("%6.4g", output));
}
});
plot.setRangeStep(XYStepMode.SUBDIVIDE, 7);
plot.setRangeValueFormat(new CustomFormat() {
@Override
public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) {
return new StringBuffer(String.format("%6.4g", value));
}
});
plot.getLegendWidget().setVisible(false);
plot.getTitleWidget().setVisible(false);
plot.centerOnRangeOrigin(0.0);
mainSeries = new FunctionWrapper(new FunctionWrapper.MathFunction() {
@Override
public double call(double x) {
if (checkXLogScale.isChecked()) { x = logScaleRecover(x); }
eval.setVariable('x', x);
ExpressionCalculator.OptionUnion op = eval.evaluate(' ');
return op.getValue();
}
}, prefPlot);
plot.addSeries(new XYSeries() {
final static int DIVIDE = 8;
@Override
public int size() {
return DIVIDE + 1;
}
@Override
public Number getX(int index) {
return minX + (maxX - minX) / DIVIDE * index;
}
@Override
public Number getY(int index) {
return 0.0;
}
@Override
public String getTitle() {
return null;
}
}, new LineAndPointFormatter(Color.rgb(255, 0, 0), null, null, null));
resetY();
plot.addSeries(mainSeries, new LineAndPointFormatter(Color.rgb(50, 0, 0), null, null, null));
updatePlotBound();
if (mainSeries.isAllInvalid()) {
new AlertDialog.Builder(this)
.setTitle(R.string.error)
.setMessage(R.string.cannot_evaluate_at_the_range)
.setPositiveButton(android.R.string.yes, null)
.setIconAttribute(android.R.attr.alertDialogIcon)
.show();
}
}
private double[] findBingoRange(double fromX, final ExpressionCalculator eval) {
FunctionWrapper.MathFunction func = new FunctionWrapper.MathFunction() {
@Override
public double call(double x) {
eval.setVariable('x', x);
ExpressionCalculator.OptionUnion op = eval.evaluate(' ');
return op.getValue();
}
};
double x1 = fromX, y1 = func.call(fromX);
double[] result = new double[]{0, fromX};
long round = 0;
while (isNormal(x1) && round < 20) {
double x2 = x1, y2 = Double.NaN;
double inc = Math.ulp((float)x1);
round++;
while (isNormal(x2)) {
x2 += inc;
inc *= 10.0;
if (y1 != (y2 = func.call(x2))) {
break;
}
}
double x_inter = (x2*y1 - x1*y2) / (y1-y2);
double y_inter = func.call(x_inter);
if (!isNormal(x_inter)) {
break;
} else if (Math.signum(y1) * Math.signum(y_inter) == -1 || y1 == 0.0) {
result[0] = x1;
result[1] = x_inter;
break;
}
x1 = x_inter;
y1 = y_inter;
}
java.util.Arrays.sort(result);
result[0] -= Math.max(Math.ulp((float)result[0]) * 100, Math.abs(result[0]) * 0.1);
result[1] += Math.max(Math.ulp((float)result[1]) * 100, Math.abs(result[1]) * 0.1);
return result;
}
private void submitSelectRange() {
double realMinX = getRealMinX();
double realMaxX = getRealMaxX();
final ExpressionCalculator eval = new ExpressionCalculator();
for (Character c: anotherSide.keySet()) {
eval.setVariable(c, anotherSide.get(c));
}
SolveTask task = new SolveTask(this, realMinX, realMaxX);
// Don't use AsyncTask.get() to retrieve result, it will block main UI
task.setOnResultListener(new SolveTask.OnResultListener() {
@Override
public void onResult(Double result) {
if (result != null) {
Intent resultData = new Intent();
resultData.putExtra("LAST_RESULT", result);
PlotActivity.this.setResult(Activity.RESULT_OK, resultData);
}
}
});
task.execute(new FunctionWrapper.MathFunction() {
@Override
public double call(double x) {
eval.setVariable('x', x);
return eval.evaluate(' ').getValue();
}
});
}
private void updatePlotBound() {
double realMinX = getRealMinX();
double realMaxX = getRealMaxX();
textLowerBound.setValue(realMinX);
textUpperBound.setValue(realMaxX);
mainSeries.setBound(minX, maxX);
plot.setDomainBoundaries(
minX,
Math.max(maxX, minX + Math.ulp((float)minX) * mainSeries.size()),
BoundaryMode.FIXED);
nZero = mainSeries.getNZero();
plot.setRangeBoundaries(-maxAbsY, maxAbsY, BoundaryMode.FIXED);
int color_id = R.color.colorPermission;
if (mainSeries.isAllInvalid() || nZero != 1) {
color_id = R.color.colorProhibition;
}
int color = ContextCompat.getColor(plot.getContext(), color_id);
plot.getGraphWidget().getGridBackgroundPaint().setColor(color);
plot.redraw();
}
private static final int NONE = 0;
private static final int ONE_FINGER_DRAG = 1;
private static final int TWO_FINGERS_DRAG = 2;
private int mode = NONE;
private PointF firstFinger;
private double distBetweenFingers;
@Override
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // Start gesture
firstFinger = new PointF(event.getX(), event.getY());
mode = ONE_FINGER_DRAG;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger
distBetweenFingers = spacing(event);
// the distance check is done to avoid false alarms
if (distBetweenFingers > 5f) {
mode = TWO_FINGERS_DRAG;
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == ONE_FINGER_DRAG) {
PointF oldFirstFinger = firstFinger;
firstFinger = new PointF(event.getX(), event.getY());
scroll(oldFirstFinger.x - firstFinger.x);
} else if (mode == TWO_FINGERS_DRAG) {
double oldDist = distBetweenFingers;
distBetweenFingers = spacing(event);
if (onDirectionX(event)) {
zoom(oldDist / distBetweenFingers);
} else {
maxAbsY *= oldDist / distBetweenFingers;
}
}
updatePlotBound();
break;
}
return true;
}
private void resetY() {
mainSeries.setBound(minX, maxX);
if (mainSeries.isAllInvalid()) {
maxAbsY = 1.0;
} else {
maxAbsY = Math.max(Math.abs(mainSeries.getMaxY()), Math.abs(mainSeries.getMinY()));
maxAbsY *= SCALE_YAXIS;
}
}
private void zoom(double scale) {
double domainSpan = maxX - minX;
double domainMidPoint = maxX - domainSpan / 2.0f;
double offset = domainSpan * scale / 2.0f;
double min = domainMidPoint - offset;
double max = domainMidPoint + offset;
min = Math.min(min, mainSeries.getX(mainSeries.size() - 1).doubleValue());
max = Math.max(max, mainSeries.getX(0).doubleValue());
double realMinX = checkXLogScale.isChecked() ? logScaleRecover(min) : min;
double realMaxX = checkXLogScale.isChecked() ? logScaleRecover(max) : max;
if (min < max && isNormal(realMinX) && isNormal(realMaxX)) {
minX = min;
maxX = max;
}
}
private void scroll(double pan) {
double domainSpan = maxX - minX;
double step = domainSpan / plot.getWidth();
double offset = pan * step;
double min = minX + offset;
double max = maxX + offset;
double realMinX = checkXLogScale.isChecked() ? logScaleRecover(min) : min;
double realMaxX = checkXLogScale.isChecked() ? logScaleRecover(max) : max;
if (min < max && isNormal(realMinX) && isNormal(realMaxX)) {
minX = min;
maxX = max;
}
}
private double spacing(MotionEvent event) {
double x = event.getX(0) - event.getX(1);
double y = event.getY(0) - event.getY(1);
return Math.hypot(x, y);
}
private boolean onDirectionX(MotionEvent event) {
double x = event.getX(0) - event.getX(1);
double y = event.getY(0) - event.getY(1);
return Math.abs(y) < Math.abs(x);
}
private static double logScale(double val) {
return Math.log(val);
}
private static double logScaleRecover(double val) {
return Math.exp(val);
}
private double getRealMinX() {
return checkXLogScale.isChecked() ? logScaleRecover(minX) : minX;
}
private double getRealMaxX() {
return checkXLogScale.isChecked() ? logScaleRecover(maxX) : maxX;
}
private boolean isNormal(double n) {
return !(Double.isInfinite(n) || Double.isNaN(n));
}
}
|
package ru.stqa.pft.sandbox.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqa.pft.sandbox.model.Square;
public class SquareTests {
@Test
public void testArea(){
Square square = new Square(5);
Assert.assertEquals(square.area(),25.0);
}
}
|
package me.cvhc.equationsolver;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;
import com.androidplot.xy.XYStepMode;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.HashMap;
public class PlotActivity extends AppCompatActivity implements OnTouchListener {
private TextView textUpperBound, textLowerBound;
private XYPlot plot;
private CheckBox checkXLogScale;
private HashMap<Character, String> anotherSide;
private SharedPreferences sharedPreferences;
private FunctionWrapper mainSeries = null;
private double minX, maxX;
private double maxAbsY;
private Double lastResult = null;
private int nZero = 0;
private static double SCALE_YAXIS = 1.12;
private class BoundSettingListener implements View.OnClickListener {
@Override
public void onClick(View v) {
final TextView label = (TextView)v;
final DecimalSettingView settingView = new DecimalSettingView(PlotActivity.this);
final String who;
double realMinX = getRealMinX();
double readMaxX = getRealMaxX();
final double thisValue, anotherValue;
if (v == textLowerBound) {
thisValue = realMinX;
anotherValue = readMaxX;
who = "Lower";
} else if (v == textUpperBound) {
thisValue = readMaxX;
anotherValue = realMinX;
who = "Upper";
} else {
throw new RuntimeException();
}
AlertDialog.Builder alert = new AlertDialog.Builder(PlotActivity.this)
.setTitle(String.format("Setting %s Bound", who))
.setView(settingView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Double n = settingView.getInputValue().doubleValue();
label.setText(n.toString());
if (who.equals("Lower")) {
minX = checkXLogScale.isChecked() ? logScale(n) : n;
} else {
maxX = checkXLogScale.isChecked() ? logScale(n) : n;
}
resetY();
updatePlotBound();
}
})
.setNegativeButton(android.R.string.cancel, null);
final AlertDialog dialog = alert.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
settingView.setDefaultValue(thisValue);
settingView.setOnInputValueChangedListener(new DecimalSettingView.OnInputValueChangedListener() {
@Override
public void onInputValueChanged(Number val) {
Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
if (who.equals("Lower")) {
if (val.doubleValue() < anotherValue) {
positiveButton.setEnabled(true);
settingView.setWarning(null);
} else {
positiveButton.setEnabled(false);
settingView.setWarning("Invalid Bound");
}
} else if (who.equals("Upper")) {
if (val.doubleValue() > anotherValue) {
positiveButton.setEnabled(true);
settingView.setWarning(null);
} else {
positiveButton.setEnabled(false);
settingView.setWarning("Invalid Bound");
}
}
}
});
dialog.show();
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plot);
// initialize View objects
Button buttonApply = (Button)findViewById(R.id.buttonApply);
Button buttonReset = (Button)findViewById(R.id.buttonReset);
textLowerBound = (TextView)findViewById(R.id.textLowerBound);
textUpperBound = (TextView)findViewById(R.id.textUpperBound);
checkXLogScale = (CheckBox)findViewById(R.id.checkXLogScale);
plot = (XYPlot)findViewById(R.id.plot);
assert buttonApply != null;
assert buttonReset != null;
assert textLowerBound != null;
assert textUpperBound != null;
assert checkXLogScale != null;
assert plot != null;
textLowerBound.setOnClickListener(new BoundSettingListener());
textUpperBound.setOnClickListener(new BoundSettingListener());
// read data from Intent object
Intent intent = getIntent();
final ExpressionCalculator eval = new ExpressionCalculator();
anotherSide = (HashMap<Character, String>)intent.getSerializableExtra("EXPRESSION");
for (Character c: anotherSide.keySet()) {
eval.setVariable(c, anotherSide.get(c));
}
// load preferences
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int prefPlot = sharedPreferences.getInt("pref_plot_samples", 200);
minX = sharedPreferences.getFloat("pref_default_lower_bound", 0.0F);
maxX = sharedPreferences.getFloat("pref_default_upper_bound", 1.0F);
// listeners
buttonApply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String warning = null;
if (nZero == 0) {
warning = "Probably no zero point in select range.";
} else if (nZero > 1) {
warning = "It seems there are multiple zero points in select range.";
}
if (warning != null) {
new AlertDialog.Builder(PlotActivity.this)
.setTitle(android.R.string.dialog_alert_title)
.setMessage(warning)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
submitSelectRange();
}
})
.setNegativeButton(android.R.string.no, null)
.setIconAttribute(android.R.attr.alertDialogIcon)
.show();
} else {
submitSelectRange();
}
}
});
buttonReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float min = sharedPreferences.getFloat("pref_default_lower_bound", 0.0F);
float max = sharedPreferences.getFloat("pref_default_upper_bound", 1.0F);
minX = checkXLogScale.isChecked() ? logScale(min) : min;
maxX = checkXLogScale.isChecked() ? logScale(max) : min;
if (minX >= maxX || !isNormal(minX) || !isNormal(maxX)) {
minX = checkXLogScale.isChecked() ? logScale(1e-14) : 0.0;
maxX = checkXLogScale.isChecked() ? 0.0 : 1.0;
}
resetY();
updatePlotBound();
}
});
abstract class CustomFormat extends NumberFormat {
@Override
abstract public StringBuffer format(double v, StringBuffer b, FieldPosition f);
@Override
public StringBuffer format(long v, StringBuffer b, FieldPosition f) { return null; }
@Override
public Number parse(String s, ParsePosition p) { return null; }
}
checkXLogScale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
minX = logScale(minX);
maxX = logScale(maxX);
if (!isNormal(minX) || !isNormal(maxX)) {
minX = logScale(Math.pow(10, -14.0));
maxX = 0.0;
}
} else {
minX = logScaleRecover(minX);
maxX = logScaleRecover(maxX);
}
mainSeries.resetCache();
resetY();
updatePlotBound();
}
});
// plot UI settings
plot.setOnTouchListener(this);
plot.setDomainStep(XYStepMode.SUBDIVIDE, 5);
plot.setDomainValueFormat(new CustomFormat() {
@Override
public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) {
double output = checkXLogScale.isChecked() ? logScaleRecover(value) : value;
return new StringBuffer(String.format("%6.4g", output));
}
});
plot.setRangeStep(XYStepMode.SUBDIVIDE, 7);
plot.setRangeValueFormat(new CustomFormat() {
@Override
public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) {
return new StringBuffer(String.format("%6.4g", value));
}
});
plot.getLegendWidget().setVisible(false);
plot.getTitleWidget().setVisible(false);
plot.centerOnRangeOrigin(0.0);
mainSeries = new FunctionWrapper(new FunctionWrapper.MathFunction() {
@Override
public double call(double x) {
if (checkXLogScale.isChecked()) { x = logScaleRecover(x); }
eval.setVariable('x', x);
ExpressionCalculator.OptionUnion op = eval.evaluate(' ');
return op.getValue();
}
}, prefPlot);
plot.addSeries(new XYSeries() {
final static int DIVIDE = 8;
@Override
public int size() {
return DIVIDE + 1;
}
@Override
public Number getX(int index) {
return minX + (maxX - minX) / DIVIDE * index;
}
@Override
public Number getY(int index) {
return 0.0;
}
@Override
public String getTitle() {
return null;
}
}, new LineAndPointFormatter(Color.rgb(255, 0, 0), null, null, null));
resetY();
plot.addSeries(mainSeries, new LineAndPointFormatter(Color.rgb(50, 0, 0), null, null, null));
updatePlotBound();
}
private void submitSelectRange() {
double realMinX = getRealMinX();
double realMaxX = getRealMaxX();
final ExpressionCalculator eval = new ExpressionCalculator();
for (Character c: anotherSide.keySet()) {
eval.setVariable(c, anotherSide.get(c));
}
SolveTask task = new SolveTask(this, realMinX, realMaxX);
// Don't use AsyncTask.get() to retrieve result, it will block main UI
task.setOnResultListener(new SolveTask.OnResultListener() {
@Override
public void onResult(Double result) {
if (result != null) {
Intent resultData = new Intent();
resultData.putExtra("LAST_RESULT", lastResult);
setResult(Activity.RESULT_OK, resultData);
}
}
});
task.execute(new FunctionWrapper.MathFunction() {
@Override
public double call(double x) {
eval.setVariable('x', x);
return eval.evaluate(' ').getValue();
}
});
}
private void updatePlotBound() {
double realMinX = getRealMinX();
double realMaxX = getRealMaxX();
textLowerBound.setText(String.format(getString(R.string.format_bound), realMinX));
textUpperBound.setText(String.format(getString(R.string.format_bound), realMaxX));
mainSeries.setBound(minX, maxX);
plot.setDomainBoundaries(minX, maxX, BoundaryMode.FIXED);
nZero = mainSeries.getNZero();
plot.setRangeBoundaries(-maxAbsY, maxAbsY, BoundaryMode.FIXED);
int color_id = R.color.colorPermission;
if (mainSeries.isAllInvalid() || nZero != 1) {
color_id = R.color.colorProhibition;
}
int color = ContextCompat.getColor(plot.getContext(), color_id);
plot.getGraphWidget().getGridBackgroundPaint().setColor(color);
plot.redraw();
}
private static final int NONE = 0;
private static final int ONE_FINGER_DRAG = 1;
private static final int TWO_FINGERS_DRAG = 2;
private int mode = NONE;
private PointF firstFinger;
private double distBetweenFingers;
@Override
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // Start gesture
firstFinger = new PointF(event.getX(), event.getY());
mode = ONE_FINGER_DRAG;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger
distBetweenFingers = spacing(event);
// the distance check is done to avoid false alarms
if (distBetweenFingers > 5f) {
mode = TWO_FINGERS_DRAG;
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == ONE_FINGER_DRAG) {
PointF oldFirstFinger = firstFinger;
firstFinger = new PointF(event.getX(), event.getY());
scroll(oldFirstFinger.x - firstFinger.x);
} else if (mode == TWO_FINGERS_DRAG) {
double oldDist = distBetweenFingers;
distBetweenFingers = spacing(event);
if (onDirectionX(event)) {
zoom(oldDist / distBetweenFingers);
} else {
maxAbsY *= oldDist / distBetweenFingers;
}
}
updatePlotBound();
break;
}
return true;
}
private void resetY() {
mainSeries.setBound(minX, maxX);
if (mainSeries.isAllInvalid()) {
maxAbsY = 1.0;
} else {
maxAbsY = Math.max(Math.abs(mainSeries.getMaxY()), Math.abs(mainSeries.getMinY()));
maxAbsY *= SCALE_YAXIS;
}
}
private void zoom(double scale) {
double domainSpan = maxX - minX;
double domainMidPoint = maxX - domainSpan / 2.0f;
double offset = domainSpan * scale / 2.0f;
double min = domainMidPoint - offset;
double max = domainMidPoint + offset;
min = Math.min(min, mainSeries.getX(mainSeries.size() - 1).doubleValue());
max = Math.max(max, mainSeries.getX(0).doubleValue());
double realMinX = checkXLogScale.isChecked() ? logScaleRecover(min) : min;
double realMaxX = checkXLogScale.isChecked() ? logScaleRecover(max) : max;
if (min < max && isNormal(realMinX) && isNormal(realMaxX)) {
minX = min;
maxX = max;
}
}
private void scroll(double pan) {
double domainSpan = maxX - minX;
double step = domainSpan / plot.getWidth();
double offset = pan * step;
double min = minX + offset;
double max = maxX + offset;
double realMinX = checkXLogScale.isChecked() ? logScaleRecover(min) : min;
double realMaxX = checkXLogScale.isChecked() ? logScaleRecover(max) : max;
if (min < max && isNormal(realMinX) && isNormal(realMaxX)) {
minX = min;
maxX = max;
}
}
private double spacing(MotionEvent event) {
double x = event.getX(0) - event.getX(1);
double y = event.getY(0) - event.getY(1);
return Math.hypot(x, y);
}
private boolean onDirectionX(MotionEvent event) {
double x = event.getX(0) - event.getX(1);
double y = event.getY(0) - event.getY(1);
return Math.abs(y) < Math.abs(x);
}
private static double logScale(double val) {
return Math.log(val);
}
private static double logScaleRecover(double val) {
return Math.exp(val);
}
private double getRealMinX() {
return checkXLogScale.isChecked() ? logScaleRecover(minX) : minX;
}
private double getRealMaxX() {
return checkXLogScale.isChecked() ? logScaleRecover(maxX) : maxX;
}
private boolean isNormal(double n) {
return !(Double.isInfinite(n) || Double.isNaN(n));
}
}
|
package me.mcomella.fathomtest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TODO: 1) Inject fathom into webview viewing page
// 2) Figure out if there is a better way to get the source (e.g. XHR). I've had trouble with this in the past.
final WebView webView = (WebView) findViewById(R.id.webview);
final WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setWebViewClient(new InjectClient());
webView.setWebChromeClient(new ChromeClient());
webView.loadUrl("http://apple.com");
}
// Log javascript errors.
public class ChromeClient extends WebChromeClient {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.d("lol", consoleMessage.messageLevel() + "> " + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + ": " + consoleMessage.message());
Toast.makeText(MainActivity.this, "console: " + consoleMessage.message(), Toast.LENGTH_SHORT).show();
return super.onConsoleMessage(consoleMessage);
}
}
public class InjectClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final String script = Util.getStringFromResources(view.getContext(), R.raw.redirect);
view.evaluateJavascript(script, new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
Log.d("lol", "s: " + s);
Toast.makeText(MainActivity.this, "Finished: " + s, Toast.LENGTH_SHORT).show();
}
});
}
}
}
|
package net.sourceforge.servestream.service;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.sourceforge.servestream.provider.Media;
import net.sourceforge.servestream.utils.URLUtils;
import net.sourceforge.servestream.utils.Utils;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
public class DownloadManager {
private static final String TAG = DownloadManager.class.getName();
private MediaPlaybackService mMediaPlaybackService = null;
private long mTotalSizeInBytes = -1;
private long mLength = -1;
private File mPartialFile = null;
private File mCompleteFile = null;
private DownloadTask mDownloadTask = null;
private PollingAsyncTask mPollingAsyncTask = null;
public DownloadManager(MediaPlaybackService mediaPlaybackService) {
mMediaPlaybackService = mediaPlaybackService;
}
public void download(long id) {
URL url = null;
String uri = getUri(mMediaPlaybackService, id);
if (uri != null) {
try {
url = new URL(uri);
} catch (MalformedURLException e) {
e.printStackTrace();
return;
}
}
mTotalSizeInBytes = -1;
mLength = -1;
mPartialFile = new File(Utils.getDownloadDirectory(), "mediafile" + id + ".partial.dat");
mCompleteFile = new File(Utils.getDownloadDirectory(), "mediafile" + id + ".complete.dat");
Utils.deleteFile(mPartialFile);
Utils.deleteFile(mCompleteFile);
Log.v(TAG, "=============> " + mPartialFile.toString());
mDownloadTask = new DownloadTask(mPartialFile, mCompleteFile);
mDownloadTask.execute(url);
mPollingAsyncTask = new PollingAsyncTask();
mPollingAsyncTask.execute();
}
public void cancelDownload() {
if (mDownloadTask != null) {
DownloadTask downloadTask = mDownloadTask;
downloadTask.cancel(false);
mDownloadTask = null;
}
}
public void cancelPollingTask() {
if (mPollingAsyncTask != null) {
PollingAsyncTask pollingAsyncTask = mPollingAsyncTask;
pollingAsyncTask.cancel(false);
mPollingAsyncTask = null;
}
}
public File getCompleteFile() {
if (mCompleteFile != null && mCompleteFile.exists()) {
return mCompleteFile;
}
return null;
}
public long getCompleteFileDuration() {
long duration = 0;
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(getCompleteFile().toString());
mediaPlayer.prepare();
duration = mediaPlayer.getDuration();
} catch (Exception e) {
}
return duration;
}
public File getPartialFile() {
return mPartialFile;
}
public synchronized boolean isCompleteFileAvailable() {
if (mCompleteFile != null && mCompleteFile.exists()) {
return true;
}
return false;
}
public synchronized double getPercentDownloaded() {
if (mCompleteFile != null && mCompleteFile.exists()) {
return 1.0;
}
return (double) mPartialFile.length() / (double) mTotalSizeInBytes;
}
public synchronized boolean isDownloadCancelled() {
return mDownloadTask != null && mDownloadTask.isCancelled();
}
public void delete() {
cancelDownload();
cancelPollingTask();
Utils.deleteFile(mPartialFile);
Utils.deleteFile(mCompleteFile);
}
/**
* @return the length
*/
public long getLength() {
long length = -1;
if (isCompleteFileAvailable()) {
if (mLength == -1) {
mLength = getCompleteFileDuration();
}
length = mLength;
}
return length;
}
private class DownloadTask extends AsyncTask<URL, Void, Void> {
private File mPartialFile = null;
private File mCompleteFile = null;
public DownloadTask(File partialFile, File completeFile) {
mPartialFile = partialFile;
mCompleteFile = completeFile;
}
@Override
protected Void doInBackground(URL... url) {
HttpURLConnection conn = null;
BufferedInputStream in = null;
FileOutputStream out = null;
boolean appendToFile = false;
byte[] buffer = new byte[1024 * 16];
//long count = 0;
Log.v(TAG, "starting download task");
while (!mCompleteFile.exists() && !isCancelled()) {
try {
conn = determineRange(url[0], mPartialFile.length());
if (conn.getResponseCode() == HttpURLConnection.HTTP_PARTIAL) {
appendToFile = true;
} else {
mTotalSizeInBytes = conn.getContentLength();
}
in = new BufferedInputStream(conn.getInputStream());
out = new FileOutputStream(mPartialFile, appendToFile);
int i;
while (((i = in.read(buffer)) != -1) && !isCancelled()) {
out.write(buffer, 0, i);
//count += i;
}
out.flush();
out.close();
Utils.copyFile(mPartialFile, mCompleteFile);
Log.v(TAG, "download task is complete");
} catch (IOException e) {
e.printStackTrace();
} finally {
Utils.closeInputStream(in);
Utils.closeHttpConnection(conn);
Utils.closeOutputStream(out);
}
}
return null;
}
private HttpURLConnection determineRange(URL url, long bytesProcessed) {
HttpURLConnection conn = null;
conn = URLUtils.getConnection(url);
if (conn == null) {
return null;
}
conn.setConnectTimeout(6000);
conn.setReadTimeout(6000);
conn.setRequestProperty("Range", "bytes=" + bytesProcessed + "-");
try {
conn.setRequestMethod("GET");
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
}
private class PollingAsyncTask extends AsyncTask<Void, Void, Void> {
//int INITIAL_BUFFER = Math.max(100000, 160 * 1024 / 8 * 5);
int INITIAL_BUFFER = 81920;
public PollingAsyncTask() {
super();
}
@Override
protected Void doInBackground(Void... stream) {
Log.v(TAG, "polling task started");
while (!bufferingComplete() && !isCancelled()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.v(TAG, "setDataSource called");
mMediaPlaybackService.getMediaPlayer().setDataSource(getPartialFile().getPath(), true);
return null;
}
private boolean bufferingComplete() {
return getPartialFile().length() >= INITIAL_BUFFER;
}
}
private String getUri(Context context, long id) {
String uri = null;
// Form an array specifying which columns to return.
String [] projection = new String [] { Media.MediaColumns.URI };
// Get the base URI for the Media Files table in the Media content provider.
Uri mediaFile = Media.MediaColumns.CONTENT_URI;
// Make the query.
Cursor cursor = context.getContentResolver().query(mediaFile,
projection,
Media.MediaColumns._ID + "= ? ",
new String [] { String.valueOf(id) },
null);
if (cursor.moveToFirst()) {
int uriColumn = cursor.getColumnIndex(Media.MediaColumns.URI);
uri = cursor.getString(uriColumn);
}
cursor.close();
return uri;
}
}
|
package net.ssehub.kernel_haven.util;
import java.net.URL;
import java.net.URLClassLoader;
import net.ssehub.kernel_haven.util.null_checks.NonNull;
/**
* A {@link ClassLoader} to be used by KernelHaven. Starting with Java 9, it is required that this is set as the
* <code>java.system.class.loader</code> in order for the plugin system to work.
*
* @author Adam
*/
public class KernelHavenClassLoader extends URLClassLoader {
/**
* Creates this class loader. This will be called by the JVM if <code>java.system.class.loader</code> is set to
* this class.
*
* @param parent The parent class loader to delegate to.
*/
public KernelHavenClassLoader(@NonNull ClassLoader parent) {
super(new URL[0], parent);
}
// make this method public
@Override
public void addURL(URL url) {
super.addURL(url);
}
}
|
package net.tetrisconcept.poochy.nullpomino.ai;
import mu.nu.nullpo.game.component.Controller;
import mu.nu.nullpo.game.component.Field;
import mu.nu.nullpo.game.component.Piece;
import mu.nu.nullpo.game.component.WallkickResult;
import mu.nu.nullpo.game.play.GameEngine;
import mu.nu.nullpo.game.play.GameManager;
import mu.nu.nullpo.game.subsystem.ai.DummyAI;
import org.apache.log4j.Logger;
/**
* PoochyBot Combo Race AI
* @author Poochy.EXE
* Poochy.Spambucket@gmail.com
*/
public class ComboRaceBot extends DummyAI implements Runnable {
/** Log */
static Logger log = Logger.getLogger(ComboRaceBot.class);
/** List of field state codes which are possible to sustain a stable combo */
private static final int[] FIELDS = {
0x7, 0xB, 0xD, 0xE,
0x13, 0x15, 0x16, 0x19, 0x1A, 0x1C,
0x23, 0x29,
0x31, 0x32,
0x49, 0x4C,
0x61, 0x68,
0x83, 0x85, 0x86, 0x89, 0x8A, 0x8C,
0xC4, 0xC8,
0x111, 0x888
};
protected int[] scores = {6, 7, 7, 6, 8, 3, 2, 9, 3, 4, 3, 1, 8, 4, 1, 3, 1, 1, 4, 3, 9, 2, 3, 8, 4, 8, 3, 3};
protected Transition[][] moves;
protected int[] nextQueueIDs;
protected boolean createTablesRequest;
/** Direction(0: None) */
public int bestRtSub;
/** Evaluation score */
public int bestPts;
/** Movement state. 0 = initial, 1 = twist, 2 = post-twist */
public int movestate;
/** count */
public int delay;
/** The GameEngine that owns this AI */
public GameEngine gEngine;
/** The GameManager that owns this AI */
public GameManager gManager;
/** When true,Think routine */
public boolean thinkRequest;
/** true when thread is executing the think routine. */
public boolean thinking;
/** time */
public int thinkDelay;
/** When true, */
public volatile boolean threadRunning;
/** Thread for executing the think routine */
public Thread thread;
/** Last input if done in ARE */
protected int inputARE;
/** Number of pieces to think ahead */
protected static final int MAX_THINK_DEPTH = 5;
/** Set to true to print debug information */
protected static final boolean DEBUG_ALL = false;
/** Did the thinking thread finish successfully? */
protected boolean thinkComplete;
/** Did the thinking thread find a possible position? */
protected boolean thinkSuccess;
/** Was the game in ARE as of the last frame? */
protected boolean inARE;
/*
* AI's name
*/
@Override
public String getName() {
return "Combo Race AI V1.01";
}
/*
* Called at initialization
*/
@Override
public void init(GameEngine engine, int playerID) {
delay = 0;
gEngine = engine;
gManager = engine.owner;
thinkRequest = false;
thinking = false;
threadRunning = false;
createTablesRequest = false;
inputARE = 0;
thinkComplete = false;
thinkSuccess = false;
inARE = false;
if( ((thread == null) || !thread.isAlive()) && (engine.aiUseThread) ) {
thread = new Thread(this, "AI_" + playerID);
thread.setDaemon(true);
thread.start();
thinkDelay = engine.aiThinkDelay;
thinkCurrentPieceNo = 0;
thinkLastPieceNo = 0;
}
}
@Override
public void shutdown(GameEngine engine, int playerID) {
if((thread != null) && (thread.isAlive())) {
thread.interrupt();
threadRunning = false;
thread = null;
}
}
/*
* Called whenever a new piece is spawned
*/
@Override
public void newPiece(GameEngine engine, int playerID) {
if(!engine.aiUseThread) {
thinkBestPosition(engine, playerID);
} else if ((!thinking && !thinkComplete) || !engine.aiPrethink
|| engine.getARE() <= 0 || engine.getARELine() <= 0) {
thinkRequest = true;
thinkCurrentPieceNo++;
}
movestate = 0;
}
/*
* Called at the start of each frame
*/
@Override
public void onFirst(GameEngine engine, int playerID) {
inputARE = 0;
boolean newInARE = engine.stat == GameEngine.STAT_ARE;
if ((engine.aiPrethink && engine.getARE() > 0 && engine.getARELine() > 0)
&& ((newInARE && !inARE) || (!thinking && !thinkSuccess)))
{
if (DEBUG_ALL) log.debug("Begin pre-think of next piece.");
thinkComplete = false;
thinkRequest = true;
}
inARE = newInARE;
if(inARE && delay >= engine.aiMoveDelay) {
int input = 0;
Piece nextPiece = engine.getNextObject(engine.nextPieceCount);
if (bestHold && thinkComplete)
{
input |= Controller.BUTTON_BIT_D;
if (engine.holdPieceObject == null)
nextPiece = engine.getNextObject(engine.nextPieceCount+1);
else
nextPiece = engine.holdPieceObject;
}
if (nextPiece == null)
return;
nextPiece = checkOffset(nextPiece, engine);
//input |= calcIRS(nextPiece, engine);
if (threadRunning && !thinking && (thinkCurrentPieceNo <= thinkLastPieceNo))
{
int spawnX = engine.getSpawnPosX(engine.field, nextPiece);
if(bestX - spawnX > 1) {
// left
input |= Controller.BUTTON_BIT_LEFT;
} else if(spawnX - bestX > 1) {
// right
input |= Controller.BUTTON_BIT_RIGHT;
}
delay = 0;
}
if (DEBUG_ALL) log.debug("Currently in ARE. Next piece type = " + nextPiece.id + ", IRS = " + input);
//engine.ctrl.setButtonBit(input);
inputARE = input;
}
}
/*
* Called after every frame
*/
@Override
public void onLast(GameEngine engine, int playerID) {
if (engine.stat == GameEngine.STAT_READY && engine.statc[0] == 0)
createTablesRequest = true;
}
/*
* Set button input states
*/
@Override
public void setControl(GameEngine engine, int playerID, Controller ctrl) {
if( (engine.nowPieceObject != null) && (engine.stat == GameEngine.STAT_MOVE) &&
(delay >= engine.aiMoveDelay) && (engine.statc[0] > 0) &&
(!engine.aiUseThread || (threadRunning && !thinking && (thinkCurrentPieceNo <= thinkLastPieceNo))) )
{
inputARE = 0;
int input = 0; // Button input data
Piece pieceNow = checkOffset(engine.nowPieceObject, engine);
int nowX = engine.nowPieceX;
int nowY = engine.nowPieceY;
int rt = pieceNow.direction;
Field fld = engine.field;
boolean pieceTouchGround = pieceNow.checkCollision(nowX, nowY + 1, fld);
int nowType = pieceNow.id;
//int width = fld.getWidth();
int moveDir = 0; //-1 = left, 1 = right
int rotateDir = 0; //-1 = left, 1 = right
int drop = 0; //1 = up, -1 = down
if((bestHold == true) && thinkComplete && engine.isHoldOK()) {
// Hold
input |= Controller.BUTTON_BIT_D;
/*
Piece holdPiece = engine.holdPieceObject;
if (holdPiece != null)
input |= calcIRS(holdPiece, engine);
*/
} else {
if (DEBUG_ALL) log.debug("bestX = " + bestX + ", nowX = " + nowX +
", bestY = " + bestY + ", nowY = " + nowY +
", bestRt = " + bestRt + ", rt = " + rt +
", bestRtSub = " + bestRtSub);
printPieceAndDirection(nowType, rt);
// Rotation
/*
//Rotate iff near destination or stuck
int xDiff = Math.abs(nowX - bestX);
if (bestX < nowX && nowType == Piece.PIECE_I &&
rt == Piece.DIRECTION_DOWN && bestRt != rt)
xDiff--;
if((rt != bestRt && ((xDiff <= 1) ||
(bestX == 0 && nowX == 2 && nowType == Piece.PIECE_I) ||
(((nowX < bestX && pieceNow.checkCollision(nowX+1, nowY, rt, fld)) ||
(nowX > bestX && pieceNow.checkCollision(nowX-1, nowY, rt, fld))) &&
!(pieceNow.getMaximumBlockX()+nowX == width-2 && (rt&1) == 1) &&
!(pieceNow.getMinimumBlockY()+nowY == 2 && pieceTouchGround && (rt&1) == 0 && nowType != Piece.PIECE_I)))))
*/
if (rt != bestRt)
{
boolean best180 = Math.abs(rt - bestRt) == 2;
//if (DEBUG_ALL) log.debug("Case 1 rotation");
int lrot = engine.getRotateDirection(-1);
int rrot = engine.getRotateDirection(1);
if (DEBUG_ALL) log.debug("lrot = " + lrot + ", rrot = " + rrot);
if(best180 && (engine.ruleopt.rotateButtonAllowDouble) && !ctrl.isPress(Controller.BUTTON_E))
input |= Controller.BUTTON_BIT_E;
else if (bestRt == rrot)
rotateDir = 1;
else if(bestRt == lrot)
rotateDir = -1;
else if (engine.ruleopt.rotateButtonAllowReverse && best180 && (rt&1) == 1)
{
if(rrot == Piece.DIRECTION_UP)
rotateDir = 1;
else
rotateDir = -1;
}
else
rotateDir = 1;
}
int minX = pieceNow.getMostMovableLeft(nowX, nowY, rt, fld);
int maxX = pieceNow.getMostMovableRight(nowX, nowY, rt, fld);
if(movestate == 0 && (rt == bestRt)
&& ((bestX < minX - 1) || (bestX > maxX + 1) || (bestY < nowY))) {
//thinkBestPosition(engine, playerID);
thinkRequest = true;
thinkComplete = false;
//thinkCurrentPieceNo++;
//System.out.println("rethink c:" + thinkCurrentPieceNo + " l:" + thinkLastPieceNo);
if (DEBUG_ALL) log.debug("Needs rethink - cannot reach desired position");
} else {
if((nowX == bestX) && (pieceTouchGround)) {
if (rt == bestRt) {
// rotation
if(bestRtSub != 0 && movestate == 0) {
bestRt = pieceNow.getRotateDirection(bestRtSub, bestRt);
rotateDir = bestRtSub;
bestRtSub = 0;
movestate = 1;
}
}
}
if((nowX == bestX || movestate > 0) && (rt == bestRt)) {
moveDir = 0;
if(bestRtSub == 0) {
if (pieceTouchGround && engine.ruleopt.softdropLock)
drop = -1;
else if(engine.ruleopt.harddropEnable)
drop = 1;
else if(engine.ruleopt.softdropEnable || engine.ruleopt.softdropLock)
drop = -1;
} else {
if(engine.ruleopt.harddropEnable && !engine.ruleopt.harddropLock)
drop = 1;
else if(engine.ruleopt.softdropEnable && !engine.ruleopt.softdropLock)
drop = -1;
}
}
else if (nowX > bestX)
moveDir = -1;
else if(nowX < bestX)
moveDir = 1;
}
}
//Convert parameters to input
if(moveDir == -1 && !ctrl.isPress(Controller.BUTTON_LEFT))
input |= Controller.BUTTON_BIT_LEFT;
else if(moveDir == 1 && !ctrl.isPress(Controller.BUTTON_RIGHT))
input |= Controller.BUTTON_BIT_RIGHT;
if(drop == 1 && !ctrl.isPress(Controller.BUTTON_UP))
input |= Controller.BUTTON_BIT_UP;
else if(drop == -1)
input |= Controller.BUTTON_BIT_DOWN;
if (rotateDir != 0)
{
boolean defaultRotateRight = (engine.owRotateButtonDefaultRight == 1 ||
(engine.owRotateButtonDefaultRight == -1 &&
engine.ruleopt.rotateButtonDefaultRight));
if(engine.ruleopt.rotateButtonAllowDouble &&
rotateDir == 2 && !ctrl.isPress(Controller.BUTTON_E))
input |= Controller.BUTTON_BIT_E;
else if(engine.ruleopt.rotateButtonAllowReverse &&
!defaultRotateRight && (rotateDir == 1))
{
if(!ctrl.isPress(Controller.BUTTON_B))
input |= Controller.BUTTON_BIT_B;
}
else if(engine.ruleopt.rotateButtonAllowReverse &&
defaultRotateRight && (rotateDir == -1))
{
if(!ctrl.isPress(Controller.BUTTON_B))
input |= Controller.BUTTON_BIT_B;
}
else if(!ctrl.isPress(Controller.BUTTON_A))
input |= Controller.BUTTON_BIT_A;
}
if (DEBUG_ALL) log.debug ("Input = " + input + ", moveDir = " + moveDir + ", rotateDir = " + rotateDir +
", drop = " + drop);
delay = 0;
ctrl.setButtonBit(input);
}
else {
delay++;
ctrl.setButtonBit(inputARE);
}
}
protected void printPieceAndDirection(int pieceType, int rt)
{
String result = "Piece ";
switch (pieceType)
{
case Piece.PIECE_I: result = result + "I"; break;
case Piece.PIECE_L: result = result + "L"; break;
case Piece.PIECE_O: result = result + "O"; break;
case Piece.PIECE_Z: result = result + "Z"; break;
case Piece.PIECE_T: result = result + "T"; break;
case Piece.PIECE_J: result = result + "J"; break;
case Piece.PIECE_S: result = result + "S"; break;
case Piece.PIECE_I1: result = result + "I1"; break;
case Piece.PIECE_I2: result = result + "I2"; break;
case Piece.PIECE_I3: result = result + "I3"; break;
case Piece.PIECE_L3: result = result + "L3"; break;
}
result = result + ", direction ";
switch (rt)
{
case Piece.DIRECTION_LEFT: result = result + "left"; break;
case Piece.DIRECTION_DOWN: result = result + "down"; break;
case Piece.DIRECTION_UP: result = result + "up"; break;
case Piece.DIRECTION_RIGHT: result = result + "right"; break;
}
if (DEBUG_ALL) log.debug(result);
}
/*
public int calcIRS(Piece piece, GameEngine engine)
{
piece = checkOffset(piece, engine);
int nextType = piece.id;
Field fld = engine.field;
int spawnX = engine.getSpawnPosX(fld, piece);
SpeedParam speed = engine.speed;
boolean gravityHigh = speed.gravity > speed.denominator;
int width = fld.getWidth();
int midColumnX = (width/2)-1;
if(Math.abs(spawnX - bestX) == 1)
{
if (bestRt == 1)
{
if (engine.ruleopt.rotateButtonDefaultRight)
return Controller.BUTTON_BIT_A;
else
return Controller.BUTTON_BIT_B;
}
else if (bestRt == 3)
{
if (engine.ruleopt.rotateButtonDefaultRight)
return Controller.BUTTON_BIT_B;
else
return Controller.BUTTON_BIT_A;
}
}
else if (nextType == Piece.PIECE_L)
{
if (gravityHigh && fld.getHighestBlockY(midColumnX-1) <
Math.min(fld.getHighestBlockY(midColumnX), fld.getHighestBlockY(midColumnX+1)))
return 0;
else if (engine.ruleopt.rotateButtonDefaultRight)
return Controller.BUTTON_BIT_B;
else
return Controller.BUTTON_BIT_A;
}
else if (nextType == Piece.PIECE_J)
{
if (gravityHigh && fld.getHighestBlockY(midColumnX+1) <
Math.min(fld.getHighestBlockY(midColumnX), fld.getHighestBlockY(midColumnX-1)))
return 0;
if (engine.ruleopt.rotateButtonDefaultRight)
return Controller.BUTTON_BIT_A;
else
return Controller.BUTTON_BIT_B;
}
//else if (nextType == Piece.PIECE_I)
// return Controller.BUTTON_BIT_A;
return 0;
}
*/
/**
* Search for the best choice
* @param engine The GameEngine that owns this AI
* @param playerID Player ID
*/
public void thinkBestPosition(GameEngine engine, int playerID) {
if (DEBUG_ALL) log.debug("thinkBestPosition called, inARE = " + inARE + ", piece: ");
bestHold = false;
bestX = 0;
bestY = 0;
bestRt = 0;
bestRtSub = 0;
bestPts = Integer.MIN_VALUE;
thinkSuccess = false;
Field fld;
if (engine.field == null)
fld = new Field(engine.fieldWidth, engine.fieldHeight,
engine.fieldHiddenHeight, engine.ruleopt.fieldCeiling);
else
fld = new Field(engine.field);
Piece pieceNow = engine.nowPieceObject;
Piece pieceHold = engine.holdPieceObject;
boolean holdBoxEmpty = (pieceHold == null);
int nextIndex = engine.nextPieceCount;
if (inARE || pieceNow == null)
{
pieceNow = engine.getNextObjectCopy(nextIndex);
nextIndex++;
}
if(holdBoxEmpty)
pieceHold = engine.getNextObjectCopy(nextIndex);
else if (holdBoxEmpty)
pieceHold = engine.getNextObjectCopy(engine.nextPieceCount);
pieceNow = checkOffset(pieceNow, engine);
pieceHold = checkOffset(pieceHold, engine);
boolean holdOK = engine.isHoldOK();
nextQueueIDs = new int[MAX_THINK_DEPTH-1];
for (int i = 0; i < nextQueueIDs.length; i++)
nextQueueIDs[i] = engine.getNextID(nextIndex+i);
int state = fieldToIndex(fld);
if (state < 0)
{
thinkLastPieceNo++;
return;
}
Transition t = moves[state][pieceNow.id];
while (t != null)
{
int holdID = -1;
if (engine.holdPieceObject != null)
holdID = engine.holdPieceObject.id;
int pts = thinkMain(engine, t.newField, holdID, 0);
if (pts > bestPts)
{
bestPts = pts;
bestX = t.x + 3;
bestRt = t.rt;
bestY = pieceNow.getBottom(bestX, 0, bestRt, fld);
bestRtSub = t.rtSub;
bestHold = false;
thinkSuccess = true;
}
t = t.next;
}
if (pieceHold.id != pieceNow.id && holdOK)
{
t = moves[state][pieceHold.id];
while (t != null)
{
int pts = thinkMain(engine, t.newField, pieceNow.id, holdBoxEmpty ? 1 : 0);
if (pts > bestPts)
{
bestPts = pts;
bestX = t.x + 3;
bestRt = t.rt;
bestY = pieceNow.getBottom(bestX, 0, bestRt, fld);
bestRtSub = t.rtSub;
bestHold = true;
thinkSuccess = true;
}
t = t.next;
}
}
thinkLastPieceNo++;
//System.out.println("X:" + bestX + " Y:" + bestY + " R:" + bestRt + " H:" + bestHold + " Pts:" + bestPts);
}
/**
* Think routine
* @param engine GameEngine
* @param state Think state
* @param holdID Hold piece ID
* @param depth Search depth
* @return Evaluation score
*/
public int thinkMain(GameEngine engine, int state, int holdID, int depth) {
if (state == -1)
return 0;
if (depth == nextQueueIDs.length)
{
int result = scores[state]*10;
if (holdID == Piece.PIECE_I)
result += 1000;
else if (holdID == Piece.PIECE_T)
result += 3;
else if (holdID == Piece.PIECE_L || holdID == Piece.PIECE_J)
result++;
return result;
}
int bestPts = 0;
Transition t = moves[state][nextQueueIDs[depth]];
while (t != null)
{
bestPts = Math.max(bestPts,
thinkMain(engine, t.newField, holdID, depth+1) + 1000);
t = t.next;
}
if (engine.ruleopt.holdEnable)
{
if (holdID == -1)
bestPts = Math.max(bestPts, thinkMain(engine, state, nextQueueIDs[depth], depth+1));
else
{
t = moves[state][holdID];
while (t != null)
{
bestPts = Math.max(bestPts,
thinkMain(engine, t.newField, nextQueueIDs[depth], depth+1) + 1000);
t = t.next;
}
}
}
return bestPts;
}
public static Piece checkOffset(Piece p, GameEngine engine)
{
Piece result = new Piece(p);
result.big = engine.big;
if (!p.offsetApplied)
result.applyOffsetArray(engine.ruleopt.pieceOffsetX[p.id], engine.ruleopt.pieceOffsetY[p.id]);
return result;
}
public void run() {
log.info("ComboRaceBot: Thread start");
threadRunning = true;
while(threadRunning) {
if(thinkRequest) {
thinkRequest = false;
thinking = true;
try {
thinkBestPosition(gEngine, gEngine.playerID);
thinkComplete = true;
log.debug("ComboRaceBot: thinkBestPosition completed successfully");
} catch (Throwable e) {
log.debug("ComboRaceBot: thinkBestPosition Failed", e);
}
thinking = false;
}
else if (createTablesRequest)
createTables(gEngine);
if(thinkDelay > 0) {
try {
Thread.sleep(thinkDelay);
} catch (InterruptedException e) {
break;
}
}
}
threadRunning = false;
log.info("ComboRaceBot: Thread end");
}
/**
* Constructs the moves table if necessary.
*/
public void createTables (GameEngine engine)
{
if (moves != null)
return;
moves = new Transition[FIELDS.length][7];
Field fldEmpty = new Field(4, Field.DEFAULT_HEIGHT, Field.DEFAULT_HIDDEN_HEIGHT);
Field fldBackup = new Field(fldEmpty);
Field fldTemp = new Field(fldEmpty);
Piece[] pieces = new Piece[7];
for (int p = 0; p < 7; p++)
{
pieces[p] = checkOffset(new Piece(p), engine);
pieces[p].setColor(1);
}
int count = 0;
for (int i = 0; i < FIELDS.length; i++)
{
fldBackup.copy(fldEmpty);
int code = FIELDS[i];
for (int y = Field.DEFAULT_HEIGHT-1; y > Field.DEFAULT_HEIGHT-4; y
for (int x = 3; x >= 0; x
{
if ((code & 1) == 1)
fldBackup.setBlockColor(x, y, 1);
code >>= 1;
}
for (int p = 0; p < 7; p++)
{
int tempX = engine.getSpawnPosX(fldBackup, pieces[p]);
for (int rt = 0; rt < Piece.DIRECTION_COUNT; rt++)
{
int minX = pieces[p].getMostMovableLeft(tempX, 0, rt, fldBackup);
int maxX = pieces[p].getMostMovableRight(tempX, 0, rt, fldBackup);
for (int x = minX; x <= maxX; x++)
{
int y = pieces[p].getBottom(x, 0, rt, fldBackup);
if (p == Piece.PIECE_L || p == Piece.PIECE_T || p == Piece.PIECE_J || rt < 2)
{
fldTemp.copy(fldBackup);
pieces[p].placeToField(x, y, rt, fldTemp);
if (fldTemp.checkLine() == 1)
{
fldTemp.clearLine();
fldTemp.downFloatingBlocks();
int index = fieldToIndex(fldTemp, 0);
if (index >= 0)
{
moves[i][p] = new Transition(x, rt, index, moves[i][p]);
count++;
}
}
if (p == Piece.PIECE_O)
continue;
}
// Left rotation
if(!engine.ruleopt.rotateButtonDefaultRight || engine.ruleopt.rotateButtonAllowReverse) {
int rot = pieces[p].getRotateDirection(-1, rt);
int newX = x;
int newY = y;
fldTemp.copy(fldBackup);
if(pieces[p].checkCollision(x, y, rot, fldTemp) && (engine.wallkick != null) &&
(engine.ruleopt.rotateWallkick)) {
WallkickResult kick = engine.wallkick.executeWallkick(x, y, -1, rt, rot,
(engine.ruleopt.rotateMaxUpwardWallkick != 0), pieces[p], fldTemp, null);
if(kick != null) {
newX = x + kick.offsetX;
newY = pieces[p].getBottom(newX, y + kick.offsetY, rot, fldTemp);
}
}
if (!pieces[p].checkCollision(newX, newY, rot, fldTemp)
&& newY > pieces[p].getBottom(newX, 0, rot, fldTemp))
{
pieces[p].placeToField(newX, newY, rot, fldTemp);
if (fldTemp.checkLine() == 1)
{
fldTemp.clearLine();
fldTemp.downFloatingBlocks();
int index = fieldToIndex(fldTemp, 0);
if (index >= 0)
{
moves[i][p] = new Transition(x, rt, -1, index, moves[i][p]);
count++;
}
}
}
}
// Right rotation
if(engine.ruleopt.rotateButtonDefaultRight || engine.ruleopt.rotateButtonAllowReverse) {
int rot = pieces[p].getRotateDirection(1, rt);
int newX = x;
int newY = y;
fldTemp.copy(fldBackup);
if(pieces[p].checkCollision(x, y, rot, fldTemp) && (engine.wallkick != null) &&
(engine.ruleopt.rotateWallkick)) {
WallkickResult kick = engine.wallkick.executeWallkick(x, y, 1, rt, rot,
(engine.ruleopt.rotateMaxUpwardWallkick != 0), pieces[p], fldTemp, null);
if(kick != null) {
newX = x + kick.offsetX;
newY = pieces[p].getBottom(newX, y + kick.offsetY, rot, fldTemp);
}
}
if (!pieces[p].checkCollision(newX, newY, rot, fldTemp)
&& newY > pieces[p].getBottom(newX, 0, rot, fldTemp))
{
pieces[p].placeToField(newX, newY, rot, fldTemp);
if (fldTemp.checkLine() == 1)
{
fldTemp.clearLine();
fldTemp.downFloatingBlocks();
int index = fieldToIndex(fldTemp, 0);
if (index >= 0)
{
moves[i][p] = new Transition(x, rt, 1, index, moves[i][p]);
count++;
}
}
}
}
}
if (pieces[p].id == Piece.PIECE_O)
break;
}
}
}
log.debug("Transition table created. Total entries: " + count);
//TODO: PageRank scores for each state
}
/**
* Converts field to field state int code
* @param field Field object
* @param valleyX Leftmost x-coordinate of 4-block-wide valley to combo in
* @return Field state int code.
*/
public static int fieldToCode(Field field, int valleyX)
{
int height = field.getHeight();
int result = 0;
for (int y = height-3; y < height; y++)
for (int x = 0; x < 4; x++)
{
result <<= 1;
if (!field.getBlockEmptyF(x+valleyX, y))
result++;
}
return result;
}
public static int fieldToCode(Field field)
{
return fieldToCode(field, 3);
}
/**
* Converts field state int code to FIELDS array index
* @param field Field state int code
* @return State index if found; -1 if not found.
*/
public static int fieldToIndex(int field)
{
int min = 0;
int max = FIELDS.length-1;
int mid;
while (min <= max)
{
mid = (min+max) >> 1;
if (FIELDS[mid] > field)
max = mid-1;
else if (FIELDS[mid] < field)
min = mid+1;
else
return mid;
}
return -1;
}
/**
* Converts field object to FIELDS array index
* @param field Field object
* @param valleyX Leftmost x-coordinate of 4-block-wide valley to combo in
* @return State index if found; -1 if not found.
*/
public static int fieldToIndex(Field field, int valleyX)
{
return fieldToIndex(fieldToCode(field, valleyX));
}
public static int fieldToIndex(Field field)
{
return fieldToIndex(fieldToCode(field));
}
protected static class Transition
{
public int x, rt, rtSub, newField;
public Transition next;
public Transition (int bestX, int bestRt, int bestRtSub, int newFld)
{
x = bestX;
rt = bestRt;
rtSub = bestRtSub;
newField = newFld;
}
public Transition (int bestX, int bestRt, int newFld)
{
x = bestX;
rt = bestRt;
rtSub = 0;
newField = newFld;
}
public Transition (int bestX, int bestRt, int bestRtSub, int newFld, Transition nxt)
{
x = bestX;
rt = bestRt;
rtSub = bestRtSub;
newField = newFld;
next = nxt;
}
public Transition (int bestX, int bestRt, int newFld, Transition nxt)
{
x = bestX;
rt = bestRt;
rtSub = 0;
newField = newFld;
next = nxt;
}
}
}
|
package org.jetel.connection.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.connection.jdbc.driver.JdbcDriver;
import org.jetel.connection.jdbc.driver.JdbcDriverDescription;
import org.jetel.connection.jdbc.driver.JdbcDriverFactory;
import org.jetel.connection.jdbc.specific.DBConnectionInstance;
import org.jetel.connection.jdbc.specific.JdbcSpecific;
import org.jetel.connection.jdbc.specific.JdbcSpecificDescription;
import org.jetel.connection.jdbc.specific.JdbcSpecificFactory;
import org.jetel.connection.jdbc.specific.JdbcSpecific.OperationType;
import org.jetel.connection.jdbc.specific.impl.DefaultJdbcSpecific;
import org.jetel.data.Defaults;
import org.jetel.database.IConnection;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.JetelException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.GraphElement;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.crypto.Enigma;
import org.jetel.util.file.FileUtils;
import org.jetel.util.primitive.TypedProperties;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
public class DBConnection extends GraphElement implements IConnection {
private static final Log logger = LogFactory.getLog(DBConnection.class);
public final static String SQL_QUERY_PROPERTY = "sqlQuery";
public final static String XML_JDBC_SPECIFIC_ATTRIBUTE = "jdbcSpecific";
public final static String XML_DRIVER_LIBRARY_ATTRIBUTE = "driverLibrary";
public static final String XML_JNDI_NAME_ATTRIBUTE = "jndiName";
public static final String XML_DBURL_ATTRIBUTE = "dbURL";
public static final String XML_DBDRIVER_ATTRIBUTE = "dbDriver";
public static final String XML_DBCONFIG_ATTRIBUTE = "dbConfig";
public static final String XML_DATABASE_ATTRIBUTE = "database"; // database type - used to lookup in build-in JDBC drivers
public static final String XML_PASSWORD_ATTRIBUTE = "password";
public static final String XML_USER_ATTRIBUTE = "user";
public static final String XML_THREAD_SAFE_CONNECTIONS="threadSafeConnection";
public static final String XML_IS_PASSWORD_ENCRYPTED = "passwordEncrypted";
public static final String XML_HOLDABILITY = "holdability";
public static final String XML_TRANSACTION_ISOLATION = "transactionIsolation";
public static final String XML_JDBC_PROPERTIES_PREFIX = "jdbc.";
public static final String EMBEDDED_UNLOCK_CLASS = "com.ddtek.jdbc.extensions.ExtEmbeddedConnection";
private final static String[] TRANSACTION_ISOLATION = {"TRANSACTION_NONE", "READ_UNCOMMITTED", "READ_COMMITTED",
"REPEATABLE_READ", "SERIALIZABLE"
};
private static final String[] HOLDABILITY = {"HOLD_CURSORS", "CLOSE_CURSORS"};
// not yet used by component
public static final String XML_NAME_ATTRIBUTE = "name";
private String configFileName;
private String dbUrl;
private boolean threadSafeConnections;
private boolean isPasswordEncrypted;
private String jndiName;
private String database;
private String dbDriver;
private String user;
private String password;
private String driverLibrary;
private String jdbcSpecificId;
private Integer holdability;
private Integer transactionIsolation;
// properties specific to the JDBC connection (not used by Clover)
private TypedProperties jdbcProperties;
private Map<CacheKey, DBConnectionInstance> connectionsCache = new HashMap<CacheKey, DBConnectionInstance>();
private DBConnectionInstance connectionInstance; //this variable is used in case threadSafe = false
private JdbcDriver jdbcDriver;
private JdbcSpecific jdbcSpecific;
private URL[] driverLibraryURLs;
/**
* Constructor for the DBConnection object.
*
* @param configFilename properties filename containing definition of driver, dbURL, username, password
*/
public DBConnection(String id, String configFilename) {
super(id);
this.configFileName = configFilename;
}
/**
* Constructor.
* @param id
* @param properties
*/
public DBConnection(String id, Properties properties) {
super(id);
fromProperties(properties);
}
/**
* Iterates over the given properties and finds which are the standard DBConnection properties
* and which are the JDBC connection properties.
*
* @param configProperties
*/
private void fromProperties(Properties properties) {
TypedProperties typedProperties = new TypedProperties(properties, getGraph());
setUser(typedProperties.getStringProperty(XML_USER_ATTRIBUTE, null));
setPassword(typedProperties.getStringProperty(XML_PASSWORD_ATTRIBUTE, null));
setDbUrl(typedProperties.getStringProperty(XML_DBURL_ATTRIBUTE, null));
setDbDriver(typedProperties.getStringProperty(XML_DBDRIVER_ATTRIBUTE, null));
setDatabase(typedProperties.getStringProperty(XML_DATABASE_ATTRIBUTE, null));
setDriverLibrary(typedProperties.getStringProperty(XML_DRIVER_LIBRARY_ATTRIBUTE, null));
setJdbcSpecificId(typedProperties.getStringProperty(XML_JDBC_SPECIFIC_ATTRIBUTE, null));
setJndiName(typedProperties.getStringProperty(XML_JNDI_NAME_ATTRIBUTE, null));
setThreadSafeConnections(typedProperties.getBooleanProperty(XML_THREAD_SAFE_CONNECTIONS, true));
setPasswordEncrypted(typedProperties.getBooleanProperty(XML_IS_PASSWORD_ENCRYPTED, false));
try {
setHoldability(typedProperties.getIntProperty(XML_HOLDABILITY));
} catch (NumberFormatException e) {
int index = StringUtils.findString(typedProperties.getStringProperty(XML_HOLDABILITY), HOLDABILITY);
if (index != -1) {
setHoldability(index + 1);
}else {
logger.warn("Unknown holdability");
}
}
try {
setTransactionIsolation(typedProperties.getIntProperty(XML_TRANSACTION_ISOLATION));
} catch (Exception e) {
int index = StringUtils.findString(typedProperties.getStringProperty(XML_HOLDABILITY), TRANSACTION_ISOLATION);
if (index != -1) {
setTransactionIsolation(index > 0 ? 2 ^ (index - 1) : 0);
}else {
logger.warn("Unknown transaction isolation");
}
}
jdbcProperties = typedProperties.getPropertiesStartWith(XML_JDBC_PROPERTIES_PREFIX);
}
/**
* Prepares properties needed to establish connection.
* Resulted properties collection contains all extra properties
* (properties with prefix 'jdbc.') and user name and password.
* @return
*/
public Properties createConnectionProperties() {
Properties ret = new Properties();
ret.putAll(getExtraProperties());
ret.setProperty(XML_USER_ATTRIBUTE, getUser());
ret.setProperty(XML_PASSWORD_ATTRIBUTE, getPassword());
return ret;
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#init()
*/
synchronized public void init() throws ComponentNotReadyException {
if(isInitialized()) return;
super.init();
if(!StringUtils.isEmpty(configFileName)) {
try {
URL projectURL = getGraph() != null ? getGraph().getProjectURL() : null;
InputStream stream = FileUtils.getFileURL(projectURL, configFileName).openStream();
Properties tempProperties = new Properties();
tempProperties.load(stream);
fromProperties(tempProperties);
stream.close();
} catch (Exception ex) {
throw new ComponentNotReadyException(ex);
}
}
prepareDriverLibraryURLs();
prepareJdbcSpecific();
prepareJdbcDriver();
//check validity of the given url
// but only for jdbc connection
try {
if (StringUtils.isEmpty(getJndiName())) {
if (!getJdbcDriver().getDriver().acceptsURL(getDbUrl())) {
throw new ComponentNotReadyException("Unacceptable connection url: '" + getDbUrl() + "'");
}
}
} catch (SQLException e) {
throw new ComponentNotReadyException(e);
}
//decrypt password
decryptPassword();
}
private void prepareJdbcDriver() throws ComponentNotReadyException {
if(!StringUtils.isEmpty(getJndiName())) {
return;
}
if(!StringUtils.isEmpty(getDatabase())) {
//database connection is parameterized by DB identifier to the list of build-in JDBC drivers
String database = getDatabase();
JdbcDriverDescription jdbcDriverDescription = JdbcDriverFactory.getJdbcDriverDescriptor(database);
if(jdbcDriverDescription == null) {
throw new ComponentNotReadyException("Can not create JDBC driver '" + database + "'. This type of JDBC driver is not supported.");
}
jdbcDriver = jdbcDriverDescription.createJdbcDriver();
} else {
//database connection is full specified by dbDriver and driverLibrary attributes
jdbcDriver = new JdbcDriver(null, getDbDriver(), getDbDriver(), getDriverLibraryURLs(), getJdbcSpecific(), null);
}
}
/**
* @param elementId
* @return
* @throws JetelException
*/
public synchronized DBConnectionInstance getConnection(String elementId) throws JetelException {
return getConnection(elementId, OperationType.UNKNOWN);
}
/**
* Returns connection instance for the given elementId and operation type. If this db connection
* is threads safe, all connection are cached, and elementId and operation type
* servers as key to hash map.
* This is main method for using DBConnection class. Each graph element can claim its respective db connection.
* @param elementId
* @param operationType
* @return
* @throws JetelException
*/
public synchronized DBConnectionInstance getConnection(String elementId, OperationType operationType) throws JetelException {
DBConnectionInstance connection = null;
if (isThreadSafeConnections()) {
CacheKey key = new CacheKey(elementId, operationType);
connection = (DBConnectionInstance) connectionsCache.get(key);
if (connection == null) {
connection = new DBConnectionInstance(this, connect(operationType), operationType);
connectionsCache.put(key, connection);
}
} else {
if (connectionInstance == null) {
connectionInstance = new DBConnectionInstance(this, connect(operationType), operationType);
}
connection = connectionInstance;
}
return connection;
}
private Connection connect(OperationType operationType) throws JetelException {
if (!StringUtils.isEmpty(getJndiName())) {
try {
Context initContext = new InitialContext();
DataSource ds = (DataSource)initContext.lookup(getJndiName());
return ds.getConnection();
} catch (Exception e) {
throw new JetelException("Cannot establish DB connection to JNDI:" + getJndiName() + " " + e.getMessage(), e);
}
} else {
try {
return getJdbcSpecific().createSQLConnection(this, operationType);
} catch (JetelException e) {
throw new JetelException("Cannot establish DB connection (" + getId() + ").", e);
}
}
}
/**
* Commits and closes all allocated connections.
*
* @see org.jetel.graph.GraphElement#free()
*/
synchronized public void free() {
if (!isInitialized()) return;
super.free();
if (threadSafeConnections) {
for (DBConnectionInstance connectionInstance : connectionsCache.values()) {
Connection connection = connectionInstance.getSqlConnection();
closeConnection(connection);
}
connectionsCache.clear();
} else {
if (connectionInstance != null) {
Connection connection = connectionInstance.getSqlConnection();
closeConnection(connection);
connectionInstance = null;
}
}
jdbcDriver.free();
}
private void closeConnection(Connection connection) {
try {
if (!connection.isClosed()) {
if (!connection.getAutoCommit()) {
try {
connection.commit();
} catch (SQLException e) {
logger.warn("DBConnection '" + getId() + "' commit operation failed.");
}
}
connection.close();
}
} catch (SQLException e) {
logger.warn("DBConnection '" + getId() + "' close operation failed.");
}
}
/**
* Creates DBConnection based on xml node.
*
* @param graph
* @param nodeXML
* @return
* @throws XMLConfigurationException
*/
public static DBConnection fromXML(TransformationGraph graph, Element nodeXML) throws XMLConfigurationException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph);
try {
String id = xattribs.getString(XML_ID_ATTRIBUTE);
// do we have dbConfig parameter specified ??
if (xattribs.exists(XML_DBCONFIG_ATTRIBUTE)) {
return new DBConnection(id, xattribs.getString(XML_DBCONFIG_ATTRIBUTE));
} else {
Properties connectionProps = xattribs.attributes2Properties(new String[] {XML_ID_ATTRIBUTE});
return new DBConnection(id, connectionProps);
}
} catch (Exception e) {
throw new XMLConfigurationException("DBConnection: "
+ xattribs.getString(XML_ID_ATTRIBUTE, "unknown ID") + ":" + e.getMessage(), e);
}
}
/**
* Saves to the given output stream all DBConnection properties.
* @param outStream
* @throws IOException
*/
public void saveConfiguration(OutputStream outStream) throws IOException {
Properties propsToStore = new Properties();
TypedProperties extraProperties = getExtraProperties();
Set<Object> jdbcProps = extraProperties.keySet();
for (Object key : jdbcProps) {
String propName = (String) key;
propsToStore.setProperty(XML_JDBC_PROPERTIES_PREFIX + propName, extraProperties.getProperty(propName));
}
if(getUser() != null) {
propsToStore.setProperty(XML_USER_ATTRIBUTE, getUser());
}
if(getPassword() != null) {
propsToStore.setProperty(XML_PASSWORD_ATTRIBUTE, getPassword());
}
if(getDbUrl() != null) {
propsToStore.setProperty(XML_DBURL_ATTRIBUTE, getDbUrl());
}
if(getDbDriver() != null) {
propsToStore.setProperty(XML_DBDRIVER_ATTRIBUTE, getDbDriver());
}
if(getDatabase() != null) {
propsToStore.setProperty(XML_DATABASE_ATTRIBUTE, getDatabase());
}
if(getDriverLibrary() != null) {
propsToStore.setProperty(XML_DRIVER_LIBRARY_ATTRIBUTE, getDriverLibrary());
}
if(getJdbcSpecificId() != null) {
propsToStore.setProperty(XML_JDBC_SPECIFIC_ATTRIBUTE, getJdbcSpecificId());
}
if(getJndiName() != null) {
propsToStore.setProperty(XML_JNDI_NAME_ATTRIBUTE, getJndiName());
}
if (getHoldability() != null) {
propsToStore.setProperty(XML_HOLDABILITY, Integer.toString(getHoldability()));
}
if (getTransactionIsolation() != null) {
propsToStore.setProperty(XML_TRANSACTION_ISOLATION, Integer.toString(getTransactionIsolation()));
}
propsToStore.setProperty(XML_THREAD_SAFE_CONNECTIONS, Boolean.toString(isThreadSafeConnections()));
propsToStore.setProperty(XML_IS_PASSWORD_ENCRYPTED, Boolean.toString(isPasswordEncrypted()));
propsToStore.store(outStream, null);
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#toString()
*/
public String toString() {
if (!isInitialized()) {
return "DBConnection id='" + getId() + "' - not initialized";
}
StringBuffer strBuf = new StringBuffer(255);
strBuf.append("DBConnection driver[").append(getJdbcDriver());
strBuf.append("]:jndi[").append(getJndiName());
strBuf.append("]:url[").append(getDbUrl());
strBuf.append("]:user[").append(getUser()).append("]");
return strBuf.toString();
}
/**
* Decrypts the password entry in the configuration properties if the
* isPasswordEncrypted property is set to "y" or "yes". If any error occurs
* and decryption fails, the original password entry will be used.
*
* @param configProperties configuration properties
* @throws ComponentNotReadyException
*/
private void decryptPassword() throws ComponentNotReadyException {
if (isPasswordEncrypted()) {
if (getGraph() == null)
return;
Enigma enigma = getGraph().getEnigma();
if (enigma == null) {
logger.error("Can't decrypt password on DBConnection (id=" + this.getId() + "). Please set the password as engine parameter -pass.");
//throw new ComponentNotReadyException(this, "Can't decrypt password on DBConnection (id=" + this.getId() + "). Please set the password as engine parameter -pass.");
return;
}
String decryptedPassword = null;
try {
decryptedPassword = enigma.decrypt(getPassword());
} catch (JetelException e) {
logger.error("Can't decrypt password on DBConnection (id=" + this.getId() + "). Incorrect password.");
//throw new ComponentNotReadyException(this, "Can't decrypt password on DBConnection (id=" + this.getId() + "). Please set the password as engine parameter -pass.", e);
}
// If password decryption returns failure, try with the password
// as it is.
if (decryptedPassword != null) {
setPassword(decryptedPassword);
}
}
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#checkConfig()
*/
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
//TODO
return status;
}
/* (non-Javadoc)
* @see org.jetel.database.IConnection#createMetadata(java.util.Properties)
*/
public DataRecordMetadata createMetadata(Properties parameters) throws SQLException {
if (!isInitialized()) {
throw new IllegalStateException("DBConnection has to be initialized to be able to create metadata.");
}
Statement statement;
ResultSet resultSet;
String sqlQuery = parameters.getProperty(SQL_QUERY_PROPERTY);
if(StringUtils.isEmpty(sqlQuery)) {
throw new IllegalArgumentException("JDBC stub for clover metadata can't find sqlQuery parameter.");
}
Connection connection;
try {
connection = connect(OperationType.UNKNOWN);
} catch (JetelException e) {
throw new SQLException(e.getMessage());
}
statement = connection.createStatement();
resultSet = statement.executeQuery(sqlQuery);
return SQLUtil.dbMetadata2jetel(resultSet.getMetaData(), getJdbcSpecific());
}
public boolean isThreadSafeConnections() {
return threadSafeConnections;
}
protected void setThreadSafeConnections(boolean threadSafeConnections) {
this.threadSafeConnections = threadSafeConnections;
}
public boolean isPasswordEncrypted() {
return isPasswordEncrypted;
}
protected void setPasswordEncrypted(boolean isPasswordEncrypted) {
this.isPasswordEncrypted = isPasswordEncrypted;
}
public String getJndiName() {
return jndiName;
}
protected void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
public JdbcDriver getJdbcDriver() {
return jdbcDriver;
}
protected void setJdbcDriver(JdbcDriver jdbcDriver) {
this.jdbcDriver = jdbcDriver;
}
public String getDbUrl() {
return dbUrl;
}
protected void setDbUrl(String dbUrl) {
this.dbUrl = dbUrl;
}
public String getUser() {
return user;
}
protected void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
protected void setPassword(String password) {
this.password = password;
}
public String getDatabase() {
return database;
}
protected void setDatabase(String database) {
this.database = database;
}
public String getDbDriver() {
return dbDriver;
}
protected void setDbDriver(String dbDriver) {
this.dbDriver = dbDriver;
}
public String getDriverLibrary() {
return driverLibrary;
}
private void prepareDriverLibraryURLs() throws ComponentNotReadyException {
if(!StringUtils.isEmpty(driverLibrary)) {
String[] libraryPaths = driverLibrary.split(Defaults.DEFAULT_PATH_SEPARATOR_REGEX);
driverLibraryURLs = new URL[libraryPaths.length];
for(int i = 0; i < libraryPaths.length; i++) {
try {
driverLibraryURLs[i] = FileUtils.getFileURL(getGraph() != null ? getGraph().getProjectURL() : null, libraryPaths[i]);
} catch (MalformedURLException ex1) {
throw new ComponentNotReadyException("Can not create JDBC connection '" + getId() + "'. Malformed URL: " + ex1.getMessage(), ex1);
}
}
}
}
private URL[] getDriverLibraryURLs() {
return driverLibraryURLs;
}
protected void setDriverLibrary(String driverLibrary) {
this.driverLibrary = driverLibrary;
}
public String getJdbcSpecificId() {
return jdbcSpecificId;
}
protected void setJdbcSpecificId(String jdbcSpecificId) {
this.jdbcSpecificId = jdbcSpecificId;
}
private void prepareJdbcSpecific() throws ComponentNotReadyException {
if(!StringUtils.isEmpty(getJdbcSpecificId())) {
JdbcSpecificDescription jdbcSpecificDescription = JdbcSpecificFactory.getJdbcSpecificDescription(getJdbcSpecificId());
if(jdbcSpecificDescription != null) {
jdbcSpecific = jdbcSpecificDescription.getJdbcSpecific();
} else {
throw new ComponentNotReadyException("JDBC specific '" + getJdbcSpecificId() + "' does not exist.");
}
}
}
public JdbcSpecific getJdbcSpecific() {
if(jdbcSpecific != null) {
return jdbcSpecific;
} else {
JdbcDriver jdbcDriver = getJdbcDriver();
if(jdbcDriver != null) {
JdbcSpecific ret = getJdbcDriver().getJdbcSpecific();
if (ret != null) {
return ret;
}
}
return DefaultJdbcSpecific.getInstance();
}
}
public TypedProperties getExtraProperties() {
return jdbcProperties;
}
/**
* This class is used as a key value to the connectionsCache map.
*/
private static class CacheKey {
private String elementId;
private OperationType operationType;
private int hashCode;
public CacheKey(String elementId, OperationType operationType) {
this.elementId = elementId;
this.operationType = operationType;
}
public String getElementId() {
return elementId;
}
public OperationType getOperationType() {
return operationType;
}
@Override
public boolean equals(Object obj) {
if(super.equals(obj)) {
return true;
}
if(!(obj instanceof CacheKey)) {
return false;
}
CacheKey key = (CacheKey) obj;
return elementId.equals(key.elementId) && operationType == key.operationType;
}
@Override
public int hashCode() {
if(hashCode == 0) {
hashCode = (23 + elementId.hashCode()) * 37 + operationType.hashCode();
}
return hashCode;
}
}
/**
* @return the holdability
*/
public Integer getHoldability() {
return holdability;
}
/**
* @param holdability the holdability to set
*/
public void setHoldability(Integer holdability) {
this.holdability = holdability;
}
/**
* @return the transactionIsolation
*/
public Integer getTransactionIsolation() {
return transactionIsolation;
}
/**
* @param transactionIsolation the transactionIsolation to set
*/
public void setTransactionIsolation(Integer transactionIsolation) {
this.transactionIsolation = transactionIsolation;
}
}
|
package fi.hu.cs.titokone;
import fi.hu.cs.ttk91.TTK91CompileException;
import java.util.HashMap;
import java.util.Vector;
/** This class knows everything about the relation between symbolic
code and binary code. It can transform a full source to binary or
one symbolic command to binary or vice versa. Empty out all compiler
commands and empty lines at the start
of round 2.*/
public class Compiler {
/** This field contains the source code as a String array. */
private String[] source;
/** This field holds the declared variables, labels and other
symbols. It acts as a pointer to the symbolTable Vector where
the actual data is stored. */
private HashMap symbols;
/** This field holds the invalid values to be introduced
(i.e. already used labels can't be re-used. */
private HashMap invalidLabels;
/** This field tells the next line to be checked. */
private int nextLine;
/** This field holds all the valid symbols on a label. */
private final String VALIDLABELCHARS = "0123456789abcdefghijklmnopqrstuvwxyz_";
private final int NOTVALID = -1;
private final int EMPTY = -1;
/** Maximum value of the address part. */
private final int MAXINT = 32767;
/** Minimum value of the address part. */
private final int MININT = -32767;
/** This field holds the value of Stdin if it was set with DEF command. */
private String defStdin;
/** This field holds the value of Stdout if it was set with DEF command. */
private String defStdout;
/** This field keeps track of whether we are in the first round of
compilation or the second. It is set by compile() and updated
by compileLine(). */
private boolean firstRound;
/** This field counts the number of actual command lines found
during the first round. */
private int commandLineCount;
/** This array contains the code. During the first round this
field holds the clean version of the code (stripped of
compiler commands like def, ds, dc etc.)
*/
private Vector code;
/** This field acts as a symboltable, it is a String array vector
where 1:st position holds the name of the symbol and the
second either it's value (label, equ) or the command (ds 10,
dc 10) */
private Vector symbolTable;
/** This array contains the data. */
private String[] data;
// Second Round
/** This field holds the Memoryline objects for the code. These
are passed to the Application constructor at the end of the
compile process, and are gathered during the second round from
first round commands in code-array
*/
private MemoryLine[] codeMemoryLines;
/** This field holds the Memoryline objects for the data
area. Much like the code part, this is gathered during the
second round and passed to the Application when
getApplication() method is called.
*/
private MemoryLine[] dataMemoryLines;
/** This value tells if all the lines are processed twice and
getApplication can be run.
*/
private boolean compileFinished;
/** This field contains the CompileDebugger instance to inform of
any compilation happenings. */
private CompileDebugger compileDebugger;
/** This field contains the SymbolicInterpreter instance to use as
part of the compilation.
*/
private SymbolicInterpreter symbolicInterpreter;
/** This constructor sets up the class. It also initializes an
instance of CompileDebugger. */
public Compiler() {
compileDebugger = new CompileDebugger();
symbolicInterpreter = new SymbolicInterpreter();
}
/** This function initializes transforms a symbolic source code into an
application class. After this, call compileLine() to actually compile
the application one line at a time, and finally getApplication() to get
the finished application.
@param source The symbolic source code to be compiled. */
public void compile(String source) {
firstRound = true;
compileFinished = false;
while (source.indexOf("\r\n") != -1) {
source = source.substring(0, source.indexOf("\r\n")) + source.substring(source.indexOf("\r\n") + 1);
}
this.source = source.split("[\n\r\f\u0085\u2028\u2029]");
// antti: removed + from the split and added the while loop (21.04.2004)
nextLine = 0;
defStdin = "";
defStdout = "";
code = new Vector();
symbols = new HashMap();
symbolTable = new Vector();
invalidLabels = new HashMap();
invalidLabels.put("crt", new Integer(0));
invalidLabels.put("kbd", new Integer(1));
invalidLabels.put("stdin", new Integer(6));
invalidLabels.put("stdout", new Integer(7));
invalidLabels.put("halt", new Integer(11));
invalidLabels.put("read", new Integer(12));
invalidLabels.put("write", new Integer(13));
invalidLabels.put("time", new Integer(14));
invalidLabels.put("date", new Integer(15));
}
/** This function goes through one line of the code. On the first
round, it gathers the symbols and their definitions to a
symbol table and conducts syntax-checking, on the second round
it transforms each command to its binary format. For the
transformations, the CompileConstants class is used. It calls
the private methods firstRoundProcess() and
secondRoundProcess() to do the actual work, if there is any to
do. The transfer from first round of compilation to the
second is done automatically; during it,
initializeSecondRound() is called.
@return A CompileInfo debug information object, describing
what happened during the compilation of this line and whether
this is the first or second round of compilation or null if
there are no more lines left to process.
@throws TTK91CompileException If a) there is a syntax error
during the first round of checking (error code 101) or b) a
symbol is still undefined after the first round of compilation
is finished. */
public CompileInfo compileLine() throws TTK91CompileException {
CompileInfo info;
if (firstRound) {
if (nextLine == source.length) {
compileDebugger.firstPhase();
info = initializeSecondRound();
return info;
} else {
compileDebugger.firstPhase(nextLine, source[nextLine]);
info = firstRoundProcess(source[nextLine]);
++nextLine;
return info;
}
} else {
if (nextLine == code.size()) {
compileDebugger.finalPhase();
compileFinished = true;
return null;
} else {
compileDebugger.secondPhase(nextLine, source[nextLine]);
info = secondRoundProcess((String)code.get(nextLine));
++nextLine;
return info;
}
}
}
/** This method returns the readily-compiled application if the
compilation is complete, or null otherwise. */
public Application getApplication() throws IllegalStateException {
if (compileFinished) {
dataMemoryLines = new MemoryLine[data.length];
for (int i = 0; i < data.length; ++i) {
dataMemoryLines[i] = new MemoryLine(Integer.parseInt(data[i]), "");
}
SymbolTable st = new SymbolTable();
String[] tempSTLine;
for (int i = 0; i < symbolTable.size(); ++i) {
tempSTLine = (String[])symbolTable.get(i);
st.addSymbol(tempSTLine[0], Integer.parseInt(tempSTLine[1]));
}
if (!defStdin.equals("")) { st.addDefinition("stdin", defStdin); }
if (!defStdout.equals("")) { st.addDefinition("stdout", defStdout); }
return new Application(codeMemoryLines, dataMemoryLines, st);
} else {
throw new IllegalStateException(new Message("Compilation is not " +
"finished " +
"yet.").toString());
}
}
/** This function transforms a binary command number to a MemoryLine
containing both the binary and the symbolic command corresponding
to it.
@param binary The command to be translated as binary.
@return A MemoryLine instance containing both the information
about the symbolic command and the binary version of it. */
public MemoryLine getSymbolicAndBinary(int binary) {
BinaryInterpreter bi = new BinaryInterpreter();
return new MemoryLine(binary, bi.binaryToString(binary));
}
/** This function transforms a MemoryLine containing only the binary
command to a MemoryLine containing both the binary and the
symbolic command corresponding to it.
@param binaryOnly A MemoryLine containing the binary only of the
command to be translated as binary. If the MemoryLine contains
both, the pre-set symbolic value is ignored.
@return A MemoryLine instance containing both the information
about the symbolic command and the binary version of it. */
public MemoryLine getSymbolicAndBinary(MemoryLine binaryOnly) {
BinaryInterpreter bi = new BinaryInterpreter();
return new MemoryLine(binaryOnly.getBinary(),
bi.binaryToString(binaryOnly.getBinary()));
}
/** This function gathers new symbol information from the given line
and checks its syntax. If a data reservation is detected, the
dataAreaSize is incremented accordingly. If the line contains
an actual command, commandLineCount is incremented.
@param line The line of code to process.
@return A CompileInfo object describing what was done, or null if
the first round has been completed. This will be the sign for
the compiler to prepare for the second round and start it. */
private CompileInfo firstRoundProcess(String line)
throws TTK91CompileException {
String[] lineTemp = parseCompilerCommandLine(line);
boolean nothingFound = true;
String comment = "";
String[] commentParameters;
int intValue = 0;
String[] symbolTableEntry = new String[2];
boolean labelFound = false;
boolean variableUsed = false;
if (lineTemp == null) {
lineTemp = parseLine(line);
if (lineTemp == null) {
// not a valid command
comment = new Message("Invalid command.").toString();
throw new TTK91CompileException(comment);
} else {
if (lineTemp[1].equals("")) {
// line empty;
} else {
code.add(line);
if (!lineTemp[0].equals("")) {
nothingFound = false;
labelFound = true;
// label found
if (invalidLabels.containsKey(lineTemp[0])) {
// not a valid label
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
} else {
invalidLabels.put(lineTemp[0], null);
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = "" +
(code.size() - 1);
symbolTable.add(Integer.parseInt((String) symbols.get(lineTemp[0])),
symbolTableEntry);
} else {
symbols.put(lineTemp[0],
new Integer(code.size() - 1));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = "" +
(code.size() - 1);
symbolTable.add(symbolTableEntry);
}
compileDebugger.foundLabel(lineTemp[0],
code.size() -1);
}
}
try {
Integer.parseInt(lineTemp[4]);
} catch(NumberFormatException e) {
// variable used
nothingFound = false;
variableUsed = true;
compileDebugger.foundSymbol(lineTemp[4]);
if (!symbols.containsKey(lineTemp[4])) {
if (invalidLabels.get(lineTemp[4]) == null) {
symbols.put(lineTemp[4], new
Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[4];
symbolTableEntry[1] = "";
symbolTable.add(symbolTableEntry);
} else {
// reserver word was used
symbols.put(lineTemp[4],
new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[4];
symbolTableEntry[1] = "" +
(Integer) invalidLabels.get(lineTemp[4]);
symbolTable.add(symbolTableEntry);
}
}
}
if (variableUsed && labelFound) {
commentParameters = new String[2];
commentParameters[0] = lineTemp[0];
commentParameters[1] = lineTemp[4];
comment = new Message("Found label {0} and variable " +
"{1}.").toString();
compileDebugger.setComment(comment);
} else {
if (variableUsed) {
comment = new Message("Variable {0} used.",
lineTemp[4]).toString();
compileDebugger.setComment(comment);
} else {
if (labelFound) {
comment = new Message("Label {0} found.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
}
}
}
}
} else {
// compiler command
boolean allCharsValid = true;
boolean atLeastOneNonNumber = false;
if (invalidLabels.containsKey(lineTemp[0])) {
// not a valid label
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
}
if(!validLabelName(lineTemp[0])) {
// not a valid label;
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
} else {
if (invalidLabels.containsKey(lineTemp[0])) {
comment = new Message("Invalid label.").toString();
throw new TTK91CompileException(comment);
}
if (lineTemp[1].equalsIgnoreCase("ds")) {
intValue = 0;
try {
intValue = Integer.parseInt(lineTemp[2]);
} catch(NumberFormatException e) {
comment = new Message("Invalid size for a " +
"DS.").toString();
throw new TTK91CompileException(comment);
}
if (intValue < 0 || intValue > MAXINT) {
comment = new Message("Invalid size for a " +
"DS.").toString();
throw new TTK91CompileException(comment);
}
}
if (lineTemp[1].equalsIgnoreCase("dc")) {
intValue = 0;
if (lineTemp[2].trim().length() > 0) {
try {
intValue = Integer.parseInt(lineTemp[2]);
} catch(NumberFormatException e) {
comment = new Message("Invalid value for a " +
"DC.").toString();
throw new TTK91CompileException(comment);
}
if (intValue < MININT || intValue > MAXINT) {
comment = new Message("Invalid value for a " +
"DC.").toString();
throw new TTK91CompileException(comment);
}
}
}
if (lineTemp[1].equalsIgnoreCase("equ")) {
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[2];
symbolTable.add(Integer.parseInt((String) symbols.get(lineTemp[0])),
symbolTableEntry);
} else {
symbols.put(lineTemp[0], new Integer(symbolTable.size()));
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[2];
symbolTable.add(symbolTableEntry);
}
compileDebugger.foundEQU(lineTemp[0], intValue);
commentParameters = new String[2];
commentParameters[0] = lineTemp[0];
commentParameters[1] = lineTemp[2];
comment = new Message("Variable {0} defined as {1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equals("ds")) {
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.add(Integer.parseInt((String)symbols.get(lineTemp[0])),
symbolTableEntry);
} else {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.add(symbolTableEntry);
}
compileDebugger.foundDS(lineTemp[0]);
comment = new Message("Found variable {0}.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equals("dc")) {
compileDebugger.foundDC(lineTemp[0]);
if (symbols.containsKey(lineTemp[0])) {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.add(Integer.parseInt((String)symbols.get(lineTemp[0])),
symbolTableEntry);
} else {
symbolTableEntry[0] = lineTemp[0];
symbolTableEntry[1] = lineTemp[1] + " " +
lineTemp[2];
symbolTable.add(symbolTableEntry);
}
compileDebugger.foundDC(lineTemp[0]);
comment = new Message("Found variable {0}.",
lineTemp[0]).toString();
compileDebugger.setComment(comment);
}
if (lineTemp[1].equals("def")) {
if (lineTemp[0].equals("stdin") ||
lineTemp[0].equals("stdout")) {
if (lineTemp[0].equals("stdin")) {
defStdin = lineTemp[2];
} else {
defStdout = lineTemp[2];
}
compileDebugger.foundDEF(lineTemp[0], lineTemp[2]);
commentParameters = new String[2];
commentParameters[0] = lineTemp[0].toUpperCase();
commentParameters[1] = lineTemp[2];
comment = new Message("{0} defined as {1}.",
commentParameters).toString();
compileDebugger.setComment(comment);
} else {
comment = new Message("Invalid DEF " +
"operation.").toString();
throw new TTK91CompileException(comment);
}
}
}
}
return compileDebugger.lineCompiled();
}
/** This method initializes the code and data area arrays for the
second round processing according to the dataAreaSize and
commandLineCount variables. It also resets the StringTokenizer
by calling tokenize(). Before entering the second round we
must clear all the empty lines like compiler-codes
(pseudo-codes) and lines with nothing but comments.
*/
private CompileInfo initializeSecondRound() {
nextLine = 0;
firstRound = false;
// copy the code.
String[] newCode = new String[code.size()];
for (int i= 0; i < newCode.length; ++i)
newCode[i] = (String)code.get(i);
String[] lineTemp;
int dataAreaSize = 0;
// calculate the size of data-area
for (int i = 0; i < symbolTable.size(); ++i) {
lineTemp = (String[])symbolTable.get(i);
if (lineTemp[1].trim().length() > 3) {
if (lineTemp[1].substring(0,2).equalsIgnoreCase("ds")) {
dataAreaSize += Integer.parseInt(lineTemp[1].substring(3));
} else {
if (lineTemp[1].substring(0,2).equalsIgnoreCase("dc"))
++dataAreaSize;
}
}
}
if (!defStdin.equals("")) ++dataAreaSize;
if (!defStdout.equals("")) ++dataAreaSize;
String[] data = new String[dataAreaSize];
String[] newSymbolTableLine = new String[2];
newSymbolTableLine[0] = "";
newSymbolTableLine[1] = "";
int nextPosition = 0;
int nextMemorySlot = newCode.length;
int dsValue = 0;
// update variable values to symbolTable
for (int i = 0; i < symbolTable.size(); ++i) {
lineTemp = (String[])symbolTable.get(i);
if (lineTemp[1].trim().length() > 2) {
if (lineTemp[1].substring(0,2).equalsIgnoreCase("ds")) {
dsValue = Integer.parseInt(lineTemp[1].substring(3));
newSymbolTableLine[0] = lineTemp[0];
newSymbolTableLine[1] = "" + nextMemorySlot;
symbolTable.add(i, newSymbolTableLine);
++nextMemorySlot;
for (int j = nextPosition;
j < nextPosition + dsValue; ++nextPosition) {
data[j] = "" + 0;
}
} else {
if (lineTemp[1].substring(0,2).equalsIgnoreCase("dc")) {
if (lineTemp[1].length() > 3) {
data[nextPosition] = lineTemp[1].substring(3);
} else { data[nextPosition] = "" + 0; }
newSymbolTableLine[0] = lineTemp[0];
newSymbolTableLine[1] = "" + nextMemorySlot;
symbolTable.add(i, newSymbolTableLine);
++nextMemorySlot;
++nextPosition;
}
}
}
}
if (!defStdin.equals("")) {
data[nextPosition] = "STDIN " + defStdin;
++nextPosition;
}
if (!defStdout.equals("")) {
data[nextPosition] = "STDOUT " + defStdout;
}
// make new SymbolTable
String[][] newSymbolTable = new String[symbolTable.size()][2];
for (int i = 0; i < newSymbolTable.length; ++i) {
newSymbolTable[i] = (String[])symbolTable.get(i);
}
// prepare for the second round.
codeMemoryLines = new MemoryLine[newCode.length];
compileDebugger.finalFirstPhase(newCode, data, newSymbolTable);
return compileDebugger.lineCompiled();
}
/** This function transforms any commands to binary and stores both
forms in the code array, or sets any initial data values in the
data array. It uses CompileConstants as its aid.
@param line The line of code to process.
@return A CompileInfo object describing what was done, or
null if the second round and thus the compilation has been
completed. */
private CompileInfo secondRoundProcess(String line)
throws TTK91CompileException {
/* Antti: 04.03.04
Do a pure binary translation first, then when all sections are
complete, convert the binary to an integer. Needs variables for
opcode(8bit), first operand(3 bit)(r0 to r7), m-part(memory format,
direct, indirect or from code), possible index register (3 bit) and 16
bits for the address. Once STORE is converted to a 00000001 and the
rest of the code processed we get 32bit binary that is the opcode from
symbolic opcode.
Antti 08.03.04 Teemu said that we should support the machine
spec instead of Koksi with this one. No need to support opcodes like
Muumuu LOAD R1, 100 kissa etc. Only tabs and extra spacing. So we need
to support opcodes like LOAD R1, 100 but not codes like LOAD R1, =R2.
Basic functionality: (Trim between each phase.) Check if there is a
label (8 first are the meaningful ones also must have one
non-number)) Convert opcode (8bit) check which register (0 to
7) =, Rj/addr or @ (00, 01 or 10) if addr(Ri) or Rj(Ri)(0 to
7) convert address (16bit) check if the rest is fine (empty or
starts with ;)
Store both formats to a data array (symbolic and binary).
*/
// check if variable is set!
int addressAsInt = 0;
int lineAsBinary;
String comment;
String[] symbolTableEntry;
String[] lineTemp = parseLine(line);
if (!lineTemp[4].equals("")) {
try {
addressAsInt = Integer.parseInt(lineTemp[4]);
} catch (NumberFormatException e) {
Object tempObject = symbolTable.get(Integer.parseInt((String)symbols.get(lineTemp[4])));
symbolTableEntry = (String[])tempObject;
if (symbolTableEntry[1].equals("")) {
comment = new Message("").toString();
throw new TTK91CompileException(comment);
}
addressAsInt = Integer.parseInt((String)symbolTableEntry[1]);
}
}
lineAsBinary = symbolicInterpreter.stringToBinary(lineTemp[1],
lineTemp[2],
lineTemp[3],
addressAsInt + "",
lineTemp[5]);
compileDebugger.setBinary(lineAsBinary);
codeMemoryLines[nextLine] = new MemoryLine(lineAsBinary, line);
// comment
String lineAsZerosAndOnes = symbolicInterpreter.intToBinary(lineAsBinary, 32);
String binaryByPositions =
symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(0, 8),
true) + ":" +
symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(8, 11),
false) + ":" +
symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(11, 13),
false) + ":" +
symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(13, 16),
false) + ":" +
symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(16),
true);
String[] commentParameters = {line, "" + lineAsBinary, binaryByPositions};
comment = new Message("{0} --> {1} ({2}) ", commentParameters).toString();
compileDebugger.setComment(comment);
return compileDebugger.lineCompiled();
}
/** This method parses a String and tries to find a label, opCode
and all the other parts of a Command line.
@param symbolicOpCode Symbolic form of an operation code. */
public String[] parseLine(String symbolicOpcode) {
String label = "";
String opcode = "";
String firstRegister = "";
String addressingMode = "";
String secondRegister = "";
String address = "";
String[] parsedLine;
String wordTemp = "";
int nextToCheck = 0; // for looping out the spacing
int fieldEnd = 0; // searches the end of a field (' ', ',')
fieldEnd = symbolicOpcode.indexOf(";");
if (fieldEnd != -1) { symbolicOpcode = symbolicOpcode.substring(0, fieldEnd); }
symbolicOpcode = symbolicOpcode.replace('\t',' ');
symbolicOpcode = symbolicOpcode.toLowerCase();
symbolicOpcode = symbolicOpcode.trim();
if (symbolicOpcode.length() == 0) {
parsedLine = new String[6];
for (int i = 0; i < parsedLine.length; ++i) parsedLine[i] = "";
return parsedLine;
}
String[] lineAsArray = symbolicOpcode.split("[ \t]+");
int lineAsArrayIndex = 0;
/* label */
wordTemp = lineAsArray[lineAsArrayIndex];
if (symbolicInterpreter.getOpcode(wordTemp) == -1) {
if(!validLabelName(wordTemp))
return null;
label = wordTemp;
++lineAsArrayIndex;
}
/* opcode */
if (lineAsArrayIndex < lineAsArray.length) {
opcode = lineAsArray[lineAsArrayIndex];
++lineAsArrayIndex;
if (symbolicInterpreter.getOpcode(opcode) < 0) { return null; }
} else { return null; }
/*first register*/
if (lineAsArrayIndex < lineAsArray.length) {
// first register might end with a ','. Not when push Sp etc.
if (lineAsArray[lineAsArrayIndex].charAt(
lineAsArray[lineAsArrayIndex].length() -1) == ',') {
if (symbolicInterpreter.getRegisterId(
lineAsArray[lineAsArrayIndex].substring(0,
lineAsArray[lineAsArrayIndex].length() - 1)
) != -1) {
firstRegister = lineAsArray[lineAsArrayIndex].substring(0,
lineAsArray[lineAsArrayIndex].length() -1);
++lineAsArrayIndex;
}
} else {
if (symbolicInterpreter.getRegisterId(
lineAsArray[lineAsArrayIndex]) != -1) {
firstRegister = lineAsArray[lineAsArrayIndex];
++lineAsArrayIndex;
}
}
}
/* addressingMode */
if (lineAsArrayIndex < lineAsArray.length) {
if (lineAsArray[lineAsArrayIndex].charAt(0) == '=' ||
lineAsArray[lineAsArrayIndex].charAt(0) == '@') {
addressingMode = "" + lineAsArray[lineAsArrayIndex].charAt(0);
} else { addressingMode = ""; }
}
/*address and second register*/
if (lineAsArrayIndex < lineAsArray.length) {
if (lineAsArray[lineAsArrayIndex].indexOf("(") != -1) {
if (lineAsArray[lineAsArrayIndex].indexOf(")") <
lineAsArray[lineAsArrayIndex].indexOf("(")) {
return null;
} else {
address = lineAsArray[lineAsArrayIndex].substring(
addressingMode.length(),
lineAsArray[lineAsArrayIndex].indexOf("(")
);
secondRegister = lineAsArray[lineAsArrayIndex].substring(
lineAsArray[lineAsArrayIndex].indexOf("(") + 1,
lineAsArray[lineAsArrayIndex].indexOf(")")
);
if (symbolicInterpreter.getRegisterId(secondRegister) == -1) {
return null;
}
}
} else {
address = lineAsArray[lineAsArrayIndex].substring(addressingMode.length());
}
}
if (symbolicInterpreter.getRegisterId(address) != -1) {
secondRegister = address;
address = "";
}
if (opcode.length() > 0) {
if (opcode.charAt(0) == 'j' || opcode.charAt(0) == 'J') {
// Opcode matches jneg/jzer/jpos or the negations
// jnneg/jnzer/jnpos.
if(opcode.toLowerCase().matches("j" + "n?" +
"((neg)|(zer)|(pos))")) {
if (firstRegister.equals("")) return null;
}
if (addressingMode.equals("=") || address.equals("")) return null;
} else {
if (opcode.equalsIgnoreCase("nop")) {
// (do nothing)
} else {
if (opcode.equalsIgnoreCase("pop")) {
if (addressingMode.equals("@") ||
addressingMode.equals("=") || !address.equals(""))
return null;
} else {
if (firstRegister.equals("") ||
(address.equals("") && secondRegister.equals("")))
return null;
}
}
}
}
if (addressingMode.equals("=") && address.equals(""))
return null;
if (opcode.equalsIgnoreCase("store") && address.equals(""))
return null;
if (opcode.equalsIgnoreCase("store") && addressingMode.equals("="))
return null;
if (opcode.equals("") && (!label.equals("") ||
!firstRegister.equals("") ||
!addressingMode.equals("") ||
!address.equals("") ||
!secondRegister.equals(""))) {
return null;
}
parsedLine = new String[6];
parsedLine[0] = label.trim();
parsedLine[1] = opcode.trim();
parsedLine[2] = firstRegister.trim();
parsedLine[3] = addressingMode.trim();
parsedLine[4] = address.trim();
parsedLine[5] = secondRegister.trim();
return parsedLine;
}
/** This function tries to find a compiler command from the
line. Works much like parseLine but this time valid opcodes
are DEF, EQU, DC and DS.
@param line String representing one line from source code.
@return String array with label in position 0, command in the
position 1 and position 2 contains the parameter.
*/
public String[] parseCompilerCommandLine(String line) {
int fieldEnd = 0;
int nextToCheck = 0;
String label = "";
String opcode = "";
String value = "";
int intValue;
String[] parsedLine;
/* preprosessing */
line = line.trim();
line = line.toLowerCase();
line = line.replace('\t',' ');
fieldEnd = line.indexOf(";");
if (fieldEnd != -1) { line = line.substring(0, fieldEnd); }
/* LABEL opcode value */
fieldEnd = line.indexOf(" ");
if (fieldEnd == -1) {
label = line.substring(nextToCheck);
fieldEnd = line.length();
} else {
label = line.substring(nextToCheck, fieldEnd);
}
nextToCheck = fieldEnd + 1;
/* label OPCODE value */
if (nextToCheck < line.length()) {
while (line.charAt(nextToCheck) == ' ') { ++nextToCheck; }
fieldEnd = line.indexOf(' ', nextToCheck);
if (fieldEnd == -1) {
opcode = line.substring(nextToCheck);
fieldEnd = line.length();
} else {
opcode = line.substring(nextToCheck, fieldEnd);
}
if (!opcode.matches("((dc)|(ds)|(equ)|(def))")) {
return null;
}
nextToCheck = fieldEnd;
}
/* label opcode VALUE */
if (nextToCheck < line.length()) {
while (line.charAt(nextToCheck) == ' ') { ++nextToCheck; }
value = line.substring(nextToCheck);
if (value.length() > 0) {
try {
intValue = Integer.parseInt(value);
if (opcode.equalsIgnoreCase("ds") && intValue < 1) {
return null;
}
} catch (NumberFormatException e) { return null; }
}
}
if (!opcode.equalsIgnoreCase("dc") && value.equals("")) return null;
parsedLine = new String[3];
parsedLine[0] = label;
parsedLine[1] = opcode;
parsedLine[2] = value;
return parsedLine;
}
/** This method tests whether a label name contains at least one
non-number and consists of 0-9, A- and _.
It does not check whether the label is in use already or if it
is a reserved word.
@param labelName The label name to test.
@return True if the label consists of valid characters, false
otherwise. */
private boolean validLabelName(String labelName) {
// It must have one non-number. Valid characters are A-, 0-9 and _.
// Test 1: the word contains one or more of the following:
// a-z, A-Z, _, 0-9, , , in any order.
// Test 2: the word also contains one non-number (class \D
// means anything but 0-9) surrounded by any number of
// any character. All these 'anything buts' and 'anys' are
// also valid characters, since we check that in Test 1.
if(labelName.matches("[\\w]+") &&
labelName.matches(".*\\D.*")) {
return true;
}
return false;
}
}
|
package net.wisedog.android.whooing.activity;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import net.wisedog.android.whooing.Define;
import net.wisedog.android.whooing.R;
import net.wisedog.android.whooing.WhooingApplication;
import net.wisedog.android.whooing.adapter.TransactionAddAdapter;
import net.wisedog.android.whooing.api.Entries;
import net.wisedog.android.whooing.dataset.TransactionItem;
import net.wisedog.android.whooing.db.AccountsDbOpenHelper;
import net.wisedog.android.whooing.db.AccountsEntity;
import net.wisedog.android.whooing.dialog.AccountChooserDialog;
import net.wisedog.android.whooing.dialog.AccountChooserDialog.AccountChooserListener;
import net.wisedog.android.whooing.engine.DataRepository;
import net.wisedog.android.whooing.engine.GeneralProcessor;
import net.wisedog.android.whooing.widget.WiTextView;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
/**
* @author Wisedog(me@wisedog.net)
*
*/
public class TransactionAdd extends SherlockFragmentActivity implements AccountChooserListener{
protected static final int DATE_DIALOG_ID = 0;
protected static final int REQUEST_CODE_LEFT = 10;
protected static final int REQUEST_CODE_RIGHT = 11;
private WiTextView mDateDisplay;
private ArrayList<AccountsEntity> mAccountsList = null;
private AccountsEntity mLeftAccount = null;
private AccountsEntity mRightAccount = null;
private ArrayList<TransactionItem> mDataArray = null;
private ArrayList<TransactionItem> mEntryItemArray = null;
private TransactionAddAdapter mLastestadapter = null;
private int mYear;
private int mMonth;
private int mDay;
/* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_Styled);
super.onCreate(savedInstanceState);
setContentView(R.layout.add_transaction);
Intent intent = getIntent();
if(intent.getBooleanExtra("showEntries", false))
;
this.setTitle(intent.getStringExtra("title"));
if(getAllAccountsInfo() > 0){
mLeftAccount = mAccountsList.get(0);
mRightAccount = mAccountsList.get(0);
}
if(initUi() == false){
setResult(RESULT_CANCELED);
finish();
return;
}
AsyncTask<Void, Integer, JSONObject> task = new AsyncTask<Void, Integer, JSONObject>(){
@Override
protected JSONObject doInBackground(Void... arg0) {
Entries entries = new Entries();
JSONObject result = entries.getLatest(Define.APP_SECTION, Define.APP_ID,
Define.REAL_TOKEN, Define.APP_SECRET, Define.TOKEN_SECRET, 5);
return result;
}
@Override
protected void onPostExecute(JSONObject result) {
if(Define.DEBUG && result != null){
Log.d("wisedog", "API Call - API_GET_ENTRIES_LATEST : " + result.toString());
}
try {
showLatestTransaction(result);
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(result);
}
};
task.execute();
}
protected void setEntry(String itemName){
if(itemName == null){
return;
}
for(int i = 0; i < mEntryItemArray.size(); i++){
TransactionItem item = mEntryItemArray.get(i);
if(item.item.compareToIgnoreCase(itemName) == 0){
GeneralProcessor processor = new GeneralProcessor(this);
AccountsEntity leftEntity = processor.findAccountById(item.l_account_id);
AccountsEntity rightEntity = processor.findAccountById(item.r_account_id);
setLeftAccount(leftEntity);
setRightAccount(rightEntity);
break;
}
}
}
/**
* Initialize UI
* */
public boolean initUi(){
if(mAccountsList == null){
return false;
}
mDateDisplay = (WiTextView)findViewById(R.id.add_transaction_text_date);
ImageButton dateChangeBtn = (ImageButton)findViewById(R.id.add_transaction_change_btn);
dateChangeBtn.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
//Initialize edittext
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.add_transaction_auto_complete);
textView.setText("");
((EditText)findViewById(R.id.add_transaction_edit_amount)).setText("");
Locale locale = new Locale(Define.LOCALE_LANGUAGE, Define.COUNTRY_CODE);
java.text.DateFormat df = java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM, locale);
String date = df.format(new java.util.Date()).toString();
mDateDisplay.setText(date);
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH)+1;
mDay = c.get(Calendar.DAY_OF_MONTH);
if(mLeftAccount != null && mRightAccount != null){
WiTextView textLeft = (WiTextView)findViewById(R.id.add_transaction_text_left_account);
WiTextView textRight = (WiTextView)findViewById(R.id.add_transaction_text_right_account);
textLeft.setText(mLeftAccount.title + GeneralProcessor.getPlusMinus(mLeftAccount, true));
textRight.setText(mRightAccount.title + GeneralProcessor.getPlusMinus(mRightAccount, false));
}
//To support transaction insert suggest
DataRepository repository = WhooingApplication.getInstance().getRepo(); //DataRepository.getInstance();
JSONObject obj = repository.getLastestItems();
JSONArray array = null;
mEntryItemArray = new ArrayList<TransactionItem>();
ArrayList<String> entryItemStringArray = new ArrayList<String>();
if(obj != null){
try {
array = obj.getJSONArray("results");
for(int i = 0; i < array.length(); i++){
JSONObject objItem = (JSONObject) array.get(i);
TransactionItem item = new TransactionItem("",objItem.getString("item"), objItem.getDouble("money"),
objItem.getString("l_account"), objItem.getString("l_account_id"),
objItem.getString("l_account_id"), objItem.getString("r_account_id"));
mEntryItemArray.add(item);
entryItemStringArray.add(item.item);
}
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
String[] lastestStringItems = entryItemStringArray.toArray(new String[entryItemStringArray.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, lastestStringItems);
textView.setAdapter(adapter);
textView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
String str = (String) arg0.getAdapter().getItem(position);
setEntry(str);
}
});
return true;
}
/**
* Click Listener for Left/Right accounts button
* @param v View what be clicked
* */
public void onClickLRAccount(View v){
String mode = "";
if(v.getId() == R.id.add_transaction_text_left_account){
mode = "left";
}else{
mode = "right";
}
DialogFragment newFragment = AccountChooserDialog.newInstance(mAccountsList, mYear, mMonth, mDay, mode);
newFragment.show(getSupportFragmentManager(), "dialog");
}
/**
* Set left account from selection of AccountsSelection
* @param entity Chosen item from AccountsSelection Activity
* */
public void setLeftAccount(AccountsEntity entity){
if(entity == null){
return;
}
this.mLeftAccount = entity;
WiTextView textLeft = (WiTextView)findViewById(R.id.add_transaction_text_left_account);
textLeft.setText(mLeftAccount.title + GeneralProcessor.getPlusMinus(mLeftAccount, true));
}
/**
* Set right account from selection of AccountsSelection
* @param entity Chosen item from AccountsSelection Activity
* */
public void setRightAccount(AccountsEntity entity){
if(entity == null){
return;
}
this.mRightAccount = entity;
WiTextView textRight = (WiTextView)findViewById(R.id.add_transaction_text_right_account);
textRight.setText(mRightAccount.title + GeneralProcessor.getPlusMinus(mRightAccount, false));
}
/**
* Get AccountsEntity List
* @return Size of accounts list
* */
public int getAllAccountsInfo(){
AccountsDbOpenHelper dbHelper = new AccountsDbOpenHelper(this);
mAccountsList = dbHelper.getAllAccountsInfo();
if(mAccountsList != null){
return mAccountsList.size();
}
return 0;
}
/**
* Show lastest Transaction
* @param obj JSON formatted data from calling API_GET_ENTRIES_LATEST
* */
public void showLatestTransaction(JSONObject obj) throws JSONException{
mDataArray = new ArrayList<TransactionItem>();
JSONArray array = obj.getJSONArray("results");
int count = array.length();
for(int i = 0; i < count; i++){
JSONObject entity = array.getJSONObject(i);
TransactionItem item = new TransactionItem(
entity.getString("entry_date"),
entity.getString("item"),
entity.getDouble("money"),
entity.getString("l_account"),
entity.getString("l_account_id"),
entity.getString("r_account"),
entity.getString("r_account_id")
);
mDataArray.add(item);
}
ListView lastestTransactionList = (ListView)findViewById(R.id.list_lastest_transaction);
mLastestadapter = new TransactionAddAdapter(this, mDataArray);
lastestTransactionList.setAdapter(mLastestadapter);
}
private void getAccountsByDate(int year, int i, int dayOfMonth) {
// TODO DB Open
//Convert Date(String) to integer
// select * from accounts where open_date > date
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mDateDisplay.setText(new StringBuilder()
.append(year).append("-")
.append(monthOfYear+1).append("-")
.append(dayOfMonth));
mYear = year;
mMonth = monthOfYear+1;
mDay = dayOfMonth;
getAccountsByDate(year, monthOfYear+1, dayOfMonth);
}
};
public void onClickGo(View v){
if(checkValidation() == false){
return;
}
Button goBtn = (Button)findViewById(R.id.add_transaction_btn_go);
EditText amountEdit = (EditText)findViewById(R.id.add_transaction_edit_amount);
String amount = amountEdit.getText().toString();
double amountDouble = Double.valueOf(amount);
final Bundle bundle = new Bundle();
int formattedDate = mYear * 10000 + mMonth * 100 + mDay;
bundle.putInt("entry_date", formattedDate);
bundle.putParcelable("l_account", mLeftAccount);
bundle.putParcelable("r_account", mRightAccount);
bundle.putString("item", ((EditText)findViewById(R.id.add_transaction_auto_complete)).getText().toString());
bundle.putDouble("money", amountDouble);
bundle.putString("memo", "");
goBtn.setEnabled(false);
goBtn.setText(getString(R.string.text_loading));
AsyncTask<Void, Integer, JSONObject> mTask = new AsyncTask<Void, Integer, JSONObject>(){
@Override
protected JSONObject doInBackground(Void... arg0) {
Entries entryInsert = new Entries();
JSONObject result = entryInsert.insertEntry(Define.APP_SECTION, Define.APP_ID,
Define.REAL_TOKEN, Define.APP_SECRET, Define.TOKEN_SECRET, bundle);
return result;
}
@Override
protected void onPostExecute(JSONObject result) {
if(Define.DEBUG && result != null){
Log.d("wisedog", "API Call - API_POST_ENTRIES : " + result.toString());
}
Button goBtn = (Button)findViewById(R.id.add_transaction_btn_go);
goBtn.setEnabled(true);
goBtn.setText("go");
try {
JSONArray objResult = result.getJSONArray("results");
if(mDataArray != null){
for(int i = 0; i < objResult.length() ; i++){
TransactionItem item = new TransactionItem((JSONObject) objResult.get(i));
mDataArray.add(i, item);
}
if(mLastestadapter != null){
mLastestadapter.setData(mDataArray);
mLastestadapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(TransactionAdd.this, TransactionAdd.this.getString(
R.string.add_transaction_add_complete), Toast.LENGTH_SHORT).show();
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.add_transaction_auto_complete);
textView.setText("");
((EditText)findViewById(R.id.add_transaction_edit_amount)).setText("");
textView.requestFocus();
//Clear cached data - mt, pl, bs ...
DataRepository repository = WhooingApplication.getInstance().getRepo();
repository.clearCachedData();
super.onPostExecute(result);
}
};
//Start task
mTask.execute();
}
/* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
if(data == null){
return;
}
if(requestCode == REQUEST_CODE_LEFT){
AccountsEntity entity = data.getParcelableExtra("selection");
setLeftAccount(entity);
}else if(requestCode == REQUEST_CODE_RIGHT){
AccountsEntity entity = data.getParcelableExtra("selection");
setRightAccount(entity);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Check field values validation for put entry
* @return All is validated, return true, otherwise return false
* */
public boolean checkValidation(){
//Check Item edit
final AutoCompleteTextView editItem = (AutoCompleteTextView)findViewById(R.id.add_transaction_auto_complete);
String itemStr = editItem.getText().toString();
if(itemStr.equals("")){
Toast.makeText(this, "Check Item", Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
public void run() {
editItem.requestFocus();
}
});
return false;
}
//Check Amount edit
final EditText editAmount = (EditText)findViewById(R.id.add_transaction_edit_amount);
String itemAmount = editAmount.getText().toString();
if(itemAmount.equals("")){
Toast.makeText(this, "Check Amount", Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
public void run() {
editAmount.requestFocus();
}
});
return false;
}
if(mLeftAccount == null || mRightAccount == null){
Toast.makeText(this, "Check left/right", Toast.LENGTH_SHORT).show();
return false;
}
if(mLeftAccount.account_id.equals(mRightAccount.account_id)){
Toast.makeText(this, "Left and Right are the same", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
@Override
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case DATE_DIALOG_ID:
final Calendar c = Calendar.getInstance();
return new DatePickerDialog(this, mDateSetListener, c.get(Calendar.YEAR),
c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
}
return null;
}
/**
* @return return left-account entity
*
* */
public AccountsEntity getLeftAccounts(){
return mLeftAccount;
}
/**
* @return return right-account entity
* */
public AccountsEntity getRightAccounts(){
return mRightAccount;
}
public void onFinishingChoosing(AccountsEntity entity, String mode) {
if(mode.equals("left")){
setLeftAccount(entity);
}else if(mode.equals("right")){
setRightAccount(entity);
}
}
}
|
package org.jetel.component;
import static org.jetel.ctl.TransformLangParserTreeConstants.JJTASSIGNMENT;
import static org.jetel.ctl.TransformLangParserTreeConstants.JJTFIELDACCESSEXPRESSION;
import static org.jetel.ctl.TransformLangParserTreeConstants.JJTFUNCTIONDECLARATION;
import static org.jetel.ctl.TransformLangParserTreeConstants.JJTIMPORTSOURCE;
import static org.jetel.ctl.TransformLangParserTreeConstants.JJTRETURNSTATEMENT;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.jetel.component.TransformLanguageDetector.TransformLanguage;
import org.jetel.ctl.ErrorMessage;
import org.jetel.ctl.ITLCompiler;
import org.jetel.ctl.MetadataErrorDetail;
import org.jetel.ctl.NavigatingVisitor;
import org.jetel.ctl.TLCompiler;
import org.jetel.ctl.TLCompilerFactory;
import org.jetel.ctl.TLUtils;
import org.jetel.ctl.TransformLangExecutor;
import org.jetel.ctl.ASTnode.CLVFBlock;
import org.jetel.ctl.ASTnode.CLVFFieldAccessExpression;
import org.jetel.ctl.ASTnode.SimpleNode;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.MissingFieldException;
import org.jetel.graph.ContextProvider;
import org.jetel.graph.Node;
import org.jetel.graph.TransformationGraph;
import org.jetel.graph.runtime.CloverClassPath;
import org.jetel.interpreter.ParseException;
import org.jetel.interpreter.TransformLangParser;
import org.jetel.interpreter.ASTnode.CLVFDirectMapping;
import org.jetel.interpreter.ASTnode.CLVFFunctionDeclaration;
import org.jetel.interpreter.ASTnode.CLVFStart;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.plugin.PluginDescriptor;
import org.jetel.util.CodeParser;
import org.jetel.util.classloader.MultiParentClassLoader;
import org.jetel.util.compile.ClassLoaderUtils;
import org.jetel.util.compile.DynamicCompiler;
import org.jetel.util.compile.DynamicJavaClass;
import org.jetel.util.file.FileUtils;
import org.jetel.util.property.PropertyRefResolver;
import org.jetel.util.property.RefResFlag;
import org.jetel.util.string.CommentsProcessor;
/**
* @deprecated use {@link TransformFactory} instead
* @deprecated use {@link TransformLanguageDetector} instead
* @deprecated use {@link TLUtils} instead
* @deprecated use {@link ClassLoaderUtils} instead
*/
@Deprecated
public class RecordTransformFactory {
/**
* @deprecated use {@link TransformLanguage#JAVA} instead
*/
@Deprecated
public static final int TRANSFORM_JAVA_SOURCE=1;
/**
* @deprecated use {@link TransformLanguage#CTL1} instead
*/
@Deprecated
public static final int TRANSFORM_CLOVER_TL=2;
/**
* @deprecated use {@link TransformLanguage#JAVA_PREPROCESS} instead
*/
@Deprecated
public static final int TRANSFORM_JAVA_PREPROCESS=3;
/**
* @deprecated use {@link TransformLanguage#CTL2} instead
*/
@Deprecated
public static final int TRANSFORM_CTL = 4;
/**
* @deprecated use {@link TransformLanguageDetector#PATTERN_CLASS} instead
*/
@Deprecated
public static final Pattern PATTERN_CLASS = Pattern.compile("class\\s+\\w+");
/**
* @deprecated use {@link TransformLanguageDetector#PATTERN_TL_CODE} instead
*/
@Deprecated
public static final Pattern PATTERN_TL_CODE = Pattern.compile("function\\s+((transform)|(generate))");
/**
* @deprecated use {@link TransformLanguageDetector#PATTERN_CTL_CODE} instead
*/
@Deprecated
public static final Pattern PATTERN_CTL_CODE = Pattern.compile("function\\s+[a-z]*\\s+((transform)|(generate))");
/**
* @deprecated use {@link TransformLanguageDetector#PATTERN_PARTITION_CODE} instead
*/
@Deprecated
public static final Pattern PATTERN_PARTITION_CODE = Pattern.compile("function\\s+getOutputPort");
/**
* @deprecated use {@link TransformLanguageDetector#PATTERN_CTL_PARTITION_CODE} instead
*/
@Deprecated
public static final Pattern PATTERN_CTL_PARTITION_CODE = Pattern.compile("function\\s+[a-z]*\\s+getOutputPort");
/**
* @deprecated use {@link TransformLanguageDetector#PATTERN_PREPROCESS_1} instead
*/
@Deprecated
public static final Pattern PATTERN_PREPROCESS_1 = Pattern.compile("\\$\\{out\\.");
/**
* @deprecated use {@link TransformLanguageDetector#PATTERN_PREPROCESS_2} instead
*/
@Deprecated
public static final Pattern PATTERN_PREPROCESS_2 = Pattern.compile("\\$\\{in\\.");
/**
* Verifier class checking if a CTL function only contains direct mappings.
* Direct mapping is an assignment statement where left hand side contains an output field reference.
*
* @author Michal Tomcanyi <michal.tomcanyi@javlin.cz>
*/
private static class SimpleTransformVerifier extends NavigatingVisitor {
private final String functionName;
private final org.jetel.ctl.ASTnode.Node ast;
/**
* Allocates verifier which will verify that the <code>functionName</code>
* contains only simple mappings
*
* @param functionName function to validate
*/
public SimpleTransformVerifier(String functionName, org.jetel.ctl.ASTnode.Node ast) {
this.functionName = functionName;
this.ast = ast;
}
/**
* Scans AST tree for function and checks it only contains direct mappings
* (i.e. assignments where LHS is an output field reference)
*
* @return true if function is simple, false otherwise
*/
public boolean check() {
return (Boolean)ast.jjtAccept(this, null);
}
@Override
public Object visit(org.jetel.ctl.ASTnode.CLVFStart node, Object data) {
// functions can only be declared in start or import nodes
for (int i=0; i<node.jjtGetNumChildren(); i++) {
final SimpleNode child = (SimpleNode)node.jjtGetChild(i);
final int id = child.getId();
switch (id) {
case JJTIMPORTSOURCE:
// scan imports
child.jjtAccept(this, data);
break;
case JJTFUNCTIONDECLARATION:
if (((org.jetel.ctl.ASTnode.CLVFFunctionDeclaration)child).getName().equals(functionName)) {
// scan statements in function body
return child.jjtGetChild(2).jjtAccept(this, data);
}
break;
}
}
return false;
}
@Override
public Object visit(CLVFBlock node, Object data) {
// we must have come here as the block is 'transform' function body
for (int i=0; i<node.jjtGetNumChildren(); i++) {
final SimpleNode child = (SimpleNode)node.jjtGetChild(i);
// statement must be an assignment and a direct mapping into output field
if (child.getId() != JJTASSIGNMENT && child.getId() != JJTRETURNSTATEMENT) {
// not an assignment - fail quickly
return false;
}
if (child.getId() != JJTRETURNSTATEMENT) {
// check if direct mapping
final SimpleNode lhs = (SimpleNode)child.jjtGetChild(0);
if (lhs.getId() != JJTFIELDACCESSEXPRESSION) {
// not a mapping
return false;
}
if (!((CLVFFieldAccessExpression) lhs).isOutput()) {
// lhs must be an output field
return false;
}
}
}
// all statements are direct mappings
return true;
}
}
/**
* @deprecated use {@link TransformFactory#createTransform()} instead
*/
@Deprecated
public static RecordTransform createTransform(String transform, String transformClass, String transformUrl,
String charset, Node node, DataRecordMetadata inMetaData[], DataRecordMetadata outMetadata[])
throws ComponentNotReadyException, MissingFieldException {
return createTransform(transform, transformClass, transformUrl, charset, node, inMetaData, outMetadata,
ClassLoaderUtils.createNodeClassLoader(node), node.getGraph().getRuntimeContext().getClassPath());
}
/**
*
* @param transform
* @param transformClass
* @param transformURL
* @param charset
* @param node
* @param inMetadata
* @param outMetadata
* @param transformationParameters
* @param classLoader
* @param classPath
* @return
* @throws MissingFieldException if the CTL transformation tried to access non-existing field
* @throws ComponentNotReadyException
*/
private static RecordTransform createTransform(String transform, String transformClass, String transformURL,
String charset, Node node, DataRecordMetadata[] inMetadata, DataRecordMetadata[] outMetadata,
ClassLoader classLoader, CloverClassPath classPath) throws ComponentNotReadyException, MissingFieldException {
//if classpath wasn't passed, empty one is automatically prepared
if (classPath == null) {
classPath = new CloverClassPath();
}
// create transformation
RecordTransform transformation = null;
Log log = LogFactory.getLog(node.getClass());
Logger logger = Logger.getLogger(node.getClass());
//without these parameters we cannot create transformation
if (transform == null && transformClass == null && transformURL == null) {
throw new ComponentNotReadyException("Record transformation is not defined.");
}
//resolve references at given transformation string
if (transform != null) {
PropertyRefResolver refResolver= new PropertyRefResolver(node.getGraph().getGraphProperties());
transform = refResolver.resolveRef(transform, RefResFlag.SPEC_CHARACTERS_OFF);
}
if (transformClass != null) {
//get transformation from link to the compiled class
transformation = (RecordTransform)loadClassInstance(transformClass, classLoader);
}else if (transform == null && transformURL != null){
transform = FileUtils.getStringFromURL(node.getGraph().getRuntimeContext().getContextURL(), transformURL, charset);
PropertyRefResolver refResolver= new PropertyRefResolver(node.getGraph().getGraphProperties());
transform = refResolver.resolveRef(transform, RefResFlag.SPEC_CHARACTERS_OFF);
}
if (transformClass == null) {
switch (guessTransformType(transform)) {
case TRANSFORM_JAVA_SOURCE:
// try compile transform parameter as java code
// try preprocessing if applicable
transformation = RecordTransformFactory.loadClassDynamic(
log, null, transform, inMetadata, outMetadata, node, false);
break;
case TRANSFORM_CLOVER_TL:
transformation = new RecordTransformTL(transform, logger);
break;
case TRANSFORM_CTL:
final ITLCompiler compiler =
TLCompilerFactory.createCompiler(node.getGraph(),inMetadata,outMetadata,"UTF-8");
List<ErrorMessage> msgs = compiler.compile(transform, CTLRecordTransform.class, node.getId());
if (compiler.errorCount() > 0) {
String report = ErrorMessage.listToString(msgs, logger);
String message = "CTL code compilation finished with " + compiler.errorCount() + " errors" + report;
for (ErrorMessage msg: msgs) {
if (msg.getDetail() instanceof MetadataErrorDetail) {
MetadataErrorDetail detail = (MetadataErrorDetail) msg.getDetail();
throw new MissingFieldException(message, detail.isOutput(), detail.getRecordId(), detail.getFieldName());
}
}
throw new ComponentNotReadyException(message);
}
Object ret = compiler.getCompiledCode();
if (ret instanceof TransformLangExecutor) {
// setup interpreted runtime
transformation = new CTLRecordTransformAdapter((TransformLangExecutor)ret, logger);
} else if (ret instanceof RecordTransform){
transformation = (RecordTransform)ret;
} else {
// this should never happen as compiler always generates correct interface
throw new ComponentNotReadyException("Invalid type of record transformation");
}
break;
case TRANSFORM_JAVA_PREPROCESS:
transformation = RecordTransformFactory.loadClassDynamic(log,
"Transform" + node.getId(), transform, inMetadata, outMetadata, node, true);
break;
default:
// logger.error("Can't determine transformation code type at
// component ID :"+node.getId());
throw new ComponentNotReadyException(
"Can't determine transformation code type at component ID :" + node.getId());
}
}
transformation.setNode(node);
return transformation;
}
/**
* Answers instance of given <tt>transformClassName</tt>.
*
* @param transformClassName
* @param loader class loader to lookup class by name
* @return
* @throws ComponentNotReadyException
* @deprecated use {@link ClassLoaderUtils#loadClassInstance(String, ClassLoader)} instead
*/
@Deprecated
public static Object loadClassInstance(String transformClassName, ClassLoader loader)
throws ComponentNotReadyException {
try {
Class<?> klass = Class.forName(transformClassName, true, loader);
return klass.newInstance();
} catch (ClassNotFoundException e) {
throw new ComponentNotReadyException("Cannot find class: " + transformClassName, e);
} catch (IllegalAccessException e) {
throw new ComponentNotReadyException("Cannot instantiate class: " + transformClassName, e);
} catch (InstantiationException e) {
throw new ComponentNotReadyException("Cannot instantiate class: " + transformClassName, e);
} catch (ExceptionInInitializerError e) {
throw new ComponentNotReadyException("Cannot initialize class: " + transformClassName, e);
} catch (LinkageError e) {
throw new ComponentNotReadyException("Cannot link class: " + transformClassName, e);
} catch (SecurityException e) {
throw new ComponentNotReadyException("Cannot instantiate class: " + transformClassName, e);
}
}
/**
* @deprecated use {@link ClassLoaderUtils#loadClassInstance(String, Node)} instead
*/
@Deprecated
public static Object loadClassInstance(String transformClassName) throws ComponentNotReadyException {
Node node = ContextProvider.getNode();
if (node == null) {
return loadClassInstance(transformClassName, Thread.currentThread().getContextClassLoader());
} else {
return loadClassInstance(transformClassName, node);
}
}
/**
* Answers instance of class with given <tt>transformClassName</tt>. The supplied node
* is used as a context to fetch its class loader and the runtime class path as well.
*
* @param transformClassName
* @param node
* @return
* @throws ComponentNotReadyException
* @deprecated use {@link ClassLoaderUtils#loadClassInstance(String, Node)} instead
*/
@Deprecated
public static Object loadClassInstance(String transformClassName, Node node) throws ComponentNotReadyException {
return loadClassInstance(transformClassName, ClassLoaderUtils.createNodeClassLoader(node));
}
/**
* @deprecated use {@link ClassLoaderUtils#loadClassInstance(Class, String, Node)} instead
*/
@Deprecated
public static <T> T loadClassInstance(String transformClassName, Class<T> expectedType, Node node)
throws ComponentNotReadyException {
Object instance = loadClassInstance(transformClassName, node);
try {
return expectedType.cast(instance);
} catch (ClassCastException e) {
throw new ComponentNotReadyException(node, "Provided class '" + transformClassName + "' does not extend/implement " + expectedType.getName());
}
}
private static ClassLoader getCTLLibsClassLoader() {
Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
for (PluginDescriptor plugin : DynamicCompiler.getCTLRelatedPlugins()) {
loaders.add(plugin.getClassLoader());
}
return new MultiParentClassLoader(loaders.toArray(new ClassLoader[loaders.size()]));
}
/**
* @param logger
* @param className
* @param transformCode
* @param inMetadata
* @param outMetadata
* @return
* @throws ComponentNotReadyException
* @deprecated use {@link TransformFactory#createTransform()} instead
*/
@Deprecated
public static RecordTransform loadClassDynamic(Log logger, String className, String transformCode,
DataRecordMetadata[] inMetadata, DataRecordMetadata[] outMetadata, Node node, boolean addTransformCodeStub) throws ComponentNotReadyException {
// creating dynamicTransformCode from internal transformation format
CodeParser codeParser = new CodeParser(inMetadata, outMetadata);
if (!addTransformCodeStub)
// we must turn this off, because we don't have control about the rest of Java source
// and thus we cannot create the declaration of symbolic constants
codeParser.setUseSymbolicNames(false);
codeParser.setSourceCode(transformCode);
codeParser.parse();
if (addTransformCodeStub)
codeParser.addTransformCodeStub("Transform" + className);
return loadClassDynamic(codeParser.getSourceCode(), node);
}
/**
* @param logger
* @param dynamicTransformCode
* @return
* @throws ComponentNotReadyException
* @deprecated use {@link TransformFactory#createTransform()} instead
*/
@Deprecated
public static RecordTransform loadClassDynamic(String sourceCode, Node node)
throws ComponentNotReadyException {
return DynamicJavaClass.instantiate(sourceCode, RecordTransform.class, node);
}
private static Pattern getPattern(String hashBang) {
return Pattern.compile("^\\s*" + hashBang);
}
/**
* Guesses type of transformation code based on
* code itself - looks for certain patterns within the code
*
* @param transform
* @return guessed transformation type or -1 if can't determine
* @deprecated use {@link TransformLanguageDetector#guessLanguage(String)} instead
*/
@Deprecated
public static int guessTransformType(String transform){
String commentsStripped = CommentsProcessor.stripComments(transform);
// First, try to identify the starting string
if (getPattern(WrapperTL.TL_TRANSFORM_CODE_ID).matcher(transform).find() ||
getPattern(WrapperTL.TL_TRANSFORM_CODE_ID2).matcher(transform).find()) {
return TRANSFORM_CLOVER_TL;
}
if (getPattern(TransformLangExecutor.CTL_TRANSFORM_CODE_ID).matcher(transform).find()) {
// new CTL implementation
return TRANSFORM_CTL;
}
if (PATTERN_CTL_CODE.matcher(commentsStripped).find()
|| PATTERN_CTL_PARTITION_CODE.matcher(commentsStripped).find()){
// clover internal transformation language
return TRANSFORM_CTL;
}
if (PATTERN_TL_CODE.matcher(commentsStripped).find()
|| PATTERN_PARTITION_CODE.matcher(commentsStripped).find()){
// clover internal transformation language
return TRANSFORM_CLOVER_TL;
}
if (PATTERN_CLASS.matcher(commentsStripped).find()){
// full java source code
return TRANSFORM_JAVA_SOURCE;
}
if (PATTERN_PREPROCESS_1.matcher(commentsStripped).find() ||
PATTERN_PREPROCESS_2.matcher(commentsStripped).find() ){
// semi-java code which has to be preprocessed
return TRANSFORM_JAVA_PREPROCESS;
}
return -1;
}
// Following old TL parser functions are now deprecated
@Deprecated
private static boolean isTLSimpleTransformFunctionNode(CLVFStart record, String functionName, int functionParams) {
int numTopChildren = record.jjtGetNumChildren();
/* Detection of simple mapping inside transform(idx) function */
if (record.jjtHasChildren()) {
for (int i = 0; i < numTopChildren; i++) {
org.jetel.interpreter.ASTnode.Node node = record.jjtGetChild(i);
if (node instanceof org.jetel.interpreter.ASTnode.CLVFFunctionDeclaration) {
if (((CLVFFunctionDeclaration)node).name.equals(functionName)) {
CLVFFunctionDeclaration transFunction = (CLVFFunctionDeclaration)node;
if (transFunction.numParams != functionParams)
return false;
int numTransChildren = transFunction.jjtGetNumChildren();
for (int j = 0; j < numTransChildren; j++) {
org.jetel.interpreter.ASTnode.Node fNode = transFunction.jjtGetChild(j);
if (!(fNode instanceof CLVFDirectMapping)) {
// System.out.println("Function transform(idx) must contain direct mappings only");
return false;
}
}
return true;
}
}
}
}
return false;
}
/**
* @deprecated use {@link TLUtils#isTLSimpleTransform(DataRecordMetadata[], DataRecordMetadata[], String)} instead
*/
@Deprecated
public static boolean isTLSimpleTransform(DataRecordMetadata[] inMeta,
DataRecordMetadata[] outMeta, String transform) {
return isTLSimpleFunction(inMeta, outMeta, transform, "transform");
}
/**
* @deprecated use {@link TLUtils#isTLSimpleFunction(DataRecordMetadata[], DataRecordMetadata[], String, String)} instead
*/
@Deprecated
public static boolean isTLSimpleFunction(DataRecordMetadata[] inMeta,
DataRecordMetadata[] outMeta, String transform, String funtionName) {
TransformLangParser parser = new TransformLangParser(inMeta, outMeta, transform);
CLVFStart record = null;
try {
record = parser.Start();
record.init();
} catch (ParseException e) {
System.out.println("Error when parsing expression: " + e.getMessage().split(System.getProperty("line.separator"))[0]);
return false;
}
return isTLSimpleTransformFunctionNode(record, funtionName, 0);
}
/**
* @deprecated use {@link TLUtils#isTLSimpleDenormalizer(DataRecordMetadata[], DataRecordMetadata[], String)} instead
*/
@Deprecated
public static boolean isTLSimpleDenormalizer(DataRecordMetadata[] inMeta,
DataRecordMetadata[] outMeta, String transform) {
TransformLangParser parser = new TransformLangParser(inMeta, outMeta, transform);
CLVFStart record = null;
try {
record = parser.Start();
record.init();
} catch (ParseException e) {
System.out.println("Error when parsing expression: " + e.getMessage().split(System.getProperty("line.separator"))[0]);
return false;
}
return isTLSimpleTransformFunctionNode(record, "transform", 0);
}
/**
* @deprecated use {@link TLUtils#isTLSimpleNormalizer(DataRecordMetadata[], DataRecordMetadata[], String)} instead
*/
@Deprecated
public static boolean isTLSimpleNormalizer(DataRecordMetadata[] inMeta,
DataRecordMetadata[] outMeta, String transform) {
TransformLangParser parser = new TransformLangParser(inMeta, outMeta, transform);
CLVFStart record = null;
try {
record = parser.Start();
record.init();
} catch (ParseException e) {
System.out.println("Error when parsing expression: " + e.getMessage().split(System.getProperty("line.separator"))[0]);
return false;
}
return isTLSimpleTransformFunctionNode(record, "transform", 1);
}
/**
* @deprecated use {@link TLUtils#isSimpleFunction(TransformationGraph, DataRecordMetadata[], DataRecordMetadata[], String, String)} instead
*/
@Deprecated
public static boolean isSimpleFunction(TransformationGraph graph, DataRecordMetadata[] inMeta,
DataRecordMetadata[] outMeta, String code, String functionName) {
TLCompiler compiler = new TLCompiler(graph,inMeta,outMeta);
List<ErrorMessage> msgs = compiler.validate(code);
if (compiler.errorCount() > 0) {
for (ErrorMessage msg : msgs) {
System.out.println(msg);
}
System.out.println("CTL code compilation finished with " + compiler.errorCount() + " errors");
return false;
}
final SimpleTransformVerifier verifier = new SimpleTransformVerifier(functionName,compiler.getStart());
return verifier.check();
}
}
|
package fi.hu.cs.titokone;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;
import java.util.logging.Logger;
/** This class keeps track of the settings. It can parse and save settings
file content. It provides support for a standard set of settings, but
basically anything can be stored in it. Keys used in this file cannot
contain KEY_VALUE_SEPARATOR. Whitespace around KEY_VALUE_SEPARATOR is
ignored. */
public class Settings {
private HashMap settings;
/** This string separates keys from values in the settings file.
It cannot be included in the key strings. */
public static final String KEY_VALUE_SEPARATOR = "=";
/** This field stores the comment marker to put before any comment
lines. */
private static final String COMMENT_MARKER = "
/** This pattern matches against 1 or more characters (there is a
start of a line in the start of each String, hence ignore the
first character), then 1 or more periods where there is at
least one start of line (\n\n would match ^^) and then 0 or
more other characters. We assume here that since
Pattern.MULTILINE mode is on by default now, it will be on in
other places as well. */
private static final String LINEBREAK_CHECK_REGEXP = ".+[\n\r\f" +
System.getProperty("line.separator") + "]+.*";
/** This is one of the default settings keys of values that can be
stored here. */
public static final String UI_LANGUAGE = "Language";
public static final String RUN_MODE = "Running mode";
public static final String COMPILE_MODE = "Compilation mode";
public static final String DEFAULT_STDIN = "Stdin file";
public static final String STDIN_PATH = "Stdin path";
public static final String DEFAULT_STDOUT = "Stdout file";
public static final String STDOUT_USE = "Stdout use";
public static final String STDOUT_PATH = "Stdout path";
public static final String MEMORY_SIZE = "Memory size";
/** This constructor sets up a settings class with default values.
The settingsFileContent is parsed with the help fo the
parseSettingsFile() method.
@param settingsFileContent A String containing what has been in
a settings file for parsing.
@throws ParseException If the settings text was not syntactically
correct. */
public Settings(String settingsFileContent) throws ParseException {
settings = new HashMap();
if(settingsFileContent != null)
parseSettingsFile(settingsFileContent);
}
/** This constructor sets up a settings class with no values. */
public Settings() {
settings = new HashMap();
}
public void setValue(String key, String value) {
String expMessage;
String[] parameters = new String[3];
parameters[0] = new Message("value").toString();
if(value == null) {
expMessage = new Message("Illegal {0}: null. Try an empty " +
"string instead.",
parameters).toString();
throw new IllegalArgumentException(expMessage);
}
// Check that the value string does not contain linebreaks
// in other positions than its end.
if(value.matches(LINEBREAK_CHECK_REGEXP + ".+")) {
parameters[1] = value;
parameters[2] = new Message("a linebreak").toString();
expMessage = new Message("Illegal {0} \"{1}\", contains {2}.",
parameters).toString();
throw new IllegalArgumentException(expMessage);
}
doSetValue(key, value);
}
/** This method sets a key to a certain integer value.
@param key The key to point to the value.
@param value The value to be stored. */
public void setValue(String key, int value) {
doSetValue(key, new Integer(value));
}
private void doSetValue(String key, Object value) {
String expMessage;
String[] parameters = new String[3];
parameters[0] = new Message("key").toString();
if(key == null) {
expMessage = new Message("Illegal {0}: null. Try an empty " +
"string instead.", parameters).toString();
throw new IllegalArgumentException(expMessage);
}
// The regular expression below matches any character (.)
// 0 or more times (*) followed by a KEY_VALUE_SEPARATOR,
// followed by any character 0 or more times.
if(key.matches(".*" + KEY_VALUE_SEPARATOR + ".*")) {
parameters[1] = key;
parameters[2] = "'" + KEY_VALUE_SEPARATOR + "'";
expMessage = new Message("Illegal {0} \"{1}\", contains {2}.",
parameters).toString();
throw new IllegalArgumentException(expMessage);
}
if(key.matches(LINEBREAK_CHECK_REGEXP)) {
parameters[1] = key;
parameters[2] = new Message("a linebreak").toString();
expMessage = new Message("Illegal {0} \"{1}\", contains {2}.",
parameters).toString();
throw new IllegalArgumentException(expMessage);
}
settings.put(key, value);
}
/** This method returns the value of a certain key. It will try to
cast it to an integer before returning.
@param key The key pointing to the value to be returned.
@return The value the key points to, cast to an int.
@throws ClassCastException If the value was not an int.
@throws NullPointerException If there was no value stored by that
key (or if the value stored was null for some reason). The
problem is that int cannot be null, while String in getStrValue
can. */
public int getIntValue(String key) {
return ((Integer) settings.get(key)).intValue();
}
/** This method returns the value of a certain key. It will try to
cast it to a string before returning.
@param key The key pointing to the value to be returned.
@return The value the key points to, cast to a String, or null
if there was no such value.
@throws ClassCastException If the value was not a String. */
public String getStrValue(String key) {
return (String) settings.get(key);
}
/** This method returns all the keys defined here. */
public String[] getKeys() {
return (String[]) settings.keySet().toArray(new String[0]);
}
/** This method transforms this settings class into a format which
can be parsed by parseSettingsFile.
@return String containing the non-fixed data in this class. */
public String toString() {
String keyString, valueString;
StringBuffer result;
Object value;
Iterator keyIterator = settings.keySet().iterator();
result = new StringBuffer("");
while(keyIterator.hasNext()) {
keyString = (String) keyIterator.next();
value = settings.get(keyString);
try {
valueString = (String) settings.get(keyString);
}
catch(ClassCastException mustBeAnIntegerThen) {
valueString = "" + ((Integer) value).intValue();
}
result.append(keyString + " " + KEY_VALUE_SEPARATOR + " " +
valueString + System.getProperty("line.separator",
"\n"));
}
return result.toString();
}
/** This method parses the fileContent string and sets up the settings
HashMap values accordingly. It will try to cast number strings to
integers.
@param fileContent A String containing what has been in
a settings file for parsing.
@throws ParseException If the settings text was not syntactically
correct. */
private void parseSettingsFile(String fileContent)
throws ParseException {
String[] parameters = new String[2], rows, parts;
String line, errorMessage, key, valueString;
Logger logger;
// We accept \n,\r and whatever this system uses as a line separator.
// StringTokenizer will not mind matching against eg. \r\r; it will
// be considered the same as \r.
rows = fileContent.split("[\n\r\f" +
System.getProperty("line.separator") +
"]");
for(int i = 0; i < rows.length; i++) {
line = rows[i];
// First, check if it is an empty line or a comment line.
// Ignore those.
// (Trimming does not modify the string.)
if(!line.trim().equals("") && !line.startsWith(COMMENT_MARKER)) {
parts = line.split(KEY_VALUE_SEPARATOR);
// parts.length can be > 2, because KEY_VALUE_SEPARATOR
// is allowed in the value string, even if not in the key
// string.
if(parts.length < 2) {
// Log where we failed and on what.
parameters[0] = "" + (i + 1);
parameters[1] = line;
errorMessage = new Message("Syntax error on line {0}, " +
"which was: \"{1}\".",
parameters).toString();
throw new ParseException(errorMessage, i + 1);
}
else { // Line has 2 (or more) parts as it should.
key = parts[0].trim();
valueString = parts[1].trim();
try {
setValue(key, Integer.parseInt(valueString));
}
catch(NumberFormatException notAnIntegerThen) {
setValue(key, valueString);
}
}
}
}
parameters[0] = "" + rows.length;
parameters[1] = "" + settings.size();
logger = Logger.getLogger(this.getClass().getPackage().getName());
logger.info(new Message("Settings successfully parsed, lines: " +
"{0}, unique keys found: {1}.",
parameters).toString());
}
}
|
package nonregressiontest.descriptor.defaultnodes;
import org.objectweb.proactive.ProActive;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor;
import org.objectweb.proactive.core.descriptor.data.VirtualNode;
import org.objectweb.proactive.core.node.Node;
import testsuite.test.FunctionalTest;
/**
* @author Alexandre di Costanzo
*
*/
public class TestNodes extends FunctionalTest {
private static String XML_LOCATION;
static {
String value = System.getProperty("nonregressiontest.descriptor.defaultnodes.file");
if (value != null) {
XML_LOCATION = TestNodes.class.getResource(
value).getPath();
} else {
XML_LOCATION = TestNodes.class.getResource(
"/nonregressiontest/descriptor/defaultnodes/Nodes.xml").getPath();
}
}
private static String FS = System.getProperty("file.separator");
private static ProActiveDescriptor proActiveDescriptor = null;
private static VirtualNode[] virtualNodes = null;
private static Node sameVMNode = null;
private static Node localVMNode = null;
private static Node remoteVMNode = null;
private static Node remoteACVMNode = null;
private static String remoteHostname = "localhost";
public TestNodes() {
super(" Default deployment descriptor",
" Test reading a descriptor file to create nodes needed by other tests.");
}
/**
* @see testsuite.test.FunctionalTest#action()
*/
public void action() throws Exception {
proActiveDescriptor = ProActive.getProactiveDescriptor("file:" +
XML_LOCATION);
proActiveDescriptor.activateMappings();
TestNodes.virtualNodes = proActiveDescriptor.getVirtualNodes();
for (int i = 0; i < virtualNodes.length; i++) {
VirtualNode virtualNode = virtualNodes[i];
if (virtualNode.getName().compareTo("Dispatcher") == 0) {
sameVMNode = virtualNode.getNode();
} else if (virtualNode.getName().compareTo("Dispatcher1") == 0) {
localVMNode = virtualNode.getNode();
} else if (virtualNode.getName().compareTo("Dispatcher3-AC") == 0) {
remoteACVMNode = virtualNode.getNode();
} else {
remoteVMNode = virtualNode.getNode();
}
}
remoteHostname = remoteVMNode.getNodeInformation().getInetAddress()
.getHostName();
}
/**
* TODO : remove this method, as it is used as a walkaround to use deployed nodes
* outside of the first packageGroup group of the MainManager.xml
* (the endTest() method, that kills all the deployed nodes, is indeed called at the end of each
* group of tests)
*
*/
// COMPONENTS
public Object[] action(Object[] parameters) throws Exception {
action();
return null;
}
/**
* @see testsuite.test.AbstractTest#initTest()
*/
public void initTest() throws Exception {
// nothing to do
}
/**
* @see testsuite.test.AbstractTest#endTest()
*/
public void endTest() throws Exception {
killNodes();
}
public static void killNodes() throws ProActiveException {
if (proActiveDescriptor != null) {
proActiveDescriptor.killall();
proActiveDescriptor = null;
}
}
/**
* @return
*/
public static Node getLocalVMNode() {
return localVMNode;
}
/**
* @return
*/
public static Node getRemoteVMNode() {
return remoteVMNode;
}
/**
* @return
*/
public static Node getSameVMNode() {
return sameVMNode;
}
/**
* @return
*/
public static String getRemoteHostname() {
return remoteHostname;
}
/**
* @return the node with automatic continuations enabled
*/
public static Node getRemoteACVMNode() {
return remoteACVMNode;
}
public static VirtualNode getVirtualNode(String name) {
for (int i = 0; i < virtualNodes.length; i++) {
if (virtualNodes[i].getName().equals(name)) {
return virtualNodes[i];
}
}
return null;
}
}
|
package org.jetel.component;
import static org.jetel.ctl.TransformLangParserTreeConstants.JJTASSIGNMENT;
import static org.jetel.ctl.TransformLangParserTreeConstants.JJTFIELDACCESSEXPRESSION;
import static org.jetel.ctl.TransformLangParserTreeConstants.JJTFUNCTIONDECLARATION;
import static org.jetel.ctl.TransformLangParserTreeConstants.JJTIMPORTSOURCE;
import static org.jetel.ctl.TransformLangParserTreeConstants.JJTRETURNSTATEMENT;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.ctl.ErrorMessage;
import org.jetel.ctl.ITLCompiler;
import org.jetel.ctl.NavigatingVisitor;
import org.jetel.ctl.TLCompiler;
import org.jetel.ctl.TLCompilerFactory;
import org.jetel.ctl.TransformLangExecutor;
import org.jetel.ctl.ASTnode.CLVFBlock;
import org.jetel.ctl.ASTnode.CLVFFieldAccessExpression;
import org.jetel.ctl.ASTnode.SimpleNode;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.graph.Node;
import org.jetel.graph.TransformationGraph;
import org.jetel.graph.runtime.CloverClassPath;
import org.jetel.interpreter.ParseException;
import org.jetel.interpreter.TransformLangParser;
import org.jetel.interpreter.ASTnode.CLVFDirectMapping;
import org.jetel.interpreter.ASTnode.CLVFFunctionDeclaration;
import org.jetel.interpreter.ASTnode.CLVFStart;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.CodeParser;
import org.jetel.util.classloader.GreedyURLClassLoader;
import org.jetel.util.compile.DynamicJavaClass;
import org.jetel.util.file.FileUtils;
import org.jetel.util.property.PropertyRefResolver;
import org.jetel.util.property.RefResFlag;
import org.jetel.util.string.CommentsProcessor;
public class RecordTransformFactory {
public static final int TRANSFORM_JAVA_SOURCE=1;
public static final int TRANSFORM_CLOVER_TL=2;
public static final int TRANSFORM_JAVA_PREPROCESS=3;
public static final int TRANSFORM_CTL = 4;
public static final Pattern PATTERN_CLASS = Pattern.compile("class\\s+\\w+");
public static final Pattern PATTERN_TL_CODE = Pattern.compile("function\\s+((transform)|(generate))");
public static final Pattern PATTERN_CTL_CODE = Pattern.compile("function\\s+[a-z]*\\s+((transform)|(generate))");
public static final Pattern PATTERN_PARTITION_CODE = Pattern.compile("function\\s+getOutputPort");
public static final Pattern PATTERN_CTL_PARTITION_CODE = Pattern.compile("function\\s+[a-z]*\\s+getOutputPort");
public static final Pattern PATTERN_PREPROCESS_1 = Pattern.compile("\\$\\{out\\.");
public static final Pattern PATTERN_PREPROCESS_2 = Pattern.compile("\\$\\{in\\.");
/**
* Verifier class checking if a CTL function only contains direct mappings.
* Direct mapping is an assignment statement where left hand side contains an output field reference.
*
* @author Michal Tomcanyi <michal.tomcanyi@javlin.cz>
*/
private static class SimpleTransformVerifier extends NavigatingVisitor {
private final String functionName;
private final org.jetel.ctl.ASTnode.Node ast;
/**
* Allocates verifier which will verify that the <code>functionName</code>
* contains only simple mappings
*
* @param functionName function to validate
*/
public SimpleTransformVerifier(String functionName, org.jetel.ctl.ASTnode.Node ast) {
this.functionName = functionName;
this.ast = ast;
}
/**
* Scans AST tree for function and checks it only contains direct mappings
* (i.e. assignments where LHS is an output field reference)
*
* @return true if function is simple, false otherwise
*/
public boolean check() {
return (Boolean)ast.jjtAccept(this, null);
}
@Override
public Object visit(org.jetel.ctl.ASTnode.CLVFStart node, Object data) {
// functions can only be declared in start or import nodes
for (int i=0; i<node.jjtGetNumChildren(); i++) {
final SimpleNode child = (SimpleNode)node.jjtGetChild(i);
final int id = child.getId();
switch (id) {
case JJTIMPORTSOURCE:
// scan imports
child.jjtAccept(this, data);
break;
case JJTFUNCTIONDECLARATION:
if (((org.jetel.ctl.ASTnode.CLVFFunctionDeclaration)child).getName().equals(functionName)) {
// scan statements in function body
return child.jjtGetChild(2).jjtAccept(this, data);
}
break;
}
}
return false;
}
@Override
public Object visit(CLVFBlock node, Object data) {
// we must have come here as the block is 'transform' function body
for (int i=0; i<node.jjtGetNumChildren(); i++) {
final SimpleNode child = (SimpleNode)node.jjtGetChild(i);
// statement must be an assignment and a direct mapping into output field
if (child.getId() != JJTASSIGNMENT && child.getId() != JJTRETURNSTATEMENT) {
// not an assignment - fail quickly
return false;
}
if (child.getId() != JJTRETURNSTATEMENT) {
// check if direct mapping
final SimpleNode lhs = (SimpleNode)child.jjtGetChild(0);
if (lhs.getId() != JJTFIELDACCESSEXPRESSION
|| ((CLVFFieldAccessExpression) lhs).isWildcard()) { //'$0.* = ...' is also prohibited
// not a mapping
return false;
}
}
}
// all statements are direct mappings
return true;
}
}
/**
*
* @param transform
* @param transformClass
* @param transformURL
* @param charset
* @param node
* @param inMetadata
* @param outMetadata
* @param transformationParameters
* @param classLoader
* @param classPath
* @return
* @throws ComponentNotReadyException
*/
public static RecordTransform createTransform(String transform, String transformClass, String transformURL,
String charset, Node node, DataRecordMetadata[] inMetadata, DataRecordMetadata[] outMetadata,
ClassLoader classLoader, CloverClassPath classPath) throws ComponentNotReadyException {
//if classpath wasn't passed, empty one is automatically prepared
if (classPath == null) {
classPath = new CloverClassPath();
}
// create transformation
RecordTransform transformation = null;
Log logger = LogFactory.getLog(node.getClass());
//without these parameters we cannot create transformation
if(transform == null && transformClass == null && transformURL == null) {
throw new ComponentNotReadyException("Record transformation is not defined.");
}
//resolve references at given transformation string
if (transform != null) {
PropertyRefResolver refResolver= new PropertyRefResolver(node.getGraph().getGraphProperties());
transform = refResolver.resolveRef(transform, RefResFlag.SPEC_CHARACTERS_OFF);
}
if (transformClass != null) {
//get transformation from link to the compiled class
transformation = (RecordTransform)RecordTransformFactory.loadClass(classLoader, logger,
transformClass, null, classPath);
}else if (transform == null && transformURL != null){
transform = FileUtils.getStringFromURL(node.getGraph().getRuntimeContext().getContextURL(), transformURL, charset);
PropertyRefResolver refResolver= new PropertyRefResolver(node.getGraph().getGraphProperties());
transform = refResolver.resolveRef(transform, RefResFlag.SPEC_CHARACTERS_OFF);
}
if (transformClass == null) {
switch (guessTransformType(transform)) {
case TRANSFORM_JAVA_SOURCE:
// try compile transform parameter as java code
// try preprocessing if applicable
transformation = (RecordTransform)RecordTransformFactory.loadClassDynamic(
logger, null, transform, inMetadata, outMetadata, classLoader, classPath, false);
break;
case TRANSFORM_CLOVER_TL:
transformation = new RecordTransformTL(transform, logger);
break;
case TRANSFORM_CTL:
final ITLCompiler compiler =
TLCompilerFactory.createCompiler(node.getGraph(),inMetadata,outMetadata,"UTF-8");
List<ErrorMessage> msgs = compiler.compile(transform, CTLRecordTransform.class, node.getId());
if (compiler.errorCount() > 0) {
String report = ErrorMessage.listToString(msgs, logger);
throw new ComponentNotReadyException("CTL code compilation finished with " + compiler.errorCount() + " errors" + report);
}
Object ret = compiler.getCompiledCode();
if (ret instanceof TransformLangExecutor) {
// setup interpreted runtime
transformation = new CTLRecordTransformAdapter((TransformLangExecutor)ret, logger);
} else if (ret instanceof RecordTransform){
transformation = (RecordTransform)ret;
} else {
// this should never happen as compiler always generates correct interface
throw new ComponentNotReadyException("Invalid type of record transformation");
}
break;
case TRANSFORM_JAVA_PREPROCESS:
transformation = (RecordTransform)RecordTransformFactory.loadClassDynamic(logger,
"Transform" + node.getId(), transform, inMetadata, outMetadata, classLoader,
classPath, true);
break;
default:
// logger.error("Can't determine transformation code type at
// component ID :"+node.getId());
throw new ComponentNotReadyException(
"Can't determine transformation code type at component ID :" + node.getId());
}
}
transformation.setNode(node);
return transformation;
}
/**
* @param parentClassLoader
* @param logger
* @param transformClassName
* @param libraryPaths
* @return
* @throws ComponentNotReadyException
*/
public static Object loadClass(ClassLoader parentClassLoader, Log logger,
String transformClassName, URL contextURL, CloverClassPath classPath)
throws ComponentNotReadyException {
Object instance = null;
// try to load in transformation class & instantiate
try {
instance = Class.forName(transformClassName).newInstance();
}catch(InstantiationException ex){
throw new ComponentNotReadyException("Can't instantiate transformation class: "+ex.getMessage());
}catch(IllegalAccessException ex){
throw new ComponentNotReadyException("Can't instantiate transformation class: "+ex.getMessage());
}catch (ClassNotFoundException ex) {
// let's try to load in any additional .jar library (if specified)
if (classPath.getRuntimeClassPath() == null) {
throw new ComponentNotReadyException(
"Can't find specified transformation class: "
+ transformClassName);
}
try {
URLClassLoader classLoader = new GreedyURLClassLoader(classPath.getRuntimeClassPath(), parentClassLoader);
instance = Class.forName(transformClassName, true, classLoader).newInstance();
} catch (ClassNotFoundException ex1) {
throw new ComponentNotReadyException("Can not find class: " + ex1);
} catch (Exception ex3) {
throw new ComponentNotReadyException(ex3.getMessage(), ex3);
} catch (NoClassDefFoundError err) {
throw new ComponentNotReadyException(err.getMessage(), new RuntimeException(err));
}
}
return instance;
}
/**
* @param logger
* @param className
* @param transformCode
* @param inMetadata
* @param outMetadata
* @return
* @throws ComponentNotReadyException
*/
public static RecordTransform loadClassDynamic(Log logger, String className, String transformCode,
DataRecordMetadata[] inMetadata, DataRecordMetadata[] outMetadata, ClassLoader classLoader,
CloverClassPath classPath, boolean addTransformCodeStub) throws ComponentNotReadyException {
// creating dynamicTransformCode from internal transformation format
CodeParser codeParser = new CodeParser(inMetadata, outMetadata);
if (!addTransformCodeStub)
// we must turn this off, because we don't have control about the rest of Java source
// and thus we cannot create the declaration of symbolic constants
codeParser.setUseSymbolicNames(false);
codeParser.setSourceCode(transformCode);
codeParser.parse();
if (addTransformCodeStub)
codeParser.addTransformCodeStub("Transform" + className);
return loadClassDynamic(codeParser.getSourceCode(), classLoader, classPath);
}
/**
* @param logger
* @param dynamicTransformCode
* @return
* @throws ComponentNotReadyException
*/
public static RecordTransform loadClassDynamic(String sourceCode, ClassLoader classLoader, CloverClassPath classPath)
throws ComponentNotReadyException {
Object transObject = DynamicJavaClass.instantiate(sourceCode, classLoader, classPath.getCompileClassPath());
if (transObject instanceof RecordTransform) {
return (RecordTransform) transObject;
}
throw new ComponentNotReadyException("Provided transformation class doesn't implement RecordTransform.");
}
private static Pattern getPattern(String hashBang) {
return Pattern.compile("^\\s*" + hashBang);
}
/**
* Guesses type of transformation code based on
* code itself - looks for certain patterns within the code
*
* @param transform
* @return guessed transformation type or -1 if can't determine
*/
public static int guessTransformType(String transform){
String commentsStripped = CommentsProcessor.stripComments(transform);
// First, try to identify the starting string
if (getPattern(WrapperTL.TL_TRANSFORM_CODE_ID).matcher(transform).find() ||
getPattern(WrapperTL.TL_TRANSFORM_CODE_ID2).matcher(transform).find()) {
return TRANSFORM_CLOVER_TL;
}
if (getPattern(TransformLangExecutor.CTL_TRANSFORM_CODE_ID).matcher(transform).find()) {
// new CTL implementation
return TRANSFORM_CTL;
}
if (PATTERN_CTL_CODE.matcher(commentsStripped).find()
|| PATTERN_CTL_PARTITION_CODE.matcher(commentsStripped).find()){
// clover internal transformation language
return TRANSFORM_CTL;
}
if (PATTERN_TL_CODE.matcher(commentsStripped).find()
|| PATTERN_PARTITION_CODE.matcher(commentsStripped).find()){
// clover internal transformation language
return TRANSFORM_CLOVER_TL;
}
if (PATTERN_CLASS.matcher(commentsStripped).find()){
// full java source code
return TRANSFORM_JAVA_SOURCE;
}
if (PATTERN_PREPROCESS_1.matcher(commentsStripped).find() ||
PATTERN_PREPROCESS_2.matcher(commentsStripped).find() ){
// semi-java code which has to be preprocessed
return TRANSFORM_JAVA_PREPROCESS;
}
return -1;
}
// Following old TL parser functions are now deprecated
@Deprecated
private static boolean isTLSimpleTransformFunctionNode(CLVFStart record, String functionName, int functionParams) {
int numTopChildren = record.jjtGetNumChildren();
/* Detection of simple mapping inside transform(idx) function */
if (record.jjtHasChildren()) {
for (int i = 0; i < numTopChildren; i++) {
org.jetel.interpreter.ASTnode.Node node = record.jjtGetChild(i);
if (node instanceof org.jetel.interpreter.ASTnode.CLVFFunctionDeclaration) {
if (((CLVFFunctionDeclaration)node).name.equals(functionName)) {
CLVFFunctionDeclaration transFunction = (CLVFFunctionDeclaration)node;
if (transFunction.numParams != functionParams)
return false;
int numTransChildren = transFunction.jjtGetNumChildren();
for (int j = 0; j < numTransChildren; j++) {
org.jetel.interpreter.ASTnode.Node fNode = transFunction.jjtGetChild(j);
if (!(fNode instanceof CLVFDirectMapping)) {
// System.out.println("Function transform(idx) must contain direct mappings only");
return false;
}
}
return true;
}
}
}
}
return false;
}
@Deprecated
public static boolean isTLSimpleTransform(DataRecordMetadata[] inMeta,
DataRecordMetadata[] outMeta, String transform) {
return isTLSimpleFunction(inMeta, outMeta, transform, "transform");
}
@Deprecated
public static boolean isTLSimpleFunction(DataRecordMetadata[] inMeta,
DataRecordMetadata[] outMeta, String transform, String funtionName) {
TransformLangParser parser = new TransformLangParser(inMeta, outMeta, transform);
CLVFStart record = null;
try {
record = parser.Start();
record.init();
} catch (ParseException e) {
System.out.println("Error when parsing expression: " + e.getMessage().split(System.getProperty("line.separator"))[0]);
return false;
}
return isTLSimpleTransformFunctionNode(record, funtionName, 0);
}
@Deprecated
public static boolean isTLSimpleDenormalizer(DataRecordMetadata[] inMeta,
DataRecordMetadata[] outMeta, String transform) {
TransformLangParser parser = new TransformLangParser(inMeta, outMeta, transform);
CLVFStart record = null;
try {
record = parser.Start();
record.init();
} catch (ParseException e) {
System.out.println("Error when parsing expression: " + e.getMessage().split(System.getProperty("line.separator"))[0]);
return false;
}
return isTLSimpleTransformFunctionNode(record, "transform", 0);
}
@Deprecated
public static boolean isTLSimpleNormalizer(DataRecordMetadata[] inMeta,
DataRecordMetadata[] outMeta, String transform) {
TransformLangParser parser = new TransformLangParser(inMeta, outMeta, transform);
CLVFStart record = null;
try {
record = parser.Start();
record.init();
} catch (ParseException e) {
System.out.println("Error when parsing expression: " + e.getMessage().split(System.getProperty("line.separator"))[0]);
return false;
}
return isTLSimpleTransformFunctionNode(record, "transform", 1);
}
public static boolean isSimpleFunction(TransformationGraph graph, DataRecordMetadata[] inMeta,
DataRecordMetadata[] outMeta, String code, String functionName) {
TLCompiler compiler = new TLCompiler(graph,inMeta,outMeta);
List<ErrorMessage> msgs = compiler.validate(code);
if (compiler.errorCount() > 0) {
for (ErrorMessage msg : msgs) {
System.out.println(msg);
}
System.out.println("CTL code compilation finished with " + compiler.errorCount() + " errors");
return false;
}
final SimpleTransformVerifier verifier = new SimpleTransformVerifier(functionName,compiler.getStart());
return verifier.check();
}
}
|
package com.db.autoupdater.basic;
import java.net.URL;
import com.db.autoupdater.AutoUpdateable;
import com.db.autoupdater.AutoUpdater;
import com.db.event.EventDelegate;
import com.db.event.EventObject;
import com.db.jar.SignedJarClassLoader;
import com.db.jar.SignedJarVerifier;
import com.db.logging.Logger;
import com.db.logging.LoggerManager;
import com.db.util.ConfigFile;
import com.db.util.ConfigOptions;
import com.db.util.MethodInvoker;
import com.db.util.JobDispatcher;
public abstract class AbstractAutoUpdater implements AutoUpdater
{
/**
* A JobDispatcher for sending arguments to the running
* AutoUpdateable application.
*/
protected JobDispatcher mArgumentDispatcher;
/**
* The currently running AutoUpdateable application.
*/
protected AutoUpdateable mRunningAutoUpdateable;
/**
* Gets the configuration options used to load the current
* AutoUpdateable application.
*/
protected ConfigOptions mAutoUpdateableConfig;
/**
* Set to true when this AutoUpdater requires a reload, false otherwise.
*/
protected boolean mRequiresReload;
/**
* Set to true when this AutoUpdater requires a new loader, false otherwise.
*/
protected boolean mRequiresNewLoader;
/**
* True while processing an update, false otherwise.
*/
protected boolean mProcessingUpdate;
/**
* True when this AutoUpdater should automatically check for updates, false
* when it should not.
*/
protected boolean mAutoCheckForUpdate;
/**
* The number of milliseconds to sleep in between automatic update checks.
*/
protected long mAutoCheckForUpdateInterval;
/**
* A reference to the auto update checker thread.
*/
protected Thread mAutoCheckThread;
/**
* An event delegate for check for update started events.
*/
protected EventDelegate mCheckForUpdateStartedEventDelegate;
/**
* An event delegate for update script found events.
*/
protected EventDelegate mUpdateScriptFoundEventDelegate;
/**
* An event delegate for update script not found events.
*/
protected EventDelegate mUpdateScriptNotFoundEventDelegate;
/**
* An event delegate for update script completed events.
*/
protected EventDelegate mUpdateScriptCompletedEventDelegate;
/**
* An event delegate for update script cancelled events.
*/
protected EventDelegate mUpdateScriptCancelledEventDelegate;
/**
* An event delegate for update script failed events.
*/
protected EventDelegate mUpdateScriptFailedEventDelegate;
/**
* An event delegate for update script reverted events.
*/
protected EventDelegate mUpdateScriptRevertedEventDelegate;
/**
* An event delegate for update script revert failed events.
*/
protected EventDelegate mUpdateScriptRevertFailedEventDelegate;
/**
* An event delegate for update script processed events.
*/
protected EventDelegate mUpdateScriptProcessedEventDelegate;
/**
* An event delegate for execute application events.
*/
protected EventDelegate mExecuteApplicationEventDelegate;
/**
* An event delegate for shutdown application events.
*/
protected EventDelegate mShutdownApplicationEventDelegate;
/**
* An event delegate for application shutdown events.
*/
protected EventDelegate mApplicationShutdownEventDelegate;
/**
* Creates a new AutoUpdater.
*/
public AbstractAutoUpdater()
{
// create the argument dispatcher
mArgumentDispatcher = new JobDispatcher();
// no auto-updateable application is presently running
setRunningAutoUpdateable(null);
// no configuration for the auto-updateable application yet
setAutoUpdateableConfig(null);
// no reload required by default
setRequiresReload(false);
// no new loader required by default
setRequiresNewLoader(false);
// not processing an update by default
setProcessingUpdate(false);
// do not auto check for updates by default
setAutoCheckForUpdate(false);
// default the auto check interval to 30 minutes (1800000 milliseconds)
setAutoCheckForUpdateInterval(1800000);
// create check for update started event delegate
mCheckForUpdateStartedEventDelegate = new EventDelegate();
// create update script found event delegate
mUpdateScriptFoundEventDelegate = new EventDelegate();
// create update script not found event delegate
mUpdateScriptNotFoundEventDelegate = new EventDelegate();
// create update script completed delegate
mUpdateScriptCompletedEventDelegate = new EventDelegate();
// create update script cancelled delegate
mUpdateScriptCancelledEventDelegate = new EventDelegate();
// create update script failed delegate
mUpdateScriptFailedEventDelegate = new EventDelegate();
// create update script reverted delegate
mUpdateScriptRevertedEventDelegate = new EventDelegate();
// create update script revert failed delegate
mUpdateScriptRevertFailedEventDelegate = new EventDelegate();
// create update script processed delegate
mUpdateScriptProcessedEventDelegate = new EventDelegate();
// create execute application event delegate
mExecuteApplicationEventDelegate = new EventDelegate();
// create shutdown application event delegate
mShutdownApplicationEventDelegate = new EventDelegate();
// create application shutdown delegate
mApplicationShutdownEventDelegate = new EventDelegate();
}
/**
* Fires a check for update started event.
*
* @param event the event to fire.
*/
protected void fireCheckForUpdateStartedEvent(EventObject event)
{
mCheckForUpdateStartedEventDelegate.fireEvent(event);
}
/**
* Fires an update script found event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptFoundEvent(EventObject event)
{
mUpdateScriptFoundEventDelegate.fireEvent(event);
}
/**
* Fires an update script not found event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptNotFoundEvent(EventObject event)
{
mUpdateScriptNotFoundEventDelegate.fireEvent(event);
}
/**
* Fires an update script completed event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptCompletedEvent(EventObject event)
{
mUpdateScriptCompletedEventDelegate.fireEvent(event);
}
/**
* Fires an update script cancelled event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptCancelledEvent(EventObject event)
{
mUpdateScriptCancelledEventDelegate.fireEvent(event);
}
/**
* Fires an update script failed event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptFailedEvent(EventObject event)
{
mUpdateScriptFailedEventDelegate.fireEvent(event);
}
/**
* Fires an update script reverted event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptRevertedEvent(EventObject event)
{
mUpdateScriptRevertedEventDelegate.fireEvent(event);
}
/**
* Fires an update script revert failed event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptRevertFailedEvent(EventObject event)
{
mUpdateScriptRevertFailedEventDelegate.fireEvent(event);
}
/**
* Fires an update script processed event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptProcessedEvent(EventObject event)
{
mUpdateScriptProcessedEventDelegate.fireEvent(event);
}
/**
* Fires an execute application event.
*
* @param event the event to fire.
*/
protected void fireExecuteApplicationEvent(EventObject event)
{
mExecuteApplicationEventDelegate.fireEvent(event);
}
/**
* Fires a shutdown application event.
*
* @param event the event to fire.
*/
protected void fireShutdownApplicationEvent(EventObject event)
{
mShutdownApplicationEventDelegate.fireEvent(event);
}
/**
* Fires an application shutdown event.
*
* @param event the event to fire.
*/
protected void fireApplicationShutdownEvent(EventObject event)
{
mApplicationShutdownEventDelegate.fireEvent(event);
}
/**
* Sets the currently running AutoUpdateable application.
*
* @param application the auto-updateable application that is currently
* running.
*/
protected synchronized void setRunningAutoUpdateable(
AutoUpdateable application)
{
mRunningAutoUpdateable = application;
if(application != null)
{
// start dispatching arguments
getArgumentDispatcher().startDispatching();
try
{
// wait until all of the arguments have been dispatched
while(getArgumentDispatcher().getQueuedJobCount() > 0)
{
Thread.sleep(1);
}
}
catch(InterruptedException e)
{
// ensure current thread is still interrupted
Thread.currentThread().interrupt();
}
}
else
{
// stop dispatching arguments
getArgumentDispatcher().stopDispatching();
// terminate all running jobs
getArgumentDispatcher().terminateAllRunningJobs();
}
}
/**
* Gets the currently running AutoUpdateable application.
*
* @return the currently running auto-updateable application, or null
* if none is running.
*/
protected synchronized AutoUpdateable getRunningAutoUpdateable()
{
return mRunningAutoUpdateable;
}
/**
* Sets the configuration options for the current AutoUpdateable application.
*
* @param config the configuration options for the current AutoUpdateable
* application.
*/
protected synchronized void setAutoUpdateableConfig(ConfigOptions config)
{
mAutoUpdateableConfig = config;
}
/**
* Gets the configuration options for the current AutoUpdateable application.
*
* @return the configuration options for the current AutoUpdateable
* application.
*/
protected synchronized ConfigOptions getAutoUpdateableConfig()
{
return mAutoUpdateableConfig;
}
/**
* Gets the version of the current AutoUpdateable application.
*
* @return the version of the current AutoUpdateable application.
*/
protected synchronized String getAutoUpdateableVersion()
{
String version = "";
if(getAutoUpdateableConfig() != null)
{
version = getAutoUpdateableConfig().getString(
"autoupdateable-version");
}
return version;
}
/**
* Gets the argument dispatcher for sending arguments to the
* running AutoUpdateable.
*
* @return the argument dispatcher.
*/
protected JobDispatcher getArgumentDispatcher()
{
return mArgumentDispatcher;
}
/**
* Sets whether or not this AutoUpdater requires a reload.
*
* @param reload true if this AutoUpdater requires a reload, false if not.
*/
protected synchronized void setRequiresReload(boolean reload)
{
mRequiresReload = reload;
}
/**
* Sets whether or not this AutoUpdater requires a new AutoUpdaterLoader.
*
* @param newLoader true if this AutoUpdater requires a
* new AutoUpdaterLoader, false if not.
*/
protected synchronized void setRequiresNewLoader(boolean newLoader)
{
mRequiresNewLoader = newLoader;
}
/**
* Sets whether or not this AutoUpdater is processing an update.
*
* @param processing true if this AutoUpdater is processing an update,
* false if not.
*/
protected synchronized void setProcessingUpdate(boolean processing)
{
mProcessingUpdate = processing;
}
/**
* Sets whether or not this AutoUpdater should automatically check
* for updates.
*
* @param check true if this AutoUpdater should automatically check for
* updates, false if not.
*/
protected void setAutoCheckForUpdate(boolean check)
{
mAutoCheckForUpdate = check;
}
/**
* Gets whether or not this AutoUpdater should automatically check
* for updates.
*
* @return true if this AutoUpdater should automatically check for
* updates, false if not.
*/
protected boolean shouldAutoCheckForUpdate()
{
return mAutoCheckForUpdate;
}
/**
* Checks for an update for the given application.
*
* @param application the application to check for updates of.
*
* @return true if an update was processed, false if not.
*/
protected synchronized boolean checkForUpdate(AutoUpdateable application)
{
boolean rval = false;
// fire a check for update started event
EventObject event = new EventObject("checkForUpdateStarted");
fireCheckForUpdateStartedEvent(event);
// get the update script source
UpdateScriptSource source = getUpdateScriptSource();
// check for an update script
if(source.hasUpdateScript(application))
{
// get the update script
UpdateScript script = source.getUpdateScript(application);
// validate the script
if(script.validate())
{
// fire event indicating that an update script has been found
event = new EventObject("updateScriptFound");
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" + script.getClass().getName());
event.setData("processUpdate", false);
event.setDataKeyMessage("processUpdate",
"A boolean if set to true tells the AutoUpdater to " +
"process the update script.");
fireUpdateScriptFoundEvent(event);
// see if the update should be processed
if(event.getDataBooleanValue("processUpdate"))
{
// process update script
rval = true;
processUpdateScript(application, script);
}
}
else
{
// fire event indicating that an update script has not been found
event = new EventObject("updateScriptNotFound");
fireUpdateScriptNotFoundEvent(event);
}
}
else
{
// fire event indicating that an update script has not been found
event = new EventObject("updateScriptNotFound");
fireUpdateScriptNotFoundEvent(event);
}
return rval;
}
/**
* Shutsdown any running application and processes an update script.
*
* @param application the application that is running.
* @param script the update script to process.
*/
protected synchronized void processUpdateScript(
AutoUpdateable application, UpdateScript script)
{
// ensure this thread is not interrupted
if(!Thread.currentThread().isInterrupted())
{
// now processing an update
setProcessingUpdate(true);
// fire event indicating the auto-updateable application is
// getting shutdown
EventObject event = new EventObject("shutdownApplication");
event.setData("cancel", false);
event.setDataKeyMessage("cancel",
"A boolean if set to true cancels application shutdown.");
fireShutdownApplicationEvent(event);
// make sure shutdown was not cancelled
if(!event.getDataBooleanValue("cancel"))
{
// shutdown the application
application.shutdown();
// fire event indicating the auto-updateable application has been
// shutdown
event = new EventObject("applicationShutdown");
fireApplicationShutdownEvent(event);
// process the script
boolean success = script.process();
// set whether or not this AutoUpdater requires a reload
setRequiresReload(script.autoUpdaterRequiresReload());
if(success)
{
// script processing was successful
// fire event indicating an update script was completed
event = new EventObject("updateScriptCompleted");
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" + script.getClass().getName());
fireUpdateScriptCompletedEvent(event);
}
else
{
// script processing was cancelled or there was an error
// create a new event to fire
event = new EventObject();
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" + script.getClass().getName());
event.setData("revert", true);
event.setDataKeyMessage("revert",
"A boolean if set true will tell the AutoUpdater to" +
"revert the update script.");
// fire event indicating an update script was cancelled or
// failed and will now be reverted unless cancelled
if(script.cancelled())
{
event.setName("updateScriptCancelled");
fireUpdateScriptCancelledEvent(event);
}
else
{
event.setName("updateScriptFailed");
fireUpdateScriptFailedEvent(event);
}
if(event.getDataBooleanValue("revert"))
{
// attempt to revert script
if(script.revert())
{
// fire event indicating an update script was reverted
event = new EventObject("updateScriptReverted");
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" +
script.getClass().getName());
fireUpdateScriptRevertedEvent(event);
}
else
{
// fire event indicating an update script revert failed
event = new EventObject("updateScriptRevertFailed");
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" +
script.getClass().getName());
fireUpdateScriptRevertFailedEvent(event);
}
// set whether or not this AutoUpdater requires a reload
setRequiresReload(script.autoUpdaterRequiresReload());
}
}
// no longer processing an update
setProcessingUpdate(false);
// fire event indicating an update script was processed
event = new EventObject("updateScriptProcessed");
event.setData("updateScript", script);
event.setDataKeyMessage("updateScript",
"The update script, class=" + script.getClass().getName());
fireUpdateScriptProcessedEvent(event);
}
}
}
/**
* Loads an AutoUpdateable application from the passed configuration.
*
* @param config the configuration to load an AutoUpdateable application
* from.
*
* @return the AutoUpdateable application or null if one could not be loaded.
*/
protected synchronized AutoUpdateable loadAutoUpdateable(
ConfigOptions config)
{
AutoUpdateable rval = null;
// get the class name for the AutoUpdateable
String className = config.getString("autoupdateable-class");
// get the jars necessary to load the AutoUpdateable interface
String classPath = config.getString("autoupdateable-classpath");
// get the keystore necessary to load the AutoUpdateable interface
String keystore = config.getString("autoupdateable-keystore");
// get the keystore plain text password
String password = config.getString("autoupdateable-keystore-password");
// get the keystore aliases
String aliasList = config.getString("autoupdateable-keystore-aliases");
String[] aliases = aliasList.split(",");
try
{
// build the url array for the class path
URL[] urls = new URL[0];
if(classPath != null && classPath.length() > 0)
{
// split class path for urls
String[] split = classPath.split(",");
// build url list
urls = new URL[split.length];
for(int i = 0; i < urls.length; i++)
{
urls[i] = new URL(split[i]);
}
}
// create a SignedJarVerifier
SignedJarVerifier verifier = new SignedJarVerifier(
keystore, password, aliases, true);
// create a SignedJarClassLoader for the AutoUpdateable
ClassLoader classLoader = new SignedJarClassLoader(
urls, getClass().getClassLoader(), verifier);
// load the AutoUpdateable
Class c = classLoader.loadClass(className);
rval = (AutoUpdateable)c.newInstance();
// set the auto-updateable configuration
setAutoUpdateableConfig(config);
}
catch(Throwable t)
{
getLogger().error(getClass(),
"Could not load AutoUpdateable application!" +
",class=" + className +
",classpath=" + classPath);
getLogger().debug(getClass(), Logger.getStackTrace(t));
}
return rval;
}
/**
* Runs an application while monitoring for updates in a background process.
*
* @param application the auto-updateable application to execute.
*/
protected void run(AutoUpdateable application)
{
// check for an update, start the application if there isn't one
if(!checkForUpdate(application))
{
// set automatic check flag to true
setAutoCheckForUpdate(true);
// start the update checker thread
Object[] params = new Object[]{application};
MethodInvoker updateChecker =
new MethodInvoker(this, "continuouslyCheckForUpdate", params);
mAutoCheckThread = updateChecker;
updateChecker.backgroundExecute();
// fire event indicating that the auto-updateable application
// is being executed
EventObject event = new EventObject("executeApplication");
event.setData("cancel", false);
event.setDataKeyMessage("cancel",
"A boolean if set to true cancels application execution.");
fireExecuteApplicationEvent(event);
// see if application execution should be cancelled
if(!event.getDataBooleanValue("cancel"))
{
// execute application
application.execute();
}
try
{
// sleep while the application is running
while(application.isRunning())
{
Thread.sleep(1);
}
// interrupt update checker thread if not processing an update
if(!isProcessingUpdate())
{
updateChecker.interrupt();
}
// set automatic check flag to false
setAutoCheckForUpdate(false);
// join the update checker thread
updateChecker.join();
}
catch(InterruptedException e)
{
// interrupt threads
updateChecker.interrupt();
Thread.currentThread().interrupt();
}
// ensure automatic check flag is set to false
setAutoCheckForUpdate(false);
}
}
/**
* Gets the configuration filename for the auto-updateable.
*
* @return the configuration filename for the auto-updateable.
*/
protected abstract String getConfigFilename();
/**
* Overridden to terminate the auto update checker thread.
*/
public void finalize()
{
setAutoCheckForUpdate(false);
if(mAutoCheckThread != null)
{
// make sure to interrupt the auto check thread
mAutoCheckThread.interrupt();
}
}
/**
* This method is provided for convenience. It can be overloaded to
* pause the current thread for some period of time. Another way to
* pause between update checks is to handle the checkForUpdateStarted
* event by pausing.
*
* Causes the update checker thread to pause for some period of time
* before checking for an update. The default period of time is
* 30 seconds.
*
* Throws an InterruptedException if the thread is interrupted while
* sleeping.
*
* @exception InterruptedException
*/
public void pauseUpdateCheckerThread() throws InterruptedException
{
if(getAutoCheckForUpdateInterval() > 0)
{
Thread.sleep(getAutoCheckForUpdateInterval());
}
}
/**
* Continuously checks for an update for the given application.
*
* @param application the application to check for updates of.
*/
public void continuouslyCheckForUpdate(AutoUpdateable application)
{
try
{
while(shouldAutoCheckForUpdate())
{
// pause this thread
pauseUpdateCheckerThread();
// check for an update for the application
if(shouldAutoCheckForUpdate() &&
!Thread.currentThread().isInterrupted())
{
// check for an update if the auto check interval is positive
if(getAutoCheckForUpdateInterval() > 0)
{
checkForUpdate(application);
}
}
}
}
catch(InterruptedException e)
{
// interrupt thread
Thread.currentThread().interrupt();
}
}
/**
* Runs the AutoUpdateable application.
*
* @param args the arguments to start the application with.
*
* @return true if the AutoUpdateable application should be restarted,
* false if not.
*/
public boolean runAutoUpdateable(String[] args)
{
boolean rval = false;
// get the AutoUpdateable application's config file
ConfigFile configFile = new ConfigFile(getConfigFilename());
if(configFile.read())
{
rval = runAutoUpdateable(configFile, args);
}
else
{
getLogger().error(getClass(),
"Could not read AutoUpdateable configuration file!" +
",filename=" + getConfigFilename());
}
return rval;
}
/**
* Runs the AutoUpdateable application specified the in the AutoUpdateable
* configuration.
*
* @param config the configuration to load an AutoUpdateable
* application from.
* @param args the arguments to start the application with.
*
* @return true if the AutoUpdateable application should be restarted,
* false if not.
*/
public boolean runAutoUpdateable(ConfigOptions config, String[] args)
{
boolean rval = true;
// keep running the AutoUpdateable application while it should
// restart and a reload of this AutoUpdater is not required
while(rval && !requiresReload())
{
// load the AutoUpdateable application
AutoUpdateable application = loadAutoUpdateable(config);
if(application != null)
{
// process the arguments
application.processArguments(args);
// set running AutoUpdateable
setRunningAutoUpdateable(application);
// run the application
run(application);
// AutoUpdateable no longer running
setRunningAutoUpdateable(null);
// see if the application should not restart
if(!application.shouldRestart())
{
// application should not restart
rval = false;
}
// clean up AutoUpdateable application
application = null;
System.gc();
}
else
{
// do not run application -- it can't be loaded
rval = false;
}
}
return rval;
}
/**
* Dispatches arguments to the currently running AutoUpdateable application.
*
* This method is called from by the argument dispatcher.
*
* @param args the arguments to dispatch.
*/
public void dispatchArguments(String[] args)
{
// get the currently running AutoUpdateable
AutoUpdateable application = getRunningAutoUpdateable();
if(application != null)
{
// process the arguments
application.processArguments(args);
}
}
/**
* Passes arguments to a running AutoUpdateable application.
*
* @param args the arguments to pass to a running AutoUpdateable application.
*/
public void passArguments(String[] args)
{
// create a runnable job for dispatching the arguments
MethodInvoker job = new MethodInvoker(
this, "dispatchArguments", new Object[]{args});
// queue the job
getArgumentDispatcher().queueJob(job);
}
/**
* Gets the check for update started event delegate.
*
* @return the check for update started event delegate.
*/
public EventDelegate getCheckForUpdateStartedEventDelegate()
{
return mCheckForUpdateStartedEventDelegate;
}
/**
* Gets the update script found event delegate.
*
* @return the update script found event delegate.
*/
public EventDelegate getUpdateScriptFoundEventDelegate()
{
return mUpdateScriptFoundEventDelegate;
}
/**
* Gets the update script not found event delegate.
*
* @return the update script not found event delegate.
*/
public EventDelegate getUpdateScriptNotFoundEventDelegate()
{
return mUpdateScriptNotFoundEventDelegate;
}
/**
* Gets the update script completed event delegate.
*
* @return the update script completed event delegate.
*/
public EventDelegate getUpdateScriptCompletedEventDelegate()
{
return mUpdateScriptCompletedEventDelegate;
}
/**
* Gets the update script cancelled event delegate.
*
* @return the update script cancelled event delegate.
*/
public EventDelegate getUpdateScriptCancelledEventDelegate()
{
return mUpdateScriptCancelledEventDelegate;
}
/**
* Gets the update script failed event delegate.
*
* @return the update script failed event delegate.
*/
public EventDelegate getUpdateScriptFailedEventDelegate()
{
return mUpdateScriptFailedEventDelegate;
}
/**
* Gets the update script reverted event delegate.
*
* @return the update script reverted event delegate.
*/
public EventDelegate getUpdateScriptRevertedEventDelegate()
{
return mUpdateScriptRevertedEventDelegate;
}
/**
* Gets the update script revert failed event delegate.
*
* @return the update script revert failed event delegate.
*/
public EventDelegate getUpdateScriptRevertFailedEventDelegate()
{
return mUpdateScriptRevertFailedEventDelegate;
}
/**
* Gets the update script processed event delegate.
*
* @return the update script processed event delegate.
*/
public EventDelegate getUpdateScriptProcessedEventDelegate()
{
return mUpdateScriptProcessedEventDelegate;
}
/**
* Gets the execute application event delegate.
*
* @return the execute application event delegate.
*/
public EventDelegate getExecuteApplicationEventDelegate()
{
return mExecuteApplicationEventDelegate;
}
/**
* Gets the shutdown application event delegate.
*
* @return the shutdown application event delegate.
*/
public EventDelegate getShutdownApplicationEventDelegate()
{
return mShutdownApplicationEventDelegate;
}
/**
* Gets the application shutdown event delegate.
*
* @return the application shutdown event delegate.
*/
public EventDelegate getApplicationShutdownEventDelegate()
{
return mApplicationShutdownEventDelegate;
}
/**
* Gets whether or not this AutoUpdater requires a reload.
*
* This method should return true whenever this AutoUpdater must
* be reloaded because its core libraries (i.e. classes/jars
* necessary to load this AutoUpdater) have changed via an update but the
* AutoUpdater can be reloaded.
*
* @return true if this AutoUpdater requires a reload, false if not.
*/
public synchronized boolean requiresReload()
{
return mRequiresReload;
}
/**
* Gets whether or not this AutoUpdater requires a shutdown.
*
* This method should return true whenever an update has changed this
* AutoUpdater in such a way that it requires a new AutoUpdaterLoader
* to be loaded again.
*
* @return true if this AutoUpdater requires a new loader, false if not.
*/
public synchronized boolean requiresNewLoader()
{
return mRequiresNewLoader;
}
/**
* Gets whether or not this AutoUpdater is processing an update.
*
* @return true if this AutoUpdater is processing an update, false if not.
*/
public synchronized boolean isProcessingUpdate()
{
return mProcessingUpdate;
}
/**
* Sets the number of milliseconds to wait in between automatic update
* checks.
*
* A non-positive return value indicates that no automatic update checks
* will be made.
*
* @param interval the number of milliseconds to wait in between automatic
* update checks.
*/
public void setAutoCheckForUpdateInterval(long interval)
{
mAutoCheckForUpdateInterval = interval;
}
/**
* Sets the number of milliseconds to wait in between automatic update
* checks.
*
* A non-positive return value indicates that no automatic update checks
* will be made.
*
* @return the number of milliseconds to wait in between automatic
* update checks.
*/
public long getAutoCheckForUpdateInterval()
{
return mAutoCheckForUpdateInterval;
}
/**
* Gets the UpdateScriptSource for this AutoUpdater.
*
* @return the UpdateScriptSource for this AutoUpdater.
*/
public abstract UpdateScriptSource getUpdateScriptSource();
/**
* Gets the logger for this AutoUpdater.
*
* @return the logger for this AutoUpdater.
*/
public Logger getLogger()
{
return LoggerManager.getLogger("dbautoupdater");
}
}
|
package org.intellij.ibatis.provider;
import com.intellij.psi.*;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.util.InheritanceUtil;
import java.util.ArrayList;
import java.util.List;
import org.intellij.ibatis.util.IbatisUtil;
/**
* sql map client method call filter
*/
public class SqlClientElementFilter implements ElementFilter {
public static String operationPattern = "(execute)?((query[(for)|(with)]\\w*)|insert|update|delete)";
public boolean isAcceptable(Object o, PsiElement psiElement) {
PsiLiteralExpression literalExpression = (PsiLiteralExpression) psiElement;
PsiElement parent = literalExpression.getParent().getParent();
if (parent != null && parent instanceof PsiMethodCallExpression) {
//first parameter validate
PsiElement previousElement = literalExpression.getPrevSibling();
if (previousElement != null) {
String text1 = previousElement.getText();
String text2 = "";
if (!text1.equals("(") && previousElement.getPrevSibling() != null) {
text2 = previousElement.getPrevSibling().getText();
}
if (!(text1.equals("(") || (text1.concat(text2).trim().equals("(")))) {
return false;
}
}
//method validation
final PsiMethodCallExpression callExpression = (PsiMethodCallExpression) parent;
String[] path = callExpression.getMethodExpression().getText().split("\\.");
String methodName = path[path.length - 1].trim().toLowerCase();
if (methodName.matches(operationPattern) && IbatisUtil.getConfig(psiElement) != null) {
return true;
}
}
return false;
}
public boolean isClassAcceptable(Class aClass) {
return aClass == PsiLiteralExpression.class;
}
}
|
package org.awaitility.core;
import org.junit.Test;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class ConditionAwaiterTest {
@Test public void
calculates_a_duration_of_1_nano_when_system_nano_time_is_skewed() {
Duration duration = ConditionAwaiter.calculateConditionEvaluationDuration(Duration.ofNanos(10000000L), System.nanoTime());
assertThat(duration.toNanos(), is(1L));
}
@Test public void atLeastIncludesPollDelayWithPollInterval() {
long start = System.currentTimeMillis();
await()
.pollDelay(Duration.ofMillis(100))
.pollInterval(Duration.ofMillis(50))
.atLeast(Duration.ofMillis(1000))
.until(() -> System.currentTimeMillis() - start > 1050);
}
@Test public void
originalUncaughtExceptionHandlerIsSetBackAfterConditionEvaluation() {
Thread.UncaughtExceptionHandler originalUncaughtExceptionHandler = (t, e) -> {};
Thread.setDefaultUncaughtExceptionHandler(originalUncaughtExceptionHandler);
final AtomicInteger count = new AtomicInteger(0);
await().until(() -> {
count.incrementAndGet();
return count.get() > 1;
});
assertThat(Thread.getDefaultUncaughtExceptionHandler(), is(originalUncaughtExceptionHandler));
}
}
|
package org.irmacard.credentials.idemix.info;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import org.irmacard.credentials.idemix.IdemixPublicKey;
import org.irmacard.credentials.idemix.IdemixSecretKey;
import org.irmacard.credentials.info.CredentialDescription;
import org.irmacard.credentials.info.DescriptionStore;
import org.irmacard.credentials.info.InfoException;
import org.irmacard.credentials.info.IssuerDescription;
import org.irmacard.credentials.info.TreeWalker;
import org.irmacard.credentials.info.TreeWalkerI;
/**
* TODO: Change print statements to proper Logging statements
*/
public class IdemixKeyStore {
static private URI CORE_LOCATION;
static private TreeWalkerI treeWalker;
static private final String PUBLIC_KEY_FILE = "ipk.xml";
static private final String PRIVATE_KEY_FILE = "private/isk.xml";
static IdemixKeyStore ds;
HashMap<IssuerDescription, IdemixPublicKey> publicKeys =
new HashMap<IssuerDescription, IdemixPublicKey>();
/**
* Define the CoreLocation. This has to be set before using the
* DescriptionStore or define a TreeWalker instead.
*
* @param coreLocation
* Location of configuration files.
*/
public static void setCoreLocation(URI coreLocation) {
// Make sure we have the correct URI, including trailing slash
File core = new File(coreLocation);
CORE_LOCATION = core.toURI();
}
/**
* Define the TreeWalker. This allows crawling more difficult storage
* systems, like Android's. This has to be set before using the
* DescriptionStore or define a coreLocation instead.
*
* @param treeWalker
*/
public static void setTreeWalker(TreeWalkerI treeWalker) {
IdemixKeyStore.treeWalker = treeWalker;
}
/**
* Get DescriptionStore instance
*
* @return The IdemixKeyStore instance
* @throws Exception
* if CoreLocation has not been set
*/
public static IdemixKeyStore getInstance() throws InfoException {
if (ds == null) {
ds = new IdemixKeyStore();
}
return ds;
}
private IdemixKeyStore() throws InfoException {
if (CORE_LOCATION != null) {
treeWalker = new TreeWalker(CORE_LOCATION);
retrieveIdemixKeys();
}
}
private void retrieveIdemixKeys() throws InfoException {
DescriptionStore ds = DescriptionStore.getInstance();
for (IssuerDescription id : ds.getIssuerDescriptions()) {
URI path;
try {
path = new URI(id.getID() + "/").resolve(PUBLIC_KEY_FILE);
} catch (URISyntaxException e) {
e.printStackTrace();
throw new RuntimeException();
}
try {
/*
* TODO: this is a bit of cludge, better refactor
* IssuerDescription into EntityDescription which is subclassed
* by IssuerDescription and Verifier Description, or something
* like that.
*/
IdemixPublicKey ipk = new IdemixPublicKey(
treeWalker.retrieveFile(path));
publicKeys.put(id, ipk);
} catch (InfoException e) {
// Ignoring Entity when no key is found
}
}
}
public void updatePublicKey(IssuerDescription id, IdemixPublicKey ipk) {
if (publicKeys.containsKey(id)) {
publicKeys.remove(id);
}
publicKeys.put(id, ipk);
}
public IdemixPublicKey getPublicKey(String issuer) throws InfoException {
IssuerDescription id = DescriptionStore.getInstance()
.getIssuerDescription(issuer);
if (publicKeys.containsKey(id)) {
return publicKeys.get(id);
} else {
throw new InfoException("Public key for issuer " + issuer
+ " not found.");
}
}
public IdemixSecretKey getSecretKey(CredentialDescription cd) throws InfoException {
return getSecretKey(cd.getIssuerDescription());
}
public IdemixSecretKey getSecretKey(IssuerDescription id) throws InfoException {
URI path;
try {
path = new URI(id.getID() + "/").resolve(PRIVATE_KEY_FILE);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return new IdemixSecretKey(treeWalker.retrieveFile(path));
}
public IdemixPublicKey getPublicKey(IssuerDescription id) {
return publicKeys.get(id);
}
}
|
package org.mtransit.android.ui.fragment;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import org.mtransit.android.R;
import org.mtransit.android.commons.BundleUtils;
import org.mtransit.android.commons.CollectionUtils;
import org.mtransit.android.commons.ColorUtils;
import org.mtransit.android.commons.MTLog;
import org.mtransit.android.commons.PreferenceUtils;
import org.mtransit.android.commons.StringUtils;
import org.mtransit.android.commons.ThemeUtils;
import org.mtransit.android.commons.task.MTAsyncTask;
import org.mtransit.android.data.AgencyProperties;
import org.mtransit.android.data.DataSourceProvider;
import org.mtransit.android.data.DataSourceType;
import org.mtransit.android.task.ServiceUpdateLoader;
import org.mtransit.android.task.StatusLoader;
import org.mtransit.android.ui.ActionBarController;
import org.mtransit.android.ui.MTActivityWithLocation;
import org.mtransit.android.ui.MainActivity;
import org.mtransit.android.ui.NavigationDrawerController;
import org.mtransit.android.ui.view.SlidingTabLayout;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
public class AgencyTypeFragment extends ABFragment implements ViewPager.OnPageChangeListener, MTActivityWithLocation.UserLocationListener {
private static final String TAG = AgencyTypeFragment.class.getSimpleName();
@Override
public String getLogTag() {
return TAG + "-" + this.typeId;
}
private static final String TRACKING_SCREEN_NAME = "Browse";
@Override
public String getScreenName() {
if (this.typeId != null) {
return TRACKING_SCREEN_NAME + "/" + this.typeId;
}
return TRACKING_SCREEN_NAME;
}
private static final String EXTRA_TYPE_ID = "extra_type_id";
public static AgencyTypeFragment newInstance(int typeId, DataSourceType optType) {
AgencyTypeFragment f = new AgencyTypeFragment();
Bundle args = new Bundle();
args.putInt(EXTRA_TYPE_ID, typeId);
f.typeId = typeId;
f.type = optType;
f.setArguments(args);
return f;
}
private AgencyPagerAdapter adapter;
private int lastPageSelected = -1;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
initAdapters(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); // child fragments options menus don't get updated when coming back from another activity
restoreInstanceState(savedInstanceState, getArguments());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_agency_type, menu);
java.util.List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null) {
fragment.onCreateOptionsMenu(menu, inflater);
}
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_nearby:
((MainActivity) getActivity()).addFragmentToStack(NearbyFragment.newNearbyInstance(null, this.typeId));
return true; // handled
}
java.util.List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null) {
if (fragment.onOptionsItemSelected(item)) {
return true; // handled
}
}
}
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_agency_type, container, false);
setupView(view);
return view;
}
private boolean modulesUpdated = false;
@Override
public void onModulesUpdated() {
this.modulesUpdated = true;
if (!isResumed()) {
return;
}
if (this.adapter != null) {
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
ArrayList<AgencyProperties> newAvailableAgencies = this.typeId == null ? null : DataSourceProvider.get(activity).getTypeDataSources(activity,
this.typeId);
if (CollectionUtils.getSize(newAvailableAgencies) == CollectionUtils.getSize(this.adapter.getAgencies())) {
this.modulesUpdated = false; // nothing to update
return;
}
MainActivity mainActivity = (MainActivity) activity;
if (mainActivity != null) {
if (mainActivity.isMTResumed()) {
NavigationDrawerController navigationController = mainActivity.getNavigationDrawerController();
if (navigationController != null) {
navigationController.forceReset();
this.modulesUpdated = false; // processed
}
}
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void setupAdapter(View view) {
if (view == null) {
return;
}
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(this.adapter);
SlidingTabLayout tabs = (SlidingTabLayout) view.findViewById(R.id.tabs);
tabs.setViewPager(viewPager);
if (this.lastPageSelected >= 0) {
viewPager.setCurrentItem(this.lastPageSelected);
} else {
new LoadLastPageSelectedFromUserPreference(getActivity(), this, this.typeId, this.adapter.getAgencies()).execute();
}
}
private void setupView(View view) {
if (view == null) {
return;
}
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(3);
SlidingTabLayout tabs = (SlidingTabLayout) view.findViewById(R.id.tabs);
tabs.setCustomTabView(R.layout.layout_tab_indicator, R.id.tab_title);
tabs.setOnPageChangeListener(this);
tabs.setSelectedIndicatorColors(Color.WHITE);
setupAdapter(view);
}
private ActionBarController.SimpleActionBarColorizer abColorizer;
private ActionBarController.ActionBarColorizer getABColorizer() {
if (this.abColorizer == null) {
initABColorizer();
}
return this.abColorizer;
}
private void initABColorizer() {
if (this.adapter != null) {
int defaultColor = ThemeUtils.resolveColorAttribute(getActivity(), R.attr.colorPrimary);
this.abColorizer = new ActionBarController.SimpleActionBarColorizer();
if (this.adapter.getCount() == 0) {
this.abColorizer.setBgColors(defaultColor);
} else {
ArrayList<AgencyProperties> agencies = this.adapter.getAgencies();
int[] agencyColors = new int[agencies.size()];
for (int i = 0; i < agencies.size(); i++) {
AgencyProperties agency = agencies.get(i);
agencyColors[i] = agency.hasColor() ? agency.getColorInt() : defaultColor;
}
this.abColorizer.setBgColors(agencyColors);
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (this.typeId != null) {
outState.putInt(EXTRA_TYPE_ID, this.typeId);
}
super.onSaveInstanceState(outState);
}
private void restoreInstanceState(Bundle... bundles) {
Integer typeId = BundleUtils.getInt(EXTRA_TYPE_ID, bundles);
if (typeId != null && !typeId.equals(this.typeId)) {
this.typeId = typeId;
resetType();
}
ArrayList<AgencyProperties> newAgencies = this.typeId == null ? null : DataSourceProvider.get(getActivity()).getTypeDataSources(getActivity(),
this.typeId);
if (CollectionUtils.getSize(newAgencies) == 0) {
return;
}
this.adapter.setAgencies(newAgencies);
}
private Integer typeId = null;
private DataSourceType type;
private void resetType() {
this.type = null;
}
private boolean hasType() {
if (this.type == null) {
initTypeAsync();
return false;
}
return true;
}
private void initTypeAsync() {
if (this.loadTypeTask.getStatus() == MTAsyncTask.Status.RUNNING) {
return;
}
if (this.typeId == null) {
return;
}
this.loadTypeTask.execute();
}
private MTAsyncTask<Void, Void, Boolean> loadTypeTask = new MTAsyncTask<Void, Void, Boolean>() {
@Override
public String getLogTag() {
return TAG + ">loadTypeTask";
}
@Override
protected Boolean doInBackgroundMT(Void... params) {
return initTypeSync();
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
applyNewType();
}
}
};
private void applyNewType() {
if (this.type == null) {
return;
}
getAbController().setABTitle(this, getABTitle(getActivity()), false);
getAbController().setABReady(this, isABReady(), true);
}
private boolean initTypeSync() {
if (this.type != null) {
return false;
}
if (this.typeId != null) {
this.type = DataSourceType.parseId(this.typeId);
}
return this.type != null;
}
private DataSourceType getTypeOrNull() {
if (!hasType()) {
return null;
}
return this.type;
}
private void initAdapters(Activity activity) {
this.adapter = new AgencyPagerAdapter(activity, this, null);
}
private static class LoadLastPageSelectedFromUserPreference extends MTAsyncTask<Void, Void, Integer> {
private final String TAG = AgencyTypeFragment.class.getSimpleName() + ">" + LoadLastPageSelectedFromUserPreference.class.getSimpleName();
@Override
public String getLogTag() {
return TAG;
}
private WeakReference<Context> contextWR;
private WeakReference<AgencyTypeFragment> agencyTypeFragmentWR;
private Integer typeId;
private ArrayList<AgencyProperties> newAgencies;
public LoadLastPageSelectedFromUserPreference(Context context, AgencyTypeFragment agencyTypeFragment, Integer typeId,
ArrayList<AgencyProperties> newAgencies) {
this.contextWR = new WeakReference<Context>(context);
this.agencyTypeFragmentWR = new WeakReference<AgencyTypeFragment>(agencyTypeFragment);
this.typeId = typeId;
this.newAgencies = newAgencies;
}
@Override
protected Integer doInBackgroundMT(Void... params) {
try {
String agencyAuthority;
Context context = this.contextWR == null ? null : this.contextWR.get();
if (context != null) {
agencyAuthority = PreferenceUtils.getPrefLcl(context, PreferenceUtils.getPREFS_LCL_AGENCY_TYPE_TAB_AGENCY(this.typeId),
PreferenceUtils.PREFS_LCL_AGENCY_TYPE_TAB_AGENCY_DEFAULT);
} else {
agencyAuthority = PreferenceUtils.PREFS_LCL_AGENCY_TYPE_TAB_AGENCY_DEFAULT;
}
if (this.newAgencies != null) {
for (int i = 0; i < this.newAgencies.size(); i++) {
if (this.newAgencies.get(i).getAuthority().equals(agencyAuthority)) {
return i;
}
}
}
} catch (Exception e) {
MTLog.w(this, e, "Error while determining the select agency tab!");
}
return null;
}
@Override
protected void onPostExecute(Integer lastPageSelected) {
AgencyTypeFragment agencyTypeFragment = this.agencyTypeFragmentWR == null ? null : this.agencyTypeFragmentWR.get();
if (agencyTypeFragment == null) {
return; // too late
}
if (agencyTypeFragment.lastPageSelected >= 0) {
return; // user has manually move to another page before, too late
}
if (lastPageSelected == null) {
agencyTypeFragment.lastPageSelected = 0;
} else {
agencyTypeFragment.lastPageSelected = lastPageSelected;
View view = agencyTypeFragment.getView();
if (view != null) {
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setCurrentItem(agencyTypeFragment.lastPageSelected);
}
}
agencyTypeFragment.onPageSelected(agencyTypeFragment.lastPageSelected); // tell current page it's selected
}
}
@Override
public void onResume() {
super.onResume();
if (this.modulesUpdated) {
getView().post(new Runnable() {
@Override
public void run() {
if (AgencyTypeFragment.this.modulesUpdated) {
onModulesUpdated();
}
}
});
}
if (this.lastPageSelected >= 0) {
onPageSelected(this.lastPageSelected); // tell current page it's selected
}
switchView(getView());
onUserLocationChanged(((MTActivityWithLocation) getActivity()).getUserLocation());
}
@Override
public void onUserLocationChanged(Location newLocation) {
if (newLocation != null) {
MTActivityWithLocation.broadcastUserLocationChanged(this, getChildFragmentManager(), newLocation);
}
}
private void switchView(View view) {
if (view == null) {
return;
}
if (this.adapter == null) {
showLoading(view);
} else if (this.adapter.getCount() > 0) {
showTabsAndViewPager(view);
} else {
showEmpty(view);
}
}
private void showTabsAndViewPager(View view) {
if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO
view.findViewById(R.id.loading).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO
view.findViewById(R.id.empty).setVisibility(View.GONE); // hide
}
if (this.typeId == null || this.typeId != DataSourceType.TYPE_MODULE.getId()) {
view.findViewById(R.id.tabs).setVisibility(View.VISIBLE); // show
}
view.findViewById(R.id.viewpager).setVisibility(View.VISIBLE); // show
}
private void showLoading(View view) {
if (view.findViewById(R.id.tabs) != null) { // IF inflated/present DO
view.findViewById(R.id.tabs).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.viewpager) != null) { // IF inflated/present DO
view.findViewById(R.id.viewpager).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) != null) { // IF inflated/present DO
view.findViewById(R.id.empty).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.loading) == null) { // IF NOT present/inflated DO
((ViewStub) view.findViewById(R.id.loading_stub)).inflate(); // inflate
}
view.findViewById(R.id.loading).setVisibility(View.VISIBLE); // show
}
private void showEmpty(View view) {
if (view.findViewById(R.id.tabs) != null) { // IF inflated/present DO
view.findViewById(R.id.tabs).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.viewpager) != null) { // IF inflated/present DO
view.findViewById(R.id.viewpager).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.loading) != null) { // IF inflated/present DO
view.findViewById(R.id.loading).setVisibility(View.GONE); // hide
}
if (view.findViewById(R.id.empty) == null) { // IF NOT present/inflated DO
((ViewStub) view.findViewById(R.id.empty_stub)).inflate(); // inflate
}
view.findViewById(R.id.empty).setVisibility(View.VISIBLE); // show
}
@Override
public void onPageSelected(int position) {
StatusLoader.get().clearAllTasks();
ServiceUpdateLoader.get().clearAllTasks();
if (this.adapter != null) {
String agencyAuthority = this.adapter.getAgencyAuthority(position);
if (!TextUtils.isEmpty(agencyAuthority)) {
PreferenceUtils.savePrefLcl(getActivity(), PreferenceUtils.getPREFS_LCL_AGENCY_TYPE_TAB_AGENCY(this.typeId), agencyAuthority, false);
}
}
java.util.List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment instanceof VisibilityAwareFragment) {
VisibilityAwareFragment visibilityAwareFragment = (VisibilityAwareFragment) fragment;
visibilityAwareFragment.setFragmentVisibleAtPosition(position);
}
}
}
this.lastPageSelected = position;
if (this.adapter != null) {
this.adapter.setLastVisibleFragmentPosition(this.lastPageSelected);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
onViewPagerPageChanged(position, positionOffset);
}
private int selectedPosition = -1;
private float selectionOffset = 0f;
private void onViewPagerPageChanged(int position, float positionOffset) {
this.selectedPosition = position;
this.selectionOffset = positionOffset;
this.abBgColor = getNewABBgColor();
if (this.abBgColor != null) {
View view = getView();
if (view != null) {
View tabs = view.findViewById(R.id.tabs);
if (tabs != null) {
tabs.setBackgroundColor(this.abBgColor);
}
}
getAbController().setABBgColor(this, getABBgColor(getActivity()), false);
getAbController().updateABBgColor();
}
}
private Integer abBgColor = null;
@Override
public Integer getABBgColor(Context context) {
if (this.abBgColor == null) {
this.abBgColor = getNewABBgColor();
}
return this.abBgColor;
}
private Integer getNewABBgColor() {
if (getABColorizer() != null && this.selectedPosition >= 0) {
int color = getABColorizer().getBgColor(this.selectedPosition);
if (this.selectionOffset > 0f && this.selectedPosition < (this.adapter.getCount() - 1)) {
int nextColor = getABColorizer().getBgColor(this.selectedPosition + 1);
if (color != nextColor) {
return ColorUtils.blendColors(nextColor, color, this.selectionOffset);
}
}
return color;
}
return null;
}
@Override
public void onPageScrollStateChanged(int state) {
switch (state) {
case ViewPager.SCROLL_STATE_IDLE:
resumeAllVisibleAwareChildFragment();
break;
case ViewPager.SCROLL_STATE_DRAGGING:
pauseAllVisibleAwareChildFragments();
break;
}
}
private void resumeAllVisibleAwareChildFragment() {
java.util.List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment instanceof VisibilityAwareFragment) {
VisibilityAwareFragment visibilityAwareFragment = (VisibilityAwareFragment) fragment;
visibilityAwareFragment.setFragmentVisibleAtPosition(this.lastPageSelected); // resume
}
}
}
}
private void pauseAllVisibleAwareChildFragments() {
java.util.List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment instanceof VisibilityAwareFragment) {
VisibilityAwareFragment visibilityAwareFragment = (VisibilityAwareFragment) fragment;
visibilityAwareFragment.setFragmentVisibleAtPosition(-1); // pause
}
}
}
}
@Override
public boolean isABReady() {
return hasType();
}
@Override
public CharSequence getABTitle(Context context) {
DataSourceType type = getTypeOrNull();
if (type == null) {
return context.getString(R.string.ellipsis);
}
return context.getString(type.getAllStringResId());
}
private static class AgencyPagerAdapter extends FragmentStatePagerAdapter implements SlidingTabLayout.TabColorizer, MTLog.Loggable {
private static final String TAG = AgencyTypeFragment.class.getSimpleName() + ">" + AgencyPagerAdapter.class.getSimpleName();
@Override
public String getLogTag() {
return TAG;
}
private ArrayList<AgencyProperties> agencies;
private WeakReference<Context> contextWR;
private int lastVisibleFragmentPosition = -1;
private int saveStateCount = -1;
public AgencyPagerAdapter(Context context, AgencyTypeFragment agencyTypeFragment, ArrayList<AgencyProperties> agencies) {
super(agencyTypeFragment.getChildFragmentManager());
this.contextWR = new WeakReference<Context>(context);
setAgencies(agencies);
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
if (this.saveStateCount >= 0 && this.saveStateCount != getCount()) {
return;
}
try {
super.restoreState(state, loader);
} catch (Exception e) {
MTLog.w(this, e, "Error while restoring state!");
}
}
@Override
public Parcelable saveState() {
try {
this.saveStateCount = getCount();
return super.saveState();
} catch (Exception e) {
MTLog.w(this, e, "Error while saving fragment state!");
return null;
}
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
try {
super.destroyItem(container, position, object);
} catch (Exception e) {
MTLog.w(this, e, "Error while destroying fragment at position '%s'!", position);
}
}
private ArrayList<String> agenciesAuthority = new ArrayList<String>();
public void setAgencies(ArrayList<AgencyProperties> agencies) {
this.agencies = agencies;
this.agenciesAuthority.clear();
if (this.agencies != null) {
for (AgencyProperties agency : this.agencies) {
this.agenciesAuthority.add(agency.getAuthority());
}
}
}
public ArrayList<AgencyProperties> getAgencies() {
return agencies;
}
public AgencyProperties getAgency(int position) {
return this.agencies.size() == 0 ? null : this.agencies.get(position);
}
public String getAgencyAuthority(int position) {
return this.agenciesAuthority == null || this.agenciesAuthority.size() <= position ? null : this.agenciesAuthority.get(position);
}
@Override
public int getItemPosition(Object object) {
if (object instanceof AgencyFragment) {
return getAgencyItemPosition(((AgencyFragment) object).getAgencyAuthority());
} else {
return POSITION_NONE;
}
}
private int getAgencyItemPosition(String agencyAuthority) {
int indexOf = this.agenciesAuthority == null ? -1 : this.agenciesAuthority.indexOf(agencyAuthority);
if (indexOf < 0) {
return POSITION_NONE;
}
return indexOf;
}
public void setLastVisibleFragmentPosition(int lastVisibleFragmentPosition) {
this.lastVisibleFragmentPosition = lastVisibleFragmentPosition;
}
@Override
public int getCount() {
return this.agenciesAuthority == null ? 0 : this.agenciesAuthority.size();
}
@Override
public CharSequence getPageTitle(int position) {
Context context = this.contextWR == null ? null : this.contextWR.get();
if (context == null) {
return StringUtils.EMPTY;
}
if (this.agencies == null || position >= this.agencies.size()) {
return StringUtils.EMPTY;
}
return this.agencies.get(position).getShortName();
}
@Override
public int getIndicatorColor(int position) {
return Color.WHITE;
}
@Override
public Fragment getItem(int position) {
AgencyProperties agency = getAgency(position);
if (agency != null && agency.isRTS()) {
RTSAgencyRoutesFragment f = RTSAgencyRoutesFragment.newInstance(position, this.lastVisibleFragmentPosition, agency.getAuthority());
f.setLogTag(agency.getShortName());
return f;
}
return AgencyPOIsFragment.newInstance(position, this.lastVisibleFragmentPosition, getAgencyAuthority(position), null);
}
}
public static interface AgencyFragment extends VisibilityAwareFragment {
public String getAgencyAuthority();
}
}
|
package pub.monkeyboss.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
/**
* View
* <attr name="code_length" format="integer" />
* <attr name="child_h_padding" format="dimension" /> padding
* <attr name="child_v_padding" format="dimension" /> padding
* <attr name="child_width" format="dimension" />
* <attr name="child_height" format="dimension" />
* <attr name="padding" format="dimension" /> padding
* <attr name="child_background" format="reference" /> selector backgroundbackgroundchild_backgroundfull_backgroundblank_backgroundchild_background
* <attr name="full_background" format="reference" />
* <attr name="blank_background" format="reference" />
* <attr name="cursorVisible" format="boolean" />
* <attr name="textColor" format="reference" />
* <attr name="inputType"> numberpasswordtext
* <enum name="number" value="0" />
* <enum name="text" value="1" />
* <enum name="password" value="2" />
* </attr>
*/
public class CodeInputView extends ViewGroup {
private final static int TYPE_NUMBER = 0;
private final static int TYPE_TEXT = 1;
private final static int TYPE_PASSWORD = 2;
private int length;
private int childWidth = 120;
private int childHeight = 120;
private int childHPadding = 14;
private int childVPadding = 14;
private int inputType = TYPE_NUMBER;
private int childBackground;
private int fullBackground;
private int blankBackground;
private boolean cursorVisible;
private int textColor = Color.parseColor("#333333");
private OnInputListener onInputListener;
private StringBuffer buffer = new StringBuffer();
public CodeInputView(Context context) {
this(context, null);
}
public CodeInputView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CodeInputView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.codeInputView);
length = typedArray.getInt(R.styleable.codeInputView_code_length, 4);
childHPadding = (int) typedArray.getDimension(R.styleable.codeInputView_child_h_padding, 0);
childVPadding = (int) typedArray.getDimension(R.styleable.codeInputView_child_v_padding, 0);
childBackground = typedArray.getResourceId(R.styleable.codeInputView_child_background, 0);
fullBackground = typedArray.getResourceId(R.styleable.codeInputView_full_background, 0);
blankBackground = typedArray.getResourceId(R.styleable.codeInputView_blank_background, 0);
cursorVisible = typedArray.getBoolean(R.styleable.codeInputView_cursorVisible, true);
textColor = typedArray.getColor(R.styleable.codeInputView_textColor, textColor);
inputType = typedArray.getInt(R.styleable.codeInputView_inputType, TYPE_NUMBER);
childWidth = (int) typedArray.getDimension(R.styleable.codeInputView_child_width, childWidth);
childHeight = (int) typedArray.getDimension(R.styleable.codeInputView_child_height, childHeight);
typedArray.recycle();
initViews();
}
private void initViews() {
TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 1 && buffer.length() < length) {
input(s.toString());
setChildBg();
check(true);
} else if (s.length() == 0) {
input(null);
setChildBg();
check(false);
}
}
};
OnKeyListener onKeyListener = new OnKeyListener() {
@Override
public synchronized boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_UP) {
if (buffer.length() > 0) {
delete();
}
}
return false;
}
};
for (int i = 0; i < length; i++) {
EditText editText = new EditText(getContext());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(childWidth, childHeight);
layoutParams.bottomMargin = childVPadding;
layoutParams.topMargin = childVPadding;
layoutParams.leftMargin = childHPadding;
layoutParams.rightMargin = childHPadding;
layoutParams.gravity = Gravity.CENTER;
editText.setOnKeyListener(onKeyListener);
editText.setBackgroundResource(childBackground > 0 ? childBackground : blankBackground);
editText.setTextColor(textColor);
editText.setLayoutParams(layoutParams);
editText.setGravity(Gravity.CENTER);
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1)});
switch (inputType) {
case TYPE_NUMBER:
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
break;
case TYPE_PASSWORD:
editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
break;
case TYPE_TEXT:
editText.setInputType(InputType.TYPE_CLASS_TEXT);
break;
default:
editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
editText.setId(i);
editText.setEms(1);
editText.setCursorVisible(cursorVisible);
editText.addTextChangedListener(textWatcher);
addView(editText, i);
}
}
private void check(boolean isInput) {
if (isInput) {
if (buffer.length() > 0) {
if (this.onInputListener != null) {
this.onInputListener.onInput(buffer.length(), buffer.charAt(buffer.length() - 1), buffer.toString());
}
}
} else {
if (this.onInputListener != null) {
this.onInputListener.onDelete(buffer.toString());
}
}
if (buffer.length() == length) {
if (this.onInputListener != null) {
this.onInputListener.onComplete(buffer.toString());
}
}
}
private void input(String s) {
if (s != null) {
buffer.append(s);
}
if (buffer.length() < length) {
EditText editText = (EditText) getChildAt(buffer.length());
editText.requestFocus();
}
}
private void delete() {
buffer.deleteCharAt(buffer.length() - 1);
EditText child = (EditText) getChildAt(buffer.length());
child.setText(null);
}
/**
* edittextbackground
*/
private void setChildBg() {
if (childBackground == 0) {
int count = getChildCount();
EditText child;
for (int i = 0; i < count; i++) {
child = (EditText) getChildAt(i);
if (child.getText().length() > 0) {
child.setBackgroundResource(fullBackground);
} else {
child.setBackgroundResource(blankBackground);
}
}
}
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LinearLayout.LayoutParams(getContext(), attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (buffer.length() != length) {
input(null);
} else {
delete();
}
return false;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
this.measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
if (count > 0) {
View child = getChildAt(0);
int cHeight = child.getMeasuredHeight();
int cWidth = child.getMeasuredWidth();
int maxH = cHeight + 2 * childVPadding;
int maxW = (cWidth + childHPadding) * length + childHPadding;
setMeasuredDimension(resolveSize(maxW, widthMeasureSpec),
resolveSize(maxH, heightMeasureSpec));
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
child.setVisibility(View.VISIBLE);
int cWidth = child.getMeasuredWidth();
int cHeight = child.getMeasuredHeight();
int cl = (i) * (cWidth + childHPadding) + childHPadding;
int cr = cl + cWidth;
int ct = childVPadding;
int cb = ct + cHeight;
child.layout(cl, ct, cr, cb);
}
}
public interface OnInputListener {
/**
*
*
* @param position
* @param c
* @param content
*/
void onInput(int position, char c, String content);
/**
*
*
* @param content
*/
void onDelete(String content);
/**
*
*
* @param content
*/
void onComplete(String content);
}
public void setOnInputListener(OnInputListener onInputListener) {
this.onInputListener = onInputListener;
}
}
|
package de.larsgrefer.sense_hat;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;
/**
* @author Lars Grefer
*/
@RequiredArgsConstructor
@Getter
@Setter
@Slf4j
public class TextDisplay {
private final SenseHat senseHat;
private Color background = Color.BLACK;
private Color foreground = Color.WHITE;
private Duration duration = Duration.ofMillis(250);
public void displayText(String text) throws IOException {
BufferedImage image = new BufferedImage(8, 8, BufferedImage.TYPE_USHORT_565_RGB);
Graphics2D graphics = image.createGraphics();
Font sansSerif = new Font("SansSerif", Font.PLAIN, 8);
graphics.setFont(sansSerif);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
int i = graphics.getFontMetrics().stringWidth(text);
long start = System.currentTimeMillis();
while(true) {
long d = System.currentTimeMillis() - start;
int j = (int) (d / duration.toMillis());
float factor = ((float) (d % duration.toMillis())) / duration.toMillis();
graphics.setColor(background);
graphics.setPaint(background);
graphics.fillRect(0, 0, 8, 8);
graphics.setColor(foreground);
graphics.setPaint(foreground);
graphics.drawString(text, -j - factor, 7);
senseHat.setImage(image);
if(j > i) {
break;
}
}
graphics.dispose();
}
public void setForeground(SenseHatColor foreground) {
this.foreground = foreground.toColor();
}
public void setBackground(SenseHatColor background) {
this.background = background.toColor();
}
}
|
package org.owasp.esapi.reference;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Logger;
import org.owasp.esapi.User;
import org.owasp.esapi.errors.AccessControlException;
import org.owasp.esapi.errors.EncodingException;
import org.owasp.esapi.errors.IntrusionException;
* <li>longest path prefix match, beginning / and ending /*, e.g. /access/* or /*</li>
* <li>extension match, beginning *., e.g. *.css</li>
* <li>default rule, specified by the single character pattern /</li>
* </ul>
*
* @author Jeff Williams (jeff.williams@aspectsecurity.com)
* @since June 1, 2007
* @see org.owasp.esapi.AccessController
*/
public class FileBasedAccessController implements org.owasp.esapi.AccessController {
/** The url map. */
private Map urlMap = new HashMap();
/** The function map. */
private Map functionMap = new HashMap();
/** The data map. */
private Map dataMap = new HashMap();
/** The file map. */
private Map fileMap = new HashMap();
/** The service map. */
private Map serviceMap = new HashMap();
/** The deny. */
private Rule deny = new Rule();
/** The logger. */
private Logger logger = ESAPI.getLogger("AccessController");
public FileBasedAccessController() {
}
public boolean isAuthorizedForURL(String url) {
try {
assertAuthorizedForURL( url );
return true;
} catch ( Exception e ) {
return false;
}
}
public boolean isAuthorizedForFunction(String functionName) {
try {
assertAuthorizedForFunction( functionName );
return true;
} catch ( Exception e ) {
return false;
}
}
public boolean isAuthorizedForData(String key) {
try {
assertAuthorizedForData( key );
return true;
} catch ( Exception e ) {
return false;
}
}
public boolean isAuthorizedForData(String action, Object data){
try{
assertAuthorizedForData( action, data );
return true;
}catch ( Exception e ) {
return false;
}
}
public boolean isAuthorizedForFile(String filepath) {
try {
assertAuthorizedForFile( filepath );
return true;
} catch ( Exception e ) {
return false;
}
}
public boolean isAuthorizedForService(String serviceName) {
try {
assertAuthorizedForService( serviceName );
return true;
} catch ( Exception e ) {
return false;
}
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.AccessController#isAuthorizedForURL(java.lang.String,
* java.lang.String)
*/
public void assertAuthorizedForURL(String url) throws AccessControlException {
if (urlMap==null || urlMap.isEmpty()) {
urlMap = loadRules("URLAccessRules.txt");
}
if ( !matchRule(urlMap, url) ) {
throw new AccessControlException("Not authorized for URL", "Not authorized for URL: " + url );
}
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.AccessController#isAuthorizedForFunction(java.lang.String,
* java.lang.String)
*/
public void assertAuthorizedForFunction(String functionName) throws AccessControlException {
if (functionMap==null || functionMap.isEmpty()) {
functionMap = loadRules("FunctionAccessRules.txt");
}
if ( !matchRule(functionMap, functionName) ) {
throw new AccessControlException("Not authorized for function", "Not authorized for function: " + functionName );
}
}
/**
* Checks if the current user is authorized to access the referenced data. This method simply returns if access is authorized.
* It throws an AccessControlException if access is not authorized, or the referenced data does not exist.
*
* This method enforces the following access control policy as defined in the DataAccessRules.txt configuration file:
* 1) This config file defines the name space of all the data sets for this system
* 2) This file also defines which user roles are either allowed or denied access to each data resource
* 3) This method checks to see if the resource exists in the configuration file and if not, throws and AccessControlException
* 4) It checks the policy to see if the user is authorized and if not, throws and AccessControlException
* 5) A default rule built into the method is that if the policy does not specifically grant access, access is denied,
* and an AccessControlException is thrown
*
* @param key
* the name of the target data object
*
* @throws AccessControlException
* if access is not permitted
*
* @see org.owasp.esapi.AccessController#isAuthorizedForData(java.lang.String)
*/
public void assertAuthorizedForData(String key) throws AccessControlException {
if (dataMap==null || dataMap.isEmpty()) {
dataMap = loadDataRules("DataAccessRules.txt");
}
if ( !matchRule(dataMap, key) ) {
throw new AccessControlException("Not authorized for function", "Not authorized for data: " + key );
}
}
public void assertAuthorizedForData(String action, Object data) throws AccessControlException{
if (dataMap==null || dataMap.isEmpty()) {
dataMap = loadDataRules("DataAccessRules.txt");
}
if( !matchRule(dataMap, (Class) data, action ) ){
throw new AccessControlException("Not authorized for data", "Not authorized for data: " + (Class)data);
}
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.AccessController#isAuthorizedForFile(java.lang.String,
* java.lang.String)
*/
public void assertAuthorizedForFile(String filepath) throws AccessControlException {
if (fileMap==null || fileMap.isEmpty()) {
fileMap = loadRules("FileAccessRules.txt");
}
if ( !matchRule(fileMap, filepath.replaceAll("\\\\","/"))) {
throw new AccessControlException("Not authorized for file", "Not authorized for file: " + filepath );
}
}
/*
* (non-Javadoc)
*
* @see org.owasp.esapi.interfaces.AccessController#isAuthorizedForBackendService(java.lang.String,
* java.lang.String)
*/
public void assertAuthorizedForService(String serviceName) throws AccessControlException {
if (serviceMap==null || serviceMap.isEmpty()) {
serviceMap = loadRules("ServiceAccessRules.txt");
}
if ( !matchRule(serviceMap, serviceName ) ) {
throw new AccessControlException("Not authorized for service", "Not authorized for service: " + serviceName );
}
}
/**
* Match rule.
*
* @param map
* the map
* @param path
* the path
*
* @return true, if successful
*
* @throws AccessControlException
* the access control exception
*/
private boolean matchRule(Map map, String path) {
// get users roles
User user = ESAPI.authenticator().getCurrentUser();
Set roles = user.getRoles();
// search for the first rule that matches the path and rules
Rule rule = searchForRule(map, roles, path);
return rule.allow;
}
private boolean matchRule(Map map, Class clazz, String action) {
// get users roles
User user = ESAPI.authenticator().getCurrentUser();
Set roles = user.getRoles();
// search for the first rule that matches the path and rules
Rule rule = searchForRule(map, roles, clazz, action);
return rule != null;
}
* /*, e.g. /access/* or /* - extension match, beginning *., e.g. *.css -
* default servlet, specified by the single character pattern /
*
* @param map
* the map
* @param roles
* the roles
* @param path
* the path
*
* @return the rule
*
* @throws AccessControlException
* the access control exception
*/
private Rule searchForRule(Map map, Set roles, String path) {
String canonical = null;
try {
canonical = ESAPI.encoder().canonicalize(path);
} catch (EncodingException e) {
logger.warning( Logger.SECURITY, "Failed to canonicalize input: " + path );
}
String part = canonical;
while (part.endsWith("/")) {
part = part.substring(0, part.length() - 1);
}
if (part.indexOf("..") != -1) {
throw new IntrusionException("Attempt to manipulate access control path", "Attempt to manipulate access control path: " + path );
}
// extract extension if any
String extension = "";
int extIndex = part.lastIndexOf(".");
if (extIndex != -1) {
extension = part.substring(extIndex + 1);
}
// Check for exact match - ignore any ending slash
Rule rule = (Rule) map.get(part);
* /*, e.g. /access/* or /* - extension match, beginning *., e.g. *.css -
* default servlet, specified by the single character pattern /
*
* @param map
* the map
* @param roles
* the roles
* @param path
* the paths
*
* @return the rule
*
* @throws AccessControlException
* the access control exception
*/
private Rule searchForRule(Map map, Set roles, Class clazz, String action) {
// Check for exact match - ignore any ending slash
Rule rule = (Rule) map.get(clazz);
if( ( rule != null ) && ( overlap(rule.actions, action) ) && ( overlap(rule.roles, roles) )){
return rule;
}
return null;
}
/**
* Return true if there is overlap between the two sets.
*
* @param ruleRoles
* the rule roles
* @param userRoles
* the user roles
*
* @return true, if successful
*/
private boolean overlap(Set ruleRoles, Set userRoles) {
if (ruleRoles.contains("any")) {
return true;
}
Iterator i = userRoles.iterator();
while (i.hasNext()) {
String role = (String) i.next();
if (ruleRoles.contains(role)) {
return true;
}
}
return false;
}
private boolean overlap( List ruleActions, String action){
if( ruleActions.contains(action) )
return true;
return false;
}
/**
* Load rules.
*
* @param ruleset
* the ruleset
*
* @return the hash map
*
* @throws AccessControlException
* the access control exception
*/
private Map loadRules(String ruleset) {
Map map = new HashMap();
InputStream is = null;
try {
is = new FileInputStream(new File(ESAPI.securityConfiguration().getResourceDirectory(), ruleset));
String line = "";
while ((line = ESAPI.validator().safeReadLine(is, 500)) != null) {
if (line.length() > 0 && line.charAt(0) != '
Rule rule = new Rule();
String[] parts = line.split("\\|");
// fix Windows paths
rule.path = parts[0].trim().replaceAll("\\\\", "/");
rule.roles.add(parts[1].trim().toLowerCase());
String action = parts[2].trim();
rule.allow = action.equalsIgnoreCase("allow");
if (map.containsKey(rule.path)) {
logger.warning( Logger.SECURITY, "Problem in access control file. Duplicate rule ignored: " + rule);
} else {
map.put(rule.path, rule);
}
}
}
} catch (Exception e) {
logger.warning( Logger.SECURITY, "Problem in access control file : " + ruleset, e );
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
logger.warning(Logger.SECURITY, "Failure closing access control file : " + ruleset, e);
}
}
return map;
}
/**
* Load Data rules. Class may only appear once on the list of rules.
*
* @param ruleset
* the ruleset
*
* @return the hash map
*
* @throws AccessControlException
* the access control exception
*/
private Map loadDataRules(String ruleset) {
Map map = new HashMap();
InputStream is = null;
try {
is = new FileInputStream(new File(ESAPI.securityConfiguration().getResourceDirectory(), ruleset));
String line = "";
while ((line = ESAPI.validator().safeReadLine(is, 500)) != null) {
if (line.length() > 0 && line.charAt(0) != '
Rule rule = new Rule();
String[] parts = line.split("\\|");
rule.clazz = Class.forName(parts[0].trim());
List roles = commaSplit(parts[1].trim().toLowerCase());
for(int x = 0; x < roles.size(); x++)
rule.roles.add(roles.get(x));
List action = commaSplit(parts[2].trim().toLowerCase());
for(int x = 0; x < action.size(); x++)
rule.actions.add(((String) action.get(x)).trim());
if (map.containsKey(rule.path)) {
logger.warning( Logger.SECURITY, "Problem in access control file. Duplicate rule ignored: " + rule);
} else {
map.put(rule.clazz, rule);
}
}
}
} catch (Exception e) {
logger.warning( Logger.SECURITY, "Problem in access control file : " + ruleset, e );
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
logger.warning(Logger.SECURITY, "Failure closing access control file : " + ruleset, e);
}
}
return map;
}
private List commaSplit(String input){
String[] array = input.split(",");
return Arrays.asList(array);
}
/**
* The Class Rule.
*/
private class Rule {
protected String path = "";
protected Set roles = new HashSet();
protected boolean allow = false;
protected Class clazz = null;
protected List actions = new ArrayList();
/**
*
* Creates a new Rule object.
*/
protected Rule() {
// to replace synthetic accessor method
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
return "URL:" + path + " | " + roles + " | " + (allow ? "allow" : "deny");
}
}
}
|
package com.datatorrent.stram;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.datatorrent.api.StorageAgent;
import com.datatorrent.bufferserver.util.Codec;
import com.google.common.collect.Lists;
public class FSStorageAgent implements StorageAgent
{
private static final String PATH_SEPARATOR = "/";
final String checkpointFsPath;
final Configuration conf;
FSStorageAgent(Configuration conf, String checkpointFsPath)
{
this.conf = conf;
this.checkpointFsPath = checkpointFsPath;
}
public FSStorageAgent(String checkpointFsPath)
{
conf = new Configuration();
this.checkpointFsPath = checkpointFsPath;
}
@Override
public OutputStream getSaveStream(int id, long windowId) throws IOException
{
Path path = new Path(this.checkpointFsPath + PATH_SEPARATOR + id + PATH_SEPARATOR + Codec.getStringWindowId(windowId));
logger.debug("Saving: {}", path);
FileSystem fs = FileSystem.get(path.toUri(), conf);
return fs.create(path);
}
@Override
public InputStream getLoadStream(int id, long windowId) throws IOException
{
Path path = new Path(this.checkpointFsPath + PATH_SEPARATOR + id + PATH_SEPARATOR + Codec.getStringWindowId(windowId));
logger.debug("Loading: {}", path);
FileSystem fs = FileSystem.get(path.toUri(), conf);
return fs.open(path);
}
@Override
public void delete(int id, long windowId) throws IOException
{
Path path = new Path(this.checkpointFsPath + PATH_SEPARATOR + id + PATH_SEPARATOR + Codec.getStringWindowId(windowId));
logger.debug("Deleting: {}", path);
FileSystem fs = FileSystem.get(path.toUri(), conf);
fs.delete(path, false);
}
@Override
public Collection<Long> getWindowsIds(int operatorId) throws IOException
{
Path path = new Path(this.checkpointFsPath + PATH_SEPARATOR + operatorId);
FileSystem fs = FileSystem.get(path.toUri(), conf);
FileStatus[] files = fs.listStatus(path);
if (files == null || files.length == 0) {
throw new IOException("Storage Agent has not saved anything yet!");
}
List<Long> windowIds = Lists.newArrayListWithExpectedSize(files.length);
for (FileStatus file : files) {
windowIds.add(Codec.getLongWindowId(file.getPath().getName()));
}
return windowIds;
}
@Override
public String toString()
{
return checkpointFsPath;
}
private static final Logger logger = LoggerFactory.getLogger(FSStorageAgent.class);
}
|
package com.intellij.util.io;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.LowMemoryWatcher;
import com.intellij.openapi.util.ThreadLocalCachedValue;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.*;
import com.intellij.util.containers.LimitedPool;
import com.intellij.util.containers.SLRUCache;
import org.jetbrains.annotations.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** Thread-safe implementation of persistent hash map (PHM). The implementation works in the following (generic) way:<ul>
<li> Particular key is translated via myEnumerator into an int. </li>
<li> As part of enumeration process for the new key, additional space is reserved in
myEnumerator.myStorage for offset in ".values" file (myValueStorage) where (serialized) value is stored. </li>
<li> Once new value is written the offset storage is updated. </li>
<li> When the key is removed from PHM, offset storage is set to zero. </li>
</ul>
<p>
It is important to note that offset
is non-negative and can be 4 or 8 bytes, depending on the size of the ".values" file.
PHM can work in appendable mode: for particular key additional calculated chunk of value can be appended to ".values" file with the offset
of previously calculated chunk.
For performance reasons we try hard to minimize storage occupied by keys / offsets in ".values" file: this storage is allocated as (limited)
direct byte buffers so 4 bytes offset is used until it is possible. Generic record produced by enumerator used with PHM as part of new
key enumeration is <enumerated_id>? [.values file offset 4 or 8 bytes], however for unique integral keys enumerate_id isn't produced.
Also for certain Value types it is possible to avoid random reads at all: e.g. in case Value is non-negative integer the value can be stored
directly in storage used for offset and in case of btree enumerator directly in btree leaf.
**/
public class PersistentHashMap<Key, Value> extends PersistentEnumeratorDelegate<Key> implements AppendablePersistentMap<Key, Value> {
private static final Logger LOG = Logger.getInstance(PersistentHashMap.class);
private static final boolean myDoTrace = SystemProperties.getBooleanProperty("idea.trace.persistent.map", false);
private static final int DEAD_KEY_NUMBER_MASK = 0xFFFFFFFF;
private final Path myStorageFile;
private final boolean myIsReadOnly;
private final KeyDescriptor<Key> myKeyDescriptor;
private PersistentHashMapValueStorage myValueStorage;
protected final DataExternalizer<Value> myValueExternalizer;
private static final long NULL_ADDR = 0;
private static final int INITIAL_INDEX_SIZE;
static {
String property = System.getProperty("idea.initialIndexSize");
INITIAL_INDEX_SIZE = property == null ? 4 * 1024 : Integer.valueOf(property);
}
@NonNls
static final String DATA_FILE_EXTENSION = ".values";
private long myLiveAndGarbageKeysCounter;
// first four bytes contain live keys count (updated via LIVE_KEY_MASK), last four bytes - number of dead keys
private int myReadCompactionGarbageSize;
private static final long LIVE_KEY_MASK = 1L << 32;
private static final long USED_LONG_VALUE_MASK = 1L << 62;
private static final int POSITIVE_VALUE_SHIFT = 1;
private final int myParentValueRefOffset;
private final byte @NotNull [] myRecordBuffer;
private final byte @NotNull [] mySmallRecordBuffer;
private final boolean myIntMapping;
private final boolean myDirectlyStoreLongFileOffsetMode;
private final boolean myCanReEnumerate;
private int myLargeIndexWatermarkId; // starting with this id we store offset in adjacent file in long format
private boolean myIntAddressForNewRecord;
private static final boolean doHardConsistencyChecks = false;
private volatile boolean myBusyReading;
private static class AppendStream extends DataOutputStream {
private AppendStream() {
super(null);
}
private void setOut(BufferExposingByteArrayOutputStream stream) {
out = stream;
}
}
private final LimitedPool<BufferExposingByteArrayOutputStream> myStreamPool =
new LimitedPool<>(10, new LimitedPool.ObjectFactory<BufferExposingByteArrayOutputStream>() {
@Override
@NotNull
public BufferExposingByteArrayOutputStream create() {
return new BufferExposingByteArrayOutputStream();
}
@Override
public void cleanup(@NotNull final BufferExposingByteArrayOutputStream appendStream) {
appendStream.reset();
}
});
private final SLRUCache<Key, BufferExposingByteArrayOutputStream> myAppendCache;
private boolean canUseIntAddressForNewRecord(long size) {
return myCanReEnumerate && size + POSITIVE_VALUE_SHIFT < Integer.MAX_VALUE;
}
private final LowMemoryWatcher myAppendCacheFlusher = LowMemoryWatcher.register(this::dropMemoryCaches);
public PersistentHashMap(@NotNull File file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer) throws IOException {
this(file.toPath(), keyDescriptor, valueExternalizer, INITIAL_INDEX_SIZE);
}
public PersistentHashMap(@NotNull Path file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer) throws IOException {
this(file, keyDescriptor, valueExternalizer, INITIAL_INDEX_SIZE);
}
public PersistentHashMap(@NotNull Path file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer,
final int initialSize) throws IOException {
this(file, keyDescriptor, valueExternalizer, initialSize, 0);
}
public PersistentHashMap(@NotNull Path file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer,
final int initialSize,
int version) throws IOException {
this(file, keyDescriptor, valueExternalizer, initialSize, version, null);
}
public PersistentHashMap(@NotNull Path file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer,
final int initialSize,
int version,
@Nullable PagedFileStorage.StorageLockContext lockContext) throws IOException {
this(file, keyDescriptor, valueExternalizer, initialSize, version, lockContext,
PersistentHashMapValueStorage.CreationTimeOptions.threadLocalOptions());
}
private PersistentHashMap(@NotNull Path file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer,
final int initialSize,
int version,
@Nullable PagedFileStorage.StorageLockContext lockContext,
@NotNull PersistentHashMapValueStorage.CreationTimeOptions options) throws IOException {
super(checkDataFiles(file), keyDescriptor, initialSize, lockContext, modifyVersionDependingOnOptions(version, options));
myStorageFile = file;
myKeyDescriptor = keyDescriptor;
myIsReadOnly = isReadOnly();
if (myIsReadOnly) options = options.setReadOnly();
myAppendCache = createAppendCache(keyDescriptor);
final PersistentEnumeratorBase.@NotNull RecordBufferHandler<PersistentEnumeratorBase<?>> recordHandler = myEnumerator.getRecordHandler();
myParentValueRefOffset = recordHandler.getRecordBuffer(myEnumerator).length;
myIntMapping = valueExternalizer instanceof IntInlineKeyDescriptor && wantNonNegativeIntegralValues();
myDirectlyStoreLongFileOffsetMode = keyDescriptor instanceof InlineKeyDescriptor && myEnumerator instanceof PersistentBTreeEnumerator;
myRecordBuffer = myDirectlyStoreLongFileOffsetMode ? ArrayUtilRt.EMPTY_BYTE_ARRAY : new byte[myParentValueRefOffset + 8];
mySmallRecordBuffer = myDirectlyStoreLongFileOffsetMode ? ArrayUtilRt.EMPTY_BYTE_ARRAY : new byte[myParentValueRefOffset + 4];
myEnumerator.setRecordHandler(new PersistentEnumeratorBase.RecordBufferHandler<PersistentEnumeratorBase<?>>() {
@Override
int recordWriteOffset(PersistentEnumeratorBase<?> enumerator, byte[] buf) {
return recordHandler.recordWriteOffset(enumerator, buf);
}
@Override
byte @NotNull [] getRecordBuffer(PersistentEnumeratorBase<?> enumerator) {
return myIntAddressForNewRecord ? mySmallRecordBuffer : myRecordBuffer;
}
@Override
void setupRecord(PersistentEnumeratorBase enumerator, int hashCode, int dataOffset, byte @NotNull [] buf) {
recordHandler.setupRecord(enumerator, hashCode, dataOffset, buf);
for (int i = myParentValueRefOffset; i < buf.length; i++) {
buf[i] = 0;
}
}
});
myEnumerator.setMarkCleanCallback(
new Flushable() {
@Override
public void flush() {
myEnumerator.putMetaData(myLiveAndGarbageKeysCounter);
myEnumerator.putMetaData2(myLargeIndexWatermarkId | ((long)myReadCompactionGarbageSize << 32));
}
}
);
if (myDoTrace) LOG.info("Opened " + file);
try {
myValueExternalizer = valueExternalizer;
myValueStorage = new PersistentHashMapValueStorage(getDataFile(file), options);
myLiveAndGarbageKeysCounter = myEnumerator.getMetaData();
long data2 = myEnumerator.getMetaData2();
myLargeIndexWatermarkId = (int)(data2 & DEAD_KEY_NUMBER_MASK);
myReadCompactionGarbageSize = (int)(data2 >>> 32);
myCanReEnumerate = myEnumerator.canReEnumerate();
if (!options.isReadOnly() && makesSenseToCompact()) {
compact();
}
}
catch (IOException e) {
try {
// attempt to close already opened resources
close();
}
catch (Throwable ignored) {
}
throw e; // rethrow
}
catch (Throwable t) {
LOG.error(t);
try {
// attempt to close already opened resources
close();
}
catch (Throwable ignored) {
}
throw new PersistentEnumerator.CorruptedException(file);
}
}
private static int modifyVersionDependingOnOptions(int version, @NotNull PersistentHashMapValueStorage.CreationTimeOptions options) {
return version + options.getVersion();
}
protected boolean wantNonNegativeIntegralValues() {
return false;
}
protected boolean isReadOnly() {
return false;
}
private static final int MAX_RECYCLED_BUFFER_SIZE = 4096;
private SLRUCache<Key, BufferExposingByteArrayOutputStream> createAppendCache(final KeyDescriptor<Key> keyDescriptor) {
return new SLRUCache<Key, BufferExposingByteArrayOutputStream>(16 * 1024, 4 * 1024, keyDescriptor) {
@Override
@NotNull
public BufferExposingByteArrayOutputStream createValue(final Key key) {
return myStreamPool.alloc();
}
@Override
protected void onDropFromCache(final Key key, @NotNull final BufferExposingByteArrayOutputStream bytes) {
myEnumerator.lockStorage();
try {
long previousRecord;
final int id;
if (myDirectlyStoreLongFileOffsetMode) {
previousRecord = ((PersistentBTreeEnumerator<Key>)myEnumerator).getNonNegativeValue(key);
id = -1;
}
else {
id = enumerate(key);
previousRecord = readValueId(id);
}
long headerRecord = myValueStorage.appendBytes(bytes.toByteArraySequence(), previousRecord);
if (myDirectlyStoreLongFileOffsetMode) {
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(key, headerRecord);
}
else {
updateValueId(id, headerRecord, previousRecord, key, 0);
}
if (previousRecord == NULL_ADDR) {
myLiveAndGarbageKeysCounter += LIVE_KEY_MASK;
}
if (bytes.getInternalBuffer().length <= MAX_RECYCLED_BUFFER_SIZE) {
// Avoid internal fragmentation by not retaining / reusing large append buffers (IDEA-208533)
myStreamPool.recycle(bytes);
}
}
catch (IOException e) {
markCorrupted();
throw new RuntimeException(e);
}
finally {
myEnumerator.unlockStorage();
}
}
};
}
private static boolean doNewCompact() {
return System.getProperty("idea.persistent.hash.map.oldcompact") == null;
}
private boolean forceNewCompact() {
return System.getProperty("idea.persistent.hash.map.newcompact") != null &&
(int)(myLiveAndGarbageKeysCounter & DEAD_KEY_NUMBER_MASK) > 0;
}
public final void dropMemoryCaches() {
if (myDoTrace) LOG.info("Drop memory caches " + myStorageFile);
synchronized (myEnumerator) {
doDropMemoryCaches();
}
}
protected void doDropMemoryCaches() {
myEnumerator.lockStorage();
try {
clearAppenderCaches();
}
finally {
myEnumerator.unlockStorage();
}
}
public int getSize() {
return (int)(myLiveAndGarbageKeysCounter / LIVE_KEY_MASK);
}
int getGarbageSize() {
return (int)myLiveAndGarbageKeysCounter;
}
public Path getBaseFile() {
return myEnumerator.myFile;
}
@TestOnly // public for tests
@SuppressWarnings("WeakerAccess") // used in upsource for some reason
public boolean makesSenseToCompact() {
if (myIsReadOnly) return false;
final long fileSize = myValueStorage.getSize();
final int megabyte = 1024 * 1024;
if (fileSize > 5 * megabyte) { // file is longer than 5MB and (more than 50% of keys is garbage or approximate benefit larger than 100M)
int liveKeys = (int)(myLiveAndGarbageKeysCounter / LIVE_KEY_MASK);
int deadKeys = (int)(myLiveAndGarbageKeysCounter & DEAD_KEY_NUMBER_MASK);
if (fileSize > 50 * megabyte && forceNewCompact()) return true;
if (deadKeys < 50) return false;
final long benefitSize = Math.max(100 * megabyte, fileSize / 4);
final long avgValueSize = fileSize / (liveKeys + deadKeys);
return deadKeys > liveKeys ||
avgValueSize * deadKeys > benefitSize ||
myReadCompactionGarbageSize > fileSize / 2;
}
return false;
}
@NotNull
private static Path checkDataFiles(@NotNull Path file) {
if (!Files.exists(file)) {
deleteFilesStartingWith(getDataFile(file).toFile());
}
return file;
}
public static void deleteFilesStartingWith(@NotNull File prefixFile) {
IOUtil.deleteAllFilesStartingWith(prefixFile);
}
/**
* Deletes {@param map} files and trying to close it before.
*/
public static void deleteMap(@NotNull PersistentHashMap<?, ?> map) {
Path baseFile = map.getBaseFile();
try {
map.close();
}
catch (IOException ignored) {}
deleteFilesStartingWith(baseFile.toFile());
}
@NotNull
static Path getDataFile(@NotNull Path file) { // made public for testing
return file.resolveSibling(file.getFileName() + DATA_FILE_EXTENSION);
}
@Override
public final void put(Key key, Value value) throws IOException {
if (myIsReadOnly) throw new IncorrectOperationException();
synchronized (myEnumerator) {
try {
doPut(key, value);
}
catch (IOException ex) {
myEnumerator.markCorrupted();
throw ex;
}
}
}
protected void doPut(Key key, Value value) throws IOException {
long newValueOffset = -1;
if (!myIntMapping) {
final BufferExposingByteArrayOutputStream bytes = new BufferExposingByteArrayOutputStream();
AppendStream appenderStream = ourFlyweightAppenderStream.getValue();
appenderStream.setOut(bytes);
myValueExternalizer.save(appenderStream, value);
appenderStream.setOut(null);
newValueOffset = myValueStorage.appendBytes(bytes.toByteArraySequence(), 0);
}
myEnumerator.lockStorage();
try {
myEnumerator.markDirty(true);
myAppendCache.remove(key);
long oldValueOffset;
if (myDirectlyStoreLongFileOffsetMode) {
if (myIntMapping) {
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(key, (Integer)value);
return;
}
oldValueOffset = ((PersistentBTreeEnumerator<Key>)myEnumerator).getNonNegativeValue(key);
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(key, newValueOffset);
}
else {
final int id = enumerate(key);
if (myIntMapping) {
myEnumerator.myStorage.putInt(id + myParentValueRefOffset, (Integer)value);
return;
}
oldValueOffset = readValueId(id);
updateValueId(id, newValueOffset, oldValueOffset, key, 0);
}
if (oldValueOffset != NULL_ADDR) {
myLiveAndGarbageKeysCounter++;
}
else {
myLiveAndGarbageKeysCounter += LIVE_KEY_MASK;
}
}
finally {
myEnumerator.unlockStorage();
}
}
@Override
public final int enumerate(Key name) throws IOException {
if (myIsReadOnly) throw new IncorrectOperationException();
synchronized (myEnumerator) {
myIntAddressForNewRecord = canUseIntAddressForNewRecord(myValueStorage.getSize());
return super.enumerate(name);
}
}
@ApiStatus.Experimental
public interface ValueDataAppender {
void append(DataOutput out) throws IOException;
}
/**
* Appends value chunk from specified appender to key's value.
* Important use note: value externalizer used by this map should process all bytes from DataInput during deserialization and make sure
* that deserialized value is consistent with value chunks appended.
* E.g. Value can be Set of String and individual Strings can be appended with this method for particular key, when {@link #get(Object)} will
* be eventually called for the key, deserializer will read all bytes retrieving Strings and collecting them into Set
*/
@Override
public final void appendData(Key key, @NotNull ValueDataAppender appender) throws IOException {
if (myIsReadOnly) throw new IncorrectOperationException();
synchronized (myEnumerator) {
try {
doAppendData(key, appender);
}
catch (IOException ex) {
myEnumerator.markCorrupted();
throw ex;
}
}
}
private static final ThreadLocalCachedValue<AppendStream> ourFlyweightAppenderStream = new ThreadLocalCachedValue<AppendStream>() {
@NotNull
@Override
protected AppendStream create() {
return new AppendStream();
}
};
private void doAppendData(Key key, @NotNull ValueDataAppender appender) throws IOException {
assert !myIntMapping;
myEnumerator.markDirty(true);
AppendStream appenderStream = ourFlyweightAppenderStream.getValue();
BufferExposingByteArrayOutputStream stream = myAppendCache.get(key);
appenderStream.setOut(stream);
myValueStorage.checkAppendsAllowed(stream.size());
appender.append(appenderStream);
appenderStream.setOut(null);
}
/**
* Process all keys registered in the map. Note that keys which were removed after {@link #compact()} call will be processed as well. Use
* {@link #processKeysWithExistingMapping(Processor)} to process only keys with existing mappings
*/
@Override
public final boolean processKeys(@NotNull Processor<? super Key> processor) throws IOException {
synchronized (myEnumerator) {
try {
myAppendCache.clear();
return myEnumerator.iterateData(processor);
}
catch (IOException e) {
myEnumerator.markCorrupted();
throw e;
}
}
}
@NotNull
public Collection<Key> getAllKeysWithExistingMapping() throws IOException {
final List<Key> values = new ArrayList<>();
processKeysWithExistingMapping(new CommonProcessors.CollectProcessor<>(values));
return values;
}
public final boolean processKeysWithExistingMapping(Processor<? super Key> processor) throws IOException {
synchronized (myEnumerator) {
try {
myAppendCache.clear();
return myEnumerator.processAllDataObject(processor, new PersistentEnumerator.DataFilter() {
@Override
public boolean accept(final int id) {
return readValueId(id) != NULL_ADDR;
}
});
}
catch (IOException e) {
myEnumerator.markCorrupted();
throw e;
}
}
}
@Override
public final Value get(Key key) throws IOException {
synchronized (myEnumerator) {
myBusyReading = true;
try {
return doGet(key);
}
catch (IOException ex) {
try {
myEnumerator.markCorrupted();
} catch (Exception e) {
LOG.warn(e);
}
throw ex;
}
finally {
myBusyReading = false;
}
}
}
public boolean isBusyReading() {
return myBusyReading;
}
@Nullable
protected Value doGet(Key key) throws IOException {
myEnumerator.lockStorage();
final long valueOffset;
final int id;
try {
myAppendCache.remove(key);
if (myDirectlyStoreLongFileOffsetMode) {
valueOffset = ((PersistentBTreeEnumerator<Key>)myEnumerator).getNonNegativeValue(key);
if (myIntMapping) {
return (Value)(Integer)(int)valueOffset;
}
id = -1;
}
else {
id = tryEnumerate(key);
if (id == PersistentEnumeratorBase.NULL_ID) {
return null;
}
if (myIntMapping) {
return (Value)(Integer)myEnumerator.myStorage.getInt(id + myParentValueRefOffset);
}
valueOffset = readValueId(id);
}
if (valueOffset == NULL_ADDR) {
return null;
}
}
finally {
myEnumerator.unlockStorage();
}
final PersistentHashMapValueStorage.ReadResult readResult = myValueStorage.readBytes(valueOffset);
final Value valueRead;
try (DataInputStream input = new DataInputStream(new UnsyncByteArrayInputStream(readResult.buffer))) {
valueRead = myValueExternalizer.read(input);
}
if (myValueStorage.performChunksCompaction(readResult.chunksCount)) {
long newValueOffset = myValueStorage.compactChunks(new ValueDataAppender() {
@Override
public void append(DataOutput out) throws IOException {
myValueExternalizer.save(out, valueRead);
}
}, readResult);
myEnumerator.lockStorage();
try {
myEnumerator.markDirty(true);
if (myDirectlyStoreLongFileOffsetMode) {
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(key, newValueOffset);
}
else {
updateValueId(id, newValueOffset, valueOffset, key, 0);
}
myLiveAndGarbageKeysCounter++;
myReadCompactionGarbageSize += readResult.buffer.length;
}
finally {
myEnumerator.unlockStorage();
}
}
return valueRead;
}
public final boolean containsMapping(Key key) throws IOException {
synchronized (myEnumerator) {
return doContainsMapping(key);
}
}
private boolean doContainsMapping(Key key) throws IOException {
myEnumerator.lockStorage();
try {
myAppendCache.remove(key);
if (myDirectlyStoreLongFileOffsetMode) {
return ((PersistentBTreeEnumerator<Key>)myEnumerator).getNonNegativeValue(key) != NULL_ADDR;
}
else {
final int id = tryEnumerate(key);
if (id == PersistentEnumeratorBase.NULL_ID) {
return false;
}
if (myIntMapping) return true;
return readValueId(id) != NULL_ADDR;
}
}
finally {
myEnumerator.unlockStorage();
}
}
public final void remove(Key key) throws IOException {
if (myIsReadOnly) throw new IncorrectOperationException();
synchronized (myEnumerator) {
doRemove(key);
}
}
protected void doRemove(Key key) throws IOException {
myEnumerator.lockStorage();
try {
myAppendCache.remove(key);
final long record;
if (myDirectlyStoreLongFileOffsetMode) {
assert !myIntMapping; // removal isn't supported
record = ((PersistentBTreeEnumerator<Key>)myEnumerator).getNonNegativeValue(key);
if (record != NULL_ADDR) {
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(key, NULL_ADDR);
}
}
else {
final int id = tryEnumerate(key);
if (id == PersistentEnumeratorBase.NULL_ID) {
return;
}
assert !myIntMapping; // removal isn't supported
myEnumerator.markDirty(true);
record = readValueId(id);
updateValueId(id, NULL_ADDR, record, key, 0);
}
if (record != NULL_ADDR) {
myLiveAndGarbageKeysCounter++;
myLiveAndGarbageKeysCounter -= LIVE_KEY_MASK;
}
}
finally {
myEnumerator.unlockStorage();
}
}
@Override
public final void force() {
if (myIsReadOnly) return;
if (myDoTrace) LOG.info("Forcing " + myStorageFile);
synchronized (myEnumerator) {
doForce();
}
}
protected void doForce() {
myEnumerator.lockStorage();
try {
try {
clearAppenderCaches();
}
finally {
super.force();
}
}
finally {
myEnumerator.unlockStorage();
}
}
private void clearAppenderCaches() {
myAppendCache.clear();
myValueStorage.force();
}
@Override
public final void close() throws IOException {
if (myDoTrace) LOG.info("Closed " + myStorageFile);
synchronized (myEnumerator) {
doClose();
}
}
private void doClose() throws IOException {
myEnumerator.lockStorage();
try {
try {
myAppendCacheFlusher.stop();
try {
myAppendCache.clear();
}
catch (RuntimeException ex) {
Throwable cause = ex.getCause();
if (cause instanceof IOException) throw (IOException)cause;
throw ex;
}
}
finally {
final PersistentHashMapValueStorage valueStorage = myValueStorage;
try {
if (valueStorage != null) {
valueStorage.dispose();
}
}
finally {
super.close();
}
}
}
finally {
myEnumerator.unlockStorage();
}
}
static class CompactionRecordInfo {
final int key;
final int address;
long valueAddress;
long newValueAddress;
byte[] value;
CompactionRecordInfo(int _key, long _valueAddress, int _address) {
key = _key;
address = _address;
valueAddress = _valueAddress;
}
}
// made public for tests
public void compact() throws IOException {
if (myIsReadOnly) throw new IncorrectOperationException();
synchronized (myEnumerator) {
force();
LOG.info("Compacting " + myEnumerator.myFile);
LOG.info("Live keys:" + (int)(myLiveAndGarbageKeysCounter / LIVE_KEY_MASK) +
", dead keys:" + (int)(myLiveAndGarbageKeysCounter & DEAD_KEY_NUMBER_MASK) +
", read compaction size:" + myReadCompactionGarbageSize);
final long now = System.currentTimeMillis();
Path oldDataFile = getDataFile(myEnumerator.myFile);
final File[] oldFiles = getFilesInDirectoryWithNameStartingWith(oldDataFile);
final Path newPath = oldDataFile.resolveSibling(oldDataFile.getFileName() + ".new");
PersistentHashMapValueStorage.CreationTimeOptions options = myValueStorage.getOptions();
final PersistentHashMapValueStorage newStorage = new PersistentHashMapValueStorage(newPath, options);
myValueStorage.switchToCompactionMode();
myEnumerator.markDirty(true);
long sizeBefore = myValueStorage.getSize();
myLiveAndGarbageKeysCounter = 0;
myReadCompactionGarbageSize = 0;
try {
if (doNewCompact()) {
newCompact(newStorage);
}
else {
traverseAllRecords(new PersistentEnumerator.RecordsProcessor() {
@Override
public boolean process(final int keyId) throws IOException {
final long record = readValueId(keyId);
if (record != NULL_ADDR) {
PersistentHashMapValueStorage.ReadResult readResult = myValueStorage.readBytes(record);
long value = newStorage.appendBytes(readResult.buffer, 0, readResult.buffer.length, 0);
updateValueId(keyId, value, record, null, getCurrentKey());
myLiveAndGarbageKeysCounter += LIVE_KEY_MASK;
}
return true;
}
});
}
}
finally {
newStorage.dispose();
}
myValueStorage.dispose();
for (File f : oldFiles) {
assert FileUtil.deleteWithRenaming(f);
}
final long newSize = newStorage.getSize();
final File[] newFiles = getFilesInDirectoryWithNameStartingWith(newPath);
// newFiles should get the same names as oldDataFiles
File parentFile = newPath.getParent().toFile();
final String newBaseName = newPath.getFileName().toString();
final String oldDataFileBaseName = oldDataFile.getFileName().toString();
for (File f : newFiles) {
String nameAfterRename = StringUtil.replace(f.getName(), newBaseName, oldDataFileBaseName);
FileUtil.rename(f, new File(parentFile, nameAfterRename));
}
myValueStorage = new PersistentHashMapValueStorage(oldDataFile, options);
LOG.info("Compacted " + myEnumerator.myFile + ":" + sizeBefore + " bytes into " +
newSize + " bytes in " + (System.currentTimeMillis() - now) + "ms.");
myEnumerator.putMetaData(myLiveAndGarbageKeysCounter);
myEnumerator.putMetaData2(myLargeIndexWatermarkId);
if (myDoTrace) LOG.assertTrue(myEnumerator.isDirty());
}
}
private static File[] getFilesInDirectoryWithNameStartingWith(@NotNull Path fileFromDirectory) throws IOException {
Path parentFile = fileFromDirectory.getParent();
if (parentFile == null) return ArrayUtil.EMPTY_FILE_ARRAY;
Path fileName = fileFromDirectory.getFileName();
return Files.list(parentFile).filter(p -> {
return p.getFileName().toString().startsWith(fileName.toString());
}).map(p -> p.toFile()).toArray(File[]::new);
}
private void newCompact(@NotNull PersistentHashMapValueStorage newStorage) throws IOException {
long started = System.currentTimeMillis();
final List<CompactionRecordInfo> infos = new ArrayList<>(10000);
traverseAllRecords(new PersistentEnumerator.RecordsProcessor() {
@Override
public boolean process(final int keyId) {
final long record = readValueId(keyId);
if (record != NULL_ADDR) {
infos.add(new CompactionRecordInfo(getCurrentKey(), record, keyId));
}
return true;
}
});
LOG.info("Loaded mappings:" + (System.currentTimeMillis() - started) + "ms, keys:" + infos.size());
started = System.currentTimeMillis();
long fragments = 0;
if (!infos.isEmpty()) {
try {
fragments = myValueStorage.compactValues(infos, newStorage);
}
catch (Throwable t) {
if (!(t instanceof IOException)) throw new IOException("Compaction failed", t);
throw (IOException)t;
}
}
LOG.info("Compacted values for:" + (System.currentTimeMillis() - started) + "ms fragments:" +
(int)fragments + ", new fragments:" + (fragments >> 32));
started = System.currentTimeMillis();
try {
myEnumerator.lockStorage();
for (CompactionRecordInfo info : infos) {
updateValueId(info.address, info.newValueAddress, info.valueAddress, null, info.key);
myLiveAndGarbageKeysCounter += LIVE_KEY_MASK;
}
}
finally {
myEnumerator.unlockStorage();
}
LOG.info("Updated mappings:" + (System.currentTimeMillis() - started) + " ms");
}
private long readValueId(final int keyId) {
if (myDirectlyStoreLongFileOffsetMode) {
return ((PersistentBTreeEnumerator<Key>)myEnumerator).keyIdToNonNegativeOffset(keyId);
}
long address = myEnumerator.myStorage.getInt(keyId + myParentValueRefOffset);
if (address == 0 || address == -POSITIVE_VALUE_SHIFT) {
return NULL_ADDR;
}
if (address < 0) {
address = -address - POSITIVE_VALUE_SHIFT;
}
else {
long value = myEnumerator.myStorage.getInt(keyId + myParentValueRefOffset + 4) & 0xFFFFFFFFL;
address = ((address << 32) + value) & ~USED_LONG_VALUE_MASK;
}
return address;
}
private int smallKeys;
private int largeKeys;
private int transformedKeys;
private int requests;
private int updateValueId(int keyId, long value, long oldValue, @Nullable Key key, int processingKey) throws IOException {
if (myDirectlyStoreLongFileOffsetMode) {
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(((InlineKeyDescriptor<Key>)myKeyDescriptor).fromInt(processingKey), value);
return keyId;
}
final boolean newKey = oldValue == NULL_ADDR;
if (newKey) ++requests;
boolean defaultSizeInfo = true;
if (myCanReEnumerate) {
if (canUseIntAddressForNewRecord(value)) {
defaultSizeInfo = false;
myEnumerator.myStorage.putInt(keyId + myParentValueRefOffset, -(int)(value + POSITIVE_VALUE_SHIFT));
if (newKey) ++smallKeys;
}
else if ((keyId < myLargeIndexWatermarkId || myLargeIndexWatermarkId == 0) && (newKey || canUseIntAddressForNewRecord(oldValue))) {
// keyId is result of enumerate, if we do re-enumerate then it is no longer accessible unless somebody cached it
myIntAddressForNewRecord = false;
keyId = myEnumerator.reEnumerate(key == null ? myEnumerator.getValue(keyId, processingKey) : key);
++transformedKeys;
if (myLargeIndexWatermarkId == 0) {
myLargeIndexWatermarkId = keyId;
}
}
}
if (defaultSizeInfo) {
value |= USED_LONG_VALUE_MASK;
myEnumerator.myStorage.putInt(keyId + myParentValueRefOffset, (int)(value >>> 32));
myEnumerator.myStorage.putInt(keyId + myParentValueRefOffset + 4, (int)value);
if (newKey) ++largeKeys;
}
if (newKey && IOStatistics.DEBUG && (requests & IOStatistics.KEYS_FACTOR_MASK) == 0) {
IOStatistics.dump("small:" + smallKeys + ", large:" + largeKeys + ", transformed:" + transformedKeys +
",@" + getBaseFile());
}
if (doHardConsistencyChecks) {
long checkRecord = readValueId(keyId);
assert checkRecord == (value & ~USED_LONG_VALUE_MASK) : value;
}
return keyId;
}
@Override
public String toString() {
return super.toString() + ": " + myStorageFile;
}
@TestOnly
PersistentHashMapValueStorage getValueStorage() {
return myValueStorage;
}
@TestOnly
public boolean getReadOnly() {
return myIsReadOnly;
}
}
|
package me.izstas.rfs.server.service;
import java.io.IOException;
import java.nio.file.*;
import me.izstas.rfs.server.RfsException;
class PathUtils {
static RfsException wrapException(IOException e, String message) {
if (e instanceof AccessDeniedException) {
return new InaccessiblePathException(e);
}
if (e instanceof NoSuchFileException) {
return new NonexistentPathException(e);
}
return new RfsException(message, e);
}
static void createDirectories(Path path, boolean parent) {
if (parent && path.getParent() == null) {
return;
}
try {
Files.createDirectories(parent ? path.getParent() : path);
}
catch (FileAlreadyExistsException | NoSuchFileException e) { // While combination of these two may look weird,
// on Windows we seem to get the latter one
// if the problem is caused not by the immediate parent
// but a further ascendant
throw new NonexistentPathException("The path contains a file (not a directory) as one of the ascendants", e);
}
catch (IOException e) {
throw wrapException(e, parent ? "Can't create ascendant directories" : "Can't create directories");
}
}
private PathUtils() {
throw new AssertionError();
}
}
|
package pl.polidea.navigator.retrievers;
import java.io.File;
import pl.polidea.navigator.JsonMenuReader;
import pl.polidea.navigator.SplashScreenActivity;
import pl.polidea.navigator.factories.NavigationMenuFactoryInterface;
import pl.polidea.navigator.menu.AbstractNavigationMenu;
import pl.polidea.navigator.menu.MenuContext;
import android.os.AsyncTask;
import android.util.Log;
/**
* Loads menu from the retriever chosen.
*/
public class MenuLoaderAsyncTask extends AsyncTask<Void, Void, AbstractNavigationMenu> {
private static final String TAG = MenuLoaderAsyncTask.class.getSimpleName();
private final SplashScreenActivity activity;
private final MenuRetrieverInterface menuRetriever;
private final NavigationMenuFactoryInterface navigationMenuFactory;
public MenuLoaderAsyncTask(final SplashScreenActivity activity,
final NavigationMenuFactoryInterface naviationMenuFactory, final MenuRetrieverInterface menuRetriever) {
super();
this.activity = activity;
this.menuRetriever = menuRetriever;
this.navigationMenuFactory = naviationMenuFactory;
}
@Override
protected AbstractNavigationMenu doInBackground(final Void... params) {
Log.d(TAG, "Loading menu from " + menuRetriever);
final JsonMenuReader reader = new JsonMenuReader(new File(menuRetriever.getBaseDirectory(), "menu"),
"main_menu.json", null, navigationMenuFactory, true);
reader.createMenu(new MenuContext());
final AbstractNavigationMenu menu = reader.getMyMenu();
Log.d(TAG, " Returning menu: " + menu);
return menu;
}
@Override
protected void onPostExecute(final AbstractNavigationMenu result) {
super.onPostExecute(result);
activity.signalMenuReady(result);
}
}
|
package loci.tests;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.spi.ErrorCode;
/**
* A class for appending a timestamp to the log file name produced by the
* logging framework.
*
* @author Blazej Pindelski <bpindelski at dundee dot ac dot uk>
*/
public class TimestampedLogFileAppender extends FileAppender {
public TimestampedLogFileAppender() {
}
public TimestampedLogFileAppender(Layout layout, String filename,
boolean append, boolean bufferedIO, int bufferSize)
throws IOException {
super(layout, filename, append, bufferedIO, bufferSize);
}
public TimestampedLogFileAppender(Layout layout, String filename,
boolean append) throws IOException {
super(layout, filename, append);
}
public TimestampedLogFileAppender(Layout layout, String filename)
throws IOException {
super(layout, filename);
}
@Override
public void activateOptions() {
if (this.fileName != null) {
try {
this.setFile(this.getNewFileName(), this.fileAppend,
this.bufferedIO, this.bufferSize);
} catch (IOException e) {
this.errorHandler.error(
"Error while adding timestamp to log file name", e,
ErrorCode.FILE_OPEN_FAILURE);
}
}
}
private String getNewFileName() {
final int lastDotIndex = this.fileName.lastIndexOf(".");
String newFileName = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
String timestamp = "-" + sdf.format(new Date());
if (lastDotIndex != -1) {
newFileName = this.fileName.substring(0, lastDotIndex) +
timestamp + this.fileName.substring(lastDotIndex);
} else {
newFileName = this.fileName + timestamp;
}
return newFileName;
}
}
|
package org.spine3.server;
import com.google.protobuf.Any;
import com.google.protobuf.Empty;
import com.google.protobuf.Message;
import com.google.protobuf.StringValue;
import io.grpc.stub.StreamObserver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spine3.base.Command;
import org.spine3.base.CommandContext;
import org.spine3.base.CommandValidationError;
import org.spine3.base.EventContext;
import org.spine3.base.Response;
import org.spine3.base.UserId;
import org.spine3.server.aggregate.Aggregate;
import org.spine3.server.aggregate.AggregateRepository;
import org.spine3.server.aggregate.Apply;
import org.spine3.server.command.Assign;
import org.spine3.server.entity.IdFunction;
import org.spine3.server.event.EventSubscriber;
import org.spine3.server.event.GetProducerIdFromEvent;
import org.spine3.server.event.Subscribe;
import org.spine3.server.integration.IntegrationEvent;
import org.spine3.server.procman.CommandRouted;
import org.spine3.server.procman.ProcessManager;
import org.spine3.server.procman.ProcessManagerRepository;
import org.spine3.server.projection.Projection;
import org.spine3.server.projection.ProjectionRepository;
import org.spine3.server.storage.StorageFactory;
import org.spine3.server.storage.memory.InMemoryStorageFactory;
import org.spine3.server.type.EventClass;
import org.spine3.test.project.Project;
import org.spine3.test.project.ProjectId;
import org.spine3.test.project.command.AddTask;
import org.spine3.test.project.command.CreateProject;
import org.spine3.test.project.command.StartProject;
import org.spine3.test.project.event.ProjectCreated;
import org.spine3.test.project.event.ProjectStarted;
import org.spine3.test.project.event.TaskAdded;
import org.spine3.testdata.TestAggregateIdFactory;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.protobuf.util.TimeUtil.getCurrentTime;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.spine3.base.Identifiers.newUuid;
import static org.spine3.base.Responses.isUnsupportedCommand;
import static org.spine3.base.Responses.ok;
import static org.spine3.client.UserUtil.newUserId;
import static org.spine3.protobuf.Messages.fromAny;
import static org.spine3.testdata.TestCommands.createProjectCmd;
import static org.spine3.testdata.TestCommands.newCommandBus;
import static org.spine3.testdata.TestEventFactory.newEventBus;
import static org.spine3.testdata.TestEventFactory.projectCreatedIntegrationEvent;
import static org.spine3.testdata.TestEventMessageFactory.*;
/**
* @author Alexander Litus
*/
@SuppressWarnings("InstanceMethodNamingConvention")
public class BoundedContextShould {
private final UserId userId = newUserId(newUuid());
private final ProjectId projectId = TestAggregateIdFactory.newProjectId();
private final TestEventSubscriber subscriber = new TestEventSubscriber();
private StorageFactory storageFactory;
private BoundedContext boundedContext;
private boolean handlersRegistered = false;
@Before
public void setUp() {
storageFactory = InMemoryStorageFactory.getInstance();
boundedContext = BoundedContextTestStubs.create(storageFactory);
}
@After
public void tearDown() throws Exception {
if (handlersRegistered) {
boundedContext.getEventBus().unsubscribe(subscriber);
}
boundedContext.close();
}
/**
* Registers all test repositories, handlers etc.
*/
private void registerAll() {
final ProjectAggregateRepository repository = new ProjectAggregateRepository(boundedContext);
repository.initStorage(InMemoryStorageFactory.getInstance());
boundedContext.register(repository);
boundedContext.getEventBus().subscribe(subscriber);
handlersRegistered = true;
}
@Test
public void return_EventBus() {
assertNotNull(boundedContext.getEventBus());
}
@Test
public void return_CommandDispatcher() {
assertNotNull(boundedContext.getCommandBus());
}
@Test
public void register_AggregateRepository() {
final ProjectAggregateRepository repository = new ProjectAggregateRepository(boundedContext);
repository.initStorage(storageFactory);
boundedContext.register(repository);
}
@Test
public void register_ProcessManagerRepository() {
final ProjectPmRepo repository = new ProjectPmRepo(boundedContext);
repository.initStorage(storageFactory);
boundedContext.register(repository);
}
@Test
public void register_ProjectionRepository() {
final ProjectReportRepository repository = new ProjectReportRepository(boundedContext);
repository.initStorage(storageFactory);
boundedContext.register(repository);
}
@Test
public void return_unsupported_command_response_if_no_handlers_or_dispatchers() {
final TestResponseObserver responseObserver = new TestResponseObserver();
boundedContext.post(createProjectCmd(), responseObserver);
final Response response = responseObserver.getResponseHandled();
assertTrue(isUnsupportedCommand(response));
}
@Test
public void post_Command() {
registerAll();
final Command cmd = createProjectCmd(userId, projectId, getCurrentTime());
final TestResponseObserver observer = new TestResponseObserver();
boundedContext.post(cmd, observer);
assertEquals(ok(), observer.getResponseHandled());
}
@Test
public void notify_integration_event_subscribers() {
registerAll();
final TestResponseObserver observer = new TestResponseObserver();
final IntegrationEvent event = projectCreatedIntegrationEvent();
final Message msg = fromAny(event.getMessage());
boundedContext.notify(event, observer);
assertEquals(ok(), observer.getResponseHandled());
assertEquals(subscriber.eventHandled, msg);
}
@Test
public void verify_namespace_attribute_if_multitenant() {
final BoundedContext bc = BoundedContext.newBuilder()
.setStorageFactory(InMemoryStorageFactory.getInstance())
.setCommandBus(newCommandBus(storageFactory))
.setEventBus(newEventBus(storageFactory))
.setMultitenant(true)
.build();
final TestResponseObserver observer = new TestResponseObserver();
final Command cmd = Command.newBuilder()
// Pass empty command so that we have something valid to unpack in the context.
.setMessage(Any.pack(StringValue.getDefaultInstance()))
.build();
bc.post(cmd, observer);
assertEquals(CommandValidationError.NAMESPACE_UNKNOWN.getNumber(), observer.getResponseHandled()
.getError()
.getCode());
}
private static class TestResponseObserver implements StreamObserver<Response> {
private Response responseHandled;
@Override
public void onNext(Response response) {
this.responseHandled = response;
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
}
public Response getResponseHandled() {
return responseHandled;
}
}
@SuppressWarnings({"unused", "TypeMayBeWeakened"})
private static class ProjectAggregate extends Aggregate<ProjectId, Project, Project.Builder> {
private boolean isCreateProjectCommandHandled = false;
private boolean isAddTaskCommandHandled = false;
private boolean isStartProjectCommandHandled = false;
private boolean isProjectCreatedEventApplied = false;
private boolean isTaskAddedEventApplied = false;
private boolean isProjectStartedEventApplied = false;
// an aggregate constructor must be public because it is used via reflection
@SuppressWarnings("PublicConstructorInNonPublicClass")
public ProjectAggregate(ProjectId id) {
super(id);
}
@Assign
public ProjectCreated handle(CreateProject cmd, CommandContext ctx) {
isCreateProjectCommandHandled = true;
return projectCreatedMsg(cmd.getProjectId());
}
@Assign
public TaskAdded handle(AddTask cmd, CommandContext ctx) {
isAddTaskCommandHandled = true;
return taskAddedMsg(cmd.getProjectId());
}
@Assign
public List<ProjectStarted> handle(StartProject cmd, CommandContext ctx) {
isStartProjectCommandHandled = true;
final ProjectStarted message = projectStartedMsg(cmd.getProjectId());
return newArrayList(message);
}
@Apply
private void event(ProjectCreated event) {
final Project newState = Project.newBuilder(getState())
.setId(event.getProjectId())
.setStatus(Project.Status.CREATED)
.build();
incrementState(newState);
isProjectCreatedEventApplied = true;
}
@Apply
private void event(TaskAdded event) {
isTaskAddedEventApplied = true;
}
@Apply
private void event(ProjectStarted event) {
final Project newState = Project.newBuilder(getState())
.setId(event.getProjectId())
.setStatus(Project.Status.STARTED)
.build();
incrementState(newState);
isProjectStartedEventApplied = true;
}
}
private static class ProjectAggregateRepository extends AggregateRepository<ProjectId, ProjectAggregate> {
private ProjectAggregateRepository(BoundedContext boundedContext) {
super(boundedContext);
}
}
@SuppressWarnings("UnusedParameters") // It is intended in this empty handler class.
private static class TestEventSubscriber extends EventSubscriber {
private ProjectCreated eventHandled;
@Subscribe
public void on(ProjectCreated event, EventContext context) {
this.eventHandled = event;
}
@Subscribe
public void on(TaskAdded event, EventContext context) {
}
@Subscribe
public void on(ProjectStarted event, EventContext context) {
}
}
private static class ProjectProcessManager extends ProcessManager<ProjectId, Empty> {
// a ProcessManager constructor must be public because it is used via reflection
@SuppressWarnings("PublicConstructorInNonPublicClass")
public ProjectProcessManager(ProjectId id) {
super(id);
}
@Assign
@SuppressWarnings({"UnusedParameters", "unused"}) // OK for test method
public CommandRouted handle(CreateProject command, CommandContext ctx) {
return CommandRouted.getDefaultInstance();
}
@SuppressWarnings("UnusedParameters") // OK for test method
@Subscribe
public void on(ProjectCreated event, EventContext ctx) {
// Do nothing, just watch.
}
}
private static class ProjectPmRepo extends ProcessManagerRepository<ProjectId, ProjectProcessManager, Empty> {
private ProjectPmRepo(BoundedContext boundedContext) {
super(boundedContext);
}
@Override
public IdFunction<ProjectId, ? extends Message, EventContext> getIdFunction(EventClass eventClass) {
return GetProducerIdFromEvent.newInstance(0);
}
}
private static class ProjectReport extends Projection<ProjectId, Empty> {
@SuppressWarnings("PublicConstructorInNonPublicClass")
// Public constructor is a part of projection public API. It's called by a repository.
public ProjectReport(ProjectId id) {
super(id);
}
@SuppressWarnings("UnusedParameters") // OK for test method.
@Subscribe
public void on(ProjectCreated event, EventContext context) {
// Do nothing. We have the method so that there's one event class exposed by the repository.
}
}
private static class ProjectReportRepository extends ProjectionRepository<ProjectId, ProjectReport, Empty> {
protected ProjectReportRepository(BoundedContext boundedContext) {
super(boundedContext);
}
}
@Test(expected = IllegalArgumentException.class)
public void check_repository_has_storage_assigned_upon_registration() {
boundedContext.register(new ProjectAggregateRepository(boundedContext));
}
}
|
package com.axelor.i18n;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.axelor.common.StringUtils;
import com.axelor.db.JPA;
import com.axelor.db.Query;
import com.axelor.meta.db.MetaTranslation;
/**
* The database backed {@link ResourceBundle} that loads translations from the
* axelor database.
*
*/
public class I18nBundle extends ResourceBundle {
private final Locale locale;
private final Map<String, String> messages = new ConcurrentHashMap<>();
public I18nBundle(Locale locale) {
this.locale = locale;
}
@Override
protected Object handleGetObject(String key) {
if (StringUtils.isBlank(key)) {
return key;
}
final String result = load().get(key);
if (StringUtils.isBlank(result)) {
return key;
}
return result;
}
@Override
protected Set<String> handleKeySet() {
return load().keySet();
}
@Override
public Enumeration<String> getKeys() {
return Collections.enumeration(load().keySet());
}
private Map<String, String> load() {
if (!messages.isEmpty()) {
return messages;
}
try {
JPA.em();
} catch (Throwable e) {
return messages;
}
String lang = locale.getLanguage();
Query<MetaTranslation> query = Query.of(MetaTranslation.class).filter("self.language = ?1", lang).order("id").autoFlush(false);
if (query.count() == 0 && lang.length() > 2) {
query = Query.of(MetaTranslation.class).filter("self.language = ?1", lang.substring(0, 2));
}
long total = query.count();
int offset = 0;
int limit = 100;
while (offset < total) {
for (MetaTranslation tr : query.fetch(limit, offset)) {
if (tr.getMessage() != null) {
messages.put(tr.getKey(), tr.getMessage());
}
}
offset += limit;
}
return messages;
}
public static void invalidate() {
ResourceBundle.clearCache();
}
}
|
package protocolsupport.protocol.legacyremapper;
import java.util.HashMap;
import net.minecraft.server.v1_9_R2.SoundEffect;
public class LegacySound {
private static final HashMap<String, String> legacySounds = new HashMap<>();
//return new sound if legacy not found, so launcher will print a warning with that new sound name
public static String getSoundName(int soundType) {
String newSound = SoundEffect.a.b(SoundEffect.a.getId(soundType)).a();
String legacySound = legacySounds.get(newSound);
return legacySound != null ? legacySound : newSound;
}
public static String getLegacySoundName(String soundName) {
switch (soundName) {
case "game.player.hurt.fall.big":
case "game.neutral.hurt.fall.big":
case "game.hostile.hurt.fall.big": {
return "damage.fallbig";
}
case "game.player.hurt.fall.small":
case "game.neutral.hurt.fall.small":
case "game.hostile.hurt.fall.small": {
return "damage.fallsmall";
}
case "game.player.hurt":
case "game.player.die":
case "game.neutral.hurt":
case "game.neutral.die":
case "game.hostile.hurt":
case "game.hostile.die": {
return "damage.hit";
}
case "game.player.swim":
case "game.neutral.swim":
case "game.hostile.swim": {
return "liquid.swim";
}
case "game.player.swim.splash":
case "game.neutral.swim.splash":
case "game.hostile.swim.splash": {
return "liquid.splash";
}
default: {
return soundName;
}
}
}
private static void register(String newSound, String legacySound) {
legacySounds.put(newSound, legacySound);
}
static {
//sounds were autogenerated by comparing json files and weren't checked for correctness
register("entity.zombie_horse.ambient", "mob.horse.zombie.idle");
register("block.note.snare", "note.snare");
register("block.wood_button.click_off", "random.wood_click");
register("block.wood_button.click_on", "random.wood_click");
register("block.gravel.break", "dig.gravel");
register("block.gravel.place", "dig.gravel");
register("entity.arrow.hit", "random.bowhit");
register("block.tripwire.detach", "random.bowhit");
register("entity.splash_potion.break", "dig.glass");
register("block.glass.break", "dig.glass");
register("entity.zombie.ambient", "mob.zombie.say");
register("entity.zombie_villager.ambient", "mob.zombie.say");
register("entity.pig.death", "mob.pig.death");
register("entity.mule.hurt", "mob.horse.donkey.hit");
register("entity.donkey.hurt", "mob.horse.donkey.hit");
register("entity.generic.swim", "game.neutral.swim");
register("entity.hostile.swim", "game.neutral.swim");
register("entity.player.swim", "game.neutral.swim");
register("entity.generic.swim", "game.player.swim");
register("entity.hostile.swim", "game.player.swim");
register("entity.player.swim", "game.player.swim");
register("entity.endermen.ambient", "mob.endermen.idle");
register("block.portal.ambient", "portal.portal");
register("entity.generic.burn", "random.fizz");
register("block.fire.extinguish", "random.fizz");
register("block.redstone_torch.burnout", "random.fizz");
register("block.lava.extinguish", "random.fizz");
register("entity.generic.extinguish_fire", "random.fizz");
register("block.note.harp", "note.harp");
register("block.snow.hit", "step.snow");
register("block.snow.fall", "step.snow");
register("block.snow.step", "step.snow");
register("entity.arrow.hit_player", "random.successful_hit");
register("entity.zombie_pig.hurt", "mob.zombiepig.zpighurt");
register("entity.wolf.howl", "mob.wolf.howl");
register("entity.firework.launch", "fireworks.launch");
register("entity.cow.hurt", "mob.cow.hurt");
register("entity.cow.death", "mob.cow.hurt");
register("entity.firework.large_blast", "fireworks.largeBlast");
register("entity.blaze.hurt", "mob.blaze.hit");
register("entity.villager.death", "mob.villager.death");
register("entity.blaze.death", "mob.blaze.death");
register("entity.zombie_horse.death", "mob.horse.zombie.death");
register("entity.silverfish.death", "mob.silverfish.kill");
register("entity.endermite.death", "mob.silverfish.kill");
register("record.ward", "records.ward");
register("entity.wolf.pant", "mob.wolf.panting");
register("block.metal.break", "dig.stone");
register("block.metal.place", "dig.stone");
register("entity.armorstand.place", "dig.stone");
register("block.stone.break", "dig.stone");
register("block.stone.place", "dig.stone");
register("block.anvil.break", "dig.stone");
register("block.glass.place", "dig.stone");
register("entity.endermen.stare", "mob.endermen.stare");
register("entity.player.splash", "game.player.swim.splash");
register("entity.hostile.splash", "game.player.swim.splash");
register("entity.generic.splash", "game.player.swim.splash");
register("entity.small_magmacube.hurt", "mob.slime.small");
register("block.slime.fall", "mob.slime.small");
register("entity.small_slime.death", "mob.slime.small");
register("block.slime.step", "mob.slime.small");
register("entity.small_magmacube.death", "mob.slime.small");
register("entity.small_slime.hurt", "mob.slime.small");
register("block.slime.hit", "mob.slime.small");
register("music.nether", "music.game.nether");
register("entity.ghast.death", "mob.ghast.death");
register("entity.guardian.attack", "mob.guardian.attack");
register("block.dispenser.fail", "random.click");
register("block.comparator.click", "random.click");
register("block.stone_button.click_on", "random.click");
register("block.stone_button.click_off", "random.click");
register("block.tripwire.click_on", "random.click");
register("block.dispenser.dispense", "random.click");
register("ui.button.click", "random.click");
register("block.lever.click", "random.click");
register("block.tripwire.attach", "random.click");
register("block.stone_pressureplate.click_on", "random.click");
register("block.wood_pressureplate.click_off", "random.click");
register("block.stone_pressureplate.click_off", "random.click");
register("block.metal_pressureplate.click_off", "random.click");
register("block.tripwire.click_off", "random.click");
register("block.metal_pressureplate.click_on", "random.click");
register("block.wood_pressureplate.click_on", "random.click");
register("entity.zombie_pig.ambient", "mob.zombiepig.zpig");
register("entity.generic.death", "game.player.die");
register("entity.hostile.hurt", "game.player.die");
register("entity.player.hurt", "game.player.die");
register("entity.hostile.death", "game.player.die");
register("entity.generic.hurt", "game.player.die");
register("entity.player.death", "game.player.die");
register("music.dragon", "music.game.end.dragon");
register("entity.firework.twinkle_far", "fireworks.twinkle_far");
register("entity.elder_guardian.ambient_land", "mob.guardian.land.idle");
register("entity.guardian.ambient_land", "mob.guardian.land.idle");
register("block.grass.break", "dig.grass");
register("block.grass.place", "dig.grass");
register("entity.skeleton.step", "mob.skeleton.step");
register("entity.wither.death", "mob.wither.death");
register("entity.wolf.hurt", "mob.wolf.hurt");
register("entity.pig.saddle", "mob.horse.leather");
register("entity.horse.saddle", "mob.horse.leather");
register("entity.bat.loop", "mob.bat.loop");
register("entity.ghast.hurt", "mob.ghast.scream");
register("entity.generic.death", "game.player.hurt");
register("entity.hostile.hurt", "game.player.hurt");
register("entity.player.hurt", "game.player.hurt");
register("entity.hostile.death", "game.player.hurt");
register("entity.generic.hurt", "game.player.hurt");
register("entity.player.death", "game.player.hurt");
register("entity.generic.death", "game.neutral.die");
register("entity.hostile.hurt", "game.neutral.die");
register("entity.player.hurt", "game.neutral.die");
register("entity.hostile.death", "game.neutral.die");
register("entity.generic.hurt", "game.neutral.die");
register("entity.player.death", "game.neutral.die");
register("entity.creeper.death", "mob.creeper.death");
register("entity.horse.gallop", "mob.horse.gallop");
register("entity.wither.spawn", "mob.wither.spawn");
register("entity.endermen.hurt", "mob.endermen.hit");
register("entity.creeper.hurt", "mob.creeper.say");
register("entity.horse.step_wood", "mob.horse.wood");
register("entity.rabbit.death", "mob.rabbit.death");
register("entity.zombie_villager.converted", "mob.zombie.unfect");
register("block.anvil.use", "random.anvil_use");
register("block.enderchest.close", "random.chestclosed");
register("entity.mooshroom.shear", "mob.sheep.shear");
register("entity.sheep.shear", "mob.sheep.shear");
register("entity.item.pickup", "random.pop");
register("entity.bat.death", "mob.bat.death");
register("block.wood.place", "dig.wood");
register("block.wood.break", "dig.wood");
register("block.ladder.place", "dig.wood");
register("entity.armorstand.fall", "dig.wood");
register("block.ladder.break", "dig.wood");
register("record.chirp", "records.chirp");
register("entity.mule.death", "mob.horse.donkey.death");
register("entity.donkey.death", "mob.horse.donkey.death");
register("entity.firework.blast", "fireworks.blast");
register("entity.zombie_pig.angry", "mob.zombiepig.zpigangry");
register("entity.generic.swim", "game.hostile.swim");
register("entity.hostile.swim", "game.hostile.swim");
register("entity.player.swim", "game.hostile.swim");
register("entity.guardian.flop", "mob.guardian.flop");
register("entity.villager.yes", "mob.villager.yes");
register("entity.ghast.warn", "mob.ghast.charge");
register("entity.tnt.primed", "creeper.primed");
register("entity.creeper.primed", "creeper.primed");
register("block.sand.place", "dig.sand");
register("block.sand.break", "dig.sand");
register("entity.chicken.ambient", "mob.chicken.say");
register("record.13", "records.13");
register("record.11", "records.11");
register("entity.elder_guardian.death", "mob.guardian.elder.death");
register("entity.firework.twinkle", "fireworks.twinkle");
register("entity.skeleton_horse.death", "mob.horse.skeleton.death");
register("weather.rain", "ambient.weather.rain");
register("weather.rain.above", "ambient.weather.rain");
register("block.portal.trigger", "portal.trigger");
register("block.enderchest.open", "random.chestopen");
register("entity.horse.land", "mob.horse.land");
register("entity.endermite.step", "mob.silverfish.step");
register("entity.silverfish.step", "mob.silverfish.step");
register("entity.bat.takeoff", "mob.bat.takeoff");
register("entity.villager.no", "mob.villager.no");
register("entity.player.big_fall", "game.hostile.hurt.fall.big");
register("entity.generic.big_fall", "game.hostile.hurt.fall.big");
register("entity.hostile.big_fall", "game.hostile.hurt.fall.big");
register("entity.irongolem.step", "mob.irongolem.walk");
register("block.note.hat", "note.hat");
register("entity.zombie.attack_iron_door", "mob.zombie.metal");
register("entity.villager.trading", "mob.villager.haggle");
register("item.firecharge.use", "mob.ghast.fireball");
register("entity.ghast.shoot", "mob.ghast.fireball");
register("entity.enderdragon.shoot", "mob.ghast.fireball");
register("entity.blaze.shoot", "mob.ghast.fireball");
register("music.credits", "music.game.end.credits");
register("entity.irongolem.death", "mob.irongolem.death");
register("entity.item.break", "random.break");
register("item.shield.break", "random.break");
register("record.mellohi", "records.mellohi");
register("entity.zombie_villager.cure", "mob.zombie.remedy");
register("entity.enderpearl.throw", "random.bow");
register("block.dispenser.launch", "random.bow");
register("entity.skeleton.shoot", "random.bow");
register("entity.endereye.launch", "random.bow");
register("entity.firework.shoot", "random.bow");
register("entity.experience_bottle.throw", "random.bow");
register("entity.snowman.shoot", "random.bow");
register("entity.arrow.shoot", "random.bow");
register("entity.egg.throw", "random.bow");
register("entity.snowball.throw", "random.bow");
register("entity.bobber.throw", "random.bow");
register("entity.lingeringpotion.throw", "random.bow");
register("entity.splash_potion.throw", "random.bow");
register("entity.villager.ambient", "mob.villager.idle");
register("block.cloth.hit", "step.cloth");
register("block.cloth.step", "step.cloth");
register("block.cloth.fall", "step.cloth");
register("entity.silverfish.hurt", "mob.silverfish.hit");
register("entity.endermite.hurt", "mob.silverfish.hit");
register("music.game", "music.game");
register("block.lava.ambient", "liquid.lava");
register("entity.player.big_fall", "game.neutral.hurt.fall.big");
register("entity.generic.big_fall", "game.neutral.hurt.fall.big");
register("entity.hostile.big_fall", "game.neutral.hurt.fall.big");
register("record.mall", "records.mall");
register("entity.blaze.burn", "fire.fire");
register("block.fire.ambient", "fire.fire");
register("entity.zombie.attack_door_wood", "mob.zombie.wood");
register("entity.chicken.step", "mob.chicken.step");
register("record.stal", "records.stal");
register("entity.elder_guardian.hurt_land", "mob.guardian.land.hit");
register("entity.guardian.hurt_land", "mob.guardian.land.hit");
register("entity.chicken.egg", "mob.chicken.plop");
register("entity.donkey.chest", "mob.chicken.plop");
register("entity.enderdragon.flap", "mob.enderdragon.wings");
register("block.grass.step", "step.grass");
register("block.grass.fall", "step.grass");
register("block.grass.hit", "step.grass");
register("entity.horse.breathe", "mob.horse.breathe");
register("entity.player.big_fall", "game.player.hurt.fall.big");
register("entity.generic.big_fall", "game.player.hurt.fall.big");
register("entity.hostile.big_fall", "game.player.hurt.fall.big");
register("entity.mule.ambient", "mob.horse.donkey.idle");
register("entity.donkey.ambient", "mob.horse.donkey.idle");
register("record.far", "records.far");
register("entity.spider.step", "mob.spider.step");
register("entity.generic.death", "game.neutral.hurt");
register("entity.hostile.hurt", "game.neutral.hurt");
register("entity.player.hurt", "game.neutral.hurt");
register("entity.hostile.death", "game.neutral.hurt");
register("entity.generic.hurt", "game.neutral.hurt");
register("entity.player.death", "game.neutral.hurt");
register("entity.cow.ambient", "mob.cow.say");
register("entity.horse.jump", "mob.horse.jump");
register("entity.horse.step", "mob.horse.soft");
register("entity.player.splash", "game.neutral.swim.splash");
register("entity.hostile.splash", "game.neutral.swim.splash");
register("entity.generic.splash", "game.neutral.swim.splash");
register("entity.guardian.hurt", "mob.guardian.hit");
register("entity.enderdragon.death", "mob.enderdragon.end");
register("entity.zombie_villager.step", "mob.zombie.step");
register("entity.zombie.step", "mob.zombie.step");
register("entity.enderdragon.ambient", "mob.enderdragon.growl");
register("entity.enderdragon.growl", "mob.enderdragon.growl");
register("entity.wolf.shake", "mob.wolf.shake");
register("entity.endermen.death", "mob.endermen.death");
register("block.anvil.place", "random.anvil_land");
register("block.anvil.land", "random.anvil_land");
register("entity.generic.death", "game.hostile.hurt");
register("entity.hostile.hurt", "game.hostile.hurt");
register("entity.player.hurt", "game.hostile.hurt");
register("entity.hostile.death", "game.hostile.hurt");
register("entity.generic.hurt", "game.hostile.hurt");
register("entity.player.death", "game.hostile.hurt");
register("entity.minecart.inside", "minecart.inside");
register("entity.slime.squish", "mob.slime.big");
register("entity.magmacube.hurt", "mob.slime.big");
register("entity.magmacube.death", "mob.slime.big");
register("block.slime.break", "mob.slime.big");
register("block.slime.place", "mob.slime.big");
register("entity.slime.jump", "mob.slime.big");
register("entity.slime.hurt", "mob.slime.big");
register("entity.slime.death", "mob.slime.big");
register("block.water.ambient", "liquid.water");
register("entity.pig.hurt", "mob.pig.say");
register("entity.pig.ambient", "mob.pig.say");
register("entity.wither.shoot", "mob.wither.shoot");
register("record.blocks", "records.blocks");
register("item.firecharge.use", "item.fireCharge.use");
register("entity.ghast.shoot", "item.fireCharge.use");
register("entity.enderdragon.shoot", "item.fireCharge.use");
register("entity.blaze.shoot", "item.fireCharge.use");
register("block.sand.hit", "step.sand");
register("block.sand.step", "step.sand");
register("block.sand.fall", "step.sand");
register("music.creative", "music.game.creative");
register("entity.irongolem.hurt", "mob.irongolem.hit");
register("entity.horse.death", "mob.horse.death");
register("entity.bat.hurt", "mob.bat.hurt");
register("entity.ghast.scream", "mob.ghast.affectionate_scream");
register("entity.elder_guardian.ambient", "mob.guardian.elder.idle");
register("entity.zombie_pig.death", "mob.zombiepig.zpigdeath");
register("entity.lightning.thunder", "ambient.weather.thunder");
register("entity.minecart.riding", "minecart.base");
register("block.ladder.step", "step.ladder");
register("block.ladder.fall", "step.ladder");
register("block.ladder.hit", "step.ladder");
register("entity.donkey.angry", "mob.horse.donkey.angry");
register("ambient.cave", "ambient.cave.cave");
register("record.wait", "records.wait");
register("entity.firework.blast_far", "fireworks.blast_far");
register("entity.hostile.small_fall", "game.neutral.hurt.fall.small");
register("entity.player.small_fall", "game.neutral.hurt.fall.small");
register("entity.generic.small_fall", "game.neutral.hurt.fall.small");
register("entity.player.splash", "game.hostile.swim.splash");
register("entity.hostile.splash", "game.hostile.swim.splash");
register("entity.generic.splash", "game.hostile.swim.splash");
register("entity.generic.drink", "random.drink");
register("music.menu", "music.menu");
register("entity.generic.death", "game.hostile.die");
register("entity.hostile.hurt", "game.hostile.die");
register("entity.player.hurt", "game.hostile.die");
register("entity.hostile.death", "game.hostile.die");
register("entity.generic.hurt", "game.hostile.die");
register("entity.player.death", "game.hostile.die");
register("entity.cat.hiss", "mob.cat.hiss");
register("block.note.basedrum", "note.bd");
register("entity.spider.ambient", "mob.spider.say");
register("entity.spider.hurt", "mob.spider.say");
register("block.stone.fall", "step.stone");
register("block.anvil.fall", "step.stone");
register("block.metal.step", "step.stone");
register("block.stone.hit", "step.stone");
register("block.glass.fall", "step.stone");
register("block.stone.step", "step.stone");
register("block.anvil.step", "step.stone");
register("block.metal.hit", "step.stone");
register("block.glass.step", "step.stone");
register("block.metal.fall", "step.stone");
register("block.glass.hit", "step.stone");
register("block.anvil.hit", "step.stone");
register("entity.player.levelup", "random.levelup");
register("block.lava.pop", "liquid.lavapop");
register("entity.sheep.hurt", "mob.sheep.say");
register("entity.sheep.death", "mob.sheep.say");
register("entity.sheep.ambient", "mob.sheep.say");
register("entity.skeleton.ambient", "mob.skeleton.say");
register("entity.blaze.ambient", "mob.blaze.breathe");
register("entity.bat.ambient", "mob.bat.idle");
register("entity.magmacube.squish", "mob.magmacube.big");
register("entity.horse.ambient", "mob.horse.idle");
register("entity.hostile.small_fall", "game.hostile.hurt.fall.small");
register("entity.player.small_fall", "game.hostile.hurt.fall.small");
register("entity.generic.small_fall", "game.hostile.hurt.fall.small");
register("entity.zombie_horse.hurt", "mob.horse.zombie.hit");
register("entity.irongolem.attack", "mob.irongolem.throw");
register("block.cloth.break", "dig.cloth");
register("block.cloth.place", "dig.cloth");
register("block.gravel.fall", "step.gravel");
register("block.gravel.step", "step.gravel");
register("block.gravel.hit", "step.gravel");
register("entity.endermite.ambient", "mob.silverfish.say");
register("entity.silverfish.ambient", "mob.silverfish.say");
register("entity.cat.purr", "mob.cat.purr");
register("entity.zombie.infect", "mob.zombie.infect");
register("entity.generic.eat", "random.eat");
register("entity.wolf.ambient", "mob.wolf.bark");
register("entity.tnt.primed", "game.tnt.primed");
register("entity.creeper.primed", "game.tnt.primed");
register("entity.sheep.step", "mob.sheep.step");
register("entity.zombie_villager.death", "mob.zombie.death");
register("entity.zombie.death", "mob.zombie.death");
register("entity.shulker.teleport", "mob.endermen.portal");
register("item.chorus_fruit.teleport", "mob.endermen.portal");
register("entity.endermen.teleport", "mob.endermen.portal");
register("entity.horse.angry", "mob.horse.angry");
register("entity.wolf.growl", "mob.wolf.growl");
register("block.snow.break", "dig.snow");
register("block.snow.place", "dig.snow");
register("block.piston.extend", "tile.piston.out");
register("entity.player.burp", "random.burp");
register("entity.cow.step", "mob.cow.step");
register("entity.wither.hurt", "mob.wither.hurt");
register("entity.guardian.death_land", "mob.guardian.land.death");
register("entity.elder_guardian.death_land", "mob.guardian.land.death");
register("music.end", "music.game.end");
register("entity.chicken.hurt", "mob.chicken.hurt");
register("entity.chicken.death", "mob.chicken.hurt");
register("entity.wolf.step", "mob.wolf.step");
register("entity.wolf.death", "mob.wolf.death");
register("entity.wolf.whine", "mob.wolf.whine");
register("block.note.pling", "note.pling");
register("entity.hostile.small_fall", "game.player.hurt.fall.small");
register("entity.player.small_fall", "game.player.hurt.fall.small");
register("entity.generic.small_fall", "game.player.hurt.fall.small");
register("entity.rabbit.hurt", "mob.rabbit.hurt");
register("entity.cat.purreow", "mob.cat.purreow");
register("entity.firework.large_blast_far", "fireworks.largeBlast_far");
register("entity.skeleton.hurt", "mob.skeleton.hurt");
register("entity.spider.death", "mob.spider.death");
register("block.anvil.destroy", "random.anvil_break");
register("record.cat", "records.cat");
register("entity.wither.ambient", "mob.wither.idle");
register("entity.elder_guardian.hurt", "mob.guardian.elder.hit");
register("entity.endermen.scream", "mob.endermen.scream");
register("entity.cat.death", "mob.cat.hitt");
register("entity.cat.hurt", "mob.cat.hitt");
register("entity.small_magmacube.squish", "mob.magmacube.small");
register("item.flintandsteel.use", "fire.ignite");
register("entity.enderdragon.hurt", "mob.enderdragon.hit");
register("entity.zombie.hurt", "mob.zombie.hurt");
register("entity.zombie_villager.hurt", "mob.zombie.hurt");
register("entity.enderdragon_fireball.explode", "random.explode");
register("entity.generic.explode", "random.explode");
register("entity.lightning.impact", "random.explode");
register("block.end_gateway.spawn", "random.explode");
register("entity.slime.attack", "mob.slime.attack");
register("entity.magmacube.jump", "mob.magmacube.jump");
register("entity.bobber.splash", "random.splash");
register("entity.skeleton_horse.hurt", "mob.horse.skeleton.hit");
register("entity.rabbit.jump", "mob.rabbit.hop");
register("entity.ghast.ambient", "mob.ghast.moan");
register("entity.elder_guardian.curse", "mob.guardian.curse");
register("entity.splash_potion.break", "game.potion.smash");
register("block.glass.break", "game.potion.smash");
register("block.note.bass", "note.bassattack");
register("block.dispenser.fail", "gui.button.press");
register("block.comparator.click", "gui.button.press");
register("block.stone_button.click_on", "gui.button.press");
register("block.stone_button.click_off", "gui.button.press");
register("block.tripwire.click_on", "gui.button.press");
register("block.dispenser.dispense", "gui.button.press");
register("ui.button.click", "gui.button.press");
register("block.lever.click", "gui.button.press");
register("block.tripwire.attach", "gui.button.press");
register("block.stone_pressureplate.click_on", "gui.button.press");
register("block.wood_pressureplate.click_off", "gui.button.press");
register("block.stone_pressureplate.click_off", "gui.button.press");
register("block.metal_pressureplate.click_off", "gui.button.press");
register("block.tripwire.click_off", "gui.button.press");
register("block.metal_pressureplate.click_on", "gui.button.press");
register("block.wood_pressureplate.click_on", "gui.button.press");
register("entity.experience_orb.touch", "random.orb");
register("entity.experience_orb.pickup", "random.orb");
register("entity.wither.break_block", "mob.zombie.woodbreak");
register("entity.zombie.break_door_wood", "mob.zombie.woodbreak");
register("entity.horse.armor", "mob.horse.armor");
register("entity.rabbit.ambient", "mob.rabbit.idle");
register("block.piston.contract", "tile.piston.in");
register("entity.cat.ambient", "mob.cat.meow");
register("entity.pig.step", "mob.pig.step");
register("record.strad", "records.strad");
register("block.wood.hit", "step.wood");
register("block.wood.fall", "step.wood");
register("block.wood.step", "step.wood");
register("block.portal.travel", "portal.travel");
register("entity.guardian.death", "mob.guardian.death");
register("entity.skeleton.death", "mob.skeleton.death");
register("entity.horse.hurt", "mob.horse.hit");
register("entity.villager.hurt", "mob.villager.hit");
register("entity.skeleton_horse.ambient", "mob.horse.skeleton.idle");
//manually mapped sounds
register("block.chest.open", "random.chestopen");
register("block.chest.close", "random.chestclosed");
}
}
|
package rapanui.ui.views;
import java.awt.Insets;
import java.util.Map;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyledDocument;
import static javax.swing.text.StyleConstants.*;
import rapanui.core.*;
import rapanui.dsl.Term;
class JustificationViewer extends JTextPane {
private static final long serialVersionUID = 1L;
private static final String DEFAULT_STYLE = "default";
private static final String MATH_STYLE = "math";
private static final String BOLD_STYLE = "bold";
private static final String BOLD_MATH_STYLE = "math_bold";
public JustificationViewer() {
setEditable(false);
this.setMargin(new Insets(10,10,10,10));
initializeStyles();
}
private void initializeStyles() {
Style defaultStyle = getStyledDocument().addStyle(DEFAULT_STYLE, null);
setFontSize(defaultStyle, 14);
setItalic(defaultStyle, true);
Style mathStyle = getStyledDocument().addStyle(MATH_STYLE, defaultStyle);
setFontFamily(mathStyle, "DejaVu Sans Mono");
setItalic(mathStyle, false);
Style boldMathStyle = getStyledDocument().addStyle(BOLD_MATH_STYLE, mathStyle);
setBold(boldMathStyle, true);
Style boldStyle = getStyledDocument().addStyle(BOLD_STYLE, null);
setFontSize(boldStyle, 15);
setBold(boldStyle, true);
}
public void loadJustification(Justification justification) {
clear();
try {
appendBoldText("Es gilt ");
appendMathText(justification.getJustifiedFormula().serialize());
appendText(", " + DisplayStringHelper.shortDescription(justification) + ".\n\n");
if (justification instanceof EnvironmentPremiseJustification || justification instanceof ProofJustification)
return; // no further details
appendBoldText("Begründung:\n\n");
displayJustification(justification, 0);
} catch (BadLocationException e) {
assert false;
}
}
public void clear() {
setText(null);
}
private int displayJustification(Justification justification, int referenceCounter) throws BadLocationException {
if (justification instanceof EnvironmentPremiseJustification)
return displayJustification((EnvironmentPremiseJustification)justification, referenceCounter);
else if (justification instanceof ProofJustification)
return displayJustification((ProofJustification)justification, referenceCounter);
else if (justification instanceof SubtermEqualityJustification)
return displayJustification((SubtermEqualityJustification)justification, referenceCounter);
else if (justification instanceof RuleApplication)
return displayJustification((RuleApplication)justification, referenceCounter);
else
throw new IllegalStateException("Unknown justification type");
}
private int displayJustification(EnvironmentPremiseJustification justification, int referenceCounter)
throws BadLocationException {
appendText("Es gilt ");
appendMathText(justification.getJustifiedFormula().serialize());
appendText(" " + DisplayStringHelper.shortDescription(justification) + " [" + (++referenceCounter) + "].\n\n");
return referenceCounter;
}
private int displayJustification(ProofJustification justification, int referenceCounter)
throws BadLocationException {
appendText("Es gilt ");
appendMathText(justification.getJustifiedFormula().serialize());
appendText(" " + DisplayStringHelper.shortDescription(justification) + " [" + (++referenceCounter) + "]\n\n.");
return referenceCounter;
}
private int displayJustification(SubtermEqualityJustification justification, int referenceCounter)
throws BadLocationException {
referenceCounter = displayJustification(justification.getJustification(), referenceCounter);
appendText("Daraus folgt ");
appendMathText(justification.getJustifiedFormula().serialize());
appendText(" [" + (++referenceCounter) + "].\n\n");
return referenceCounter;
}
private int displayJustification(RuleApplication justification, int referenceCounter)
throws BadLocationException {
Justification[] premiseJustifications = justification.getPremiseJustifications();
String referenceList = "";
for (Justification premiseJustification : premiseJustifications) {
referenceCounter = displayJustification(premiseJustification, referenceCounter);
referenceList += "[" + referenceCounter + "], ";
}
if (!referenceList.isEmpty())
referenceList = referenceList.substring(0, referenceList.length() - 2);
appendText("Nach der Regel " + justification.getAppliedRule().getName() + ":\n\n");
appendMathText(justification.getAppliedRule().serialize());
appendText("\nmit ");
displayVariableTranslation(justification.getVariableTranslation());
if (!referenceList.isEmpty())
appendText(" und " + referenceList);
appendText(" folgt dann ");
appendMathText(justification.getJustifiedFormula().serialize());
appendText(" [" + (++referenceCounter) + "].\n\n");
return referenceCounter;
}
private void displayVariableTranslation(Map<String, Term> translation) throws BadLocationException {
boolean isFirst = true;
for (String variable : translation.keySet()) {
if (!isFirst)
appendText(", ");
else
isFirst = false;
appendMathText(variable + " = ");
appendBoldMathText(translation.get(variable).serialize());
}
}
private void appendBoldText(String text) throws BadLocationException {
StyledDocument document = getStyledDocument();
document.insertString(document.getLength(), text, document.getStyle(BOLD_STYLE));
}
private void appendText(String text) throws BadLocationException {
StyledDocument document = getStyledDocument();
document.insertString(document.getLength(), text, document.getStyle(DEFAULT_STYLE));
}
private void appendMathText(String mathText) throws BadLocationException {
StyledDocument document = getStyledDocument();
document.insertString(document.getLength(), mathText, document.getStyle(MATH_STYLE));
}
private void appendBoldMathText(String mathText) throws BadLocationException {
StyledDocument document = getStyledDocument();
document.insertString(document.getLength(), mathText, document.getStyle(BOLD_MATH_STYLE));
}
}
|
package com.frameworkset.util;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.frameworkset.json.JsonTypeReference;
import com.fasterxml.jackson.core.type.TypeReference;
public class TestStringUtil {
@org.junit.Test
public void testJsontoObject()
{
String ddd = "{'docId':true,'docname':'aaaa'}";
Map data = SimpleStringUtil.json2Object(ddd, HashMap.class);
System.out.println(data);
}
@org.junit.Test
public void testArrayToenum()
{
String[] datas = new String[] {"1","2"};
Enumeration enums = SimpleStringUtil.arryToenum(datas);
while(enums.hasMoreElements())
{
System.out.println(enums.nextElement());
}
}
@org.junit.Test
public void testObjecttoString()
{
String ddd = "{'docId':true,'docname':'aaaa'}";
System.out.println(SimpleStringUtil.tostring(ddd));
System.out.println(SimpleStringUtil.tostring(new String[]{"aa","bb"}));
List dd = new ArrayList();
dd.add(1);
dd.add(2);
System.out.println(SimpleStringUtil.tostring(new Object[]{"aa",null,dd}));
System.out.println(SimpleStringUtil.tostring(null));
}
@org.junit.Test
public void testIntObjecttoJson()
{
System.out.println(SimpleStringUtil.object2json(1));
}
@org.junit.Test
public void testmObjecttoJson()
{
try {
String tet ="{\"date\":\"2016 Jul 2 00:06:56\",\"router\":\"175.10.31.66\",\"program\":\"kernel\",\"unixtime\":\"1467389223\",\"msg_kunteng\":\"[136152.820000] {\\\"log-type\\\":\\\"kt-wdpi\\\",\\\"p\\\":\\\"HTTP\\\",\\\"ptype\\\":\\\"GET\\\",\\\"wip\\\":\\\"192.168.1.105\\\",\\\"wmac\\\":\\\"60ACC8010598\\\",\\\"smac\\\":\\\"847303487152\\\",\\\"lmac\\\":\\\"60ACC8010598\\\",\\\"sip\\\":\\\"192.168.199.230\\\",\\\"dip\\\":\\\"123.151.10.172\\\",\\\"sport\\\":\\\"59440\\\",\\\"dport\\\":\\\"443\\\",\\\"url\\\":\\\"http://dns.weixin.qq.com/cgi-bin/micromsg-bin/newgetdns?uin=2597445619&clientversion=637736505&scene=0&net=1&md5=02d8691b08787fbbb9fd3ba88c887619&devicetype=android-21&lan=zh_CN&sigver=2\\\"}\"}";
HashMap map = SimpleStringUtil.json2Object(tet, HashMap.class);
System.out.println(map);
// tet = "{\"date\":\"2016 Jul 3 09:00:42\",\"router\":\"175.8.11.35\",\"program\":\"kt-macscan\",\"unixtime\":\"1467507650\",\"msg_kunteng\":\"hiwifi_ac#011{\\\"d\\\":[{\\\"rssi\\\":\\\"-85\\\",\\\"macaddr\\\":\\\"DAA119E5D635\\\"},{\\\"rssi\\\":\\\"-89\\\",\\\"macaddr\\\":\\\"BC44864826C9\\\"},{\\\"rssi\\\":\\\"-66\\\",\\\"macaddr\\\":\\\"18DC561A9BD3\\\"},{\\\"rssi\\\":\\\"-87\\\",\\\"macaddr\\\":\\\"DC9B9CDDD165\\\"},{\\\"rssi\\\":\\\"-89\\\",\\\"macaddr\\\":\\\"68A3C4C20538\\\"},{\\\"rssi\\\":\\\"-77\\\",\\\"macaddr\\\":\\\"A8BBCF603AFE\\\"},{\\\"rssi\\\":\\\"-81\\\",\\\"macaddr\\\":\\\"40E230331C0A\\\"}],\\\"s\\\":\\\"scan\\\",\\\"v\\\":\\\"1\\\"} \\\"127.0.0.1\\\" \\\"60ACC8010598\\\"\",\"@version\":\"1\",\"@timestamp\":\"2016-07-03T01:00:42.997Z\",\"path\":\"/data2/log/wifimsgnew/msg_20160703.log\",\"host\":\"dell\"}";
// LogstashMacMsg LogstashMacMsg = SimpleStringUtil.json2Object(tet, LogstashMacMsg.class);
// System.out.println(LogstashMacMsg);
tet = "{\"date\":\"2016 Jul 2 11:28:45\",\"router\":\"175.10.31.66\",\"program\":\"kt-macscan\",\"unixtime\":\"1467430132\",\"msg_kunteng\":\"hiwifi_ac#011{\\\"d\\\":[{\\\"rssi\\\":\\\"-87\\\",\\\"macaddr\\\":\\\"DC9B9CDDD165\\\"},{\\\"rssi\\\":\\\"-75\\\",\\\"macaddr\\\":\\\"08FD0E10531F\\\"},{\\\"rssi\\\":\\\"-86\\\",\\\"macaddr\\\":\\\"40E230331C0A\\\"}],\\\"s\\\":\\\"scan\\\",\\\"v\\\":\\\"1\\\"} \\\"127.0.0.1\\\" \\\"60ACC8010598\\\"\"}";
MacMsg MacMsg = SimpleStringUtil.json2Object(tet, MacMsg.class);
System.out.println(MacMsg.getMsg_kunteng());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
@org.junit.Test
public void testListObjectSerial()
{
List<Integer> dd = new ArrayList<Integer>();
dd.add(1);
dd.add(2);
String json = SimpleStringUtil.object2json(dd);
dd = (List<Integer>) StringUtil.json2Object(json,new JsonTypeReference(new TypeReference<List<Integer>>(){}));
System.out.println(dd);
}
}
|
package test.producers;
import mlesiewski.simpledi.annotations.Inject;
import test.util.TestScope;
public class InjectionClient {
@Inject
UnnamedBean unnamedBean;
@Inject(name = UnnamedBeanProducer.NAMED_A)
UnnamedBean namedBeanA;
@Inject(name = UnnamedBeanProducer.NAMED_B)
UnnamedBean namedBeanB;
@Inject(scope = TestScope.NAME)
UnnamedBean scopedUnnamedBean;
}
|
package com.sun.star.sdbcx.comp.hsqldb;
/**
*
* @author oj93728
*/
public class NativeStorageAccess {
static { NativeLibraries.load(); }
public static final int READ = 1;
public static final int SEEKABLE = 2;
public static final int SEEKABLEREAD = 3;
public static final int WRITE = 4;
public static final int READWRITE = 7;
public static final int TRUNCATE = 8;
/** Creates a new instance of StorageAccess */
public NativeStorageAccess(String name,String _mode,Object key) throws java.io.IOException{
try {
int mode = NativeStorageAccess.SEEKABLEREAD;
if ( _mode.equals("rw") )
mode = NativeStorageAccess.READWRITE | NativeStorageAccess.SEEKABLE;
openStream(name, (String)key, mode);
} catch(Exception e){
throw new java.io.IOException();
}
}
public native void openStream(String name,String key, int mode);
public native void close(String name,String key) throws java.io.IOException;
public native long getFilePointer(String name,String key) throws java.io.IOException;
public native long length(String name,String key) throws java.io.IOException;
public native int read(String name,String key) throws java.io.IOException;
public native int read(String name,String key,byte[] b, int off, int len) throws java.io.IOException;
public native int readInt(String name,String key) throws java.io.IOException;
public native void seek(String name,String key,long position) throws java.io.IOException;
public native void write(String name,String key,byte[] b, int offset, int length) throws java.io.IOException;
public native void writeInt(String name,String key,int v) throws java.io.IOException;
}
|
package org.pm4j.core.pm.impl;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.metadata.BeanDescriptor;
import javax.validation.metadata.ConstraintDescriptor;
import javax.validation.metadata.PropertyDescriptor;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pm4j.common.util.CompareUtil;
import org.pm4j.common.util.collection.MapUtil;
import org.pm4j.core.exception.PmConverterException;
import org.pm4j.core.exception.PmResourceData;
import org.pm4j.core.exception.PmRuntimeException;
import org.pm4j.core.exception.PmValidationException;
import org.pm4j.core.pm.PmAspect;
import org.pm4j.core.pm.PmAttr;
import org.pm4j.core.pm.PmBean;
import org.pm4j.core.pm.PmCommandDecorator;
import org.pm4j.core.pm.PmConstants;
import org.pm4j.core.pm.PmElement;
import org.pm4j.core.pm.PmEvent;
import org.pm4j.core.pm.PmMessage;
import org.pm4j.core.pm.PmMessage.Severity;
import org.pm4j.core.pm.PmObject;
import org.pm4j.core.pm.PmOption;
import org.pm4j.core.pm.PmOptionSet;
import org.pm4j.core.pm.PmVisitor;
import org.pm4j.core.pm.annotation.PmAttrCfg;
import org.pm4j.core.pm.annotation.PmAttrCfg.Restriction;
import org.pm4j.core.pm.annotation.PmCacheCfg;
import org.pm4j.core.pm.annotation.PmCacheCfg.CacheMode;
import org.pm4j.core.pm.annotation.PmCommandCfg;
import org.pm4j.core.pm.annotation.PmCommandCfg.BEFORE_DO;
import org.pm4j.core.pm.annotation.PmOptionCfg;
import org.pm4j.core.pm.annotation.PmOptionCfg.NullOption;
import org.pm4j.core.pm.annotation.PmTitleCfg;
import org.pm4j.core.pm.api.PmCacheApi;
import org.pm4j.core.pm.api.PmEventApi;
import org.pm4j.core.pm.api.PmLocalizeApi;
import org.pm4j.core.pm.api.PmMessageUtil;
import org.pm4j.core.pm.impl.cache.PmCacheStrategy;
import org.pm4j.core.pm.impl.cache.PmCacheStrategyBase;
import org.pm4j.core.pm.impl.cache.PmCacheStrategyNoCache;
import org.pm4j.core.pm.impl.cache.PmCacheStrategyRequest;
import org.pm4j.core.pm.impl.converter.PmConverterErrorMessage;
import org.pm4j.core.pm.impl.converter.PmConverterOptionBased;
import org.pm4j.core.pm.impl.options.GenericOptionSetDef;
import org.pm4j.core.pm.impl.options.OptionSetDefNoOption;
import org.pm4j.core.pm.impl.options.PmOptionSetDef;
import org.pm4j.core.pm.impl.pathresolver.PassThroughPathResolver;
import org.pm4j.core.pm.impl.pathresolver.PathResolver;
import org.pm4j.core.pm.impl.pathresolver.PmExpressionPathResolver;
import org.pm4j.core.util.reflection.BeanAttrAccessor;
import org.pm4j.core.util.reflection.BeanAttrAccessorImpl;
import org.pm4j.core.util.reflection.ClassUtil;
import org.pm4j.core.util.reflection.ReflectionException;
import org.pm4j.navi.NaviLink;
/**
* <p> Basic implementation for PM attributes. </p>
*
* <p> Note: If you are looking for a generic PmAttr implementation
* for use in client code, use PmAttrImpl, not this base class. </p>
*
* TODOC:
*
* @param <T_PM_VALUE>
* The external PM api type.<br>
* Examples:<br>
* For a string field: the type {@link String};<br>
* For a bean reference: the PM class for the referenced bean.
* @param <T_BEAN_VALUE>
* The bean field type. <br>
* Examples:<br>
* For a string field: the type {@link String};<br>
* For a reference: The referenced class.
*
* @author olaf boede
*/
public abstract class PmAttrBase<T_PM_VALUE, T_BEAN_VALUE>
extends PmDataInputBase
implements PmAttr<T_PM_VALUE> {
private static final Log LOG = LogFactory.getLog(PmAttrBase.class);
/**
* Indicates if the value was explicitly set. This information is especially
* important for the default value logic. Default values may have only effect
* on values that are not explicitly set.
*/
private boolean valueWasSet = false;
/**
* Contains optional attribute data that in most cases doesn't exist for usual
* bean attributes.
*/
private PmAttrDataContainer<T_PM_VALUE, T_BEAN_VALUE> dataContainer;
/**
* Keeps a reference to the entered value in case of buffered data entry.
*/
private Object bufferedValue = UNKNOWN_VALUE_INDICATOR;
/** Shortcut to the next parent element. */
private PmElement pmParentElement;
/** The decorators to execute before and after setting the attribute value. */
private Collection<PmCommandDecorator> valueChangeDecorators = Collections.emptyList();
public PmAttrBase(PmObject pmParent) {
super(pmParent);
pmParentElement = (pmParent instanceof PmElement)
? (PmElement)pmParent
: PmUtil.getPmParentOfType(pmParent, PmElement.class);
}
/**
* @return The next parent of type {@link PmElement}.
*/
protected PmElement getPmParentElement() {
return pmParentElement;
}
@Override
public final PmOptionSet getOptionSet() {
MetaData md = getOwnMetaData();
Object ov = md.cacheStrategyForOptions.getCachedValue(this);
if (ov != PmCacheStrategy.NO_CACHE_VALUE) {
// just return the cache hit (if there was one)
return (PmOptionSet) ov;
}
else {
try {
PmOptionSet os = getOptionSetImpl();
// TODO: ensure that there is an option for the current value.
md.cacheStrategyForOptions.setAndReturnCachedValue(this, os);
return os;
}
catch (RuntimeException e) {
PmRuntimeException forwardedEx = PmRuntimeException.asPmRuntimeException(this, e);
// TODO olaf: Logging is required here for JSF. Make it configurable for other
// UI frameworks with better exception handling.
LOG.error("getOptionSet failed", forwardedEx);
throw forwardedEx;
}
}
}
/**
* Override this method to provide a specific option set.
* <p>
* Alternatively you may use {@link PmOptionCfg} in combination with an
* overridden {@link #getOptionValues()} method.
*
* @return An option set. In case of no options an empty option set.
*/
protected PmOptionSet getOptionSetImpl() {
PmOptionSet os = getOwnMetaData().optionSetDef.makeOptions(this);
return os;
}
/**
* A combination of {@link PmOptionCfg} and the implementation of this method
* may be used to define the options for the attribute value.
* <p>
* The id, title and value attributes of the annotation will be applied to
* the items of the provided object set to create the option set.
*
* @return The object to generate the options from.<br>
* May return <code>null</code> in case of no option values.
*/
// XXX olaf: is currently public because of the package location of OptionSetDefBase.
public Iterable<?> getOptionValues() {
throw new PmRuntimeException(this, "Please don't forget to implement getOptionValues() if you don't specifiy the options in the @PmOptions annotation.");
}
// XXX olaf: is currently public because of the package location of OptionSetDefBase.
/**
* Provides the attribute type specific default definition, if an option set
* should contain a <code>null</code> option definition or not.
* <p>
* Usualy non-list attributes provide the default
* {@link PmOptionCfg.NullOption#FOR_OPTIONAL_ATTR} and list attributes
* {@link PmOptionCfg.NullOption#NO}.
*
* @return The attribute type specific null-option generation default value.
*/
public NullOption getNullOptionDefault() {
return NullOption.FOR_OPTIONAL_ATTR;
}
/**
* Checks first if the PM is enabled.<br>
* Only if that's the case the logic provided by {@link #isPmReadonlyImpl()}
* will be used.
*/
@Override
public final boolean isRequired() {
return isPmEnabled() &&
isRequiredImpl();
}
/**
* Subclasses may implement here specific logic.
* <p>
* Please notice that the result of the external {@link #isRequired()} method
* is influenced by the {@link #isPmEnabled()} result: A disabled attribute is
* automatically NOT required.
*
* @return <code>true</code> if the attribute is required.
*/
protected boolean isRequiredImpl() {
MetaData md = getOwnMetaData();
switch (md.valueRestriction) {
case REQUIRED: return true;
case REQUIRED_IF_VISIBLE: return isPmVisible();
case READ_ONLY: return false;
case NONE: return md.required; // fall back for old annotation attribute
default: throw new PmRuntimeException(this, "Unknown enum value found.");
}
}
@Override
protected boolean isPmReadonlyImpl() {
return super.isPmReadonlyImpl() ||
getPmParentElement().isPmReadonly();
}
@Override
public final boolean isPmEnabled() {
// link enable status to read only even if the default impl of isPmEnabledImpl is overwritten
return super.isPmEnabled() && !isPmReadonly();
}
// TODO olaf: move common logic to isPmVisible. Additional effort: ensure that isPmVisible stays final
// for all PM sub classes.
@Override
protected boolean isPmVisibleImpl() {
boolean visible = super.isPmVisibleImpl();
if (visible && getOwnMetaData().hideWhenEmpty) {
visible = !isEmptyValue(getValue());
}
return visible;
}
@Override
protected void getPmStyleClassesImpl(Set<String> styleClassSet) {
super.getPmStyleClassesImpl(styleClassSet);
if (isRequired()) {
styleClassSet.add(STYLE_CLASS_REQUIRED);
}
}
@Override
public void accept(PmVisitor visitor) {
visitor.visit(this);
}
@Override
public void clearPmInvalidValues() {
boolean wasValid = isPmValid();
if (dataContainer != null) {
if (dataContainer.invalidValue != null) {
dataContainer.invalidValue = null;
}
}
if (!wasValid) {
for (PmMessage m : PmMessageUtil.getPmErrors(this)) {
this.getPmConversationImpl()._clearPmMessage(m);
}
PmEventApi.firePmEvent(this, getOwnMetaData().validationChangeEventMask);
}
}
/**
* The default implementation compares the results of {@link #getValueLocalized()}
* according to the collation sequence of the current {@link Locale}.
*/
@Override
public int compareTo(PmObject otherPm) {
return PmUtil.getAbsoluteName(this).equals(PmUtil.getAbsoluteName(otherPm))
? CompareUtil.compare(getValueLocalized(), ((PmAttr<?>)otherPm).getValueLocalized(), getPmConversation().getPmLocale())
: super.compareTo(otherPm);
}
/**
* Checks if two instances represent the same value.
* <p>
* Sub classes may override this method to provide their specific equals-conditions.
* <p>
* This correct implementation of this method is important for the changed state handling.
*
* @see #isPmValueChanged()
* @see #onPmValueChange(PmEvent)
* @see PmEvent#VALUE_CHANGE
*
* @param v1 A value. May be <code>null</code>.
* @param v2 Another value. May be <code>null</code>.
* @return <code>true</code> if both parameters represent the same value.
*/
protected boolean equalValues(T_PM_VALUE v1, T_PM_VALUE v2) {
return ObjectUtils.equals(v1, v2);
}
@SuppressWarnings("unchecked")
@Override
public final T_PM_VALUE getValue() {
MetaData md = getOwnMetaData();
Object ov = md.cacheStrategyForValue.getCachedValue(this);
if (ov != PmCacheStrategy.NO_CACHE_VALUE) {
// just return the cache hit (if there was one)
return (T_PM_VALUE) ov;
}
else {
try {
T_PM_VALUE v = null;
if (isInvalidValue() &&
dataContainer.invalidValue.isPmValueSet()) {
v = dataContainer.invalidValue.getPmValue();
}
else {
// In case of converter problems: Return the current value.
v = getValueImpl();
}
return (T_PM_VALUE) md.cacheStrategyForValue.setAndReturnCachedValue(this, v);
}
catch (RuntimeException e) {
PmRuntimeException forwardedEx = PmRuntimeException.asPmRuntimeException(this, e);
// TODO olaf: Logging is required here for JSF. Make it configurable for other
// UI frameworks with better exception handling.
LOG.error("getValue failed", forwardedEx);
throw forwardedEx;
}
}
}
@Override
public final void setValue(T_PM_VALUE value) {
if (!isPmReadonly()) {
SetValueContainer<T_PM_VALUE> vc = SetValueContainer.makeWithPmValue(this, value);
setValueImpl(vc);
}
else {
// XXX olaf: is only a workaround for the standard jsf-form behavior...
// Approach: add a configuration parameter
if (LOG.isInfoEnabled()) {
LOG.info("Ignored setValue() call for read-only attribute: " + PmUtil.getPmLogString(this));
}
}
}
@Override
public final String getValueAsString() {
try {
T_PM_VALUE value;
if (isInvalidValue()) {
if (dataContainer.invalidValue.isStringValueSet()) {
return dataContainer.invalidValue.getStringValue();
}
else {
value = dataContainer.invalidValue.getPmValue();
}
}
else {
value = getValue();
}
return value != null
? valueToStringImpl(value)
: null;
}
catch (PmRuntimeException pmrex) {
throw pmrex;
}
catch (RuntimeException e) {
PmRuntimeException forwardedEx = PmRuntimeException.asPmRuntimeException(this, e);
LOG.error("getValueAsString failed", forwardedEx);
throw forwardedEx;
}
}
/**
* The default implementation returns the result of {@link #getValueAsString()}.<br>
* If the attribute has options it tries to identify the selected option and returns the
* title for the current option.
*/
@Override
public String getValueLocalized() {
String valueAsString = getValueAsString();
PmOptionSet os = getOptionSet();
if (os != null) {
PmOption option = os.findOptionForIdString(valueAsString);
if (option != null) {
return option.getPmTitle();
}
}
// default:
return valueAsString;
}
/**
* The default implementation returns 0.
*/
@Override
public int getMinLen() {
return getOwnMetaDataWithoutPmInitCall().minLen;
}
@Override
public int getMaxLen() {
return getOwnMetaDataWithoutPmInitCall().getMaxLen();
}
@Override
public final void setValueAsString(String text) {
zz_ensurePmInitialization();
SetValueContainer<T_PM_VALUE> vc = new SetValueContainer<T_PM_VALUE>(this, text);
try {
if (isPmReadonly() &&
getFormatString() != null) {
// Some UI controls (e.g. SWT Text) send an immediate value change event when they get initialized.
// To prevent unnecessary (and problematic) set value loops, nothing happens if the actual
// value gets set to a read-only attribute.
// In case of formatted string representations the value change detection mechanism on value level
// may detect a change if the format does not represent all details of the actual value.
// To prevent such effects, this code checks if the formatted string output is still the same...
// TODO: What about changing a
if (! StringUtils.equalsIgnoreCase(getValueAsString(), vc.getStringValue())) {
throw new PmRuntimeException(this, "Illegal attempt to set a new value to a read only attribute.");
}
return;
}
clearPmInvalidValues();
try {
vc.setPmValue(StringUtils.isNotBlank(text)
? stringToValueImpl(text)
: null);
} catch (PmRuntimeException e) {
PmResourceData resData = e.getResourceData();
if (resData == null) {
setInvalidValue(vc);
getPmConversationImpl().getPmExceptionHandler().onException(this, e, false);
} else {
setAndPropagateValueConverterMessage(vc, resData.msgKey, resData.msgArgs);
if (LOG.isDebugEnabled()) {
LOG.debug("String to value conversion failed in attribute '" + PmUtil.getPmLogString(this) + "'. String value: " + text);
}
}
return;
} catch (PmConverterException e) {
PmResourceData resData = e.getResourceData();
Object[] args = Arrays.copyOf(resData.msgArgs, resData.msgArgs.length+1);
args[resData.msgArgs.length] = getPmShortTitle();
setAndPropagateValueConverterMessage(vc, resData.msgKey, args);
if (LOG.isDebugEnabled()) {
LOG.debug("String to value conversion failed in attribute '" + PmUtil.getPmLogString(this) +
"'. String value: '" + text +
"'. Caused by: " + e.getMessage());
}
return;
} catch (RuntimeException e) {
setInvalidValue(vc);
getPmConversationImpl().getPmExceptionHandler().onException(this, e, false);
if (LOG.isDebugEnabled()) {
LOG.debug("String to value conversion failed in attribute '" + PmUtil.getPmLogString(this) + "'. String value: " + text,
e);
}
return;
}
setValueImpl(vc);
}
catch (RuntimeException e) {
PmRuntimeException pme = PmRuntimeException.asPmRuntimeException(this, e);
PmMessageUtil.makeExceptionMsg(this, Severity.ERROR, pme);
LOG.error("setValueAsString failed to set value '" + vc.getStringValue() + "'", pme);
throw pme;
}
}
@Override
public void resetPmValues() {
boolean isWritable = !isPmReadonly();
if (isWritable) {
PmCacheApi.clearCachedPmValues(this);
this.valueWasSet = false;
}
clearPmInvalidValues();
if (isWritable) {
setValue(getDefaultValue());
}
}
@Override
protected void clearCachedPmValues(Set<PmCacheApi.CacheKind> cacheSet) {
super.clearCachedPmValues(cacheSet);
MetaData sd = getOwnMetaData();
if (cacheSet.contains(PmCacheApi.CacheKind.VALUE))
sd.cacheStrategyForValue.clear(this);
if (cacheSet.contains(PmCacheApi.CacheKind.OPTIONS))
sd.cacheStrategyForOptions.clear(this);
}
/**
* Gets attribute value directly from the bound data source. Does not use the
* cache and does not consider any temporarily set invalid values.
*
* @return The current attribute value.
*/
public final T_PM_VALUE getUncachedValidValue() {
return getValueImpl();
}
protected T_PM_VALUE getValueImpl() {
try {
T_BEAN_VALUE beanAttrValue = getBackingValue();
// TODO olaf: After conversion the value should be checked using
// #isEmptyValue() to be able to control the default value logic precisely.
if (beanAttrValue != null) {
return convertBackingValueToPmValue(beanAttrValue);
}
else {
// Default values may have only effect if the value was not set
// by the user:
if (valueWasSet) {
return null;
}
else {
T_PM_VALUE defaultValue = getDefaultValue();
if (defaultValue != null) {
beanAttrValue = convertPmValueToBackingValue(defaultValue);
// XXX olaf: The backing value gets changed within the 'get' functionality.
// Check if that can be postponed...
setBackingValue(beanAttrValue);
}
return defaultValue;
}
}
}
catch (Exception e) {
throw PmRuntimeException.asPmRuntimeException(this, e);
}
}
/**
* Performs a smart set operation.
* Validates the value before applying it.
*
* @param value The new value.
* @return <code>true</code> when the attribute value was really changed.
*/
protected boolean setValueImpl(SetValueContainer<T_PM_VALUE> value) {
PmEventApi.ensureThreadEventSource(this);
try {
assert value.isPmValueSet();
T_PM_VALUE newPmValue = value.getPmValue();
T_PM_VALUE currentValue = getUncachedValidValue();
// Check both values for null-value because they might be different but
// may both represent a null-value.
boolean pmValueChanged = (! equalValues(currentValue, newPmValue)) &&
(! (isEmptyValue(newPmValue) && isEmptyValue(currentValue)));
ValueChangeCommandImpl<T_PM_VALUE> cmd = new ValueChangeCommandImpl<T_PM_VALUE>(this, currentValue, newPmValue);
// New game. Forget all the old invalid stuff.
clearPmInvalidValues();
// Ensure that primitive types will not be set to null.
if ((newPmValue == null) && getOwnMetaData().primitiveType) {
setAndPropagateInvalidValue(value, PmConstants.MSGKEY_VALIDATION_MISSING_REQUIRED_VALUE);
return false;
}
// FIXME olaf: read only control should be done within the calling setValueAsString method!
// The set operation should not be performed in this case. Check for side effects...
if (pmValueChanged && isPmReadonly()) {
PmMessageUtil.makeMsg(this, Severity.ERROR, PmConstants.MSGKEY_VALIDATION_READONLY);
return false;
}
if (isValidatingOnSetPmValue()) {
// Validate even if nothing was changed. The currentValue may be invalid too.
// Example: New object with empty attributes values.
try {
validate(newPmValue);
}
catch (PmValidationException e) {
PmResourceData resData = e.getResourceData();
setAndPropagateInvalidValue(value, resData.msgKey, resData.msgArgs);
return false;
}
}
if (pmValueChanged) {
if (!beforeValueChange(currentValue, newPmValue)) {
LOG.debug("Value '" + getPmRelativeName() + "' was not changed because of the beforeDo result of the beforeValueChange() implementation");
return false;
}
for (PmCommandDecorator d : getValueChangeDecorators()) {
if (!d.beforeDo(cmd)) {
LOG.debug("Value '" + getPmRelativeName() + "' was not changed because of the beforeDo result of decorator: " + d);
return false;
}
}
// TODO olaf: a quick hack to hide password data. Should be done more general for other field names too.
if (LOG.isDebugEnabled() && !ObjectUtils.equals(getPmName(), "password")) {
LOG.debug("Changing PM value of '" + PmUtil.getPmLogString(this) + "' from '" + currentValue + "' to '" + newPmValue + "'.");
}
T_BEAN_VALUE beanAttrValue = (newPmValue != null)
? convertPmValueToBackingValue(newPmValue)
: null;
setBackingValue(beanAttrValue);
getOwnMetaData().cacheStrategyForValue.setAndReturnCachedValue(this, newPmValue);
// From now on the value should be handled as intentionally modified.
// That means that the default value shouldn't be returned, even if the
// value was set to <code>null</code>.
valueWasSet = true;
setValueChanged(currentValue, newPmValue);
for (PmCommandDecorator d : getValueChangeDecorators()) {
d.afterDo(cmd);
}
afterValueChange(currentValue, newPmValue);
PmEventApi.firePmEvent(this, PmEvent.VALUE_CHANGE);
getPmConversation().getPmCommandHistory().commandDone(cmd);
return true;
}
else {
return false;
}
} catch (RuntimeException e) {
getPmConversationImpl().getPmExceptionHandler().onException(this, e, false);
return false;
}
}
/**
* Gets called before a value change will be applied.
* <p>
* It may be overridden for application specific needs.<br>
* It may prevent the change to be applied by returning <code>false</code>.
*
* @param oldValue The old (current) attribute value.
* @param newValue The new value that should be applied.
* @return A return value <code>false</code> will prevent the value change.
*/
protected boolean beforeValueChange(T_PM_VALUE oldValue, T_PM_VALUE newValue) {
return true;
}
/**
* Gets called after a value change.
*
* @param oldValue The old attribute value.
* @param newValue The new (current) value.
*/
protected void afterValueChange(T_PM_VALUE oldValue, T_PM_VALUE newValue) {
}
/**
* Gets called whenever a string value needs to be converted to the attribute value type.
* <p>
* The default implementation uses the converter provided by {@link #getConverter()}.
*
* @param s The string to convert.
* @return The converted value.
* @throws PmConverterException If the given string can't be converted.
*/
protected T_PM_VALUE stringToValueImpl(String s) throws PmConverterException {
return (T_PM_VALUE) getConverter().stringToValue(this, s);
}
/**
* Gets called whenever the attribute value needs to be represented as a string.
* <p>
* The default implementation uses the converter provided by {@link #getConverter()}.
*
* @param v A value to convert.
* @return The string representation.
*/
protected String valueToStringImpl(T_PM_VALUE v) {
return getConverter().valueToString(this, v);
}
/**
* @return The converter that translates from and to the corresponding string representation.
*/
@SuppressWarnings("unchecked")
protected Converter<T_PM_VALUE> getConverter() {
Converter<T_PM_VALUE> c = (Converter<T_PM_VALUE>) getOwnMetaData().converter;
if (c == null) {
throw new PmRuntimeException(this, "Missing value converter.");
}
return c;
}
@Override
protected boolean isPmValueChangedImpl() {
return (dataContainer != null &&
dataContainer.originalValue != UNCHANGED_VALUE_INDICATOR) ||
super.isPmValueChangedImpl();
}
// TODO olaf: distinguish explicite changed flag and value change.
@Override
protected void setPmValueChangedImpl(boolean newChangedState) {
PmEventApi.ensureThreadEventSource(this);
setValueChanged(UNKNOWN_VALUE_INDICATOR, newChangedState
? CHANGED_VALUE_INDICATOR
: UNCHANGED_VALUE_INDICATOR);
super.setPmValueChangedImpl(newChangedState);
}
static final String UNCHANGED_VALUE_INDICATOR = "
static final String CHANGED_VALUE_INDICATOR = "
static final String UNKNOWN_VALUE_INDICATOR = "
/**
* Detects a change by checking the <code>oldValue</code> and <code>newValue</code>
* parameters.
* <p>
* Passing {@link #UNCHANGED_VALUE_INDICATOR} as <code>newValue</code> causes
* a change of the internal managed <code>originalValue</code> to 'unchanged'.<br>
* This way the current attribute value gets accepted as the 'original unchange'
* value.
*
* @param oldValue The old value.
* @param newValue The new value.
*/
private void setValueChanged(Object oldValue, Object newValue) {
boolean fireStateChange = false;
// Reset to an unchanged value state. Accepts the current value as the original one.
if (newValue == UNCHANGED_VALUE_INDICATOR) {
// prevent creation of a data container only to store the default value...
if (dataContainer != null) {
fireStateChange = (dataContainer.originalValue != UNCHANGED_VALUE_INDICATOR);
dataContainer.originalValue = UNCHANGED_VALUE_INDICATOR;
}
}
// Set the value:
else {
// Setting the attribute to the original value leads to an 'unchanged' state.
if (ObjectUtils.equals(zz_getDataContainer().originalValue, newValue)) {
fireStateChange = (dataContainer.originalValue != UNCHANGED_VALUE_INDICATOR);
dataContainer.originalValue = UNCHANGED_VALUE_INDICATOR;
}
// Setting a value which is not the original one:
else {
// Remember the current value as the original one if the attribute was in an unchanged
// state:
if (dataContainer.originalValue == UNCHANGED_VALUE_INDICATOR) {
fireStateChange = true;
dataContainer.originalValue = oldValue;
}
else {
// If the attribute gets changed back to its original value: Mark it as unchanged.
if (ObjectUtils.equals(dataContainer.originalValue, newValue)) {
fireStateChange = true;
dataContainer.originalValue = UNCHANGED_VALUE_INDICATOR;
}
}
}
}
if (fireStateChange) {
PmEventApi.firePmEvent(this, PmEvent.VALUE_CHANGED_STATE_CHANGE);
}
}
/**
* The default implementation provides the default value provided by the
* annotation {@link PmAttrCfg#defaultValue()}.
* <p>
* Subclasses may override the method {@link #getDefaultValueImpl()} to provide
* some special implementation.
*
* @return The default value for this attribute.
*/
protected final T_PM_VALUE getDefaultValue() {
return getDefaultValueImpl();
}
/**
* Reads a PM request attribute with the name of the attribute.
*
* @return The read request attribute, converted to the attribute specific
* type. <code>null</code> if there is no default value attribute
* within the given request.
* @deprecated remove as soon as a customer scenario is cleaned.
*/
private T_PM_VALUE getDefaultValueFromRequest() {
String reqValue = getPmConversationImpl().getPmToViewTechnologyConnector().readRequestValue(getPmName());
try {
return (reqValue != null)
? stringToValueImpl(reqValue)
: null;
} catch (PmConverterException e) {
throw new PmRuntimeException(this, e);
}
}
/**
* The default implementation provides the value provided by {@link PmAttrCfg#defaultValue()}.
* <p>
* Subclasses may override this method to provide some special implementation.
*
* @return The default value for this attribute.
*/
// FIXME olaf: shouldn't that method return T_BEAN_VALUE ?
// not yet changed because of the effort to change the meta data handling code...
// alternatively: add a second method getDefaultBackingValue()...
protected T_PM_VALUE getDefaultValueImpl() {
MetaData md = getOwnMetaData();
T_PM_VALUE defaultValue = null;
if (StringUtils.isNotBlank(md.defaultValueString)) {
try {
defaultValue = stringToValueImpl(md.defaultValueString);
} catch (PmConverterException e) {
throw new PmRuntimeException(this, e);
}
}
return (T_PM_VALUE) (defaultValue != null
? defaultValue
: getDefaultValueFromRequest());
}
/**
* Sets the invalid value and propagates a {@link PmValidationMessage} to the
* conversation.
*
* @param invValue
* The invalid value.
* @param msgKey
* Key for the user message.
* @param msgArgs
* Values for the user message.
*/
private void setAndPropagateInvalidValue(SetValueContainer<T_PM_VALUE> invValue, String msgKey, Object... msgArgs) {
this.getPmConversationImpl().addPmMessage(new PmValidationMessage(this, invValue, msgKey, msgArgs));
setInvalidValue(invValue);
}
/**
* Sets the invalid value and notifies listeners
*
* @param invValue
* The invalid value.
*/
private void setInvalidValue(SetValueContainer<T_PM_VALUE> invValue) {
zz_getDataContainer().invalidValue = invValue;
PmEventApi.firePmEvent(this, getOwnMetaData().validationChangeEventMask);
}
/**
* @param invValue
* The invalid value.
* @param msgKey
* Key for the user message.
* @param msgArgs
* Values for the user message.
*/
private void setAndPropagateValueConverterMessage(SetValueContainer<T_PM_VALUE> invValue, String msgKey,
Object... msgArgs) {
this.getPmConversationImpl().addPmMessage(new PmConverterErrorMessage(this, invValue, msgKey, msgArgs));
setInvalidValue(invValue);
}
/**
* @return <code>true</code> when there is an invalid user data entry.
*/
private final boolean isInvalidValue() {
return (dataContainer != null) && (dataContainer.invalidValue != null);
}
/**
* Checks the attribute type specific <code>null</code> or empty value
* condition.
*
* @return <code>true</code> when the value is a <code>null</code> or empty
* value equivalent.
*/
protected boolean isEmptyValue(T_PM_VALUE value) {
return (value == null);
}
/**
* If this method returns <code>true</code>, each {@link #setValue(Object)} will cause an
* immediate call to {@link #pmValidate()}.
* <p>
* Alternatively validation is usually triggered by a command.
*/
protected boolean isValidatingOnSetPmValue() {
return false;
}
/**
* The default validation checks just the required condition.
* More specific attribute classes have to add their specific validation
* by overriding this method.
*
* @param value The value to validate.
*/
protected void validate(T_PM_VALUE value) throws PmValidationException {
if (isRequired() &&
isEmptyValue(value)) {
throw new PmValidationException(PmMessageUtil.makeRequiredWarning(this));
}
}
void performJsr303Validations() {
Validator validator = PmImplUtil.getBeanValidator();
if (validator != null) {
Object validationBean = getOwnMetaData().valueAccessStrategy.getPropertyContainingBean(this);
if (validationBean != null &&
getOwnMetaData().validationFieldName != null) {
@SuppressWarnings("unchecked")
Set<ConstraintViolation<?>> violations = (Set<ConstraintViolation<?>>)(Object)validator.validateProperty(validationBean, getOwnMetaData().validationFieldName);
PmImplUtil.beanConstraintViolationsToPmMessages(this, violations);
}
}
}
@Override
public void pmValidate() {
if (isPmVisible() &&
isPmEnabled()) {
// A validation can only be performed if the last setValue() did not generate a converter exception.
// Otherwise the attribute will simply stay in its value converter error state.
if (!hasPmConverterErrors()) {
boolean wasValid = isPmValid();
PmConversationImpl conversation = getPmConversationImpl();
conversation.clearPmMessages(this, null);
try {
validate(getValue());
performJsr303Validations();
}
catch (PmValidationException e) {
PmResourceData exResData = e.getResourceData();
PmValidationMessage msg = new PmValidationMessage(this, exResData.msgKey, exResData.msgArgs);
conversation.addPmMessage(msg);
}
boolean isValid = isPmValid();
if (isValid != wasValid) {
PmEventApi.firePmEvent(this, getOwnMetaData().validationChangeEventMask);
}
}
}
}
private boolean hasPmConverterErrors() {
for (PmMessage m : getPmConversation().getPmMessages(this, Severity.ERROR)) {
if (m instanceof PmConverterErrorMessage) {
return true;
}
}
// no converter message found.
return false;
}
public boolean isBufferedPmValueMode() {
return getPmParentElement().isBufferedPmValueMode();
}
@SuppressWarnings("unchecked")
public void commitBufferedPmChanges() {
if (isBufferedPmValueMode() &&
bufferedValue != UNKNOWN_VALUE_INDICATOR) {
setBackingValueImpl((T_BEAN_VALUE)bufferedValue);
bufferedValue = UNKNOWN_VALUE_INDICATOR;
}
}
public void rollbackBufferedPmChanges() {
bufferedValue = UNKNOWN_VALUE_INDICATOR;
}
@SuppressWarnings("unchecked")
public T_PM_VALUE convertBackingValueToPmValue(T_BEAN_VALUE backingValue) {
return (T_PM_VALUE) backingValue;
}
@SuppressWarnings("unchecked")
public T_BEAN_VALUE convertPmValueToBackingValue(T_PM_VALUE pmAttrValue) {
return (T_BEAN_VALUE) pmAttrValue;
}
@SuppressWarnings("unchecked")
public final T_BEAN_VALUE getBackingValue() {
return (bufferedValue != UNKNOWN_VALUE_INDICATOR)
? (T_BEAN_VALUE)bufferedValue
: getBackingValueImpl();
}
public final void setBackingValue(T_BEAN_VALUE value) {
if (isBufferedPmValueMode()) {
bufferedValue = value;
}
else {
setBackingValueImpl(value);
}
}
/**
* Provides the internal (non PM) data type representation of the attribute value.
* <p>
* Attributes may override this method to provide a specific implementation.
*
* @return The value (internal data type representation).
*/
@SuppressWarnings("unchecked")
protected T_BEAN_VALUE getBackingValueImpl() {
return (T_BEAN_VALUE) getOwnMetaData().valueAccessStrategy.getValue(this);
}
/**
* Sets the internal (non PM) data type representation of the attribute value.
* <p>
* Attributes may override this method to provide a specific implementation.
*
* @param value The value to assign (internal data type representation).
*/
protected void setBackingValueImpl(T_BEAN_VALUE value) {
getOwnMetaData().valueAccessStrategy.setValue(this, value);
}
@Override
public String getFormatString() {
String key = getOwnMetaData().formatResKey;
String format = null;
// 1. fix resource key definition
if (key != null) {
format = PmLocalizeApi.findLocalization(this, key);
if (format == null) {
throw new PmRuntimeException(this, "No resource string found for configured format resource key '" + key +"'.");
}
}
// 2. no fix key: try to find a postfix based definition
else {
key = getPmResKey() + PmConstants.RESKEY_POSTFIX_FORMAT;
format = PmLocalizeApi.findLocalization(this, key);
// 3. Try a default key (if defined for this attribute)
if (format == null) {
key = getFormatDefaultResKey();
if (key != null) {
format = PmLocalizeApi.findLocalization(this, key);
}
}
}
return format;
}
/**
* Concrete attribute classes may specify here a default format resource key
* as a fallback for unspecified format localizations.
*
* @return The fallback resource key or <code>null</code> if there is none.
*/
protected String getFormatDefaultResKey() {
return null;
}
/* package */ void addValueChangeDecorator(PmCommandDecorator decorator) {
if (valueChangeDecorators.isEmpty()) {
valueChangeDecorators = new ArrayList<PmCommandDecorator>();
}
valueChangeDecorators.add(decorator);
}
@Override
Serializable getPmContentAspect(PmAspect aspect) {
switch (aspect) {
case VALUE:
T_PM_VALUE v = getValue();
return getConverter().valueToSerializable(this, v);
default:
return super.getPmContentAspect(aspect);
}
}
/**
* @return The set of decorators to consider on value change.
*/
protected Collection<PmCommandDecorator> getValueChangeDecorators() {
return valueChangeDecorators;
}
@Override
void setPmContentAspect(PmAspect aspect, Serializable value) throws PmConverterException {
PmEventApi.ensureThreadEventSource(this);
switch (aspect) {
case VALUE:
setValue(getConverter().serializeableToValue(this, value));
break;
default:
super.setPmContentAspect(aspect, value);
}
}
/**
* Provides a data container. Creates it on the fly when it does not already
* exist.
*
* @return The container for optional data parts.
*/
private final PmAttrDataContainer<T_PM_VALUE, T_BEAN_VALUE> zz_getDataContainer() {
if (dataContainer == null) {
dataContainer = new PmAttrDataContainer<T_PM_VALUE, T_BEAN_VALUE>();
}
return dataContainer;
}
// XXX olaf: really required? May be solved by overriding initMetaData too.
protected PmOptionSetDef<?> makeOptionSetDef(PmOptionCfg cfg, Method getOptionValuesMethod) {
return cfg != null
? new GenericOptionSetDef(cfg, getOptionValuesMethod)
: OptionSetDefNoOption.INSTANCE;
}
@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
@Override
protected void initMetaData(PmObjectBase.MetaData metaData) {
super.initMetaData(metaData);
MetaData myMetaData = (MetaData) metaData;
Class<?> beanClass = (getPmParent() instanceof PmBean)
? ((PmBean)getPmParent()).getPmBeanClass()
: null;
PmAttrCfg fieldAnnotation = AnnotationUtil.findAnnotation(this, PmAttrCfg.class);
zz_readBeanValidationRestrictions(beanClass, fieldAnnotation, myMetaData);
// read the option configuration first from the getOptionValues()
// method. If not found there: From the attribute- and class declaration.
Method getOptionValuesMethod = null;
PmOptionCfg optionCfg = null;
try {
getOptionValuesMethod = getClass().getMethod("getOptionValues");
if (getOptionValuesMethod.getDeclaringClass() != PmAttrBase.class) {
optionCfg = getOptionValuesMethod.getAnnotation(PmOptionCfg.class);
// XXX: not really fine for security contexts.
getOptionValuesMethod.setAccessible(true);
}
else {
getOptionValuesMethod = null;
}
} catch (Exception e) {
throw new PmRuntimeException(this, "Unable to access method 'getOptionValues'.", e);
}
if (optionCfg == null) {
optionCfg = AnnotationUtil.findAnnotation(this, PmOptionCfg.class);
}
myMetaData.optionSetDef = (PmOptionSetDef)
makeOptionSetDef(optionCfg, getOptionValuesMethod);
if (myMetaData.optionSetDef != OptionSetDefNoOption.INSTANCE) {
myMetaData.setItemConverter(
new PmConverterOptionBased(optionCfg != null ? optionCfg.id() : ""));
}
// TODO olaf: implement a simplified and more consistent option implementation...
if (optionCfg != null) {
myMetaData.nullOption = optionCfg.nullOption();
}
PmAttrCfg.AttrAccessKind accessKindCfgValue = PmAttrCfg.AttrAccessKind.DEFAULT;
boolean useReflection = true;
if (fieldAnnotation != null) {
myMetaData.hideWhenEmpty = fieldAnnotation.hideWhenEmpty();
myMetaData.setReadOnly((fieldAnnotation.valueRestriction() == Restriction.READ_ONLY) || fieldAnnotation.readOnly());
// The pm can force more constraints. It should not define less constraints as
// the bean validation definition:
if (fieldAnnotation.required()) {
myMetaData.required = true;
}
// TODO: replace 'required' and 'readOnly'.
if (fieldAnnotation.valueRestriction() != Restriction.NONE) {
myMetaData.valueRestriction = fieldAnnotation.valueRestriction();
}
accessKindCfgValue = fieldAnnotation.accessKind();
myMetaData.formatResKey = StringUtils.defaultIfEmpty(fieldAnnotation.formatResKey(), null);
if (StringUtils.isNotEmpty(fieldAnnotation.defaultValue())) {
myMetaData.defaultValueString = fieldAnnotation.defaultValue();
}
myMetaData.maxLen = fieldAnnotation.maxLen();
myMetaData.minLen = fieldAnnotation.minLen();
if (myMetaData.maxLen != -1 &&
myMetaData.minLen > myMetaData.maxLen) {
throw new PmRuntimeException(this, "minLen(" + myMetaData.minLen +
") > maxLen(" + myMetaData.maxLen + ")");
}
switch (accessKindCfgValue) {
case DEFAULT:
if (StringUtils.isNotBlank(fieldAnnotation.valuePath())) {
myMetaData.valuePathResolver = PmExpressionPathResolver.parse(fieldAnnotation.valuePath(), true);
int lastDotPos = fieldAnnotation.valuePath().lastIndexOf('.');
if (lastDotPos > 0) {
String parentPath = fieldAnnotation.valuePath().substring(0, lastDotPos);
myMetaData.valueContainingObjPathResolver = PmExpressionPathResolver.parse(parentPath, true);
}
useReflection = false;
myMetaData.valueAccessStrategy = ValueAccessByExpression.INSTANCE;
}
break;
case OVERRIDE:
useReflection = false;
myMetaData.valueAccessStrategy = ValueAccessOverride.INSTANCE;
break;
case SESSIONPROPERTY:
useReflection = false;
myMetaData.valueAccessStrategy = ValueAccessSessionProperty.INSTANCE;
break;
case LOCALVALUE:
useReflection = false;
myMetaData.valueAccessStrategy = ValueAccessLocal.INSTANCE;
break;
default:
throw new PmRuntimeException(this, "Unknown annotation kind: " + fieldAnnotation.accessKind());
}
}
// Automatic reflection access is only supported for fix PmAttr fields in a PmBean container:
if (useReflection &&
myMetaData.isPmField &&
beanClass != null) {
try {
myMetaData.beanAttrAccessor = new BeanAttrAccessorImpl(beanClass, getPmName());
if (myMetaData.beanAttrAccessor.getFieldClass().isPrimitive()) {
myMetaData.primitiveType = true;
if (fieldAnnotation == null) {
myMetaData.required = true;
}
}
myMetaData.valueAccessStrategy = ValueAccessReflection.INSTANCE;
}
catch (ReflectionException e) {
if (ClassUtil.isMethodOverridden(PmAttrBase.class, getClass(), "getBackingValueImpl")) {
myMetaData.valueAccessStrategy = ValueAccessOverride.INSTANCE;
} else {
PmObjectUtil.throwAsPmRuntimeException(this, e);
}
}
}
// Use default attribute title provider if no specific provider was configured.
if (metaData.getPmTitleProvider() == getPmConversation().getPmDefaults().getPmTitleProvider()) {
metaData.setPmTitleProvider(getPmConversation().getPmDefaults().getPmAttrTitleProvider());
}
// -- Cache configuration --
List<PmCacheCfg> cacheAnnotations = new ArrayList<PmCacheCfg>();
AnnotationUtil.findAnnotationsInPmHierarchy(this, PmCacheCfg.class, cacheAnnotations);
myMetaData.cacheStrategyForOptions = readCacheStrategy(PmCacheCfg.ATTR_OPTIONS, cacheAnnotations, CACHE_STRATEGIES_FOR_OPTIONS);
myMetaData.cacheStrategyForValue = readCacheStrategy(PmCacheCfg.ATTR_VALUE, cacheAnnotations, CACHE_STRATEGIES_FOR_VALUE);
}
private void zz_readBeanValidationRestrictions(Class<?> beanClass, PmAttrCfg fieldAnnotation, MetaData myMetaData) {
if (PmImplUtil.getBeanValidator() == null)
return;
Class<?> srcClass = ((fieldAnnotation != null) &&
(fieldAnnotation.beanInfoClass() != Void.class))
? fieldAnnotation.beanInfoClass()
: beanClass;
if (srcClass != null) {
BeanDescriptor beanDescriptor = PmImplUtil.getBeanValidator().getConstraintsForClass(srcClass);
if (beanDescriptor != null) {
myMetaData.validationFieldName = (fieldAnnotation != null) &&
(StringUtils.isNotBlank(fieldAnnotation.beanInfoField()))
? fieldAnnotation.beanInfoField()
: myMetaData.getName();
PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty(myMetaData.validationFieldName);
if (propertyDescriptor == null ||
propertyDescriptor.getConstraintDescriptors().isEmpty()) {
myMetaData.validationFieldName = null;
}
else {
for (ConstraintDescriptor<?> cd : propertyDescriptor.getConstraintDescriptors()) {
initMetaDataBeanConstraint(cd);
}
}
}
}
}
/**
* Gets called for each found {@link ConstraintDescriptor}.<br>
* The default implementation just checks the {@link NotNull} restrictions.<br/>
* Sub classes override this method to consider other restrictions.
*
* @param cd The {@link ConstraintDescriptor} to consider for this attribute.
*/
protected void initMetaDataBeanConstraint(ConstraintDescriptor<?> cd) {
MetaData metaData = getOwnMetaDataWithoutPmInitCall();
if (cd.getAnnotation() instanceof NotNull) {
metaData.valueRestriction = Restriction.REQUIRED;
}
else if (cd.getAnnotation() instanceof Size) {
Size annotation = (Size)cd.getAnnotation();
if (annotation.min() > 0) {
metaData.minLen = annotation.min();
}
if (annotation.max() < Integer.MAX_VALUE) {
metaData.maxLen = annotation.max();
}
}
}
/**
* Shared meta data for all attributes of the same kind.
* E.g. for all 'myapp.User.name' attributes.
*/
protected static class MetaData extends PmObjectBase.MetaData {
static final Object NOT_INITIALIZED = "NOT_INITIALIZED";
private BeanAttrAccessor beanAttrAccessor;
private PmOptionSetDef<PmAttr<?>> optionSetDef = OptionSetDefNoOption.INSTANCE;
private PmOptionCfg.NullOption nullOption = NullOption.DEFAULT;
private boolean hideWhenEmpty;
private boolean required;
private Restriction valueRestriction = Restriction.NONE;
private boolean primitiveType;
private PathResolver valuePathResolver;
private PathResolver valueContainingObjPathResolver = PassThroughPathResolver.INSTANCE;
private String formatResKey;
private String defaultValueString;
private PmCacheStrategy cacheStrategyForOptions = PmCacheStrategyNoCache.INSTANCE;
private PmCacheStrategy cacheStrategyForValue = PmCacheStrategyNoCache.INSTANCE;
private Converter<?> converter;
private BackingValueAccessStrategy valueAccessStrategy = ValueAccessLocal.INSTANCE;
/** Name of the field configured for JSR 303-validation.<br>
* Is <code>null</code> if there is nothing to validate this way. */
private String validationFieldName;
private int maxLen = -1;
private int minLen = 0;
private int maxLenDefault;
/**
* @param maxDefaultLen the attribute type specific maximum number of characters.
*/
public MetaData(int maxDefaultLen) {
this.maxLenDefault = maxDefaultLen;
}
/** @return The statically defined option set algorithm. */
public PmOptionSetDef<PmAttr<?>> getOptionSetDef() { return optionSetDef; }
public PmOptionCfg.NullOption getNullOption() { return nullOption; }
public String getFormatResKey() { return formatResKey; }
public void setFormatResKey(String formatResKey) { this.formatResKey = formatResKey; }
public PmCacheStrategy getCacheStrategyForOptions() { return cacheStrategyForOptions; }
public PmCacheStrategy getCacheStrategyForValue() { return cacheStrategyForValue; }
public Converter<?> getConverter() { return converter; }
public void setConverter(Converter<?> converter) { this.converter = converter; }
/**
* Multi value attributes (like lists) have specific item converters.
* <p>
* For single value attributes there is no difference between
* {@link #converter} and the <code>itemConverter</code>.
*
* @param converter The converter for attribute items.
*/
public void setItemConverter(Converter<?> converter) { setConverter(converter); }
/** @see #setItemConverter(org.pm4j.core.pm.PmAttr.Converter) */
public Converter<?> getItemConverter() { return getConverter(); }
/**
* If the converter was not explicitly defined by a user annotation, this
* method will be used to define a attribute type specific converter.
*/
public void setConverterDefault(Converter<?> converter) {
assert converter != null;
if (this.converter == null)
this.converter = converter;
}
public boolean isRequired() { return required; }
public void setRequired(boolean required) { this.required = required; }
public int getMinLen() { return minLen; }
public int getMaxLen() {
if (maxLen == -1) {
maxLen = getMaxLenDefault();
}
return maxLen;
}
/**
* Provides the attribute type specific default max length.
*
* @return The maximal number of characters default.
*/
protected int getMaxLenDefault() {
return maxLenDefault;
}
}
/**
* The default implementation defines meta data for an attribute with
* 'unlimited' length ({@link Short#MAX_VALUE}).
*/
@Override
protected PmObjectBase.MetaData makeMetaData() {
return new MetaData(Short.MAX_VALUE);
}
private final MetaData getOwnMetaData() {
return (MetaData) getPmMetaData();
}
private final MetaData getOwnMetaDataWithoutPmInitCall() {
return (MetaData) getPmMetaDataWithoutPmInitCall();
}
private static final PmCacheStrategy CACHE_VALUE_LOCAL = new PmCacheStrategyBase<PmAttrBase<?,?>>("CACHE_VALUE_LOCAL") {
@Override protected Object readRawValue(PmAttrBase<?, ?> pm) {
return (pm.dataContainer != null)
? pm.dataContainer.cachedValue
: null;
}
@Override protected void writeRawValue(PmAttrBase<?, ?> pm, Object value) {
pm.zz_getDataContainer().cachedValue = value;
}
@Override protected void clearImpl(PmAttrBase<?, ?> pm) {
if (pm.dataContainer != null) {
pm.dataContainer.cachedValue = null;
}
}
};
private static final PmCacheStrategy CACHE_OPTIONS_LOCAL = new PmCacheStrategyBase<PmAttrBase<?,?>>("CACHE_OPTIONS_LOCAL") {
@Override protected Object readRawValue(PmAttrBase<?, ?> pm) {
return (pm.dataContainer != null)
? pm.dataContainer.cachedOptionSet
: null;
}
@Override protected void writeRawValue(PmAttrBase<?, ?> pm, Object value) {
pm.zz_getDataContainer().cachedOptionSet = value;
}
@Override protected void clearImpl(PmAttrBase<?, ?> pm) {
if (pm.dataContainer != null) {
pm.dataContainer.cachedOptionSet = null;
}
}
};
private static final Map<CacheMode, PmCacheStrategy> CACHE_STRATEGIES_FOR_VALUE =
MapUtil.makeFixHashMap(
CacheMode.OFF, PmCacheStrategyNoCache.INSTANCE,
CacheMode.ON, CACHE_VALUE_LOCAL,
CacheMode.REQUEST, new PmCacheStrategyRequest("CACHE_VALUE_IN_REQUEST", "v")
);
private static final Map<CacheMode, PmCacheStrategy> CACHE_STRATEGIES_FOR_OPTIONS =
MapUtil.makeFixHashMap(
CacheMode.OFF, PmCacheStrategyNoCache.INSTANCE,
CacheMode.ON, CACHE_OPTIONS_LOCAL,
CacheMode.REQUEST, new PmCacheStrategyRequest("CACHE_OPTIONS_IN_REQUEST", "os")
);
interface BackingValueAccessStrategy {
Object getValue(PmAttrBase<?, ?> attr);
void setValue(PmAttrBase<?, ?> attr, Object value);
Object getPropertyContainingBean(PmAttrBase<?, ?> attr);
}
static class ValueAccessLocal implements BackingValueAccessStrategy {
static final BackingValueAccessStrategy INSTANCE = new ValueAccessLocal();
@Override
public Object getValue(PmAttrBase<?, ?> attr) {
return attr.dataContainer != null
? attr.dataContainer.localValue
: null;
}
@Override
public void setValue(PmAttrBase<?, ?> attr, Object value) {
attr.zz_getDataContainer().localValue = value;
}
@Override
public Object getPropertyContainingBean(PmAttrBase<?, ?> attr) {
return null;
}
}
static class ValueAccessSessionProperty implements BackingValueAccessStrategy {
static final BackingValueAccessStrategy INSTANCE = new ValueAccessSessionProperty();
@Override
public Object getValue(PmAttrBase<?, ?> attr) {
return attr.getPmConversation().getPmNamedObject(PmUtil.getAbsoluteName(attr));
}
@Override
public void setValue(PmAttrBase<?, ?> attr, Object value) {
attr.getPmConversation().setPmNamedObject(PmUtil.getAbsoluteName(attr), value);
}
@Override
public Object getPropertyContainingBean(PmAttrBase<?, ?> attr) {
return null;
}
}
// TODO: should disappear as soon as the value strategy configuration is complete.
static class ValueAccessOverride implements BackingValueAccessStrategy {
static final BackingValueAccessStrategy INSTANCE = new ValueAccessOverride();
@Override
public Object getValue(PmAttrBase<?, ?> attr) {
throw new PmRuntimeException(attr, "getBackingValueImpl() method is not implemented.");
}
@Override
public void setValue(PmAttrBase<?, ?> attr, Object value) {
throw new PmRuntimeException(attr, "setBackingValueImpl() method is not implemented.");
}
@Override
public Object getPropertyContainingBean(PmAttrBase<?, ?> attr) {
return null;
}
}
static class ValueAccessByExpression implements BackingValueAccessStrategy {
static final BackingValueAccessStrategy INSTANCE = new ValueAccessByExpression();
@Override
public Object getValue(PmAttrBase<?, ?> attr) {
return attr.getOwnMetaData().valuePathResolver.getValue(attr.getPmParent());
}
@Override
public void setValue(PmAttrBase<?, ?> attr, Object value) {
attr.getOwnMetaData().valuePathResolver.setValue(attr.getPmParent(), value);
}
@Override
public Object getPropertyContainingBean(PmAttrBase<?, ?> attr) {
return attr.getOwnMetaData().valueContainingObjPathResolver.getValue(attr.getPmParent());
}
}
static class ValueAccessReflection implements BackingValueAccessStrategy {
static final BackingValueAccessStrategy INSTANCE = new ValueAccessReflection();
@Override
public Object getValue(PmAttrBase<?, ?> attr) {
@SuppressWarnings("unchecked")
Object bean = ((PmBean<Object>)attr.getPmParentElement()).getPmBean();
return bean != null
? attr.getOwnMetaData().beanAttrAccessor.<Object>getBeanAttrValue(bean)
: null;
}
@Override
public void setValue(PmAttrBase<?, ?> attr, Object value) {
@SuppressWarnings("unchecked")
Object bean = ((PmBean<Object>)attr.getPmParentElement()).getPmBean();
if (bean == null) {
throw new PmRuntimeException(attr, "Unable to access an attribute value for a backing pmBean that is 'null'.");
}
attr.getOwnMetaData().beanAttrAccessor.setBeanAttrValue(bean, value);
}
@SuppressWarnings("unchecked")
@Override
public Object getPropertyContainingBean(PmAttrBase<?, ?> attr) {
return ((PmBean<Object>)attr.getPmParentElement()).getPmBean();
}
}
/**
* A command that changes an attribute value.
*/
@PmTitleCfg(resKey="pmValueChangeCommand")
@PmCommandCfg(beforeDo=BEFORE_DO.DO_NOTHING)
public static class ValueChangeCommandImpl<T_VALUE> extends PmCommandImpl implements ValueChangeCommand<T_VALUE> {
private final T_VALUE oldValue;
private final T_VALUE newValue;
public ValueChangeCommandImpl(PmAttrBase<T_VALUE,?> changedPmAttr, T_VALUE oldValue, T_VALUE newValue) {
super(changedPmAttr);
this.oldValue = oldValue;
this.newValue = newValue;
setUndoCommand(new ValueChangeCommandImpl<T_VALUE>(this));
}
/**
* Constructor for the corresponding undo command.
*
* @param doCommand The command to undo.
*/
private ValueChangeCommandImpl(ValueChangeCommandImpl<T_VALUE> doCommand) {
super(doCommand.getPmParent());
this.newValue = doCommand.oldValue;
this.oldValue = doCommand.newValue;
setUndoCommand(doCommand);
}
@Override @SuppressWarnings("unchecked")
protected void doItImpl() throws Exception {
((PmAttrBase<Object, ?>)getPmParent()).setValue(newValue);
}
/**
* The referenced presentation model should be enabled.
*/
@Override
protected boolean isPmEnabledImpl() {
return super.isPmEnabledImpl() && getPmParent().isPmEnabled();
}
protected NaviLink afterDo(boolean changeCommandHistory) {
if (changeCommandHistory) {
getPmConversationImpl().getPmCommandHistory().commandDone(this);
}
// PmEventApi.firePmEvent(this, PmEvent.EXEC_COMMAND);
return null;
}
public T_VALUE getNewValue() {
return newValue;
}
public T_VALUE getOldValue() {
return oldValue;
}
@SuppressWarnings("unchecked")
@Override
public PmAttr<T_VALUE> getPmAttr() {
return (PmAttr<T_VALUE>) getPmParent();
}
}
}
|
package org.pm4j.core.pm;
import static org.junit.Assert.assertEquals;
import static org.pm4j.tools.test.PmAssert.setValue;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.pm4j.core.pm.annotation.PmAttrCfg;
import org.pm4j.core.pm.annotation.PmBeanCfg;
import org.pm4j.core.pm.annotation.PmCacheCfg;
import org.pm4j.core.pm.annotation.PmCacheCfg.CacheMode;
import org.pm4j.core.pm.annotation.PmFactoryCfg;
import org.pm4j.core.pm.api.PmCacheApi;
import org.pm4j.core.pm.impl.PmAttrStringImpl;
import org.pm4j.core.pm.impl.PmBeanImpl;
import org.pm4j.core.pm.impl.PmConversationImpl;
import org.pm4j.core.pm.impl.PmElementBase;
import org.pm4j.core.pm.impl.PmTableColImpl2;
import org.pm4j.core.pm.impl.PmTableImpl2;
public class PmAttrCacheTest {
@Test
public void testSimpleAttributeCache() {
MyPojo p = new MyPojo();
MyPojoPm pPm = new MyPojoPm(new PmConversationImpl(), p);
p.s = "abc";
assertEquals(p.s, pPm.s.getValue());
assertEquals(p.s, pPm.sCached.getValue());
assertEquals(p.s, pPm.sCachedByClassSpec.getValue());
assertEquals(p.s, pPm.sClassCacheSwitchedOff.getValue());
p.s = "123";
assertEquals(p.s, pPm.s.getValue());
assertEquals("abc", pPm.sCached.getValue());
assertEquals("abc", pPm.sCachedByClassSpec.getValue());
assertEquals(p.s, pPm.sClassCacheSwitchedOff.getValue());
PmCacheApi.clearPmCache(pPm);
assertEquals(p.s, pPm.s.getValue());
assertEquals(p.s, pPm.sCached.getValue());
assertEquals(p.s, pPm.sCachedByClassSpec.getValue());
assertEquals(p.s, pPm.sClassCacheSwitchedOff.getValue());
}
@Test
public void testSimpleAttributeCacheInTableRows() {
final List<MyPojo> list = Arrays.asList(new MyPojo(), new MyPojo());
MyTablePm t = new MyTablePm(new PmConversationImpl()) {
@Override
protected Collection<MyPojo> getPmInMemoryCollectionImpl() {
return list;
}
};
MyPojoPm row1Pm = t.getRowPms().get(0);
setValue(row1Pm.s, "hi");
assertEquals("hi", row1Pm.sCached.getValue());
setValue(row1Pm.s, "hey");
assertEquals("hi", row1Pm.sCached.getValue());
PmCacheApi.clearPmCache(t);
assertEquals("hey", row1Pm.sCached.getValue());
}
// -- Domain model --
public static class MyPojo {
public String s;
// Has getters and setters to allow xPath access (used by valuePath annotation in MyPojoPm).
public String getS() { return s; }
public void setS(String s) { this.s = s; }
}
// -- Presentation models --
@PmBeanCfg(beanClass=MyPojo.class)
public static class MyPojoPm extends PmBeanImpl<MyPojo> {
public final PmAttrString s = new PmAttrStringImpl(this);
@PmCacheCfg(value=CacheMode.ON) @PmAttrCfg(valuePath="pmBean.s")
public final PmAttrString sCached = new PmAttrStringImpl(this);
@PmAttrCfg(valuePath="pmBean.s")
public final PmAttrString sCachedByClassSpec = new MyCachedAttrClass(this);
/** The attribut class wants to cache but the atttribute declaration switches off. */
@PmCacheCfg(all=CacheMode.OFF) @PmAttrCfg(valuePath="pmBean.s")
public final PmAttrString sClassCacheSwitchedOff = new MyCachedAttrClass(this);
public MyPojoPm(PmObject pmParent, MyPojo myPojo) {
super(pmParent, myPojo);
}
}
@PmCacheCfg(all=CacheMode.ON)
public static class MyCachedAttrClass extends PmAttrStringImpl {
public MyCachedAttrClass(PmElementBase pmParentBean) {
super(pmParentBean);
}
};
@PmFactoryCfg(beanPmClasses=MyPojoPm.class)
public static class MyTablePm extends PmTableImpl2<MyPojoPm, MyPojo> {
public final PmTableCol2 s = new PmTableColImpl2(this);
public MyTablePm(PmObject pmParent) {
super(pmParent);
}
}
}
|
package org.slc.sli.api.security;
import org.slc.sli.api.security.enums.DefaultRoles;
import org.slc.sli.api.security.enums.Right;
import java.security.Principal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Attribute holder for SLI Principal
*
* @author dkornishev
* @author shalka
*/
public class SLIPrincipal implements Principal {
private String id;
private String name;
private String realm;
private String externalId;
private List<String> theirRoles;
private Set<Right> rights = new HashSet<Right>();
@Override
public String getName() {
return this.name;
}
public String getId() {
return id;
}
/**
* Gets the fully-qualified LDAP string generated by OpenAM.
* @return String containing Realm information.
*/
public String getRealm() {
return realm;
}
public String getExternalId() {
return externalId;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setRealm(String realm) {
this.realm = realm;
}
public void setExternalId(String externalId) {
this.externalId = externalId;
}
public void setTheirRoles(List<String> theirRoles) {
this.theirRoles = theirRoles;
setRights(theirRoles);
}
public List<String> getTheirRoles() {
return theirRoles;
}
private void setRights(List<String> roleNames) {
rights.clear();
for (String roleName : roleNames) {
DefaultRoles role = DefaultRoles.find(roleName);
if (role != null) {
rights.addAll(role.getRights());
}
}
}
public Set<Right> getRights() {
return rights;
}
}
|
package com.lothrazar.samsmagic;
import org.apache.logging.log4j.Logger;
import com.lothrazar.samsmagic.potion.*;
import com.lothrazar.samsmagic.item.ItemChestSack;
import com.lothrazar.samsmagic.proxy.*;
import com.lothrazar.samsmagic.spell.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.event.entity.EntityEvent.EntityConstructing;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@Mod(modid = ModSpells.MODID, useMetadata = true )
public class ModSpells
{
//TODO: DO NOT RESET TIMER IF CASTING FAILS
public static final String MODID = "samsmagic";
public static final String TEXTURE_LOCATION = MODID + ":";
@Instance(value = ModSpells.MODID)
public static ModSpells instance;
@SidedProxy(clientSide="com.lothrazar.samsmagic.proxy.ClientProxy", serverSide="com.lothrazar.samsmagic.proxy.CommonProxy")
public static CommonProxy proxy;
public static Logger logger;
public static ConfigSpells cfg;
public static SimpleNetworkWrapper network;
@EventHandler
public void onPreInit(FMLPreInitializationEvent event)
{
logger = event.getModLog();
cfg = new ConfigSpells(new Configuration(event.getSuggestedConfigurationFile()));
network = NetworkRegistry.INSTANCE.newSimpleChannel( MODID );
network.registerMessage(MessageKeyCast.class, MessageKeyCast.class, MessageKeyCast.ID, Side.SERVER);
network.registerMessage(MessageKeyLeft.class, MessageKeyLeft.class, MessageKeyLeft.ID, Side.SERVER);
network.registerMessage(MessageKeyRight.class, MessageKeyRight.class, MessageKeyRight.ID, Side.SERVER);
network.registerMessage(MessageKeyToggle.class, MessageKeyToggle.class, MessageKeyToggle.ID, Side.SERVER);
network.registerMessage(MessagePotion.class, MessagePotion.class, MessagePotion.ID, Side.CLIENT);
ItemRegistry.registerItems();
PotionRegistry.registerPotionEffects();
FMLCommonHandler.instance().bus().register(instance);
MinecraftForge.EVENT_BUS.register(instance);
SpellRegistry.setup();
}
@EventHandler
public void onInit(FMLInitializationEvent event)
{
proxy.registerRenderers();
}
public static EntityItem dropItemStackInWorld(World worldObj, BlockPos pos, ItemStack stack)
{
EntityItem entityItem = new EntityItem(worldObj, pos.getX(),pos.getY(),pos.getZ(), stack);
if(worldObj.isRemote == false)//do not spawn a second 'ghost' one on client side
{
worldObj.spawnEntityInWorld(entityItem);
}
return entityItem;
}
/*
@SubscribeEvent
public void onPlayerInteract(PlayerInteractEvent event)
{
if(event.pos == null){return;}
IBlockState bstate = event.entityPlayer.worldObj.getBlockState(event.pos);
if(bstate == null){return;}
ItemStack held = event.entityPlayer.getCurrentEquippedItem();
//Block blockClicked = event.world.getBlockState(event.pos).getBlock();
//TileEntity container = event.world.getTileEntity(event.pos);
if(held != null && held.getItem() == Items.experience_bottle &&
event.action.RIGHT_CLICK_BLOCK == event.action &&
event.entityPlayer.capabilities.isCreativeMode == false &&
ModSpells.cfg.experience_bottle_return)
{
dropItemStackInWorld(event.world, event.pos, new ItemStack(Items.glass_bottle));
}
}*/
public static String posToCSV(BlockPos pos)
{
return pos.getX()+","+pos.getY()+","+pos.getZ();
}
public static BlockPos stringCSVToBlockPos(String csv)
{
String [] spl = csv.split(",");
return new BlockPos(Integer.parseInt(spl[0]),Integer.parseInt(spl[1]),Integer.parseInt(spl[2]));
}
@SubscribeEvent
public void onKeyInput(InputEvent.KeyInputEvent event)
{
if(Minecraft.getMinecraft().objectMouseOver == null){return;}
BlockPos posMouse = Minecraft.getMinecraft().objectMouseOver.getBlockPos();
if(posMouse == null){return;}
if(ClientProxy.keySpellToggle.isPressed())
{
ModSpells.network.sendToServer( new MessageKeyToggle(posMouse));
}
else if(ClientProxy.keySpellCast.isPressed())
{
ModSpells.network.sendToServer( new MessageKeyCast(posMouse));
}
else if(ClientProxy.keySpellUp.isPressed())
{
ModSpells.network.sendToServer( new MessageKeyRight(posMouse));
}
else if(ClientProxy.keySpellDown.isPressed())
{
ModSpells.network.sendToServer( new MessageKeyLeft(posMouse));
}
}
@SubscribeEvent
public void onClonePlayer(PlayerEvent.Clone event)
{
PlayerPowerups.get(event.entityPlayer).copy(PlayerPowerups.get(event.original));
}
@SubscribeEvent
public void onEntityConstructing(EntityConstructing event)
{
if (event.entity instanceof EntityPlayer && PlayerPowerups.get((EntityPlayer) event.entity) == null)
{
PlayerPowerups.register((EntityPlayer) event.entity);
}
}
@SideOnly(Side.CLIENT)
@SubscribeEvent
public void onRenderTextOverlay(RenderGameOverlayEvent.Text event)
{
EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;
PlayerPowerups props = PlayerPowerups.get(player);
if(props.getSpellToggle() != SpellRegistry.SPELL_TOGGLE_HIDE)
{
drawSpell(event);
}
}
@SubscribeEvent
public void onEntityUpdate(LivingUpdateEvent event)
{
if(event.entityLiving == null){return;}
if(event.entityLiving instanceof EntityPlayer)
{
SpellGhost.onPlayerUpdate(event);
SpellRegistry.tickSpellTimer((EntityPlayer)event.entityLiving);
}
PotionRegistry.tickSlowfall(event);
PotionRegistry.tickWaterwalk(event);
//PotionRegistry.tickLavawalk(event);
//PotionRegistry.tickFrost(event);
}
@SideOnly(Side.CLIENT)
private static void renderItemAt(ItemStack stack, int x, int y, int dim)
{
//int height = dim, width = dim;
@SuppressWarnings("deprecation")
IBakedModel iBakedModel = Minecraft.getMinecraft().getRenderItem().getItemModelMesher().getItemModel(stack);
@SuppressWarnings("deprecation")
TextureAtlasSprite textureAtlasSprite = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(iBakedModel.getTexture().getIconName());
renderTexture( textureAtlasSprite, x, y, dim);
}
@SideOnly(Side.CLIENT)
public static void renderTexture( TextureAtlasSprite textureAtlasSprite , int x, int y, int dim)
{
Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.locationBlocksTexture);
Tessellator tessellator = Tessellator.getInstance();
int height = dim, width = dim;
WorldRenderer worldrenderer = tessellator.getWorldRenderer();
worldrenderer.startDrawingQuads();
worldrenderer.addVertexWithUV((double)(x), (double)(y + height), 0.0, (double)textureAtlasSprite.getMinU(), (double)textureAtlasSprite.getMaxV());
worldrenderer.addVertexWithUV((double)(x + width), (double)(y + height), 0.0, (double)textureAtlasSprite.getMaxU(), (double)textureAtlasSprite.getMaxV());
worldrenderer.addVertexWithUV((double)(x + width), (double)(y), 0.0, (double)textureAtlasSprite.getMaxU(), (double)textureAtlasSprite.getMinV());
worldrenderer.addVertexWithUV((double)(x), (double)(y), 0.0, (double)textureAtlasSprite.getMinU(), (double)textureAtlasSprite.getMinV());
tessellator.draw();
}
@SideOnly(Side.CLIENT)
private void drawSpell(RenderGameOverlayEvent.Text event)
{
EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;
ISpell spell = SpellRegistry.getPlayerCurrentISpell(player);
if(Minecraft.getMinecraft().gameSettings.showDebugInfo)
{
event.left.add(lang("key.spell."+spell.getSpellID()));
}
else
{
int ymain = 12;
int dim = 12;
int x = 12, y = 2;
Item ptr = SpellRegistry.canPlayerCastAnything(player) ? ItemRegistry.exp_cost_dummy : ItemRegistry.exp_cost_empty_dummy;
//spell.getIconDisplayHeader()
renderItemAt(new ItemStack(ptr),x,y,dim);
//int ysmall = ymain - 3;
int xmain = 10;
ymain = 14;
if(spell.getIconDisplay() != null)
{
x = xmain;
y = ymain;
dim = 16;
renderItemAt(spell.getIconDisplay(),x,y,dim);
}
ISpell spellNext = spell.left();//SpellRegistry.getSpellFromType(spell.getSpellID().next());
ISpell spellPrev = spell.right();//SpellRegistry.getSpellFromType(spell.getSpellID().prev());
if(spellNext != null)// && spellNext.getIconDisplay() != null
{
x = xmain-3;
y = ymain + 16;
dim = 16/2;
renderItemAt(spellNext.getIconDisplay(),x,y,dim);
ISpell sLeftLeft = spellNext.left();//SpellRegistry.getSpellFromType(spellNext.getSpellID().next());
if(sLeftLeft != null && sLeftLeft.getIconDisplay() != null)
{
x = xmain-3 - 1;
y = ymain + 16+14;
dim = 16/2 - 2;
renderItemAt(sLeftLeft.getIconDisplay(),x,y,dim);
ISpell another = sLeftLeft.left();
if(another != null)
{
x = xmain-3 - 3;
y = ymain + 16+14+10;
dim = 16/2 - 4;
renderItemAt(another.getIconDisplay(),x,y,dim);
}
}
}
if(spellPrev != null)// && spellPrev.getIconDisplay() != null
{
x = xmain+6;
y = ymain + 16;
dim = 16/2;
renderItemAt(spellPrev.getIconDisplay(),x,y,dim);
ISpell sRightRight = spellPrev.right();//SpellRegistry.getSpellFromType(spellPrev.getSpellID().prev());
if(sRightRight != null && sRightRight.getIconDisplay() != null)
{
x = xmain+6 + 4;
y = ymain + 16+14;
dim = 16/2 - 2;
renderItemAt(sRightRight.getIconDisplay(),x,y,dim);
ISpell another = sRightRight.right();
if(another != null)
{
x = xmain+6 +7;
y = ymain + 16+14+10;
dim = 16/2 - 4;
renderItemAt(another.getIconDisplay(),x,y,dim);
}
}
}
}
}
public static void playSoundAt(Entity player, String sound)
{
player.worldObj.playSoundAtEntity(player, sound, 1.0F, 1.0F);
}
public static void addChatMessage(EntityPlayer player,String string)
{
player.addChatMessage(new ChatComponentTranslation(string));
}
public static void spawnParticle(World world, EnumParticleTypes type, BlockPos pos)
{
spawnParticle(world,type,pos.getX(),pos.getY(),pos.getZ());
}
public static void spawnParticle(World world, EnumParticleTypes type, double x, double y, double z)
{
for(int countparticles = 0; countparticles <= 10; ++countparticles)
{
world.spawnParticle(type, x + (world.rand.nextDouble() - 0.5D) * (double)0.8, y + world.rand.nextDouble() * (double)1.5 - (double)0.1, z + (world.rand.nextDouble() - 0.5D) * (double)0.8, 0.0D, 0.0D, 0.0D);
}
}
public static void spawnParticlePacketByID(BlockPos position, int particleID)
{
//this. fires only on server side. so send packet for client to spawn particles and so on
ModSpells.network.sendToAll(new MessagePotion(position, particleID));
}
public static String lang(String name)
{
return StatCollector.translateToLocal(name);
}
//samsmagic
public static double getExpTotal(EntityPlayer player)
{
int level = player.experienceLevel;
//this is the exp between previous and last level, not the real total
//float experience = player.experience;
//numeric reference: http://minecraft.gamepedia.com/Experience#Leveling_up
double totalExp = getXpForLevel(level);
//so now we knwo how much was used to get to current level
//double nextLevelExp = getXpToGainLevel(level);
double progress = Math.round(player.xpBarCap() * player.experience);
totalExp += (int)progress;
return totalExp;
}
public static boolean drainExp(EntityPlayer player, float f)
{
double totalExp = getExpTotal(player);
if(totalExp - f < 0)
{
return false;
}
setXp(player, (int)(totalExp - f));
return true;
}
public static int getXpToGainLevel(int level)
{
//numeric reference: http://minecraft.gamepedia.com/Experience#Leveling_up
//so if our current level is 5, we pass in5 here and find out
//how much exp to get from 5 to 6
int nextLevelExp = 0;
if(level <= 15)
nextLevelExp = 2*level + 7;
else if(level <= 30)
nextLevelExp = 5*level - 38;
else //level >= 31
nextLevelExp = 9*level - 158;
return nextLevelExp;
}
public static int getXpForLevel(int level)
{
//numeric reference: http://minecraft.gamepedia.com/Experience#Leveling_up
int totalExp = 0;
if(level <= 15)
totalExp = level*level + 6*level;
else if(level <= 30)
totalExp = (int)(2.5*level*level - 40.5*level + 360);
else //level >= 31
totalExp = (int)(4.5*level*level - 162.5*level + 2220);//fixed. was +162... by mistake
return totalExp;
}
public static int getLevelForXp(int xp)
{
int lev = 0;
while (getXpForLevel(lev) < xp)
{
lev++;
}
return lev - 1;
}
public static void setXp(EntityPlayer player, int xp)
{
player.experienceTotal = xp;
player.experienceLevel = getLevelForXp(xp);
int next = getXpForLevel(player.experienceLevel);
player.experience = (float)(player.experienceTotal - next) / (float)player.xpBarCap();
}
public static void teleportWallSafe(EntityLivingBase player, World world, BlockPos coords)
{
player.setPositionAndUpdate(coords.getX(), coords.getY(), coords.getZ());
moveEntityWallSafe(player, world);
}
public static void moveEntityWallSafe(EntityLivingBase entity, World world)
{
while (!world.getCollidingBoundingBoxes(entity, entity.getEntityBoundingBox()).isEmpty())
{
entity.setPositionAndUpdate(entity.posX, entity.posY + 1.0D, entity.posZ);
}
}
public static void addOrMergePotionEffect(EntityPlayer player, PotionEffect newp)
{
if(player.isPotionActive(newp.getPotionID()))
{
//do not use built in 'combine' function, just add up duration myself
PotionEffect p = player.getActivePotionEffect(Potion.potionTypes[newp.getPotionID()]);
int ampMax = Math.max(p.getAmplifier(), newp.getAmplifier());
player.addPotionEffect(new PotionEffect(newp.getPotionID()
,newp.getDuration()+p.getDuration()
,ampMax));
}
else
{
player.addPotionEffect(newp);
}
}
public static String posToStringCSV(BlockPos position)
{
return position.getX() + ","+position.getY()+","+position.getZ();
}
public static void incrementPlayerIntegerNBT(EntityPlayer player, String prop, int inc)
{
int prev = player.getEntityData().getInteger(prop);
prev += inc;
player.getEntityData().setInteger(prop, prev);
}
}
|
package com.example.fw;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.example.tests.ContactData;
public class ContactHelper extends HelperBase {
public ContactHelper(ApplicationManager manager) {
super(manager);
}
public void submitContactForm() {
click(By.name("submit"));
}
public void fillContactForm(ContactData contact) {
// name
type(By.name("firstname"), contact.firstName);
type(By.name("lastname"), contact.lastName);
// address
type(By.name("address"), contact.address);
// contacts
type(By.name("home"), contact.homePhone);
type(By.name("mobile"), contact.mobilePhone);
type(By.name("work"), contact.workPhone);
type(By.name("email"), contact.email_1);
type(By.name("email2"), contact.email_2);
// birth date
select(By.name("bday"), contact.birthDay);
select(By.name("bmonth"), contact.birthMonth);
type(By.name("byear"), contact.birthYear);
// group
select(By.name("new_group"), contact.contactGroup);
// extra address
type(By.name("address2"), contact.addressSecondary);
// extra contact
type(By.name("phone2"), contact.phoneSecondary);
}
public void returnToHomePage() {
click(By.linkText("home page"));
}
public void initContactEdit(int index) {
String locator = "//table[@id='maintable']//tr[" + (index + 1) + "]/td/a/img[@title='Edit']";
click(By.xpath(locator));
}
public void submitDeleteContact() {
click(By.xpath("//input[@value='Delete']"));
}
public void submitUpdate() {
click(By.xpath("//input[@value='Update']"));
}
public List<ContactData> getContacts() {
List<ContactData> contacts = new ArrayList<ContactData>();
List<WebElement> tableRows = driver.findElements(By.xpath("//table[@id='maintable']/tbody/tr[@name='entry']"));
for (WebElement tableRow : tableRows) {
ContactData contact = new ContactData();
contact.lastName = tableRow.findElement(By.xpath("td[2]")).getText();
contact.firstName = tableRow.findElement(By.xpath("td[3]")).getText();
String[] emails = tableRow.findElement(By.xpath("td/input")).getAttribute("accept").split(";");
contact.email_1 = emails.length == 1 ? emails[0] : null;
contact.email_2 = emails.length > 1 ? emails[1] : null;
contact.homePhone = tableRow.findElement(By.xpath("td[5]")).getText();
contacts.add(contact);
}
return contacts;
}
}
|
package fr.utbm.vi51.model;
import java.util.ArrayList;
import java.util.List;
import fr.utbm.vi51.parser.JSONReadAndConvertingFromLevelFile;
public class EnvironmentModel {
private List<List<Cell>> grid;
private int numberOfBody;
private Cell entry;
private Cell exit;
private List<LemmingBody> listOfBody;
private int deads = 0;
private int out = 0;
public EnvironmentModel(String level, int numberOfBody) {
this.setGrid(level, numberOfBody);
}
public void addDead(){
this.deads ++;
}
public void addOut(){
this.out ++;
}
public int getDead(){
return this.deads;
}
public int getOut(){
return this.out;
}
public int getNumberOfBody() {
return numberOfBody;
}
public List<List<Cell>> getGrid() {
return grid;
}
public void setGrid(String level, int numberOfBody) {
this.listOfBody = new ArrayList<LemmingBody>();
this.numberOfBody = numberOfBody;
JSONReadAndConvertingFromLevelFile js = new JSONReadAndConvertingFromLevelFile(level);
this.grid = js.convertingContentForGame();
if (js.getEntryPosition() != null)
this.entry = this.grid.get((int) js.getEntryPosition().getX()).get((int) js.getEntryPosition().getY());
if (js.getExitPosition() != null)
this.exit = this.grid.get((int) js.getExitPosition().getX()).get((int) js.getExitPosition().getY());
for (int i = 0; i < this.numberOfBody; i++) {
this.listOfBody.add(new LemmingBody(i, this.entry.getX(), this.entry.getY()));
this.entry.getListOfBodyInCell().add(listOfBody.get(i));
}
}
public Cell getEntry() {
return entry;
}
public Cell getExit() {
return exit;
}
// SearchedBody return the position of the body in the list of a Cell
public SearchedBody searchBody(int id) {
int p = 0;
int k = 0;
while (listOfBody.get(p).getId() != id) {
p++;
}
k = searchBodyInCell(listOfBody.get(p));
return new SearchedBody(listOfBody.get(p), k);
}
public int searchBodyInCell (LemmingBody body){
int k = 0;
while (grid.get(body.getX()).get(body.getY()).getListOfBodyInCell().get(k).getId() != body.getId()) {
k++;
}
return k;
}
public List<Percept> getPerception(int id) {
/*
* Disposition of the perception -->
* 08 02 09
* 01 00 03
* 13 04 10
* 14 05 12
* 15 06 12
* 07
*/
List<Percept> allPerception = new ArrayList<Percept>();
LemmingBody body = searchBody(id).getBody();
int x = body.getX();
int y = body.getY();
// System.out.println(x + ":" + y);
// System.out.println(grid.get(x).get(y+1).getType());
allPerception.add(new Percept(grid.get(x).get(y)));
//left
for (int i = 1; i <= body.getFovLeft(); i++){
// System.out.println((y - i+grid.get(x).size())%grid.get(x).size());
allPerception.add(new Percept(grid.get(x).get((y - i+grid.get(x).size())%grid.get(x).size())));
}
for (int j = 1; j <= body.getFovUp(); j++) {
if (x - j >= 0) {
allPerception.add(new Percept(grid.get(x - j).get(y)));
}else{
allPerception.add(new Percept(new Cell(-1, -1, TypeObject.WALL)));
}
}
//right
for (int i = 1; i <= body.getFovRight(); i++){
allPerception.add(new Percept(grid.get(x).get((y + i)%grid.get(x).size())));
}
//down
for (int j = 1; j <= body.getFovUnder(); j++) {
if (x + j < grid.size()) {
allPerception.add(new Percept(grid.get(x + j).get(y)));
}else{
allPerception.add(new Percept(new Cell(-1, -1, TypeObject.EMPTY)));
}
}
//left up
for (int i = 1; i <= body.getFovLeft(); i++) {
for (int j = 1; j <= body.getFovUp(); j++) {
if (x - j >= 0 && y - i >= 0) {
allPerception.add(new Percept(grid.get(x - j).get(y - i)));
}else{
allPerception.add(new Percept(new Cell(-1, -1, TypeObject.WALL)));
}
}
}
//right up
for (int i = 1; i <= body.getFovRight(); i++) {
for (int j = 1; j <= body.getFovUp(); j++) {
if (x - j >= 0) {
System.out.println(x-j + " " + y+i);
allPerception.add(new Percept(grid.get(x - j).get((y + i)%grid.get(x).size())));
}else{
allPerception.add(new Percept(new Cell(-1, -1, TypeObject.WALL)));
}
}
}
//right down
for (int i = 1; i <= body.getFovRight(); i++) {
for (int j = 1; j <= body.getFovUnder()-1; j++) {
if ( (x + j) < grid.size() ) {
allPerception.add(new Percept(grid.get(x + j).get((y + i)%grid.get(x).size())));
}else{
allPerception.add(new Percept(new Cell(-1, -1, TypeObject.EMPTY)));
}
}
}
//left down
for (int i = 1; i <= body.getFovLeft(); i++) {
for (int j = 1; j <= body.getFovUnder()-1; j++) {
if ( (x + j) < grid.size()) {
allPerception.add(new Percept(grid.get(x + j).get((y - i+grid.get(x).size())%grid.get(x).size())));
}else{
allPerception.add(new Percept(new Cell(-1, -1, TypeObject.EMPTY)));
}
}
}
return allPerception;
}
// with an id and a move, the body is moved
public boolean moveBody(int id, PossibleMove move) {
LemmingBody body = searchBody(id).getBody();
int p = searchBody(id).getPosition();
int x = body.getX();
int y = body.getY();
// check if the body is on a land
if (isLand(x+1, y)){
//all moves allowed
if(move == PossibleMove.MOVEBACKWARD){
body.increaseFatigue();
if (body.getOrientation().equals(Orientation.RIGHT)){
return moveLeft(body, p);
} else{
return moveRight(body,p);
}
}
else if(move == PossibleMove.MOVEFORWARD){
if (body.getOrientation().equals(Orientation.LEFT)){
return moveLeft(body, p);
} else{
return moveRight(body,p);
}
}
else if(move == PossibleMove.CLIMBFORWARD){
return climbingBody(body, p, false);
}
else if(move == PossibleMove.CLIMBBACKWARD){
return climbingBody(body, p, true);
}
else if(move == PossibleMove.DIG){
//the case is full Land
if ((y < grid.get(x).size()-1) && (grid.get(x).get(y + 1).getType().equals(TypeObject.LAND))) {
grid.get(x).get(y + 1).setType(TypeObject.HALF);
body.setOrientation(Orientation.DOWN);
//the case if half land
} else if (grid.get(x).get(y + 1).getType().equals(TypeObject.HALF)) {
grid.get(x).get(y + 1).setType(TypeObject.EMPTY);
// every body on this case fall
for (int i = 0; i < grid.get(x).get(y).getListOfBodyInCell().size(); i++) {
grid.get(x).get(y).getListOfBodyInCell().get(p).fall();
fallingBody(body, p);
}
return true;
} else {
return false;
}
}
// body climbing
} else if (body.isClimbing() && move.equals(PossibleMove.CLIMBFORWARD)){
return climbingBody(body, p, false);
} else if (body.isClimbing() && move.equals(PossibleMove.CLIMBBACKWARD)){
body.increaseFatigue();
return climbingBody(body, p, true);
// body parachute
} else if (move.equals(PossibleMove.PARACHUTE)){
if (x +1 < grid.size()){
System.out.println("premier");
body.activateParachute();
fallingBody(body, p);
statusBody(body);
return true;
} else{
return false;
}
} else {
if (x +1 < grid.size()){
System.out.println("en chemin");
if (!body.statusParachute()){
body.fall();
}
fallingBody(body, p);
statusBody(body);
return true;
} else {
return false;
}
}
return false;
}
public boolean moveLeft(LemmingBody body, int p){
int x = body.getX();
int y = body.getY();
if ((x > 0) && accessibleCase(x-1, y)) {
grid.get(x - 1).get(y).getListOfBodyInCell().add(body);
grid.get(x).get(y).getListOfBodyInCell().remove(p);
body.setX(x - 1);
body.setOrientation(Orientation.LEFT);
statusBody(body);
return true;
} else {
return false;
}
}
public boolean moveRight(LemmingBody body, int p){
int x = body.getX();
int y = body.getY();
if ((x < grid.size()) && accessibleCase(x, y+1)) {
grid.get(x).get(y+1).getListOfBodyInCell().add(body);
grid.get(x).get(y).getListOfBodyInCell().remove(p);
body.setY(y + 1);
body.setOrientation(Orientation.RIGHT);
statusBody(body);
return true;
} else {
return false;
}
}
// Action after any move
public void statusBody(LemmingBody body) {
int x = body.getX();
int y = body.getY();
// Body on the Exit
if (isExit(x, y)){
body.winner();
outLemming(body);
// if the body is on a land nothing to do except disable parachute and stop climbing
} else if (isLand(x+1,y)){
if (body.getOrientation().equals(Orientation.DOWN)){
if(body.isClimbing()){
body.increaseFatigue();
body.getUp();
} else {
body.getUp();
body.resetFatigue();
}
}
// if the body is falling
} else if (accessibleCase(x+1, y) && !body.isClimbing() && !body.statusParachute()){
body.fall();
body.setOrientation(Orientation.DOWN);
if (body.getFall()==3){
body.setOrientation(Orientation.DEAD);
killLemming(body);
}
}
}
public void fallingBody (LemmingBody body, int p){
int x = body.getX();
int y = body.getY();
grid.get(x).get(y).getListOfBodyInCell().get(p).setOrientation(Orientation.DOWN);
grid.get(x+1).get(y).getListOfBodyInCell().add(grid.get(x).get(y).getListOfBodyInCell().get(p));
grid.get(x).get(y).getListOfBodyInCell().remove(p);
//ajout pour changer la position du lemming
this.listOfBody.get(this.listOfBody.indexOf(body)).setX(x+1);
}
|
package annotator.scanner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.util.TreePath;
/** CastScanner stores information about the names and offsets of
* casts inside a method, and can also be used to scan the source
* tree and determine the index of a given cast, where the i^th
* index corresponds to the i^th cast, using 0-based indexing.
*/
public class CastScanner extends CommonScanner {
/**
* Computes the index of the given cast tree amongst all cast trees inside
* its method, using 0-based indexing.
*
* @param path the path ending in the given cast tree
* @param tree the cast tree to search for
* @return the index of the given cast tree
*/
public static int indexOfCastTree(TreePath path, Tree tree) {
// only start searching from within this method
path = findEnclosingMethod(path);
if (path == null) {
// Was called on something other than a local variable, so return
// -1 to ensure that it doesn't match anything.
return -1;
}
CastScanner lvts = new CastScanner(tree);
lvts.scan(path, null);
return lvts.index;
}
public static int indexOfCastTreeInFieldInit(TreePath path, Tree tree) {
// only start searching from within this field initializer
path = findEnclosingFieldInit(path);
if (path == null) {
return -1;
}
CastScanner lvts = new CastScanner(tree);
lvts.scan(path, null);
return lvts.index;
}
public static int indexOfCastTreeInStaticInit(TreePath path, Tree tree) {
// only start searching from within this method
path = findEnclosingStaticInit(path);
if (path == null) {
return -1;
}
CastScanner lvts = new CastScanner(tree);
lvts.scan(path, null);
return lvts.index;
}
private int index = -1;
private boolean done = false;
private Tree tree;
private CastScanner(Tree tree) {
this.index = -1;
this.done = false;
this.tree = tree;
}
@Override
public Void visitTypeCast(
TypeCastTree node,
Void p) {
if (!done) {
index++;
}
if (tree == node) {
done = true;
}
return p;
}
// Map from name of a method a list of bytecode offsets of all
// casts in that method.
private static Map<String,List<Integer>> methodNameToCastOffsets =
new HashMap<String, List<Integer>>();
/**
* Adds a cast bytecode offset to the current list of offsets for
* methodName. This method must be called with monotonically increasing
* offsets for any one method.
*
* @param methodName the name of the method
* @param offset the offset to add
*/
public static void addCastToMethod(
String methodName,
Integer offset) {
List< Integer> offsetList =
methodNameToCastOffsets.get(methodName);
if (offsetList == null) {
offsetList = new ArrayList< Integer>();
methodNameToCastOffsets.put(methodName, offsetList);
}
offsetList.add(offset);
}
/**
* Returns the index of the given offset within the list of offsets
* for the given method, using 0-based indexing,
* or returns a negative number if the offset is not one of the
* offsets in the method.
*
* @param methodName the name of the method
* @param offset the offset of the instanceof check
* @return the index of the given offset, or a negative number if the
* given offset does not exists inside the method
*/
public static Integer getMethodCastIndex(
String methodName,
Integer offset) {
List<Integer> offsetList =
methodNameToCastOffsets.get(methodName);
if (offsetList == null) {
return -1;
// throw new RuntimeException("CastScanner.getMethodCastIndex() : " +
// "did not find offsets for method: " + methodName);
}
return offsetList.indexOf(offset);
}
}
|
package core.framework.internal.resource;
import core.framework.util.Lists;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
/**
* @author neo
*/
class PoolTest {
private Pool<TestPoolResource> pool;
@BeforeEach
void createPool() {
pool = new Pool<>(TestPoolResource::new, "pool");
pool.maxIdleTime = Duration.ZERO;
pool.checkoutTimeout(Duration.ZERO);
}
@Test
void borrowAndReturn() {
PoolItem<TestPoolResource> item = pool.borrowItem();
assertThat(item.resource).isNotNull();
pool.returnItem(item);
assertThat(pool.idleItems.size()).isEqualTo(1);
assertThat(pool.size.get()).isEqualTo(1);
assertThat(pool.idleItems.getFirst().returnTime).isGreaterThan(0);
}
@Test
void borrowWithInvalidResource() {
pool.validator(resource -> false, Duration.ZERO);
var invalidResource = new TestPoolResource();
pool.returnItem(new PoolItem<>(invalidResource));
PoolItem<TestPoolResource> item = pool.borrowItem();
assertThat(item.resource).isNotNull().isNotSameAs(invalidResource);
assertThat(invalidResource.closed).isTrue();
}
@Test
void borrowWithValidatorFailure() {
pool.validator(resource -> {
throw new Error("failed validate resource");
}, Duration.ZERO);
var invalidResource = new TestPoolResource();
pool.returnItem(new PoolItem<>(invalidResource));
PoolItem<TestPoolResource> item = pool.borrowItem();
assertThat(item.resource).isNotNull().isNotSameAs(invalidResource);
assertThat(invalidResource.closed).isTrue();
}
@Test
void borrowWithinAliveWindow() {
pool.validator(resource -> false, Duration.ofMinutes(30)); // should not call validator to test
var resource = new TestPoolResource();
pool.returnItem(new PoolItem<>(resource));
PoolItem<TestPoolResource> item = pool.borrowItem();
assertThat(item.resource).isNotNull().isSameAs(resource);
}
@Test
void returnBrokenResource() {
PoolItem<TestPoolResource> item = pool.borrowItem();
assertThat(item.resource).isNotNull();
assertThat(pool.size.get()).isEqualTo(1);
item.broken = true;
pool.returnItem(item);
assertThat(pool.idleItems.size()).isZero();
assertThat(pool.size.get()).isZero();
assertThat(item.resource.closed).isTrue();
}
@Test
void refresh() {
pool.size(2, 2);
pool.refresh();
assertThat(pool.size.get()).isEqualTo(2);
assertThat(pool.idleItems.size()).isEqualTo(2);
}
@Test
void refreshWithRecycle() {
pool.size(1, 5);
List<PoolItem<TestPoolResource>> items = Lists.newArrayList();
for (int i = 0; i < 5; i++) {
items.add(pool.borrowItem());
}
items.forEach(pool::returnItem);
pool.refresh();
assertThat(pool.size.get()).isEqualTo(1);
assertThat(pool.idleItems.size()).isEqualTo(1);
}
@Test
void borrowWithTimeout() {
pool.size(0, 0);
PoolException exception = catchThrowableOfType(() -> pool.borrowItem(), PoolException.class);
assertThat(exception.errorCode()).isEqualTo("POOL_TIME_OUT");
}
@Test
void close() {
PoolItem<TestPoolResource> item = pool.borrowItem();
pool.returnItem(item);
pool.close();
assertThat(item.resource.closed).isTrue();
}
}
|
package io.asfjava.ui.demo.screen;
import java.io.Serializable;
import io.asfjava.ui.core.form.CheckBox;
import io.asfjava.ui.core.form.ComboBox;
import io.asfjava.ui.core.form.Number;
import io.asfjava.ui.core.form.Password;
import io.asfjava.ui.core.form.RadioBox;
import io.asfjava.ui.core.form.TextArea;
import io.asfjava.ui.core.form.TextField;
public class DemoForm implements Serializable {
@TextField(title = "First Name", placeHolder = "Your first name", description = "This is a description for your first name field")
private String firstName;
@TextField(title = "Last Name", placeHolder = "Your last name")
private String lastName;
@TextField(title = "eMail", placeHolder = "Your email", pattern = "^\\S+@\\S+$", validationMessage = "Your mail must be in this format jhondoe@example.com", description = "This is Text Field with pattern and validation message")
private String email;
@Number(title = "Number of children", placeHolder = "Number of children", description = "This is a number")
private Integer number;
@Password(title = "Password", placeHolder = "Please set you password", description = "This is password")
private String password;
@ComboBox(title = "Gender", titleMap = GenderTitleMap.class)
private String gender;
@ComboBox(title = "Currency", values = { "euro", "dollar" })
private String currency;
@RadioBox(title = "Civil State", titleMap = CivilStateTitelsMap.class)
private String civilState;
@TextArea(title = "Address", placeHolder = "Fill your address please", description = "This is textarea")
private String address;
@CheckBox(title = "Color", values = { "red", "bleu", "green" }, defaultvalue = "red")
private String color;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setEmail(String eMail) {
this.email = eMail;
}
public String getEmail() {
return email;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCivilState() {
return civilState;
}
public void setCivilState(String civilState) {
this.civilState = civilState;
}
public String getCurrency() {
return currency;
}
public String getColor() {
return color;
}
private static final long serialVersionUID = -5073515619469444978L;
}
|
package ca.sumost.kinetic.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import ca.sumost.kinetic.KineticTheoryGame;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "Kinetic Gas Theory";
config.width = KineticTheoryGame.VIEWPORT_WIDTH;
config.height = KineticTheoryGame.VIEWPORT_HEIGHT;
new LwjglApplication(new KineticTheoryGame(), config);
}
}
|
/* @java.file.header */
package org.gridgain.grid.kernal.processors.cache.distributed.dht.atomic;
import org.gridgain.grid.*;
import org.gridgain.grid.cache.*;
import org.gridgain.grid.kernal.processors.cache.*;
import org.gridgain.grid.kernal.processors.cache.distributed.dht.*;
import org.gridgain.grid.kernal.processors.cache.distributed.dht.preloader.*;
import org.gridgain.grid.kernal.processors.cache.distributed.near.*;
import org.gridgain.grid.kernal.processors.cache.dr.*;
import org.gridgain.grid.kernal.processors.dr.*;
import org.gridgain.grid.kernal.processors.timeout.*;
import org.gridgain.grid.kernal.processors.version.*;
import org.gridgain.grid.lang.*;
import org.gridgain.grid.product.*;
import org.gridgain.grid.security.*;
import org.gridgain.grid.util.*;
import org.gridgain.grid.util.future.*;
import org.gridgain.grid.util.lang.*;
import org.gridgain.grid.util.tostring.*;
import org.gridgain.grid.util.typedef.*;
import org.gridgain.grid.util.typedef.internal.*;
import org.jdk8.backport.*;
import org.jetbrains.annotations.*;
import sun.misc.*;
import java.io.*;
import java.nio.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import static org.gridgain.grid.GridSystemProperties.*;
import static org.gridgain.grid.cache.GridCacheAtomicWriteOrderMode.*;
import static org.gridgain.grid.cache.GridCachePeekMode.*;
import static org.gridgain.grid.cache.GridCacheWriteSynchronizationMode.*;
import static org.gridgain.grid.kernal.processors.cache.GridCacheOperation.*;
import static org.gridgain.grid.kernal.processors.cache.GridCacheUtils.*;
import static org.gridgain.grid.kernal.processors.dr.GridDrType.*;
import static org.gridgain.grid.util.direct.GridTcpCommunicationMessageAdapter.*;
/**
* Non-transactional partitioned cache.
*/
@GridToStringExclude
public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
/** Version where FORCE_TRANSFORM_BACKUP flag was introduced. */
public static final GridProductVersion FORCE_TRANSFORM_BACKUP_SINCE = GridProductVersion.fromString("6.1.2");
private static final long serialVersionUID = 0L;
/** Deferred update response buffer size. */
private static final int DEFERRED_UPDATE_RESPONSE_BUFFER_SIZE =
Integer.getInteger(GG_ATOMIC_DEFERRED_ACK_BUFFER_SIZE, 256);
/** Deferred update response timeout. */
private static final int DEFERRED_UPDATE_RESPONSE_TIMEOUT =
Integer.getInteger(GG_ATOMIC_DEFERRED_ACK_TIMEOUT, 500);
/** Unsafe instance. */
private static final Unsafe UNSAFE = GridUnsafe.unsafe();
/** Update reply closure. */
private CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> updateReplyClos;
/** Pending */
private ConcurrentMap<UUID, DeferredResponseBuffer> pendingResponses = new ConcurrentHashMap8<>();
private GridNearAtomicCache<K, V> near;
/**
* Empty constructor required by {@link Externalizable}.
*/
public GridDhtAtomicCache() {
// No-op.
}
/**
* @param ctx Cache context.
*/
public GridDhtAtomicCache(GridCacheContext<K, V> ctx) {
super(ctx);
}
/**
* @param ctx Cache context.
* @param map Cache concurrent map.
*/
public GridDhtAtomicCache(GridCacheContext<K, V> ctx, GridCacheConcurrentMap<K, V> map) {
super(ctx, map);
}
/** {@inheritDoc} */
@Override public boolean isDhtAtomic() {
return true;
}
/** {@inheritDoc} */
@Override protected void init() {
map.setEntryFactory(new GridCacheMapEntryFactory<K, V>() {
/** {@inheritDoc} */
@Override public GridCacheMapEntry<K, V> create(GridCacheContext<K, V> ctx, long topVer, K key, int hash,
V val, GridCacheMapEntry<K, V> next, long ttl, int hdrId) {
return new GridDhtAtomicCacheEntry<>(ctx, topVer, key, hash, val, next, ttl, hdrId);
}
});
updateReplyClos = new CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>>() {
@Override public void apply(GridNearAtomicUpdateRequest<K, V> req, GridNearAtomicUpdateResponse<K, V> res) {
if (ctx.config().getAtomicWriteOrderMode() == CLOCK) {
// Always send reply in CLOCK ordering mode.
sendNearUpdateReply(res.nodeId(), res);
return;
}
// Request should be for primary keys only in PRIMARY ordering mode.
assert req.hasPrimary();
if (req.writeSynchronizationMode() != FULL_ASYNC)
sendNearUpdateReply(res.nodeId(), res);
else {
if (!F.isEmpty(res.remapKeys()))
// Remap keys on primary node in FULL_ASYNC mode.
remapToNewPrimary(req);
else if (res.error() != null) {
U.error(log, "Failed to process write update request in FULL_ASYNC mode for keys: " +
res.failedKeys(), res.error());
}
}
}
};
}
/** {@inheritDoc} */
@SuppressWarnings({"IfMayBeConditional", "SimplifiableIfStatement"})
@Override public void start() throws GridException {
resetMetrics();
preldr = new GridDhtPreloader<>(ctx);
preldr.start();
ctx.io().addHandler(GridNearGetRequest.class, new CI2<UUID, GridNearGetRequest<K, V>>() {
@Override public void apply(UUID nodeId, GridNearGetRequest<K, V> req) {
processNearGetRequest(nodeId, req);
}
});
ctx.io().addHandler(GridNearAtomicUpdateRequest.class, new CI2<UUID, GridNearAtomicUpdateRequest<K, V>>() {
@Override public void apply(UUID nodeId, GridNearAtomicUpdateRequest<K, V> req) {
processNearAtomicUpdateRequest(nodeId, req);
}
});
ctx.io().addHandler(GridNearAtomicUpdateResponse.class, new CI2<UUID, GridNearAtomicUpdateResponse<K, V>>() {
@Override public void apply(UUID nodeId, GridNearAtomicUpdateResponse<K, V> res) {
processNearAtomicUpdateResponse(nodeId, res);
}
});
ctx.io().addHandler(GridDhtAtomicUpdateRequest.class, new CI2<UUID, GridDhtAtomicUpdateRequest<K, V>>() {
@Override public void apply(UUID nodeId, GridDhtAtomicUpdateRequest<K, V> req) {
processDhtAtomicUpdateRequest(nodeId, req);
}
});
ctx.io().addHandler(GridDhtAtomicUpdateResponse.class, new CI2<UUID, GridDhtAtomicUpdateResponse<K, V>>() {
@Override public void apply(UUID nodeId, GridDhtAtomicUpdateResponse<K, V> res) {
processDhtAtomicUpdateResponse(nodeId, res);
}
});
ctx.io().addHandler(GridDhtAtomicDeferredUpdateResponse.class,
new CI2<UUID, GridDhtAtomicDeferredUpdateResponse<K, V>>() {
@Override public void apply(UUID nodeId, GridDhtAtomicDeferredUpdateResponse<K, V> res) {
processDhtAtomicDeferredUpdateResponse(nodeId, res);
}
});
if (near == null) {
ctx.io().addHandler(GridNearGetResponse.class, new CI2<UUID, GridNearGetResponse<K, V>>() {
@Override public void apply(UUID nodeId, GridNearGetResponse<K, V> res) {
processNearGetResponse(nodeId, res);
}
});
}
}
/** {@inheritDoc} */
@Override public void resetMetrics() {
boolean isDrSndCache = cacheCfg.getDrSenderConfiguration() != null;
boolean isDrRcvCache = cacheCfg.getDrReceiverConfiguration() != null;
GridCacheMetricsAdapter m = new GridCacheMetricsAdapter(isDrSndCache, isDrRcvCache);
if (ctx.dht().near() != null)
m.delegate(ctx.dht().near().metrics0());
metrics = m;
}
/**
* @param near Near cache.
*/
public void near(GridNearAtomicCache<K, V> near) {
this.near = near;
}
/** {@inheritDoc} */
@Override public GridNearCacheAdapter<K, V> near() {
return near;
}
/** {@inheritDoc} */
@Override public GridCacheEntry<K, V> entry(K key) {
return new GridDhtCacheEntryImpl<>(ctx.projectionPerCall(), ctx, key, null);
}
/** {@inheritDoc} */
@Override public V peek(K key, @Nullable Collection<GridCachePeekMode> modes) throws GridException {
GridTuple<V> val = null;
if (ctx.isReplicated() || !modes.contains(NEAR_ONLY)) {
try {
val = peek0(true, key, modes, ctx.tm().txx());
}
catch (GridCacheFilterFailedException ignored) {
if (log.isDebugEnabled())
log.debug("Filter validation failed for key: " + key);
return null;
}
}
return val != null ? val.get() : null;
}
/** {@inheritDoc} */
@Override public GridCacheTxLocalAdapter<K, V> newTx(
boolean implicit,
boolean implicitSingle,
GridCacheTxConcurrency concurrency,
GridCacheTxIsolation isolation,
long timeout,
boolean invalidate,
boolean syncCommit,
boolean syncRollback,
boolean swapEnabled,
boolean storeEnabled,
int txSize,
@Nullable Object grpLockKey,
boolean partLock
) {
throw new UnsupportedOperationException("Transactions are not supported for " +
"GridCacheAtomicityMode.ATOMIC mode (use GridCacheAtomicityMode.TRANSACTIONAL instead)");
}
/** {@inheritDoc} */
@Override public GridFuture<Map<K, V>> getAllAsync(
@Nullable final Collection<? extends K> keys,
final boolean forcePrimary,
boolean skipTx,
@Nullable final GridCacheEntryEx<K, V> entry,
@Nullable final GridPredicate<GridCacheEntry<K, V>>[] filter
) {
return asyncOp(new CO<GridFuture<Map<K, V>>>() {
@Override public GridFuture<Map<K, V>> apply() {
return getAllAsync0(keys, false, forcePrimary, filter);
}
});
}
/** {@inheritDoc} */
@Override public V put(K key, V val, @Nullable GridCacheEntryEx<K, V> cached, long ttl,
@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
return putAsync(key, val, cached, ttl, filter).get();
}
/** {@inheritDoc} */
@Override public boolean putx(K key, V val, @Nullable GridCacheEntryEx<K, V> cached,
long ttl, @Nullable GridPredicate<GridCacheEntry<K, V>>... filter) throws GridException {
return putxAsync(key, val, cached, ttl, filter).get();
}
/** {@inheritDoc} */
@Override public boolean putx(K key, V val,
GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
return putxAsync(key, val, filter).get();
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<V> putAsync(K key, V val, @Nullable GridCacheEntryEx<K, V> entry,
long ttl, @Nullable GridPredicate<GridCacheEntry<K, V>>... filter) {
return updateAllAsync0(F0.asMap(key, val), null, null, null, true, false, entry, ttl, filter);
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<Boolean> putxAsync(K key, V val, @Nullable GridCacheEntryEx<K, V> entry, long ttl,
@Nullable GridPredicate<GridCacheEntry<K, V>>... filter) {
return updateAllAsync0(F0.asMap(key, val), null, null, null, false, false, entry, ttl, filter);
}
/** {@inheritDoc} */
@Override public V putIfAbsent(K key, V val) throws GridException {
return putIfAbsentAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridFuture<V> putIfAbsentAsync(K key, V val) {
return putAsync(key, val, ctx.noPeekArray());
}
/** {@inheritDoc} */
@Override public boolean putxIfAbsent(K key, V val) throws GridException {
return putxIfAbsentAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridFuture<Boolean> putxIfAbsentAsync(K key, V val) {
return putxAsync(key, val, ctx.noPeekArray());
}
/** {@inheritDoc} */
@Override public V replace(K key, V val) throws GridException {
return replaceAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridFuture<V> replaceAsync(K key, V val) {
return putAsync(key, val, ctx.hasPeekArray());
}
/** {@inheritDoc} */
@Override public boolean replacex(K key, V val) throws GridException {
return replacexAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridFuture<Boolean> replacexAsync(K key, V val) {
return putxAsync(key, val, ctx.hasPeekArray());
}
/** {@inheritDoc} */
@Override public boolean replace(K key, V oldVal, V newVal) throws GridException {
return replaceAsync(key, oldVal, newVal).get();
}
/** {@inheritDoc} */
@Override public GridFuture<Boolean> replaceAsync(K key, V oldVal, V newVal) {
return putxAsync(key, newVal, ctx.equalsPeekArray(oldVal));
}
/** {@inheritDoc} */
@Override public GridCacheReturn<V> removex(K key, V val) throws GridException {
return removexAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridCacheReturn<V> replacex(K key, V oldVal, V newVal) throws GridException {
return replacexAsync(key, oldVal, newVal).get();
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<GridCacheReturn<V>> removexAsync(K key, V val) {
return removeAllAsync0(F.asList(key), null, null, true, true, ctx.equalsPeekArray(val));
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<GridCacheReturn<V>> replacexAsync(K key, V oldVal, V newVal) {
return updateAllAsync0(F.asMap(key, newVal), null, null, null, true, true, null, 0,
ctx.equalsPeekArray(oldVal));
}
/** {@inheritDoc} */
@Override public void putAll(Map<? extends K, ? extends V> m,
GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
putAllAsync(m, filter).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> putAllAsync(Map<? extends K, ? extends V> m,
@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) {
return updateAllAsync0(m, null, null, null, false, false, null, 0, filter);
}
/** {@inheritDoc} */
@Override public void putAllDr(Map<? extends K, GridCacheDrInfo<V>> drMap) throws GridException {
putAllDrAsync(drMap).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> putAllDrAsync(Map<? extends K, GridCacheDrInfo<V>> drMap) {
metrics.onReceiveCacheEntriesReceived(drMap.size());
return updateAllAsync0(null, null, drMap, null, false, false, null, 0, null);
}
/** {@inheritDoc} */
@Override public void transform(K key, GridClosure<V, V> transformer) throws GridException {
transformAsync(key, transformer).get();
}
/** {@inheritDoc} */
@Override public <R> R transformAndCompute(K key, GridClosure<V, GridBiTuple<V, R>> transformer)
throws GridException {
return (R)updateAllAsync0(null,
Collections.singletonMap(key, new GridCacheTransformComputeClosure<>(transformer)), null, null, true,
false, null, 0, null).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> transformAsync(K key, GridClosure<V, V> transformer,
@Nullable GridCacheEntryEx<K, V> entry, long ttl) {
return updateAllAsync0(null, Collections.singletonMap(key, transformer), null, null, false, false, entry, ttl,
null);
}
/** {@inheritDoc} */
@Override public void transformAll(@Nullable Map<? extends K, ? extends GridClosure<V, V>> m) throws GridException {
transformAllAsync(m).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> transformAllAsync(@Nullable Map<? extends K, ? extends GridClosure<V, V>> m) {
if (F.isEmpty(m))
return new GridFinishedFuture<Object>(ctx.kernalContext());
return updateAllAsync0(null, m, null, null, false, false, null, 0, null);
}
/** {@inheritDoc} */
@Override public V remove(K key, @Nullable GridCacheEntryEx<K, V> entry,
@Nullable GridPredicate<GridCacheEntry<K, V>>... filter) throws GridException {
return removeAsync(key, entry, filter).get();
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<V> removeAsync(K key, @Nullable GridCacheEntryEx<K, V> entry,
@Nullable GridPredicate<GridCacheEntry<K, V>>... filter) {
return removeAllAsync0(Collections.singletonList(key), null, entry, true, false, filter);
}
/** {@inheritDoc} */
@Override public void removeAll(Collection<? extends K> keys,
GridPredicate<GridCacheEntry<K, V>>... filter) throws GridException {
removeAllAsync(keys, filter).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> removeAllAsync(Collection<? extends K> keys,
GridPredicate<GridCacheEntry<K, V>>[] filter) {
return removeAllAsync0(keys, null, null, false, false, filter);
}
/** {@inheritDoc} */
@Override public boolean removex(K key, @Nullable GridCacheEntryEx<K, V> entry,
@Nullable GridPredicate<GridCacheEntry<K, V>>... filter) throws GridException {
return removexAsync(key, entry, filter).get();
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<Boolean> removexAsync(K key, @Nullable GridCacheEntryEx<K, V> entry,
@Nullable GridPredicate<GridCacheEntry<K, V>>... filter) {
return removeAllAsync0(Collections.singletonList(key), null, entry, false, false, filter);
}
/** {@inheritDoc} */
@Override public boolean remove(K key, V val) throws GridException {
return removeAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridFuture<Boolean> removeAsync(K key, V val) {
return removexAsync(key, ctx.equalsPeekArray(val));
}
/** {@inheritDoc} */
@Override public void removeAll(GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
removeAllAsync(filter).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> removeAllAsync(GridPredicate<GridCacheEntry<K, V>>[] filter) {
return removeAllAsync(keySet(filter), filter);
}
/** {@inheritDoc} */
@Override public void removeAllDr(Map<? extends K, GridCacheVersion> drMap) throws GridException {
removeAllDrAsync(drMap).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> removeAllDrAsync(Map<? extends K, GridCacheVersion> drMap) {
metrics.onReceiveCacheEntriesReceived(drMap.size());
return removeAllAsync0(null, drMap, null, false, false, null);
}
/**
* @return {@code True} if store enabled.
*/
private boolean storeEnabled() {
return ctx.isStoreEnabled() && ctx.config().getStore() != null;
}
/**
* @param op Operation closure.
* @return Future.
*/
@SuppressWarnings("unchecked")
protected <T> GridFuture<T> asyncOp(final CO<GridFuture<T>> op) {
GridFuture<T> fail = asyncOpAcquire();
if (fail != null)
return fail;
FutureHolder holder = lastFut.get();
holder.lock();
try {
GridFuture fut = holder.future();
if (fut != null && !fut.isDone()) {
GridFuture<T> f = new GridEmbeddedFuture<>(fut,
new C2<T, Exception, GridFuture<T>>() {
@Override public GridFuture<T> apply(T t, Exception e) {
return op.apply();
}
}, ctx.kernalContext());
saveFuture(holder, f);
return f;
}
GridFuture<T> f = op.apply();
saveFuture(holder, f);
return f;
}
finally {
holder.unlock();
}
}
/** {@inheritDoc} */
@Override protected GridFuture<Boolean> lockAllAsync(Collection<? extends K> keys,
long timeout,
@Nullable GridCacheTxLocalEx<K, V> tx,
boolean isInvalidate,
boolean isRead,
boolean retval,
@Nullable GridCacheTxIsolation isolation,
GridPredicate<GridCacheEntry<K, V>>[] filter) {
return new FinishedLockFuture(new UnsupportedOperationException("Locks are not supported for " +
"GridCacheAtomicityMode.ATOMIC mode (use GridCacheAtomicityMode.TRANSACTIONAL instead)"));
}
/**
* Entry point for all public API put/transform methods.
*
* @param map Put map. Either {@code map}, {@code transformMap} or {@code drMap} should be passed.
* @param transformMap Transform map. Either {@code map}, {@code transformMap} or {@code drMap} should be passed.
* @param drPutMap DR put map.
* @param drRmvMap DR remove map.
* @param retval Return value required flag.
* @param rawRetval Return {@code GridCacheReturn} instance.
* @param cached Cached cache entry for key. May be passed if and only if map size is {@code 1}.
* @param ttl Entry time-to-live.
* @param filter Cache entry filter for atomic updates.
* @return Completion future.
*/
private GridFuture updateAllAsync0(
@Nullable final Map<? extends K, ? extends V> map,
@Nullable final Map<? extends K, ? extends GridClosure<V, V>> transformMap,
@Nullable final Map<? extends K, GridCacheDrInfo<V>> drPutMap,
@Nullable final Map<? extends K, GridCacheVersion> drRmvMap,
final boolean retval,
final boolean rawRetval,
@Nullable GridCacheEntryEx<K, V> cached,
long ttl,
@Nullable final GridPredicate<GridCacheEntry<K, V>>[] filter
) {
ctx.checkSecurity(GridSecurityPermission.CACHE_PUT);
final GridNearAtomicUpdateFuture<K, V> updateFut = new GridNearAtomicUpdateFuture<>(
ctx,
this,
ctx.config().getWriteSynchronizationMode(),
transformMap != null ? TRANSFORM : UPDATE,
map != null ? map.keySet() : transformMap != null ? transformMap.keySet() : drPutMap != null ?
drPutMap.keySet() : drRmvMap.keySet(),
map != null ? map.values() : transformMap != null ? transformMap.values() : null,
drPutMap != null ? drPutMap.values() : null,
drRmvMap != null ? drRmvMap.values() : null,
retval,
rawRetval,
cached,
ttl,
filter);
return asyncOp(new CO<GridFuture<Object>>() {
@Override public GridFuture<Object> apply() {
updateFut.map();
return updateFut;
}
});
}
/**
* Entry point for all public API remove methods.
*
* @param keys Keys to remove.
* @param drMap DR map.
* @param cached Cached cache entry for key. May be passed if and only if keys size is {@code 1}.
* @param retval Return value required flag.
* @param rawRetval Return {@code GridCacheReturn} instance.
* @param filter Cache entry filter for atomic removes.
* @return Completion future.
*/
private GridFuture removeAllAsync0(
@Nullable final Collection<? extends K> keys,
@Nullable final Map<? extends K, GridCacheVersion> drMap,
@Nullable GridCacheEntryEx<K, V> cached,
final boolean retval,
boolean rawRetval,
@Nullable final GridPredicate<GridCacheEntry<K, V>>[] filter
) {
assert keys != null || drMap != null;
ctx.checkSecurity(GridSecurityPermission.CACHE_REMOVE);
final GridNearAtomicUpdateFuture<K, V> updateFut = new GridNearAtomicUpdateFuture<>(
ctx,
this,
ctx.config().getWriteSynchronizationMode(),
DELETE,
keys != null ? keys : drMap.keySet(),
null,
null,
keys != null ? null : drMap.values(),
retval,
rawRetval,
cached,
0,
filter);
return asyncOp(new CO<GridFuture<Object>>() {
@Override public GridFuture<Object> apply() {
updateFut.map();
return updateFut;
}
});
}
/**
* Entry point to all public API get methods.
*
* @param keys Keys to remove.
* @param reload Reload flag.
* @param forcePrimary Force primary flag.
* @param filter Filter.
* @return Get future.
*/
private GridFuture<Map<K, V>> getAllAsync0(@Nullable Collection<? extends K> keys, boolean reload,
boolean forcePrimary, @Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) {
ctx.checkSecurity(GridSecurityPermission.CACHE_READ);
if (F.isEmpty(keys))
return new GridFinishedFuture<>(ctx.kernalContext(), Collections.<K, V>emptyMap());
// Optimisation: try to resolve value locally and escape 'get future' creation.
if (!reload && !forcePrimary) {
Map<K, V> locVals = new HashMap<>(keys.size(), 1.0f);
GridCacheVersion obsoleteVer = null;
boolean success = true;
long topVer = ctx.affinity().affinityTopologyVersion();
// Optimistically expect that all keys are available locally (avoid creation of get future).
for (K key : keys) {
GridCacheEntryEx<K, V> entry = null;
while (true) {
try {
entry = ctx.isSwapOrOffheapEnabled() ? entryEx(key) : peekEx(key);
// If our DHT cache do has value, then we peek it.
if (entry != null) {
boolean isNew = entry.isNewLocked();
V v = entry.innerGet(null, /*swap*/true, /*read-through*/false, /*fail-fast*/true,
/*unmarshal*/true, /**update-metrics*/true, true, filter);
// Entry was not in memory or in swap, so we remove it from cache.
if (v == null) {
if (obsoleteVer == null)
obsoleteVer = context().versions().next();
if (isNew && entry.markObsoleteIfEmpty(obsoleteVer))
removeIfObsolete(key);
success = false;
}
else
locVals.put(key, v);
}
else
success = false;
break; // While.
}
catch (GridCacheEntryRemovedException ignored) {
// No-op, retry.
}
catch (GridCacheFilterFailedException ignored) {
// No-op, skip the key.
break;
}
catch (GridDhtInvalidPartitionException ignored) {
success = false;
break; // While.
}
catch (GridException e) {
return new GridFinishedFuture<>(ctx.kernalContext(), e);
}
finally {
if (entry != null)
ctx.evicts().touch(entry, topVer);
}
}
if (!success)
break;
}
if (success)
return ctx.wrapCloneMap(new GridFinishedFuture<>(ctx.kernalContext(), locVals));
}
// Either reload or not all values are available locally.
GridPartitionedGetFuture<K, V> fut = new GridPartitionedGetFuture<>(ctx, keys, reload, forcePrimary, null,
filter);
fut.init();
return ctx.wrapCloneMap(fut);
}
/**
* Executes local update.
*
* @param nodeId Node ID.
* @param req Update request.
* @param cached Cached entry if updating single local entry.
* @param completionCb Completion callback.
*/
public void updateAllAsyncInternal(
final UUID nodeId,
final GridNearAtomicUpdateRequest<K, V> req,
@Nullable final GridCacheEntryEx<K, V> cached,
final CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb
) {
GridFuture<Object> forceFut = preldr.request(req.keys(), req.topologyVersion());
if (forceFut.isDone())
updateAllAsyncInternal0(nodeId, req, cached, completionCb);
else {
forceFut.listenAsync(new CI1<GridFuture<Object>>() {
@Override public void apply(GridFuture<Object> t) {
updateAllAsyncInternal0(nodeId, req, cached, completionCb);
}
});
}
}
/**
* Executes local update after preloader fetched values.
*
* @param nodeId Node ID.
* @param req Update request.
* @param cached Cached entry if updating single local entry.
* @param completionCb Completion callback.
*/
public void updateAllAsyncInternal0(
UUID nodeId,
GridNearAtomicUpdateRequest<K, V> req,
@Nullable GridCacheEntryEx<K, V> cached,
CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb
) {
GridNearAtomicUpdateResponse<K, V> res = new GridNearAtomicUpdateResponse<>(nodeId, req.futureVersion());
List<K> keys = req.keys();
assert !req.returnValue() || keys.size() == 1;
GridDhtAtomicUpdateFuture<K, V> dhtFut = null;
boolean remap = false;
try {
// If batch store update is enabled, we need to lock all entries.
// First, need to acquire locks on cache entries, then check filter.
List<GridDhtCacheEntry<K, V>> locked = lockEntries(keys, req.topologyVersion());
Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted = null;
try {
topology().readLock();
try {
// Do not check topology version for CLOCK versioning since
// partition exchange will wait for near update future.
if (topology().topologyVersion() == req.topologyVersion() ||
ctx.config().getAtomicWriteOrderMode() == CLOCK) {
GridNode node = ctx.discovery().node(nodeId);
if (node == null) {
U.warn(log, "Node originated update request left grid: " + nodeId);
return;
}
checkClearForceTransformBackups(req);
boolean hasNear = U.hasNearCache(node, name());
GridCacheVersion ver = req.updateVersion();
if (ver == null) {
// Assign next version for update inside entries lock.
ver = ctx.versions().next(req.topologyVersion());
if (hasNear)
res.nearVersion(ver);
}
assert ver != null : "Got null version for update request: " + req;
if (log.isDebugEnabled())
log.debug("Using cache version for update request on primary node [ver=" + ver +
", req=" + req + ']');
dhtFut = createDhtFuture(ver, req, res, completionCb, false);
GridCacheReturn<Object> retVal = null;
boolean replicate = ctx.isDrEnabled();
if (storeEnabled() && keys.size() > 1 && cacheCfg.getDrReceiverConfiguration() == null) {
// This method can only be used when there are no replicated entries in the batch.
UpdateBatchResult<K, V> updRes = updateWithBatch(nodeId, hasNear, req, res, locked, ver,
dhtFut, completionCb, replicate);
deleted = updRes.deleted();
dhtFut = updRes.dhtFuture();
}
else {
UpdateSingleResult<K, V> updRes = updateSingle(nodeId, hasNear, req, res, locked, ver,
dhtFut, completionCb, replicate);
retVal = updRes.returnValue();
deleted = updRes.deleted();
dhtFut = updRes.dhtFuture();
}
if (retVal == null)
retVal = new GridCacheReturn<>(null, true);
res.returnValue(retVal);
}
else
// Should remap all keys.
remap = true;
}
finally {
topology().readUnlock();
}
}
catch (GridCacheEntryRemovedException e) {
assert false : "Entry should not become obsolete while holding lock.";
e.printStackTrace();
}
finally {
unlockEntries(locked, req.topologyVersion());
// Enqueue if necessary after locks release.
if (deleted != null) {
assert !deleted.isEmpty();
assert ctx.deferredDelete();
for (GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion> e : deleted)
ctx.onDeferredDelete(e.get1(), e.get2());
}
}
}
catch (GridDhtInvalidPartitionException ignore) {
assert ctx.config().getAtomicWriteOrderMode() == PRIMARY;
if (log.isDebugEnabled())
log.debug("Caught invalid partition exception for cache entry (will remap update request): " + req);
remap = true;
}
if (remap) {
assert dhtFut == null;
res.remapKeys(req.keys());
completionCb.apply(req, res);
}
else {
// If there are backups, map backup update future.
if (dhtFut != null)
dhtFut.map();
// Otherwise, complete the call.
else
completionCb.apply(req, res);
}
}
/**
* Updates locked entries using batched write-through.
*
* @param nodeId Sender node ID.
* @param hasNear {@code True} if originating node has near cache.
* @param req Update request.
* @param res Update response.
* @param locked Locked entries.
* @param ver Assigned version.
* @param dhtFut Optional DHT future.
* @param completionCb Completion callback to invoke when DHT future is completed.
* @param replicate Whether replication is enabled.
* @return Deleted entries.
* @throws GridCacheEntryRemovedException Should not be thrown.
*/
@SuppressWarnings("unchecked")
private UpdateBatchResult<K, V> updateWithBatch(
UUID nodeId,
boolean hasNear,
GridNearAtomicUpdateRequest<K, V> req,
GridNearAtomicUpdateResponse<K, V> res,
List<GridDhtCacheEntry<K, V>> locked,
GridCacheVersion ver,
@Nullable GridDhtAtomicUpdateFuture<K, V> dhtFut,
CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb,
boolean replicate
) throws GridCacheEntryRemovedException {
// Cannot update in batches during DR due to possible conflicts.
assert !req.returnValue(); // Should not request return values for putAll.
int size = req.keys().size();
Map<K, V> putMap = null;
Map<K, GridClosure<V, V>> transformMap = null;
Collection<K> rmvKeys = null;
UpdateBatchResult<K, V> updRes = new UpdateBatchResult<>();
List<GridDhtCacheEntry<K, V>> filtered = new ArrayList<>(size);
GridCacheOperation op = req.operation();
int firstEntryIdx = 0;
boolean intercept = ctx.config().getInterceptor() != null;
for (int i = 0; i < locked.size(); i++) {
GridDhtCacheEntry<K, V> entry = locked.get(i);
if (entry == null)
continue;
try {
if (!checkFilter(entry, req, res)) {
if (log.isDebugEnabled())
log.debug("Entry did not pass the filter (will skip write) [entry=" + entry +
", filter=" + Arrays.toString(req.filter()) + ", res=" + res + ']');
if (hasNear)
res.addSkippedIndex(i);
firstEntryIdx++;
continue;
}
if (op == TRANSFORM) {
V old = entry.innerGet(
null,
/*read swap*/true,
/*read through*/true,
/*fail fast*/false,
/*unmarshal*/true,
/*metrics*/true,
/*event*/true,
CU.<K, V>empty());
GridClosure<V, V> transform = req.transformClosure(i);
if (transformMap == null)
transformMap = new HashMap<>();
transformMap.put(entry.key(), transform);
V updated = transform.apply(old);
if (updated == null) {
if (intercept) {
GridBiTuple<Boolean, ?> interceptorRes = ctx.config().getInterceptor().onBeforeRemove(
entry.key(), old);
if (ctx.cancelRemove(interceptorRes))
continue;
}
// Update previous batch.
if (putMap != null) {
dhtFut = updatePartialBatch(
hasNear,
firstEntryIdx,
filtered,
ver,
nodeId,
putMap,
null,
transformMap,
dhtFut,
completionCb,
req,
res,
replicate,
updRes);
firstEntryIdx = i + 1;
putMap = null;
transformMap = null;
filtered = new ArrayList<>();
}
// Start collecting new batch.
if (rmvKeys == null)
rmvKeys = new ArrayList<>(size);
rmvKeys.add(entry.key());
}
else {
if (intercept) {
updated = (V)ctx.config().getInterceptor().onBeforePut(entry.key(), old, updated);
if (updated == null)
continue;
}
// Update previous batch.
if (rmvKeys != null) {
dhtFut = updatePartialBatch(
hasNear,
firstEntryIdx,
filtered,
ver,
nodeId,
null,
rmvKeys,
transformMap,
dhtFut,
completionCb,
req,
res,
replicate,
updRes);
firstEntryIdx = i + 1;
rmvKeys = null;
transformMap = null;
filtered = new ArrayList<>();
}
if (putMap == null)
putMap = new LinkedHashMap<>(size, 1.0f);
putMap.put(entry.key(), updated);
}
}
else if (op == UPDATE) {
V updated = req.value(i);
if (intercept) {
V old = entry.innerGet(
null,
/*read swap*/true,
/*read through*/true,
/*fail fast*/false,
/*unmarshal*/true,
/*metrics*/true,
/*event*/true,
CU.<K, V>empty());
updated = (V)ctx.config().getInterceptor().onBeforePut(entry.key(), old, updated);
if (updated == null)
continue;
}
assert updated != null;
if (putMap == null)
putMap = new LinkedHashMap<>(size, 1.0f);
putMap.put(entry.key(), updated);
}
else {
assert op == DELETE;
if (intercept) {
V old = entry.innerGet(
null,
/*read swap*/true,
/*read through*/true,
/*fail fast*/false,
/*unmarshal*/true,
/*metrics*/true,
/*event*/true,
CU.<K, V>empty());
GridBiTuple<Boolean, ?> interceptorRes = ctx.config().getInterceptor().onBeforeRemove(
entry.key(), old);
if (ctx.cancelRemove(interceptorRes))
continue;
}
if (rmvKeys == null)
rmvKeys = new ArrayList<>(size);
rmvKeys.add(entry.key());
}
filtered.add(entry);
}
catch (GridException e) {
res.addFailedKey(entry.key(), e);
}
catch (GridCacheFilterFailedException ignore) {
assert false : "Filter should never fail with failFast=false and empty filter.";
}
}
// Store final batch.
if (putMap != null || rmvKeys != null) {
dhtFut = updatePartialBatch(
hasNear,
firstEntryIdx,
filtered,
ver,
nodeId,
putMap,
rmvKeys,
transformMap,
dhtFut,
completionCb,
req,
res,
replicate,
updRes);
}
else
assert filtered.isEmpty();
updRes.dhtFuture(dhtFut);
return updRes;
}
/**
* Updates locked entries one-by-one.
*
* @param nodeId Originating node ID.
* @param hasNear {@code True} if originating node has near cache.
* @param req Update request.
* @param res Update response.
* @param locked Locked entries.
* @param ver Assigned update version.
* @param dhtFut Optional DHT future.
* @param completionCb Completion callback to invoke when DHT future is completed.
* @param replicate Whether DR is enabled for that cache.
* @return Return value.
* @throws GridCacheEntryRemovedException Should be never thrown.
*/
private UpdateSingleResult<K, V> updateSingle(
UUID nodeId,
boolean hasNear,
GridNearAtomicUpdateRequest<K, V> req,
GridNearAtomicUpdateResponse<K, V> res,
List<GridDhtCacheEntry<K, V>> locked,
GridCacheVersion ver,
@Nullable GridDhtAtomicUpdateFuture<K, V> dhtFut,
CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb,
boolean replicate
) throws GridCacheEntryRemovedException {
GridCacheReturn<Object> retVal = null;
Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted = null;
List<K> keys = req.keys();
long topVer = req.topologyVersion();
boolean checkReaders = hasNear || ctx.discovery().hasNearCache(name(), topVer);
boolean readersOnly = false;
boolean intercept = ctx.config().getInterceptor() != null;
// Avoid iterator creation.
for (int i = 0; i < keys.size(); i++) {
K k = keys.get(i);
GridCacheOperation op = req.operation();
// We are holding java-level locks on entries at this point.
// No GridCacheEntryRemovedException can be thrown.
try {
GridDhtCacheEntry<K, V> entry = locked.get(i);
if (entry == null)
continue;
GridCacheVersion newDrVer = req.drVersion(i);
long newDrTtl = req.drTtl(i);
long newDrExpireTime = req.drExpireTime(i);
assert !(newDrVer instanceof GridCacheVersionEx) : newDrVer; // Plain version is expected here.
if (newDrVer == null)
newDrVer = ver;
boolean primary = !req.fastMap() || ctx.affinity().primary(ctx.localNode(), entry.key(),
req.topologyVersion());
byte[] newValBytes = req.valueBytes(i);
Object writeVal = req.writeValue(i);
Collection<UUID> readers = null;
Collection<UUID> filteredReaders = null;
if (checkReaders) {
readers = entry.readers();
filteredReaders = F.view(entry.readers(), F.notEqualTo(nodeId));
}
GridCacheUpdateAtomicResult<K, V> updRes = entry.innerUpdate(
ver,
nodeId,
locNodeId,
op,
writeVal,
newValBytes,
primary && storeEnabled(),
req.returnValue(),
req.ttl(),
true,
true,
primary,
ctx.config().getAtomicWriteOrderMode() == CLOCK, // Check version in CLOCK mode on primary node.
req.filter(),
replicate ? primary ? DR_PRIMARY : DR_BACKUP : DR_NONE,
newDrTtl,
newDrExpireTime,
newDrVer,
true,
intercept);
if (dhtFut == null && !F.isEmpty(filteredReaders)) {
dhtFut = createDhtFuture(ver, req, res, completionCb, true);
readersOnly = true;
}
if (dhtFut != null) {
if (updRes.sendToDht()) { // Send to backups even in case of remove-remove scenarios.
GridDrReceiverConflictContextImpl ctx = updRes.drConflictContext();
long ttl = updRes.newTtl();
long drExpireTime = updRes.drExpireTime();
if (ctx == null)
newDrVer = null;
else if (ctx.isMerge()) {
newDrVer = null; // DR version is discarded in case of merge.
newValBytes = null; // Value has been changed.
}
GridClosure<V, V> transformC = null;
if (req.forceTransformBackups() && op == TRANSFORM)
transformC = (GridClosure<V, V>)writeVal;
if (!readersOnly)
dhtFut.addWriteEntry(entry, updRes.newValue(), newValBytes, transformC,
drExpireTime >= 0L ? ttl : -1L, drExpireTime, newDrVer, drExpireTime < 0L ? ttl : 0L);
if (!F.isEmpty(filteredReaders))
dhtFut.addNearWriteEntries(filteredReaders, entry, updRes.newValue(), newValBytes,
transformC, drExpireTime < 0L ? ttl : 0L);
}
else {
if (log.isDebugEnabled())
log.debug("Entry did not pass the filter or conflict resolution (will skip write) " +
"[entry=" + entry + ", filter=" + Arrays.toString(req.filter()) + ']');
}
}
if (hasNear) {
if (primary && updRes.sendToDht()) {
if (!U.nodeIds(context().affinity().nodes(entry.partition(), topVer)).contains(nodeId)) {
GridDrReceiverConflictContextImpl ctx = updRes.drConflictContext();
res.nearTtl(updRes.newTtl());
if (ctx != null && ctx.isMerge())
newValBytes = null;
// If put the same value as in request then do not need to send it back.
if (op == TRANSFORM || writeVal != updRes.newValue())
res.addNearValue(i, updRes.newValue(), newValBytes);
if (updRes.newValue() != null || newValBytes != null) {
GridFuture<Boolean> f = entry.addReader(nodeId, req.messageId(), topVer);
assert f == null : f;
}
}
else if (F.contains(readers, nodeId)) // Reader became primary or backup.
entry.removeReader(nodeId, req.messageId());
else
res.addSkippedIndex(i);
}
else
res.addSkippedIndex(i);
}
if (updRes.removeVersion() != null) {
if (deleted == null)
deleted = new ArrayList<>(keys.size());
deleted.add(F.t(entry, updRes.removeVersion()));
}
// Create only once.
if (retVal == null) {
Object ret = updRes.oldValue();
if (op == TRANSFORM && writeVal instanceof GridCacheTransformComputeClosure) {
assert req.returnValue();
ret = ((GridCacheTransformComputeClosure<V, ?>)writeVal).returnValue();
}
retVal = new GridCacheReturn<>(req.returnValue() ? ret : null, updRes.success());
}
}
catch (GridException e) {
res.addFailedKey(k, e);
}
}
return new UpdateSingleResult<>(retVal, deleted, dhtFut);
}
/**
* @param hasNear {@code True} if originating node has near cache.
* @param firstEntryIdx Index of the first entry in the request keys collection.
* @param entries Entries to update.
* @param ver Version to set.
* @param nodeId Originating node ID.
* @param putMap Values to put.
* @param rmvKeys Keys to remove.
* @param transformMap Transform closures.
* @param dhtFut DHT update future if has backups.
* @param completionCb Completion callback to invoke when DHT future is completed.
* @param req Request.
* @param res Response.
* @param replicate Whether replication is enabled.
* @param batchRes Batch update result.
* @return Deleted entries.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
@Nullable private GridDhtAtomicUpdateFuture<K, V> updatePartialBatch(
boolean hasNear,
int firstEntryIdx,
List<GridDhtCacheEntry<K, V>> entries,
final GridCacheVersion ver,
UUID nodeId,
@Nullable Map<K, V> putMap,
@Nullable Collection<K> rmvKeys,
@Nullable Map<K, GridClosure<V, V>> transformMap,
@Nullable GridDhtAtomicUpdateFuture<K, V> dhtFut,
CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb,
final GridNearAtomicUpdateRequest<K, V> req,
final GridNearAtomicUpdateResponse<K, V> res,
boolean replicate,
UpdateBatchResult<K, V> batchRes
) {
assert putMap == null ^ rmvKeys == null;
assert req.drVersions() == null : "updatePartialBatch cannot be called when there are DR entries in the batch.";
long topVer = req.topologyVersion();
boolean checkReaders = hasNear || ctx.discovery().hasNearCache(name(), topVer);
try {
GridCacheOperation op;
if (putMap != null) {
// If fast mapping, filter primary keys for write to store.
Map<K, V> storeMap = req.fastMap() ?
F.view(putMap, new P1<K>() {
@Override public boolean apply(K key) {
return ctx.affinity().primary(ctx.localNode(), key, req.topologyVersion());
}
}) :
putMap;
ctx.store().putAllToStore(null, F.viewReadOnly(storeMap, new C1<V, GridBiTuple<V, GridCacheVersion>>() {
@Override public GridBiTuple<V, GridCacheVersion> apply(V v) {
return F.t(v, ver);
}
}));
op = UPDATE;
}
else {
// If fast mapping, filter primary keys for write to store.
Collection<K> storeKeys = req.fastMap() ?
F.view(rmvKeys, new P1<K>() {
@Override public boolean apply(K key) {
return ctx.affinity().primary(ctx.localNode(), key, req.topologyVersion());
}
}) :
rmvKeys;
ctx.store().removeAllFromStore(null, storeKeys);
op = DELETE;
}
boolean intercept = ctx.config().getInterceptor() != null;
// Avoid iterator creation.
for (int i = 0; i < entries.size(); i++) {
GridDhtCacheEntry<K, V> entry = entries.get(i);
assert Thread.holdsLock(entry);
if (entry.obsolete()) {
assert req.operation() == DELETE : "Entry can become obsolete only after remove: " + entry;
continue;
}
try {
// We are holding java-level locks on entries at this point.
V writeVal = op == UPDATE ? putMap.get(entry.key()) : null;
assert writeVal != null || op == DELETE : "null write value found.";
boolean primary = !req.fastMap() || ctx.affinity().primary(ctx.localNode(), entry.key(),
req.topologyVersion());
Collection<UUID> readers = null;
Collection<UUID> filteredReaders = null;
if (checkReaders) {
readers = entry.readers();
filteredReaders = F.view(entry.readers(), F.notEqualTo(nodeId));
}
GridCacheUpdateAtomicResult<K, V> updRes = entry.innerUpdate(
ver,
nodeId,
locNodeId,
op,
writeVal,
null,
false,
false,
req.ttl(),
true,
true,
primary,
ctx.config().getAtomicWriteOrderMode() == CLOCK, // Check version in CLOCK mode on primary node.
req.filter(),
replicate ? primary ? DR_PRIMARY : DR_BACKUP : DR_NONE,
-1L,
-1L,
null,
false,
false);
if (intercept) {
if (op == UPDATE)
ctx.config().getInterceptor().onAfterPut(entry.key(), updRes.newValue());
else {
assert op == DELETE : op;
// Old value should be already loaded for 'GridCacheInterceptor.onBeforeRemove'.
ctx.config().<K, V>getInterceptor().onAfterRemove(entry.key(), updRes.oldValue());
}
}
batchRes.addDeleted(entry, updRes, entries);
if (dhtFut == null && !F.isEmpty(filteredReaders)) {
dhtFut = createDhtFuture(ver, req, res, completionCb, true);
batchRes.readersOnly(true);
}
if (dhtFut != null) {
GridCacheValueBytes valBytesTuple = op == DELETE ? GridCacheValueBytes.nil():
entry.valueBytes();
byte[] valBytes = valBytesTuple.getIfMarshaled();
GridClosure<V, V> transformC = transformMap == null ? null : transformMap.get(entry.key());
if (!batchRes.readersOnly())
dhtFut.addWriteEntry(entry, writeVal, valBytes, transformC, -1, -1, null, req.ttl());
if (!F.isEmpty(filteredReaders))
dhtFut.addNearWriteEntries(filteredReaders, entry, writeVal, valBytes, transformC,
req.ttl());
}
if (hasNear) {
if (primary) {
if (!U.nodeIds(context().affinity().nodes(entry.partition(), topVer)).contains(nodeId)) {
if (req.operation() == TRANSFORM) {
int idx = firstEntryIdx + i;
GridCacheValueBytes valBytesTuple = entry.valueBytes();
byte[] valBytes = valBytesTuple.getIfMarshaled();
res.addNearValue(idx, writeVal, valBytes);
}
res.nearTtl(req.ttl());
if (writeVal != null || !entry.valueBytes().isNull()) {
GridFuture<Boolean> f = entry.addReader(nodeId, req.messageId(), topVer);
assert f == null : f;
}
} else if (readers.contains(nodeId)) // Reader became primary or backup.
entry.removeReader(nodeId, req.messageId());
else
res.addSkippedIndex(firstEntryIdx + i);
}
else
res.addSkippedIndex(firstEntryIdx + i);
}
}
catch (GridCacheEntryRemovedException e) {
assert false : "Entry cannot become obsolete while holding lock.";
e.printStackTrace();
}
}
}
catch (GridException e) {
res.addFailedKeys(putMap != null ? putMap.keySet() : rmvKeys, e);
}
return dhtFut;
}
/**
* Acquires java-level locks on cache entries. Returns collection of locked entries.
*
* @param keys Keys to lock.
* @param topVer Topology version to lock on.
* @return Collection of locked entries.
* @throws GridDhtInvalidPartitionException If entry does not belong to local node. If exception is thrown,
* locks are released.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
private List<GridDhtCacheEntry<K, V>> lockEntries(List<K> keys, long topVer)
throws GridDhtInvalidPartitionException {
if (keys.size() == 1) {
K key = keys.get(0);
while (true) {
try {
GridDhtCacheEntry<K, V> entry = entryExx(key, topVer);
UNSAFE.monitorEnter(entry);
if (entry.obsolete())
UNSAFE.monitorExit(entry);
else
return Collections.singletonList(entry);
}
catch (GridDhtInvalidPartitionException e) {
// Ignore invalid partition exception in CLOCK ordering mode.
if (ctx.config().getAtomicWriteOrderMode() == CLOCK)
return Collections.singletonList(null);
else
throw e;
}
}
}
else {
List<GridDhtCacheEntry<K, V>> locked = new ArrayList<>(keys.size());
while (true) {
for (K key : keys) {
try {
GridDhtCacheEntry<K, V> entry = entryExx(key, topVer);
locked.add(entry);
}
catch (GridDhtInvalidPartitionException e) {
// Ignore invalid partition exception in CLOCK ordering mode.
if (ctx.config().getAtomicWriteOrderMode() == CLOCK)
locked.add(null);
else
throw e;
}
}
boolean retry = false;
for (int i = 0; i < locked.size(); i++) {
GridCacheMapEntry<K, V> entry = locked.get(i);
if (entry == null)
continue;
UNSAFE.monitorEnter(entry);
if (entry.obsolete()) {
// Unlock all locked.
for (int j = 0; j <= i; j++) {
if (locked.get(j) != null)
UNSAFE.monitorExit(locked.get(j));
}
// Clear entries.
locked.clear();
// Retry.
retry = true;
break;
}
}
if (!retry)
return locked;
}
}
}
/**
* Releases java-level locks on cache entries.
*
* @param locked Locked entries.
* @param topVer Topology version.
*/
private void unlockEntries(Collection<GridDhtCacheEntry<K, V>> locked, long topVer) {
// Process deleted entries before locks release.
assert ctx.deferredDelete();
// Entries to skip eviction manager notification for.
// Enqueue entries while holding locks.
Collection<K> skip = null;
for (GridCacheMapEntry<K, V> entry : locked) {
if (entry != null && entry.deleted()) {
if (skip == null)
skip = new HashSet<>(locked.size(), 1.0f);
skip.add(entry.key());
}
}
// Release locks.
for (GridCacheMapEntry<K, V> entry : locked) {
if (entry != null)
UNSAFE.monitorExit(entry);
}
// Try evict partitions.
for (GridDhtCacheEntry<K, V> entry : locked) {
if (entry != null)
entry.onUnlock();
}
if (skip != null && skip.size() == locked.size())
// Optimization.
return;
// Must touch all entries since update may have deleted entries.
// Eviction manager will remove empty entries.
for (GridCacheMapEntry<K, V> entry : locked) {
if (entry != null && (skip == null || !skip.contains(entry.key())))
ctx.evicts().touch(entry, topVer);
}
}
/**
* @param entry Entry to check.
* @param req Update request.
* @param res Update response. If filter evaluation failed, key will be added to failed keys and method
* will return false.
* @return {@code True} if filter evaluation succeeded.
*/
private boolean checkFilter(GridCacheEntryEx<K, V> entry, GridNearAtomicUpdateRequest<K, V> req,
GridNearAtomicUpdateResponse<K, V> res) {
try {
return ctx.isAll(entry.wrapFilterLocked(), req.filter());
}
catch (GridException e) {
res.addFailedKey(entry.key(), e);
return false;
}
}
/**
* @param req Request to remap.
*/
private void remapToNewPrimary(GridNearAtomicUpdateRequest<K, V> req) {
if (log.isDebugEnabled())
log.debug("Remapping near update request locally: " + req);
Collection<?> vals;
Collection<GridCacheDrInfo<V>> drPutVals;
Collection<GridCacheVersion> drRmvVals;
if (req.drVersions() == null) {
vals = req.values();
drPutVals = null;
drRmvVals = null;
}
else if (req.operation() == UPDATE) {
int size = req.keys().size();
drPutVals = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
Long ttl = req.drTtl(i);
if (ttl == null)
drPutVals.add(new GridCacheDrInfo<>(req.value(i), req.drVersion(i)));
else
drPutVals.add(new GridCacheDrExpirationInfo<>(req.value(i), req.drVersion(i), ttl,
req.drExpireTime(i)));
}
vals = null;
drRmvVals = null;
}
else {
assert req.operation() == DELETE;
drRmvVals = req.drVersions();
vals = null;
drPutVals = null;
}
final GridNearAtomicUpdateFuture<K, V> updateFut = new GridNearAtomicUpdateFuture<>(
ctx,
this,
ctx.config().getWriteSynchronizationMode(),
req.operation(),
req.keys(),
vals,
drPutVals,
drRmvVals,
req.returnValue(),
false,
null,
req.ttl(),
req.filter());
updateFut.map();
}
/**
* Creates backup update future if necessary.
*
* @param writeVer Write version.
* @param updateReq Update request.
* @param updateRes Update response.
* @param completionCb Completion callback to invoke when future is completed.
* @param force If {@code true} then creates future without optimizations checks.
* @return Backup update future or {@code null} if there are no backups.
*/
@Nullable private GridDhtAtomicUpdateFuture<K, V> createDhtFuture(
GridCacheVersion writeVer,
GridNearAtomicUpdateRequest<K, V> updateReq,
GridNearAtomicUpdateResponse<K, V> updateRes,
CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb,
boolean force
) {
if (!force) {
if (updateReq.fastMap())
return null;
long topVer = updateReq.topologyVersion();
Collection<GridNode> nodes = ctx.kernalContext().discovery().cacheAffinityNodes(name(), topVer);
// We are on primary node for some key.
assert !nodes.isEmpty();
if (nodes.size() == 1) {
if (log.isDebugEnabled())
log.debug("Partitioned cache topology has only one node, will not create DHT atomic update future " +
"[topVer=" + topVer + ", updateReq=" + updateReq + ']');
return null;
}
}
GridDhtAtomicUpdateFuture<K, V> fut = new GridDhtAtomicUpdateFuture<>(ctx, completionCb, writeVer, updateReq,
updateRes);
ctx.mvcc().addAtomicFuture(fut.version(), fut);
return fut;
}
/**
* @param nodeId Sender node ID.
* @param res Near get response.
*/
private void processNearGetResponse(UUID nodeId, GridNearGetResponse<K, V> res) {
if (log.isDebugEnabled())
log.debug("Processing near get response [nodeId=" + nodeId + ", res=" + res + ']');
GridPartitionedGetFuture<K, V> fut = (GridPartitionedGetFuture<K, V>)ctx.mvcc().<Map<K, V>>future(
res.version(), res.futureId());
if (fut == null) {
if (log.isDebugEnabled())
log.debug("Failed to find future for get response [sender=" + nodeId + ", res=" + res + ']');
return;
}
fut.onResult(nodeId, res);
}
/**
* @param nodeId Sender node ID.
* @param req Near atomic update request.
*/
private void processNearAtomicUpdateRequest(UUID nodeId, GridNearAtomicUpdateRequest<K, V> req) {
if (log.isDebugEnabled())
log.debug("Processing near atomic update request [nodeId=" + nodeId + ", req=" + req + ']');
req.nodeId(ctx.localNodeId());
updateAllAsyncInternal(nodeId, req, null, updateReplyClos);
}
/**
* @param nodeId Sender node ID.
* @param res Near atomic update response.
*/
@SuppressWarnings("unchecked")
private void processNearAtomicUpdateResponse(UUID nodeId, GridNearAtomicUpdateResponse<K, V> res) {
if (log.isDebugEnabled())
log.debug("Processing near atomic update response [nodeId=" + nodeId + ", res=" + res + ']');
res.nodeId(ctx.localNodeId());
GridNearAtomicUpdateFuture<K, V> fut = (GridNearAtomicUpdateFuture)ctx.mvcc().atomicFuture(res.futureVersion());
if (fut != null)
fut.onResult(nodeId, res);
else
U.warn(log, "Failed to find near update future for update response (will ignore) " +
"[nodeId=" + nodeId + ", res=" + res + ']');
}
/**
* @param nodeId Sender node ID.
* @param req Dht atomic update request.
*/
private void processDhtAtomicUpdateRequest(UUID nodeId, GridDhtAtomicUpdateRequest<K, V> req) {
if (log.isDebugEnabled())
log.debug("Processing dht atomic update request [nodeId=" + nodeId + ", req=" + req + ']');
GridCacheVersion ver = req.writeVersion();
// Always send update reply.
GridDhtAtomicUpdateResponse<K, V> res = new GridDhtAtomicUpdateResponse<>(req.futureVersion());
Boolean replicate = ctx.isDrEnabled();
boolean intercept = req.forceTransformBackups() && ctx.config().getInterceptor() != null;
for (int i = 0; i < req.size(); i++) {
K key = req.key(i);
try {
while (true) {
GridDhtCacheEntry<K, V> entry = null;
try {
entry = entryExx(key);
V val = req.value(i);
byte[] valBytes = req.valueBytes(i);
GridClosure<V, V> transform = req.transformClosure(i);
GridCacheOperation op = transform != null ? TRANSFORM :
(val != null || valBytes != null) ?
UPDATE :
DELETE;
GridCacheUpdateAtomicResult<K, V> updRes = entry.innerUpdate(
ver,
nodeId,
nodeId,
op,
op == TRANSFORM ? transform : val,
valBytes,
/*write-through*/false,
/*retval*/false,
req.ttl(),
/*event*/true,
/*metrics*/true,
/*primary*/false,
/*check version*/!req.forceTransformBackups(),
CU.<K, V>empty(),
replicate ? DR_BACKUP : DR_NONE,
req.drTtl(i),
req.drExpireTime(i),
req.drVersion(i),
false,
intercept);
if (updRes.removeVersion() != null)
ctx.onDeferredDelete(entry, updRes.removeVersion());
entry.onUnlock();
break; // While.
}
catch (GridCacheEntryRemovedException ignored) {
if (log.isDebugEnabled())
log.debug("Got removed entry while updating backup value (will retry): " + key);
entry = null;
}
finally {
if (entry != null)
ctx.evicts().touch(entry, req.topologyVersion());
}
}
}
catch (GridDhtInvalidPartitionException ignored) {
// Ignore.
}
catch (GridException e) {
res.addFailedKey(key, new GridException("Failed to update key on backup node: " + key, e));
}
}
if (isNearEnabled(cacheCfg))
((GridNearAtomicCache<K, V>)near()).processDhtAtomicUpdateRequest(nodeId, req, res);
try {
if (res.failedKeys() != null || res.nearEvicted() != null || req.writeSynchronizationMode() == FULL_SYNC)
ctx.io().send(nodeId, res);
else {
// No failed keys and sync mode is not FULL_SYNC, thus sending deferred response.
sendDeferredUpdateResponse(nodeId, req.futureVersion());
}
}
catch (GridTopologyException ignored) {
U.warn(log, "Failed to send DHT atomic update response to node because it left grid: " +
req.nodeId());
}
catch (GridException e) {
U.error(log, "Failed to send DHT atomic update response (did node leave grid?) [nodeId=" + nodeId +
", req=" + req + ']', e);
}
}
/**
* Checks if entries being transformed are empty. Clears forceTransformBackup flag enforcing
* sending transformed value to backups if at least one empty entry is found.
*
* @param req Near atomic update request.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
private void checkClearForceTransformBackups(GridNearAtomicUpdateRequest<K, V> req) {
if (ctx.isStoreEnabled() && req.operation() == TRANSFORM) {
List<K> keys = req.keys();
for (int i = 0; i < keys.size(); i++) {
GridDhtCacheEntry<K, V> entry = entryExx(keys.get(i), req.topologyVersion());
if (!entry.hasValue()) {
req.forceTransformBackups(false);
return;
}
}
}
}
/**
* @param nodeId Node ID to send message to.
* @param ver Version to ack.
*/
private void sendDeferredUpdateResponse(UUID nodeId, GridCacheVersion ver) {
while (true) {
DeferredResponseBuffer buf = pendingResponses.get(nodeId);
if (buf == null) {
buf = new DeferredResponseBuffer(nodeId);
DeferredResponseBuffer old = pendingResponses.putIfAbsent(nodeId, buf);
if (old == null) {
// We have successfully added buffer to map.
ctx.time().addTimeoutObject(buf);
}
else
buf = old;
}
if (!buf.addResponse(ver))
// Some thread is sending filled up buffer, we can remove it.
pendingResponses.remove(nodeId, buf);
else
break;
}
}
/**
* @param nodeId Sender node ID.
* @param res Dht atomic update response.
*/
private void processDhtAtomicUpdateResponse(UUID nodeId, GridDhtAtomicUpdateResponse<K, V> res) {
if (log.isDebugEnabled())
log.debug("Processing dht atomic update response [nodeId=" + nodeId + ", res=" + res + ']');
GridDhtAtomicUpdateFuture<K, V> updateFut = (GridDhtAtomicUpdateFuture<K, V>)ctx.mvcc().
atomicFuture(res.futureVersion());
if (updateFut != null)
updateFut.onResult(nodeId, res);
else
U.warn(log, "Failed to find DHT update future for update response [nodeId=" + nodeId +
", res=" + res + ']');
}
/**
* @param nodeId Sender node ID.
* @param res Deferred atomic update response.
*/
private void processDhtAtomicDeferredUpdateResponse(UUID nodeId, GridDhtAtomicDeferredUpdateResponse<K, V> res) {
if (log.isDebugEnabled())
log.debug("Processing deferred dht atomic update response [nodeId=" + nodeId + ", res=" + res + ']');
for (GridCacheVersion ver : res.futureVersions()) {
GridDhtAtomicUpdateFuture<K, V> updateFut = (GridDhtAtomicUpdateFuture<K, V>)ctx.mvcc().atomicFuture(ver);
if (updateFut != null)
updateFut.onResult(nodeId);
else
U.warn(log, "Failed to find DHT update future for deferred update response [nodeId=" +
nodeId + ", res=" + res + ']');
}
}
/**
* @param nodeId Originating node ID.
* @param res Near update response.
*/
private void sendNearUpdateReply(UUID nodeId, GridNearAtomicUpdateResponse<K, V> res) {
try {
ctx.io().send(nodeId, res);
}
catch (GridTopologyException ignored) {
U.warn(log, "Failed to send near update reply to node because it left grid: " +
nodeId);
}
catch (GridException e) {
U.error(log, "Failed to send near update reply (did node leave grid?) [nodeId=" + nodeId +
", res=" + res + ']', e);
}
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridDhtAtomicCache.class, this, super.toString());
}
/**
* Result of {@link GridDhtAtomicCache#updateSingle} execution.
*/
private static class UpdateSingleResult<K, V> {
private final GridCacheReturn<Object> retVal;
private final Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted;
private final GridDhtAtomicUpdateFuture<K, V> dhtFut;
/**
* @param retVal Return value.
* @param deleted Deleted entries.
* @param dhtFut DHT future.
*/
private UpdateSingleResult(GridCacheReturn<Object> retVal,
Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted,
GridDhtAtomicUpdateFuture<K, V> dhtFut) {
this.retVal = retVal;
this.deleted = deleted;
this.dhtFut = dhtFut;
}
/**
* @return Return value.
*/
private GridCacheReturn<Object> returnValue() {
return retVal;
}
/**
* @return Deleted entries.
*/
private Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted() {
return deleted;
}
/**
* @return DHT future.
*/
public GridDhtAtomicUpdateFuture<K, V> dhtFuture() {
return dhtFut;
}
}
/**
* Result of {@link GridDhtAtomicCache#updateWithBatch} execution.
*/
private static class UpdateBatchResult<K, V> {
private Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted;
private GridDhtAtomicUpdateFuture<K, V> dhtFut;
private boolean readersOnly;
/**
* @param entry Entry.
* @param updRes Entry update result.
* @param entries All entries.
*/
private void addDeleted(GridDhtCacheEntry<K, V> entry, GridCacheUpdateAtomicResult<K, V> updRes,
Collection<GridDhtCacheEntry<K, V>> entries) {
if (updRes.removeVersion() != null) {
if (deleted == null)
deleted = new ArrayList<>(entries.size());
deleted.add(F.t(entry, updRes.removeVersion()));
}
}
/**
* @return Deleted entries.
*/
private Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted() {
return deleted;
}
/**
* @return DHT future.
*/
public GridDhtAtomicUpdateFuture<K, V> dhtFuture() {
return dhtFut;
}
/**
* @param dhtFut DHT future.
*/
private void dhtFuture(@Nullable GridDhtAtomicUpdateFuture<K, V> dhtFut) {
this.dhtFut = dhtFut;
}
/**
* @return {@code True} if only readers (not backups) should be updated.
*/
private boolean readersOnly() {
return readersOnly;
}
/**
* @param readersOnly {@code True} if only readers (not backups) should be updated.
*/
private void readersOnly(boolean readersOnly) {
this.readersOnly = readersOnly;
}
}
private static class FinishedLockFuture extends GridFinishedFutureEx<Boolean> implements GridDhtFuture<Boolean> {
private static final long serialVersionUID = 0L;
/**
* Empty constructor required by {@link Externalizable}.
*/
public FinishedLockFuture() {
// No-op.
}
/**
* @param err Error.
*/
private FinishedLockFuture(Throwable err) {
super(err);
}
/** {@inheritDoc} */
@Override public Collection<Integer> invalidPartitions() {
return Collections.emptyList();
}
}
/**
* Deferred response buffer.
*/
private class DeferredResponseBuffer extends ReentrantReadWriteLock implements GridTimeoutObject {
private static final long serialVersionUID = 0L;
/** Filled atomic flag. */
private AtomicBoolean guard = new AtomicBoolean(false);
/** Response versions. */
private Collection<GridCacheVersion> respVers = new ConcurrentLinkedDeque8<>();
/** Node ID. */
private final UUID nodeId;
/** Timeout ID. */
private final GridUuid timeoutId;
/** End time. */
private final long endTime;
/**
* @param nodeId Node ID to send message to.
*/
private DeferredResponseBuffer(UUID nodeId) {
this.nodeId = nodeId;
timeoutId = GridUuid.fromUuid(nodeId);
endTime = U.currentTimeMillis() + DEFERRED_UPDATE_RESPONSE_TIMEOUT;
}
/** {@inheritDoc} */
@Override public GridUuid timeoutId() {
return timeoutId;
}
/** {@inheritDoc} */
@Override public long endTime() {
return endTime;
}
/** {@inheritDoc} */
@Override public void onTimeout() {
if (guard.compareAndSet(false, true)) {
writeLock().lock();
try {
finish();
}
finally {
writeLock().unlock();
}
}
}
/**
* Adds deferred response to buffer.
*
* @param ver Version to send.
* @return {@code True} if response was handled, {@code false} if this buffer is filled and cannot be used.
*/
public boolean addResponse(GridCacheVersion ver) {
readLock().lock();
boolean snd = false;
try {
if (guard.get())
return false;
respVers.add(ver);
if (respVers.size() > DEFERRED_UPDATE_RESPONSE_BUFFER_SIZE && guard.compareAndSet(false, true))
snd = true;
}
finally {
readLock().unlock();
}
if (snd) {
// Wait all threads in read lock to finish.
writeLock().lock();
try {
finish();
ctx.time().removeTimeoutObject(this);
}
finally {
writeLock().unlock();
}
}
return true;
}
/**
* Sends deferred notification message and removes this buffer from pending responses map.
*/
private void finish() {
GridDhtAtomicDeferredUpdateResponse<K, V> msg = new GridDhtAtomicDeferredUpdateResponse<>(respVers);
try {
ctx.io().send(nodeId, msg);
}
catch (GridTopologyException ignored) {
if (log.isDebugEnabled())
log.debug("Failed to send deferred dht update response to remote node (did node leave grid?) " +
"[nodeId=" + nodeId + ", msg=" + msg + ']');
}
catch (GridException e) {
U.error(log, "Failed to send deferred dht update response to remote node [nodeId="
+ nodeId + ", msg=" + msg + ']', e);
}
pendingResponses.remove(nodeId, this);
}
}
@SuppressWarnings("PublicInnerClass")
public static class DhtAtomicUpdateRequestConverter603 extends GridVersionConverter {
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (!commState.putInt(-1))
return false;
commState.idx++;
case 1:
if (!commState.putInt(-1))
return false;
commState.idx++;
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
case 1:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
}
return true;
}
}
@SuppressWarnings("PublicInnerClass")
public static class DhtAtomicUpdateResponseConverter603 extends GridVersionConverter {
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (!commState.putInt(-1))
return false;
commState.idx++;
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
}
return true;
}
}
@SuppressWarnings("PublicInnerClass")
public static class NearAtomicUpdateResponseConverter603 extends GridVersionConverter {
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (!commState.putInt(-1))
return false;
commState.idx++;
case 1:
if (!commState.putLong(0))
return false;
commState.idx++;
case 2:
if (!commState.putInt(-1))
return false;
commState.idx++;
case 3:
if (!commState.putInt(-1))
return false;
commState.idx++;
case 4:
if (!commState.putCacheVersion(null))
return false;
commState.idx++;
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
case 1:
if (buf.remaining() < 8)
return false;
long nearTtl = commState.getLong();
assert nearTtl == 0 : nearTtl;
commState.idx++;
case 2:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
case 3:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
case 4:
GridCacheVersion nearVer0 = commState.getCacheVersion();
if (nearVer0 == CACHE_VER_NOT_READ)
return false;
assert nearVer0 == null : nearVer0;
commState.idx++;
}
return true;
}
}
/**
* GridNearAtomicUpdateRequest converter for version 6.1.2
*/
@SuppressWarnings("PublicInnerClass")
public static class GridNearAtomicUpdateRequestConverter612 extends GridVersionConverter {
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (!commState.putBoolean(false))
return false;
commState.idx++;
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0: {
if (buf.remaining() < 1)
return false;
commState.getBoolean();
commState.idx++;
}
}
return true;
}
}
/**
* GridDhtAtomicUpdateRequest converter for version 6.1.2
*/
@SuppressWarnings("PublicInnerClass")
public static class GridDhtAtomicUpdateRequestConverter612 extends GridVersionConverter {
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0: {
if (!commState.putInt(-1))
return false;
commState.idx++;
}
case 1: {
if (!commState.putBoolean(false))
return false;
commState.idx++;
}
case 2: {
if (!commState.putInt(-1))
return false;
commState.idx++;
}
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
if (commState.readSize >= 0) {
for (int i = commState.readItems; i < commState.readSize; i++) {
byte[] _val = commState.getByteArray();
if (_val == BYTE_ARR_NOT_READ)
return false;
commState.readItems++;
}
}
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
case 1:
if (buf.remaining() < 1)
return false;
commState.getBoolean();
commState.idx++;
case 2:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
if (commState.readSize >= 0) {
for (int i = commState.readItems; i < commState.readSize; i++) {
byte[] _val = commState.getByteArray();
if (_val == BYTE_ARR_NOT_READ)
return false;
commState.readItems++;
}
}
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
}
return true;
}
}
}
|
package org.opendaylight.controller.cluster.raft;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import akka.japi.Procedure;
import com.google.common.base.Supplier;
import java.util.Collections;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.internal.matchers.Same;
import org.opendaylight.controller.cluster.DataPersistenceProvider;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockReplicatedLogEntry;
import org.opendaylight.controller.cluster.raft.base.messages.DeleteEntries;
import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Unit tests for ReplicatedLogImpl.
*
* @author Thomas Pantelis
*/
public class ReplicatedLogImplTest {
private static final Logger LOG = LoggerFactory.getLogger(RaftActorRecoverySupportTest.class);
@Mock
private DataPersistenceProvider mockPersistence;
@Mock
private RaftActorBehavior mockBehavior;
@Mock
private SnapshotManager mockSnapshotManager;
private RaftActorContext context;
private final DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
context = new RaftActorContextImpl(null, null, "test",
new ElectionTermImpl(mockPersistence, "test", LOG),
-1, -1, Collections.<String,String>emptyMap(), configParams, LOG) {
@Override
public SnapshotManager getSnapshotManager() {
return mockSnapshotManager;
}
};
}
private void verifyPersist(Object message) throws Exception {
verifyPersist(message, new Same(message));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void verifyPersist(Object message, Matcher<?> matcher) throws Exception {
ArgumentCaptor<Procedure> procedure = ArgumentCaptor.forClass(Procedure.class);
verify(mockPersistence).persist(Matchers.argThat(matcher), procedure.capture());
procedure.getValue().apply(message);
}
@SuppressWarnings("unchecked")
@Test
public void testAppendAndPersistExpectingNoCapture() throws Exception {
ReplicatedLog log = ReplicatedLogImpl.newInstance(context, mockPersistence, mockBehavior);
MockReplicatedLogEntry logEntry = new MockReplicatedLogEntry(1, 1, new MockPayload("1"));
log.appendAndPersist(logEntry);
verifyPersist(logEntry);
assertEquals("size", 1, log.size());
reset(mockPersistence);
Procedure<ReplicatedLogEntry> mockCallback = Mockito.mock(Procedure.class);
log.appendAndPersist(logEntry, mockCallback);
verifyPersist(logEntry);
verify(mockCallback).apply(same(logEntry));
verifyNoMoreInteractions(mockSnapshotManager);
assertEquals("size", 2, log.size());
}
@Test
public void testAppendAndPersistExpectingCaptureDueToJournalCount() throws Exception {
configParams.setSnapshotBatchCount(2);
doReturn(1L).when(mockBehavior).getReplicatedToAllIndex();
ReplicatedLog log = ReplicatedLogImpl.newInstance(context, mockPersistence, mockBehavior);
MockReplicatedLogEntry logEntry1 = new MockReplicatedLogEntry(1, 2, new MockPayload("2"));
MockReplicatedLogEntry logEntry2 = new MockReplicatedLogEntry(1, 3, new MockPayload("3"));
log.appendAndPersist(logEntry1);
verifyPersist(logEntry1);
verifyNoMoreInteractions(mockSnapshotManager);
reset(mockPersistence);
log.appendAndPersist(logEntry2);
verifyPersist(logEntry2);
verify(mockSnapshotManager).capture(same(logEntry2), eq(1L));
assertEquals("size", 2, log.size());
}
@Test
public void testAppendAndPersistExpectingCaptureDueToDataSize() throws Exception {
doReturn(1L).when(mockBehavior).getReplicatedToAllIndex();
context.setTotalMemoryRetriever(new Supplier<Long>() {
@Override
public Long get() {
return 100L;
}
});
ReplicatedLog log = ReplicatedLogImpl.newInstance(context, mockPersistence, mockBehavior);
int dataSize = 600;
MockReplicatedLogEntry logEntry = new MockReplicatedLogEntry(1, 2, new MockPayload("2", dataSize));
doReturn(true).when(mockSnapshotManager).capture(same(logEntry), eq(1L));
log.appendAndPersist(logEntry);
verifyPersist(logEntry);
verify(mockSnapshotManager).capture(same(logEntry), eq(1L));
reset(mockPersistence, mockSnapshotManager);
logEntry = new MockReplicatedLogEntry(1, 3, new MockPayload("3", 5));
log.appendAndPersist(logEntry);
verifyPersist(logEntry);
verifyNoMoreInteractions(mockSnapshotManager);
assertEquals("size", 2, log.size());
}
@Test
public void testRemoveFromAndPersist() throws Exception {
ReplicatedLog log = ReplicatedLogImpl.newInstance(context, mockPersistence, mockBehavior);
log.append(new MockReplicatedLogEntry(1, 0, new MockPayload("0")));
log.append(new MockReplicatedLogEntry(1, 1, new MockPayload("1")));
log.append(new MockReplicatedLogEntry(1, 2, new MockPayload("2")));
log.removeFromAndPersist(1);
DeleteEntries deleteEntries = new DeleteEntries(1);
verifyPersist(deleteEntries, match(deleteEntries));
assertEquals("size", 1, log.size());
reset(mockPersistence);
log.removeFromAndPersist(1);
verifyNoMoreInteractions(mockPersistence);
}
public Matcher<DeleteEntries> match(final DeleteEntries actual){
return new BaseMatcher<DeleteEntries>() {
@Override
public boolean matches(Object o) {
DeleteEntries other = (DeleteEntries) o;
return actual.getFromIndex() == other.getFromIndex();
}
@Override
public void describeTo(Description description) {
description.appendText("DeleteEntries: fromIndex: " + actual.getFromIndex());
}
};
}
}
|
package org.jaggeryjs.hostobjects.web;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaggeryjs.hostobjects.log.LogHostObject;
import org.jaggeryjs.scriptengine.EngineConstants;
import org.jaggeryjs.scriptengine.engine.JaggeryContext;
import org.jaggeryjs.scriptengine.engine.RhinoEngine;
import org.jaggeryjs.scriptengine.exceptions.ScriptException;
import org.jaggeryjs.scriptengine.util.HostObjectUtil;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.*;
/**
* TODO :
* getLocale
* getPathTransalted
*/
public class RequestHostObject extends ScriptableObject {
private static final Log log = LogFactory.getLog(RequestHostObject.class);
private static final String hostObjectName = "Request";
private HttpServletRequest request;
private boolean isMultipart = false;
private Map<String, FileItem> parameterMap = new HashMap<String, FileItem>();
private Scriptable parameters = null;
private Scriptable files = null;
private Scriptable cookies = null;
private Scriptable locales = null;
private Object content = null;
private Context context;
public RequestHostObject() {
}
public static Scriptable jsConstructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr)
throws ScriptException {
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, hostObjectName, argsCount, true);
}
if (!(args[0] instanceof HttpServletRequest)) {
HostObjectUtil.getReservedHostObjectWarn(hostObjectName);
}
RequestHostObject rho = new RequestHostObject();
rho.request = (HttpServletRequest) args[0];
rho.isMultipart = ServletFileUpload.isMultipartContent(rho.request);
rho.context = cx;
return rho;
}
@Override
public String getClassName() {
return hostObjectName;
}
public static Object jsFunction_getContent(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getContent";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
try {
if (rho.content != null) {
return rho.content;
}
String data = HostObjectUtil.streamToString(rho.request.getInputStream());
String contentType = rho.request.getContentType();
if (contentType != null) {
contentType = contentType.trim().toLowerCase();
if (contentType.startsWith("application/json") ||
contentType.startsWith("application/json/badgerfish")) {
rho.content = (data != null && !"".equals(data)) ? HostObjectUtil.parseJSON(thisObj, data) : null;
} else {
rho.content = data;
}
} else {
rho.content = data;
}
return rho.content;
} catch (IOException e) {
String msg = "Error occurred while reading Servlet InputStream";
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
public static Object jsFunction_getStream(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getStream";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
try {
return cx.newObject(thisObj, "Stream", new Object[]{rho.request.getInputStream()});
} catch (IOException e) {
String msg = "Error occurred while reading Servlet InputStream";
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
public static String jsFunction_getMethod(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getMethod";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getMethod();
}
public static String jsFunction_getUser(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getUser";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
Principal principle = rho.request.getUserPrincipal();
if (principle == null) {
return null;
}
return principle.getName();
}
public static String jsFunction_getContextPath(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getContextPath";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getContextPath();
}
public static String jsFunction_getPathTranslated(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getPathTranslated";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getPathTranslated();
}
public static String jsFunction_getProtocol(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getProtocol";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getProtocol();
}
public static String jsFunction_getQueryString(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getQueryString";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getQueryString();
}
public static String jsFunction_getContentType(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getContentType";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getContentType();
}
public static int jsFunction_getContentLength(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getContentLength";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getContentLength();
}
public static Scriptable jsFunction_getAllParameters(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getAllParameters";
int argsCount = args.length;
if (argsCount > 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
if (!rho.isMultipart) {
parseParameters(rho);
return rho.parameters;
}
String encoding = null;
if (argsCount == 1) {
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
encoding = (String) args[0];
}
parseMultipart(rho);
// if no encoding is specified, UTF-8 is assumed.
parseMultipartParams(rho, encoding == null ? "UTF-8" : encoding);
return rho.parameters;
}
public static Scriptable jsFunction_getAllFiles(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getAllFiles";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
if (!rho.isMultipart) {
return null;
}
parseMultipart(rho);
return rho.files;
}
public static String jsFunction_getRequestURI(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getRequestURI";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getRequestURI();
}
public static String jsFunction_getRequestURL(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getRequestURL";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
String strURL = rho.request.getRequestURL().toString();
return strURL;
}
public static boolean jsFunction_isSecure(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "isSecure";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.isSecure();
}
public static String jsFunction_getHeader(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getHeader";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(
hostObjectName, functionName, "1", "string", args[0], false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getHeader((String) args[0]);
}
public static Scriptable jsFunction_getAllHeaders(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getAllHeaders";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
Enumeration<String> names = rho.request.getHeaderNames();
Scriptable headers = cx.newObject(thisObj);
while (names.hasMoreElements()) {
String name = names.nextElement();
headers.put(name, headers, rho.request.getHeader(name));
}
return headers;
}
public static String jsFunction_getRemoteAddr(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getRemoteAddr";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getRemoteAddr();
}
public static String jsFunction_getLocale(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getLocale";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getLocale().getLanguage();
}
public static Scriptable jsFunction_getAllLocales(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getAllLocales";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
Enumeration<Locale> locales = rho.request.getLocales();
Scriptable localesOut = cx.newObject(thisObj);
while (locales.hasMoreElements()) {
Locale localname = locales.nextElement();
localesOut.put(localname.getLanguage(), localesOut, rho.request.getLocales());
}
return localesOut;
}
public static int jsFunction_getLocalPort(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getLocalPort";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
return rho.request.getLocalPort();
}
public static Object jsFunction_getParameter(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getParameter";
int argsCount = args.length;
if (argsCount != 1 && argsCount != 2) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
if (argsCount == 2 && !(args[1] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "2", "string", args[1], false);
}
String parameter = (String) args[0];
RequestHostObject rho = (RequestHostObject) thisObj;
if (!rho.isMultipart) {
return getParameter(parameter, rho.request, rho);
}
parseMultipart(rho);
FileItem item = rho.parameterMap.get(parameter);
if (item == null) {
return null;
}
if (argsCount == 1) {
return item.getString();
}
try {
return item.getString((String) args[1]);
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
throw new ScriptException(e);
}
}
public static Scriptable jsFunction_getFile(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getFile";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
if (!rho.isMultipart) {
return null;
}
parseMultipart(rho);
Object obj = rho.files.get((String) args[0], thisObj);
if (obj instanceof Scriptable) {
return (Scriptable) obj;
}
return null;
}
public HttpServletRequest getHttpServletRequest() {
return this.request;
}
private static void parseMultipart(RequestHostObject rho) throws ScriptException {
if (rho.files != null) {
return;
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(rho.request);
} catch (FileUploadException e) {
log.error(e.getMessage(), e);
throw new ScriptException(e);
}
// Process the uploaded items
String name;
rho.files = rho.context.newObject(rho);
for (Object obj : items) {
FileItem item = (FileItem) obj;
name = item.getFieldName();
if (item.isFormField()) {
rho.parameterMap.put(name, item);
} else {
rho.files.put(item.getFieldName(), rho.files, rho.context.newObject(rho, "File", new Object[]{item}));
}
}
}
private static void parseMultipartParams(RequestHostObject rho, String encoding) throws ScriptException {
if (rho.parameters != null) {
return;
}
rho.parameters = rho.context.newObject(rho);
for (String name : rho.parameterMap.keySet()) {
try {
rho.parameters.put(name, rho.parameters, rho.parameterMap.get(name).getString(encoding));
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
throw new ScriptException(e);
}
}
}
private static void parseParameters(RequestHostObject rho) {
if (rho.parameters != null) {
return;
}
rho.parameters = rho.context.newObject(rho);
Enumeration params = rho.request.getParameterNames();
while (params.hasMoreElements()) {
String name = (String) params.nextElement();
rho.parameters.put(name, rho.parameters, getParameter(name, rho.request, rho));
}
}
public static Scriptable jsFunction_getCookie(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getCookie";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
if (rho.cookies == null) {
rho.cookies = rho.context.newObject(rho);
parseCookies(cx, thisObj, rho);
}
if (rho.cookies.get((String) args[0], rho.cookies) != NOT_FOUND) {
return (Scriptable) rho.cookies.get((String) args[0], rho.cookies);
} else {
return null;
}
}
public static Scriptable jsFunction_getAllCookies(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getAllCookies";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
if (rho.cookies == null) {
rho.cookies = cx.newObject(rho);
parseCookies(cx, thisObj, rho);
}
return rho.cookies;
}
public static String jsFunction_getMappedPath(Context cx, Scriptable thisObj, Object[] args, Function funObj)
throws ScriptException {
String functionName = "getMappedPath";
int argsCount = args.length;
if (argsCount != 0) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
RequestHostObject rho = (RequestHostObject) thisObj;
JaggeryContext context = (JaggeryContext) RhinoEngine.getContextProperty(EngineConstants.JAGGERY_CONTEXT);
Stack stack = (Stack) context.getProperty(LogHostObject.JAGGERY_INCLUDES_CALLSTACK);
String path = (String) stack.firstElement();
if (rho.request.getRequestURI().equals(path)) {
return null;
}
return path;
}
private static void parseCookies(Context cx, Scriptable thisObj, RequestHostObject rho) {
if (rho.request.getCookies() != null) {
for (Cookie cookie : rho.request.getCookies()) {
Scriptable o = cx.newObject(thisObj);
o.put("name", o, cookie.getName());
o.put("value", o, cookie.getValue());
o.put("comment", o, cookie.getComment());
o.put("domain", o, cookie.getDomain());
o.put("maxAge", o, cookie.getMaxAge());
o.put("path", o, cookie.getPath());
o.put("secure", o, cookie.getSecure());
o.put("version", o, cookie.getVersion());
rho.cookies.put(cookie.getName(), rho.cookies, o);
}
}
}
private static Object getParameter(String name, HttpServletRequest request, Scriptable scope) {
String[] values = request.getParameterValues(name);
if (values == null) {
return null;
}
if (values.length == 1) {
return values[0];
}
return Context.javaToJS(values, scope);
}
}
|
package net.sf.taverna.t2.workbench.ui.views.contextualviews.merge;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import net.sf.taverna.t2.workbench.file.FileManager;
import net.sf.taverna.t2.workbench.ui.impl.configuration.colour.ColourManager;
import net.sf.taverna.t2.workbench.ui.views.contextualviews.ContextualView;
import net.sf.taverna.t2.workflowmodel.Dataflow;
import net.sf.taverna.t2.workflowmodel.Datalink;
import net.sf.taverna.t2.workflowmodel.EventForwardingOutputPort;
import net.sf.taverna.t2.workflowmodel.EventHandlingInputPort;
import net.sf.taverna.t2.workflowmodel.Merge;
import net.sf.taverna.t2.workflowmodel.MergeInputPort;
import net.sf.taverna.t2.workflowmodel.TokenProcessingEntity;
import net.sf.taverna.t2.workflowmodel.utils.Tools;
/**
* Contextual view for a {@link Merge} inside a workflow.
*
* @author Alex Nenadic
*
*/
@SuppressWarnings("serial")
public class MergeContextualView extends ContextualView{
private Merge merge;
private Dataflow workflow;
private JEditorPane editorPane;
public MergeContextualView(Merge merge) {
this.merge = merge;
workflow = FileManager.getInstance().getCurrentDataflow();
initView();
}
@Override
public JComponent getMainFrame() {
return panelForHtml(buildHtml());
}
@Override
public String getViewTitle() {
return "Merge " + merge.getLocalName();
}
/**
* Update the view with the latest information
* from the configuration bean.
*/
@Override
public void refreshView() {
editorPane.setText(buildHtml());
repaint();
}
private String buildHtml() {
String html = "<html><head>" + getStyle() + "</head><body>";
html += buildTableOpeningTag();
html += "<tr><td colspan=\"3\"><b>" + getViewTitle() + "</b></td></tr>";
html += "<tr><td colspan=\"3\"><b>Ordered incoming links (entity.port -> merge.port)</b></td></tr>";
html += "<tr><td><b>No.</b></td><td><b>From</b></td><td><b>To</b></td></tr>";
int counter = 1;
for (MergeInputPort mergeInputPort : merge.getInputPorts()){
EventForwardingOutputPort sourcePort = mergeInputPort.getIncomingLink().getSource();
// Get the name TokenProcessingEntity (Processor or another Merge or Dataflow) and
// its port that contains the source EventForwardingOutputPort
TokenProcessingEntity entity = Tools.getTokenProcessingEntityWithEventForwardingOutputPort(sourcePort, workflow);
if (entity != null){
html += "<tr><td>"+ (counter++) + ".</td><td>" + entity.getLocalName() + "."
+ sourcePort.getName() + "</td><td>" + merge.getLocalName() + "." + mergeInputPort.getName()
+ "</td></tr>";
}
}
html += "<tr><td colspan=\"3\"><b>Outgoing link (merge.port -> entity.port)</b></td></tr>";
html += "<tr><td><b>No.</b></td><td><b>From</b></td><td><b>To</b></td></tr>";
Object[] links = merge.getOutputPort().getOutgoingLinks().toArray();
// There will be only one link in the set
EventHandlingInputPort targetPort = ((Datalink) links[0]).getSink();
TokenProcessingEntity entity = Tools.getTokenProcessingEntityWithEventHandlingInputPort(targetPort,workflow);
// Find the other part of the link (if any - could have been deleted)
if (entity != null){
html += "<tr><td>1.</td><td>" + merge.getLocalName() + "."
+ merge.getOutputPort().getName() + "</td><td>"
+ entity.getLocalName() + "." + targetPort.getName()
+ "</td></tr>";
}
html += "</table>";
html += "</body></html>";
return html;
}
private String buildTableOpeningTag() {
String result = "<table ";
Map<String, String> props = getTableProperties();
for (String key : props.keySet()) {
result += key + "=\"" + props.get(key) + "\" ";
}
result += ">";
return result;
}
protected Map<String, String> getTableProperties() {
Map<String, String> result = new HashMap<String, String>();
result.put("border", "1");
return result;
}
protected String getStyle() {
String backgroundColour = ColourManager
.getInstance()
.getDefaultPropertyMap().get("net.sf.taverna.t2.workflowmodel.Merge");
String style = "<style type='text/css'>";
style += "table {align:center; border:solid black 1px; background-color:\""+backgroundColour+"\";width:100%; height:100%; overflow:auto;}";
style += "</style>";
return style;
}
protected JPanel panelForHtml(String html) {
final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
editorPane = new JEditorPane("text/html", html);
editorPane.setEditable(false);
panel.add(editorPane, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton configureButton = new JButton(new AbstractAction(){
public void actionPerformed(ActionEvent e) {
MergeConfigurationView mergeConfigurationView = new MergeConfigurationView(merge);
mergeConfigurationView.setLocationRelativeTo(panel);
mergeConfigurationView.setVisible(true);
}
});
configureButton.setText("Configure");
buttonPanel.add(configureButton);
panel.add(buttonPanel, BorderLayout.SOUTH);
return panel;
}
}
|
package org.eclipse.birt.report.engine.emitter.html;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IMetadataFilter;
import org.eclipse.birt.report.engine.api.InstanceID;
import org.eclipse.birt.report.engine.content.IBandContent;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IColumn;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IElement;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IGroupContent;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.IReportContent;
import org.eclipse.birt.report.engine.content.IRowContent;
import org.eclipse.birt.report.engine.content.ITableBandContent;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.content.ITextContent;
import org.eclipse.birt.report.engine.emitter.HTMLTags;
import org.eclipse.birt.report.engine.emitter.HTMLWriter;
import org.eclipse.birt.report.engine.emitter.html.util.HTMLEmitterUtil;
import org.eclipse.birt.report.engine.internal.util.HTMLUtil;
import org.eclipse.birt.report.engine.ir.DataItemDesign;
import org.eclipse.birt.report.engine.ir.ExtendedItemDesign;
import org.eclipse.birt.report.engine.ir.LabelItemDesign;
import org.eclipse.birt.report.engine.ir.ListItemDesign;
import org.eclipse.birt.report.engine.ir.ReportItemDesign;
import org.eclipse.birt.report.engine.ir.TableItemDesign;
import org.eclipse.birt.report.engine.ir.TemplateDesign;
import org.eclipse.birt.report.engine.ir.TextItemDesign;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.FilterConditionHandle;
import org.eclipse.birt.report.model.api.TableHandle;
/**
* Used to output metadata, including group collpase/expand icon, column filter
* icon, element select handle container and instance id, element type id,etc.
*
*/
public class MetadataEmitter
{
/**
* Stores row state used to check if current row is start of detail rows.
*/
private Stack detailRowStateStack = new Stack( );
/**
* Strores tags so that tags can be ouput in pairs.
*/
private HTMLWriter writer;
private boolean displayFilterIcon;
private boolean displayGroupIcon;
private boolean wrapTemplateTable;
private IDGenerator idGenerator;
private List ouputInstanceIDs;
private String imagePath;
private String htmlIDNamespace;
/**
* attrNamePrefix must contain colon ':'.
*/
private String attrNamePrefix;
/**
* the instance ID of current wrapping table.
*/
private InstanceID wrapperTableIID = null;
protected String attrType, attrRowType, attrElementType, attrIID;
/**
*
* @param writer
* @param htmlOption
* @param idGenerator
* @param attrNamePrefix
* : the prefix of the attribute name.
*/
public MetadataEmitter( HTMLWriter writer, HTMLRenderOption htmlOption,
String attrNamePrefix, IDGenerator idGenerator )
{
this.writer = writer;
this.displayFilterIcon = htmlOption.getDisplayFilterIcon( );
this.displayGroupIcon = htmlOption.getDisplayGroupIcon( );
this.wrapTemplateTable = htmlOption.getWrapTemplateTable( );
this.ouputInstanceIDs = htmlOption.getInstanceIDs( );
this.imagePath = htmlOption.getAppBaseURL( );
if ( imagePath != null )
{
if ( !imagePath.endsWith( "/" ) )
{
imagePath = imagePath + "/";
}
}
else
{
imagePath = "";
}
assert idGenerator != null;
this.idGenerator = idGenerator;
this.attrNamePrefix = attrNamePrefix;
initializeAttrName( attrNamePrefix );
}
/**
* Initialize the attribute name for metadata.
*
* @param prefix
* : the prefix of the attribute name.
*/
public void initializeAttrName( String prefix )
{
if ( prefix == null )
{
attrType = HTMLTags.ATTR_TYPE;
attrRowType = HTMLTags.ATTR_ROW_TYPE;
attrElementType = "element_type";
attrIID = "iid";
}
else
{
attrType = prefix + HTMLTags.ATTR_TYPE;
attrRowType = prefix + HTMLTags.ATTR_ROW_TYPE;
attrElementType = prefix + "element_type";
attrIID = prefix + "iid";
}
}
/**
* Starts a table. To ensure column filter is output in the first detail
* row, a state is used to record if first detail row is reached and if
* column filter icon is ouput.
*
* @param table
*/
public void startTable( ITableContent table )
{
Object generateBy = table.getGenerateBy( );
DetailRowState state = null;
if ( generateBy instanceof TableItemDesign )
{
state = new DetailRowState( false, false, true );
}
else
{
state = new DetailRowState( false, false, false );
}
detailRowStateStack.push( state );
}
/**
* Ends a table. Pop the detail row state for this table.
*
* @param table
*/
public void endTable( ITableContent table )
{
detailRowStateStack.pop( );
}
/**
* Starts a row. If the row is the first row of the table, the
* <code>isStartOfDetail</code> is set so that column filter icon will be
* input into the cells in this row.
*
* @param row
*/
public void startRow( IRowContent row )
{
//FIXME: code view: hasOutput has same meaning as isStartOfDetail?
// if (!state.hasOutput)
// if (isRowInDtealBand(row))
// hasOutput = true;
// isStartOfDeatil = true;
if ( isRowInDetailBand( row ) )
{
DetailRowState state = (DetailRowState) detailRowStateStack.peek( );
if ( !state.hasOutput && !state.isStartOfDetail && state.isTable )
{
state.isStartOfDetail = true;
state.hasOutput = true;
}
}
}
public void endRow( IRowContent row )
{
DetailRowState state = (DetailRowState) detailRowStateStack.peek( );
if ( state.isStartOfDetail )
{
state.isStartOfDetail = false;
}
}
/**
* Starts a cell. Output a wrap table if group icon or column filter need to
* be output in this cell. Output group icon before the items in this cell.
*
* @param cell
*/
public void startCell( ICellContent cell )
{
boolean needColumnFilter = needColumnFilter(cell);
boolean needGroupIcon = needGroupIcon(cell);
if ( needColumnFilter || needGroupIcon )
{
writer.openTag( HTMLTags.TAG_TABLE );
writer.attribute( HTMLTags.ATTR_HEIGHT, "100%" );
writer.attribute( HTMLTags.ATTR_WIDTH, "100%" );
writer.openTag( HTMLTags.TAG_TR );
//FIXME: code review: move the td outputting to "if ( needGroupIcon )". remove useless style.
writer.openTag( HTMLTags.TAG_TD );
writer.attribute( "align", cell.getComputedStyle( ).getTextAlign( ) ); //$NON-NLS-1$
}
if ( needGroupIcon )
{
// include select handle table
writer.attribute( HTMLTags.ATTR_STYLE, "vertical-align:top"
+ ";text-align:right" );
//FIXME: code review: in performance mode the computedStyel can't be used.
writer.attribute( "align", cell.getComputedStyle( ).getTextAlign( ) ); //$NON-NLS-1$
writer.attribute( HTMLTags.ATTR_WIDTH, "1px" );
writer.openTag( HTMLTags.TAG_IMAGE );
writer.attribute( HTMLTags.ATTR_SRC, imagePath + "./images/iv/collapsexpand.gif" );
writer.attribute( HTMLTags.ATTR_STYLE, "cursor:pointer" );
String bookmark = idGenerator.generateUniqueID( );
HTMLEmitterUtil.setBookmark( writer, null, htmlIDNamespace, bookmark );
writer.attribute( attrElementType, "GROUP" );
exportElementID( bookmark, "GROUP", -1 );
writer.closeTag( HTMLTags.TAG_IMAGE );
writer.closeTag( HTMLTags.TAG_TD );
writer.openTag( HTMLTags.TAG_TD );
writer.attribute( "align", cell.getComputedStyle( ).getTextAlign( ) ); //$NON-NLS-1$
}
}
/**
* Ends a cell. Complete the wrap table for group icon and column filter
* icon and output the column filter icon.
*
* @param cell
*/
public void endCell( ICellContent cell )
{
boolean needColumnFilter = needColumnFilter(cell);
boolean needGroupIcon = needGroupIcon(cell);
if ( needColumnFilter )
{
// include select handle table
writer.closeTag( HTMLTags.TAG_TD );
writer.openTag( HTMLTags.TAG_TD );
writer.attribute( HTMLTags.ATTR_STYLE, "vertical-align:top" );
writer.openTag( HTMLTags.TAG_IMAGE );
//FIXME: code review: output the width?
writer.attribute( HTMLTags.ATTR_SRC, imagePath + "./images/iv/columnicon.gif" );
writer.attribute( HTMLTags.ATTR_ALT, getColumnFilterText( cell ) );
writer.attribute( HTMLTags.ATTR_STYLE, "cursor:pointer" );
writer.attribute( HTMLTags.ATTR_COLUMN, cell.getColumnInstance( )
.getInstanceID( ).toString( ) );
String bookmark = idGenerator.generateUniqueID( );
HTMLEmitterUtil.setBookmark( writer, null, htmlIDNamespace, bookmark );
writer.attribute( attrElementType, "COLOUMNINFO" );
exportElementID( bookmark, "COLOUMNINFO", -1 );
writer.closeTag( HTMLTags.TAG_IMAGE );
}
if ( needColumnFilter || needGroupIcon )
{
writer.closeTag( HTMLTags.TAG_TD );
writer.closeTag( HTMLTags.TAG_TR );
writer.closeTag( HTMLTags.TAG_TABLE );
}
}
private void exportElementID( String bookmark, String elementType, long componentID )
{
if ( ouputInstanceIDs != null )
{
if ( bookmark != null )
{
assert elementType != null;
String htmlBookmark;
if ( null != htmlIDNamespace )
{
htmlBookmark = htmlIDNamespace + bookmark;
}
else
{
htmlBookmark = bookmark;
}
StringBuffer buffer = new StringBuffer( );
buffer.append( htmlBookmark );
buffer.append( "," );
buffer.append( elementType );
buffer.append( "," );
buffer.append( componentID );
ouputInstanceIDs.add( buffer.toString( ) );
}
}
}
/**
* Output metadata properties.
* @param map
* @param element
* @param tagName
* @return boolean: has the bookmark been output?
*/
public boolean outputMetadataProperty( HashMap propertyMap, Object element,
String tagName )
{
if ( propertyMap == null )
{
return false;
}
boolean iidOutput = false;
boolean bookmarkOutput = false;
boolean elementTypeOutput = false;
boolean addToIIDList = false;
InstanceID iid = null;
String bookmark = null;
String elementType = null;
Iterator ite = propertyMap.entrySet( ).iterator( );
while ( ite.hasNext( ) )
{
Map.Entry entry = (Map.Entry) ite.next( );
Object keyObj = entry.getKey( );
Object valueObj = entry.getValue( );
if ( keyObj instanceof String )
{
String keyStr = (String) keyObj;
if ( keyStr == IMetadataFilter.KEY_OUTPUT_IID )
{
Object genBy = null;
if ( element instanceof IContent )
{
iid = ( (IContent) element ).getInstanceID( );
genBy = ( (IContent) element ).getGenerateBy( );
}
else if ( element instanceof IColumn )
{
iid = ( (IColumn) element ).getInstanceID( );
genBy = ( (IColumn) element ).getGenerateBy( );
}
if ( iid != null )
{
if ( ( genBy instanceof TableItemDesign )
|| ( genBy instanceof ListItemDesign )
|| ( genBy instanceof ExtendedItemDesign ) )
{
writer.attribute( attrIID, iid.toUniqueString( ) );
}
else
{
writer.attribute( attrIID, iid.toString( ) );
}
iidOutput = true;
}
}
else if ( keyStr == IMetadataFilter.KEY_OUTPUT_BOOKMARK )
{
if ( element instanceof IContent )
{
IContent content = (IContent) element;
bookmark = content.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
content.setBookmark( bookmark );
}
HTMLEmitterUtil.setBookmark( writer,
tagName,
htmlIDNamespace,
bookmark );
bookmarkOutput = true;
}
}
else if ( keyStr == IMetadataFilter.KEY_ATTR_ELEMENT_TYPE )
{
if ( valueObj == null )
{
continue;
}
elementType = (String) valueObj;
writer.attribute( attrElementType, elementType );
elementTypeOutput = true;
}
else if ( keyStr == IMetadataFilter.KEY_ADD_INTO_IID_LIST )
{
addToIIDList = true;
}
else if ( keyStr.equalsIgnoreCase( IMetadataFilter.KEY_ATTR_TYPE ) )
{
if ( valueObj != null )
{
writer.attribute( attrType, (String) valueObj );
}
}
else if ( keyStr == IMetadataFilter.KEY_ATTR_ROW_TYPE )
{
if ( valueObj != null )
{
writer.attribute( attrRowType, (String) valueObj );
}
}
else if ( keyStr == IMetadataFilter.KEY_OUTPUT_GOURP_ID )
{
if ( element instanceof IRowContent )
{
String groupId = ( (IRowContent) element ).getGroupId( );
if ( groupId != null )
{
writer.attribute( HTMLTags.ATTR_GOURP_ID, groupId );
}
}
}
else
{
if ( valueObj != null )
{
if ( keyStr.length( ) > 0 )
{
if ( attrNamePrefix != null )
{
writer.attribute( attrNamePrefix + keyStr,
valueObj.toString( ) );
}
else
{
writer.attribute( keyStr, valueObj.toString( ) );
}
}
}
}
}
}
if ( addToIIDList && iidOutput && bookmarkOutput && elementTypeOutput )
{
exportElementID( bookmark, elementType, iid.getComponentID( ) );
}
return bookmarkOutput;
}
/**
* Checks if a row is in detail band.
*
* @param row
* @return
*/
private boolean isRowInDetailBand( IRowContent row )
{
IElement parent = row.getParent( );
if ( !( parent instanceof IBandContent ) )
{
return false;
}
IBandContent band = (IBandContent) parent;
if ( band.getBandType( ) == IBandContent.BAND_DETAIL )
{
return true;
}
return false;
}
//FIXME: code review: rename to getPredefineStyle or other names????
public String getMetadataStyleClass( IContent content )
{
Object generateBy = content.getGenerateBy( );
String styleName = null;
if ( content instanceof ITextContent )
{
if ( generateBy instanceof LabelItemDesign )
{
styleName = "birt-label-design";
}
else if ( generateBy instanceof DataItemDesign )
{
styleName = "birt-data-design";
}
else
{
styleName = "birt-label-design";
}
}
else if( content instanceof IImageContent)
{
if ( generateBy instanceof ExtendedItemDesign )
{
styleName = "birt-chart-design";
}
}
//FIXME: should we still ouput "birt-label-design" for ForeignContent
else if ( content instanceof IForeignContent )
{
styleName = "birt-label-design";
}
return styleName;
}
/**
* Checks if column filter icons need to be output. Column filter icons need
* to be output when:
* <ol>
* <li><code>displayGroupIcon</code> is set to true. And
* <li>The cell is in the first row of detail. And
* <li>The cell has child(any items). And
* <li>The column containing the cell has column filters.
* </ol>
*
* @param cell
* @return
*/
private boolean needColumnFilter( ICellContent cell )
{
//FIXME: code review: do the action only when displayFilterIcon is true.
IColumn columnInstance = cell.getColumnInstance( );
if ( columnInstance == null )
{
return false;
}
DetailRowState state = (DetailRowState) detailRowStateStack.peek( );
return state.isStartOfDetail
&& columnInstance.hasDataItemsInDetail( )
&& displayFilterIcon
&& getFilterConditions( cell ).size() > 0;
}
/**
* Checks if group icon needs to be displayed in this cell.
*
* @param cell
* @return
*/
private boolean needGroupIcon( ICellContent cell )
{
//FIXME: code view: put displayGroupIcon ahead.
return cell.getDisplayGroupIcon( ) && displayGroupIcon;
}
/**
* judge the table content is a top-level template table or not.
*
* @param table
* table content
*/
private boolean isTopLevelTemplateTable( ITableContent table )
{
Object genBy = table.getGenerateBy( );
if ( genBy instanceof TableItemDesign )
{
TableItemDesign tableDesign = (TableItemDesign) genBy;
DesignElementHandle handle = tableDesign.getHandle( );
// judge the content is belong table template element or not.
if ( ( null != handle ) && handle.isTemplateParameterValue( ) )
{
// judge the content is the top-level template table or not.
DesignElementHandle parentHandle = handle.getContainer( );
while ( null != parentHandle )
{
if ( ( parentHandle instanceof TableHandle )
&& parentHandle.isTemplateParameterValue( ) )
{
return false;
}
parentHandle = parentHandle.getContainer( );
}
return true;
}
}
return false;
}
/**
* wrap the top-level template table
*
* @param table
* table content
*/
public void startWrapTable( ITableContent table )
{
if ( wrapTemplateTable && isTopLevelTemplateTable( table ) )
{
wrapperTableIID = table.getInstanceID( );
writer.openTag( HTMLTags.TAG_TABLE );
writer.attribute( HTMLTags.ATTR_STYLE,
" border: medium none ; border-collapse: collapse; width: 100%;" );
writer.openTag( HTMLTags.TAG_TBODY );
writer.openTag( HTMLTags.TAG_TR );
writer.attribute( HTMLTags.ATTR_STYLE, " vertical-align: top;" );
writer.openTag( HTMLTags.TAG_TD );
writer.openTag( HTMLTags.TAG_IMAGE );
writer.attribute( HTMLTags.ATTR_SRC, imagePath
+ "./images/bizRD/sidetab_active.gif" );
writer.attribute( HTMLTags.ATTR_STYLE,
" width: 20px; height: 60px;" );
writer.closeTag( HTMLTags.TAG_IMAGE );
writer.closeTag( HTMLTags.TAG_TD );
writer.openTag( HTMLTags.TAG_TD );
writer.attribute( HTMLTags.ATTR_STYLE, " border: 2px solid black;" );
}
}
/**
* wrap the top-level template table
*
* @param table
* table content
*/
public void endWrapTable( ITableContent table )
{
if ( wrapTemplateTable && ( table.getInstanceID( ) == wrapperTableIID ) )
{
wrapperTableIID = null;
writer.closeTag( HTMLTags.TAG_TD );
writer.closeTag( HTMLTags.TAG_TR );
writer.closeTag( HTMLTags.TAG_TBODY );
writer.closeTag( HTMLTags.TAG_TABLE );
}
}
/**
* Generates description text for the filters of a column which contains the
* specified cell.
*
* @param cell
* the cell.
* @return the description text.
*/
private String getColumnFilterText( ICellContent cell )
{
List filterConditions = getFilterConditions( cell );
StringBuffer conditionString = new StringBuffer( );
for ( int i = 0; i < filterConditions.size( ); i++)
{
if ( i != 0 )
{
conditionString.append( ';' );
}
FilterConditionHandle condition = (FilterConditionHandle) filterConditions
.get( i );
conditionString.append( HTMLUtil.getFilterDescription( condition ) );
}
return conditionString.toString( );
}
private HashMap filterConditions = new HashMap();
/**
* Gets filter conditions of the column which contains the specified cell.
*
* @param cell
* the cell.
* @return the column filter conditions. Empty list is returned when the
* column has no filter conditions.
*/
private List getFilterConditions( ICellContent cell )
{
IRowContent row = (IRowContent) cell.getParent( );
ITableContent table = row.getTable( );
List filters = null;
if ( table != null )
{
Object genBy = table.getGenerateBy( );
if ( genBy instanceof TableItemDesign )
{
TableHandle tableHandle = (TableHandle) ( (TableItemDesign) genBy )
.getHandle( );
int columnCount = tableHandle.getColumnCount();
List[] tableFilters = (List[])filterConditions.get(tableHandle);
if (tableFilters == null)
{
tableFilters = new List[columnCount];
filterConditions.put(tableHandle, tableFilters);
}
//FIXME: code view: column id should be gotten from design.
int columnId = cell.getColumn();
if (columnId < columnCount)
{
filters = tableFilters[columnId];
if (filters == null)
{
filters = tableHandle.getFilters( cell.getColumn( ) );
tableFilters[columnId] = filters;
}
}
}
}
return filters == null ? Collections.EMPTY_LIST : filters;
}
public void setHTMLIDNamespace( String namespace)
{
this.htmlIDNamespace = namespace;
}
}
class DetailRowState
{
public boolean isStartOfDetail;
public boolean hasOutput;
public boolean isTable;
// FIXME: code view: remove isStartOfDetail and hasOutput parameters since
// they are both false from start.
public DetailRowState( boolean isStartOfDetail, boolean hasOutput,
boolean isTable )
{
this.isStartOfDetail = isStartOfDetail;
this.hasOutput = hasOutput;
this.isTable = isTable;
}
}
|
package org.innovateuk.ifs.admin.controller;
import org.innovateuk.ifs.admin.form.InviteUserForm;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.controller.ValidationHandler;
import org.innovateuk.ifs.invite.resource.InviteUserResource;
import org.innovateuk.ifs.invite.service.InviteUserService;
import org.innovateuk.ifs.user.resource.AdminRoleType;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.function.Supplier;
import static org.innovateuk.ifs.controller.ErrorToObjectErrorConverterFactory.asGlobalErrors;
import static org.innovateuk.ifs.controller.ErrorToObjectErrorConverterFactory.fieldErrorsToFieldErrors;
/**
* This controller will handle all CRUD requests related to users managed by IFS Administrators.
*/
@Controller
@RequestMapping("/admin")
@PreAuthorize("hasAuthority('ifs_administrator')")
public class InviteUserController {
private static final String FORM_ATTR_NAME = "form";
@Autowired
private InviteUserService inviteUserService;
@GetMapping("/invite-user")
public String inviteNewUser(Model model,
HttpServletRequest request,
UserResource loggedInUser) {
return viewInviteNewUser(model);
}
private String viewInviteNewUser(Model model) {
InviteUserForm form = new InviteUserForm();
model.addAttribute(FORM_ATTR_NAME, form);
return "admin/invite-new-user";
}
@PostMapping("/invite-user")
public String saveUserInvite(Model model,
HttpServletRequest request,
@Valid @ModelAttribute(FORM_ATTR_NAME) InviteUserForm form,
@SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler,
UserResource loggedInUser) {
//TODO - Temp code till its set in the form
/* form.setRole(AdminRoleType.IFS_ADMINISTRATOR);
InviteUserResource inviteUserResource = constructInviteUserResource(form);
ServiceResult<Void> saveResult = inviteUserService.saveUserInvite(inviteUserResource);
return "admin/users/active";*/
Supplier<String> failureView = () -> "admin/invite-new-user";
return validationHandler.failNowOrSucceedWith(failureView, () -> {
InviteUserResource inviteUserResource = constructInviteUserResource(form);
ServiceResult<Void> saveResult = inviteUserService.saveUserInvite(inviteUserResource);
return validationHandler.addAnyErrors(saveResult, fieldErrorsToFieldErrors(), asGlobalErrors()).
failNowOrSucceedWith(failureView, () -> "admin/users/active");
});
}
private InviteUserResource constructInviteUserResource(InviteUserForm form) {
UserResource invitedUser = new UserResource();
invitedUser.setFirstName(form.getFirstName());
invitedUser.setLastName(form.getLastName());
invitedUser.setEmail(form.getEmailAddress());
InviteUserResource inviteUserResource = new InviteUserResource(invitedUser, form.getRole());
return inviteUserResource;
}
}
|
package org.opendaylight.controller.networkconfig.neutron.implementation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap;
import org.apache.felix.dm.Component;
import org.opendaylight.controller.clustering.services.CacheConfigException;
import org.opendaylight.controller.clustering.services.CacheExistException;
import org.opendaylight.controller.clustering.services.IClusterContainerServices;
import org.opendaylight.controller.clustering.services.IClusterServices;
import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
import org.opendaylight.controller.networkconfig.neutron.INeutronPortCRUD;
import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD;
import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
import org.opendaylight.controller.networkconfig.neutron.NeutronPort;
import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
import org.opendaylight.controller.networkconfig.neutron.Neutron_IPs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NeutronPortInterface implements INeutronPortCRUD {
private static final Logger logger = LoggerFactory.getLogger(NeutronPortInterface.class);
private String containerName = null;
private IClusterContainerServices clusterContainerService = null;
private ConcurrentMap<String, NeutronPort> portDB;
// methods needed for creating caches
void setClusterContainerService(IClusterContainerServices s) {
logger.debug("Cluster Service set");
clusterContainerService = s;
}
void unsetClusterContainerService(IClusterContainerServices s) {
if (clusterContainerService == s) {
logger.debug("Cluster Service removed!");
clusterContainerService = null;
}
}
@SuppressWarnings("deprecation")
private void allocateCache() {
if (clusterContainerService == null) {
logger.error("un-initialized clusterContainerService, can't create cache");
return;
}
logger.debug("Creating Cache for OpenDOVE");
try {
// neutron caches
clusterContainerService.createCache("neutronPorts",
EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
} catch (CacheConfigException cce) {
logger.error("Cache couldn't be created for OpenDOVE - check cache mode");
} catch (CacheExistException cce) {
logger.error("Cache for OpenDOVE already exists, destroy and recreate");
}
logger.debug("Cache successfully created for OpenDOVE");
}
@SuppressWarnings({ "unchecked", "deprecation" })
private void retrieveCache() {
if (clusterContainerService == null) {
logger.error("un-initialized clusterContainerService, can't retrieve cache");
return;
}
logger.debug("Retrieving cache for Neutron Ports");
portDB = (ConcurrentMap<String, NeutronPort>) clusterContainerService
.getCache("neutronPorts");
if (portDB == null) {
logger.error("Cache couldn't be retrieved for Neutron Ports");
}
logger.debug("Cache was successfully retrieved for Neutron Ports");
}
@SuppressWarnings("deprecation")
private void destroyCache() {
if (clusterContainerService == null) {
logger.error("un-initialized clusterMger, can't destroy cache");
return;
}
logger.debug("Destroying Cache for HostTracker");
clusterContainerService.destroyCache("neutronPorts");
}
private void startUp() {
allocateCache();
retrieveCache();
}
/**
* Function called by the dependency manager when all the required
* dependencies are satisfied
*
*/
void init(Component c) {
Dictionary<?, ?> props = c.getServiceProperties();
if (props != null) {
containerName = (String) props.get("containerName");
logger.debug("Running containerName: {}", containerName);
} else {
// In the Global instance case the containerName is empty
containerName = "";
}
startUp();
}
/**
* Function called by the dependency manager when at least one dependency
* become unsatisfied or when the component is shutting down because for
* example bundle is being stopped.
*
*/
void destroy() {
destroyCache();
}
/**
* Function called by dependency manager after "init ()" is called and after
* the services provided by the class are registered in the service registry
*
*/
void start() {
}
/**
* Function called by the dependency manager before the services exported by
* the component are unregistered, this will be followed by a "destroy ()"
* calls
*
*/
void stop() {
}
// this method uses reflection to update an object from it's delta.
private boolean overwrite(Object target, Object delta) {
Method[] methods = target.getClass().getMethods();
for(Method toMethod: methods){
if(toMethod.getDeclaringClass().equals(target.getClass())
&& toMethod.getName().startsWith("set")){
String toName = toMethod.getName();
String fromName = toName.replace("set", "get");
try {
Method fromMethod = delta.getClass().getMethod(fromName);
Object value = fromMethod.invoke(delta, (Object[])null);
if(value != null){
toMethod.invoke(target, value);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
return true;
}
// IfNBPortCRUD methods
@Override
public boolean portExists(String uuid) {
return portDB.containsKey(uuid);
}
@Override
public NeutronPort getPort(String uuid) {
if (!portExists(uuid)) {
return null;
}
return portDB.get(uuid);
}
@Override
public List<NeutronPort> getAllPorts() {
Set<NeutronPort> allPorts = new HashSet<NeutronPort>();
for (Entry<String, NeutronPort> entry : portDB.entrySet()) {
NeutronPort port = entry.getValue();
allPorts.add(port);
}
logger.debug("Exiting getAllPorts, Found {} OpenStackPorts", allPorts.size());
List<NeutronPort> ans = new ArrayList<NeutronPort>();
ans.addAll(allPorts);
return ans;
}
@Override
public boolean addPort(NeutronPort input) {
if (portExists(input.getID())) {
return false;
}
portDB.putIfAbsent(input.getID(), input);
// if there are no fixed IPs, allocate one for each subnet in the network
INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
if (input.getFixedIPs().size() == 0) {
List<Neutron_IPs> list = input.getFixedIPs();
Iterator<NeutronSubnet> subnetIterator = systemCRUD.getAllSubnets().iterator();
while (subnetIterator.hasNext()) {
NeutronSubnet subnet = subnetIterator.next();
if (subnet.getNetworkUUID().equals(input.getNetworkUUID())) {
list.add(new Neutron_IPs(subnet.getID()));
}
}
}
Iterator<Neutron_IPs> fixedIPIterator = input.getFixedIPs().iterator();
while (fixedIPIterator.hasNext()) {
Neutron_IPs ip = fixedIPIterator.next();
NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
if (ip.getIpAddress() == null) {
ip.setIpAddress(subnet.getLowAddr());
}
if (!ip.getIpAddress().equals(subnet.getGatewayIP())) {
subnet.allocateIP(ip.getIpAddress());
}
else {
subnet.setGatewayIPAllocated();
}
subnet.addPort(input);
}
INeutronNetworkCRUD networkIf = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
NeutronNetwork network = networkIf.getNetwork(input.getNetworkUUID());
network.addPort(input);
return true;
}
@Override
public boolean removePort(String uuid) {
if (!portExists(uuid)) {
return false;
}
NeutronPort port = getPort(uuid);
portDB.remove(uuid);
INeutronNetworkCRUD networkCRUD = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
NeutronNetwork network = networkCRUD.getNetwork(port.getNetworkUUID());
network.removePort(port);
Iterator<Neutron_IPs> fixedIPIterator = port.getFixedIPs().iterator();
while (fixedIPIterator.hasNext()) {
Neutron_IPs ip = fixedIPIterator.next();
NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
if (!ip.getIpAddress().equals(subnet.getGatewayIP())) {
subnet.releaseIP(ip.getIpAddress());
}
else {
subnet.resetGatewayIPAllocated();
}
subnet.removePort(port);
}
return true;
}
@Override
public boolean updatePort(String uuid, NeutronPort delta) {
if (!portExists(uuid)) {
return false;
}
NeutronPort target = portDB.get(uuid);
// remove old Fixed_IPs
if (delta.getFixedIPs() != null) {
NeutronPort port = getPort(uuid);
INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
for (Neutron_IPs ip: port.getFixedIPs()) {
NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
subnet.releaseIP(ip.getIpAddress());
}
// allocate new Fixed_IPs
for (Neutron_IPs ip: delta.getFixedIPs()) {
NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
if (ip.getIpAddress() == null) {
ip.setIpAddress(subnet.getLowAddr());
}
subnet.allocateIP(ip.getIpAddress());
}
}
return overwrite(target, delta);
}
@Override
public boolean macInUse(String macAddress) {
List<NeutronPort> ports = getAllPorts();
Iterator<NeutronPort> portIterator = ports.iterator();
while (portIterator.hasNext()) {
NeutronPort port = portIterator.next();
if (macAddress.equalsIgnoreCase(port.getMacAddress())) {
return true;
}
}
return false;
}
@Override
public NeutronPort getGatewayPort(String subnetUUID) {
INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
NeutronSubnet subnet = systemCRUD.getSubnet(subnetUUID);
Iterator<NeutronPort> portIterator = getAllPorts().iterator();
while (portIterator.hasNext()) {
NeutronPort port = portIterator.next();
List<Neutron_IPs> fixedIPs = port.getFixedIPs();
if (fixedIPs.size() == 1) {
if (subnet.getGatewayIP().equals(fixedIPs.get(0).getIpAddress())) {
return port;
}
}
}
return null;
}
}
|
/* @java.file.header */
package org.gridgain.grid.kernal.processors.cache.datastructures;
import org.gridgain.grid.*;
import org.gridgain.grid.cache.*;
import org.gridgain.grid.cache.datastructures.*;
import org.gridgain.grid.kernal.*;
import org.gridgain.grid.kernal.processors.cache.*;
import org.gridgain.grid.kernal.processors.cache.query.continuous.*;
import org.gridgain.grid.kernal.processors.task.*;
import org.gridgain.grid.lang.*;
import org.gridgain.grid.resources.*;
import org.gridgain.grid.util.*;
import org.gridgain.grid.util.typedef.*;
import org.gridgain.grid.util.typedef.internal.*;
import org.jdk8.backport.*;
import org.jetbrains.annotations.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static org.gridgain.grid.cache.GridCacheAtomicWriteOrderMode.*;
import static org.gridgain.grid.cache.GridCacheFlag.*;
import static org.gridgain.grid.cache.GridCacheMode.*;
import static org.gridgain.grid.cache.GridCacheTxConcurrency.*;
import static org.gridgain.grid.cache.GridCacheTxIsolation.*;
import static org.gridgain.grid.kernal.GridClosureCallMode.*;
import static org.gridgain.grid.kernal.processors.cache.GridCacheOperation.*;
/**
* Manager of data structures.
*/
public final class GridCacheDataStructuresManager<K, V> extends GridCacheManagerAdapter<K, V> {
/** Initial capacity. */
private static final int INITIAL_CAPACITY = 10;
/** Cache contains only {@code GridCacheInternal,GridCacheInternal}. */
private GridCacheProjection<GridCacheInternal, GridCacheInternal> dsView;
/** Internal storage of all dataStructures items (sequence, queue , atomic long etc.). */
private final ConcurrentMap<GridCacheInternal, GridCacheRemovable> dsMap;
/** Queues map. */
private final ConcurrentMap<GridUuid, GridCacheQueueProxy> queuesMap;
/** Query notifying about queue update. */
private GridCacheContinuousQueryAdapter queueQry;
/** Queue query creation guard. */
private final AtomicBoolean queueQryGuard = new AtomicBoolean();
/** Cache contains only {@code GridCacheAtomicValue}. */
private GridCacheProjection<GridCacheInternalKey, GridCacheAtomicLongValue> atomicLongView;
/** Cache contains only {@code GridCacheCountDownLatchValue}. */
private GridCacheProjection<GridCacheInternalKey, GridCacheCountDownLatchValue> cntDownLatchView;
/** Cache contains only {@code GridCacheAtomicReferenceValue}. */
private GridCacheProjection<GridCacheInternalKey, GridCacheAtomicReferenceValue> atomicRefView;
/** Cache contains only {@code GridCacheAtomicStampedValue}. */
private GridCacheProjection<GridCacheInternalKey, GridCacheAtomicStampedValue> atomicStampedView;
/** Cache contains only entry {@code GridCacheSequenceValue}. */
private GridCacheProjection<GridCacheInternalKey, GridCacheAtomicSequenceValue> seqView;
/** Cache contains only entry {@code GridCacheQueueHeader}. */
private GridCacheProjection<GridCacheQueueHeaderKey, GridCacheQueueHeader> queueHdrView;
/** Busy lock. */
private final GridSpinBusyLock busyLock = new GridSpinBusyLock();
/** Init latch. */
private final CountDownLatch initLatch = new CountDownLatch(1);
/** Init flag. */
private boolean initFlag;
/** Set keys used for set iteration. */
private ConcurrentMap<GridUuid, GridConcurrentHashSet<GridCacheSetItemKey>> setDataMap = new ConcurrentHashMap8<>();
/** Sets map. */
private final ConcurrentMap<GridUuid, GridCacheSetProxy> setsMap;
/**
* Default constructor.
*/
public GridCacheDataStructuresManager() {
dsMap = new ConcurrentHashMap8<>(INITIAL_CAPACITY);
queuesMap = new ConcurrentHashMap8<>(INITIAL_CAPACITY);
setsMap = new ConcurrentHashMap8<>(INITIAL_CAPACITY);
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override protected void onKernalStart0() {
try {
dsView = cctx.cache().<GridCacheInternal, GridCacheInternal>projection
(GridCacheInternal.class, GridCacheInternal.class).flagsOn(CLONE);
if (transactionalWithNear()) {
cntDownLatchView = cctx.cache().<GridCacheInternalKey, GridCacheCountDownLatchValue>projection
(GridCacheInternalKey.class, GridCacheCountDownLatchValue.class).flagsOn(CLONE);
atomicLongView = cctx.cache().<GridCacheInternalKey, GridCacheAtomicLongValue>projection
(GridCacheInternalKey.class, GridCacheAtomicLongValue.class).flagsOn(CLONE);
atomicRefView = cctx.cache().<GridCacheInternalKey, GridCacheAtomicReferenceValue>projection
(GridCacheInternalKey.class, GridCacheAtomicReferenceValue.class).flagsOn(CLONE);
atomicStampedView = cctx.cache().<GridCacheInternalKey, GridCacheAtomicStampedValue>projection
(GridCacheInternalKey.class, GridCacheAtomicStampedValue.class).flagsOn(CLONE);
seqView = cctx.cache().<GridCacheInternalKey, GridCacheAtomicSequenceValue>projection
(GridCacheInternalKey.class, GridCacheAtomicSequenceValue.class).flagsOn(CLONE);
}
if (supportsQueue())
queueHdrView = cctx.cache().<GridCacheQueueHeaderKey, GridCacheQueueHeader>projection
(GridCacheQueueHeaderKey.class, GridCacheQueueHeader.class).flagsOn(CLONE);
initFlag = true;
}
finally {
initLatch.countDown();
}
}
/** {@inheritDoc} */
@Override protected void onKernalStop0(boolean cancel) {
super.onKernalStop0(cancel);
busyLock.block();
if (queueQry != null) {
try {
queueQry.close();
}
catch (GridException e) {
U.warn(log, "Failed to cancel queue header query.", e);
}
}
for (GridCacheQueueProxy q : queuesMap.values())
q.delegate().onKernalStop();
}
/**
* Gets a sequence from cache or creates one if it's not cached.
*
* @param name Sequence name.
* @param initVal Initial value for sequence. If sequence already cached, {@code initVal} will be ignored.
* @param create If {@code true} sequence will be created in case it is not in cache.
* @return Sequence.
* @throws GridException If loading failed.
*/
public final GridCacheAtomicSequence sequence(final String name, final long initVal,
final boolean create) throws GridException {
waitInitialization();
checkTransactionalWithNear();
final GridCacheInternalKey key = new GridCacheInternalKeyImpl(name);
try {
// Check type of structure received by key from local cache.
GridCacheAtomicSequence val = cast(dsMap.get(key), GridCacheAtomicSequence.class);
if (val != null)
return val;
return CU.outTx(new Callable<GridCacheAtomicSequence>() {
@Override
public GridCacheAtomicSequence call() throws Exception {
try (GridCacheTx tx = CU.txStartInternal(cctx, dsView, PESSIMISTIC, REPEATABLE_READ)) {
GridCacheAtomicSequenceValue seqVal = cast(dsView.get(key),
GridCacheAtomicSequenceValue.class);
// Check that sequence hasn't been created in other thread yet.
GridCacheAtomicSequenceEx seq = cast(dsMap.get(key), GridCacheAtomicSequenceEx.class);
if (seq != null) {
assert seqVal != null;
return seq;
}
if (seqVal == null && !create)
return null;
// We should use offset because we already reserved left side of range.
long off = cctx.config().getAtomicSequenceReserveSize() > 1 ?
cctx.config().getAtomicSequenceReserveSize() - 1 : 1;
long upBound;
long locCntr;
if (seqVal == null) {
locCntr = initVal;
upBound = locCntr + off;
// Global counter must be more than reserved region.
seqVal = new GridCacheAtomicSequenceValue(upBound + 1);
}
else {
locCntr = seqVal.get();
upBound = locCntr + off;
// Global counter must be more than reserved region.
seqVal.set(upBound + 1);
}
// Update global counter.
dsView.putx(key, seqVal);
// Only one thread can be in the transaction scope and create sequence.
seq = new GridCacheAtomicSequenceImpl(name, key, seqView, cctx,
locCntr, upBound);
dsMap.put(key, seq);
tx.commit();
return seq;
}
catch (Error | Exception e) {
dsMap.remove(key);
U.error(log, "Failed to make atomic sequence: " + name, e);
throw e;
}
}
}, cctx);
}
catch (Exception e) {
throw new GridException("Failed to get sequence by name: " + name, e);
}
}
/**
* Removes sequence from cache.
*
* @param name Sequence name.
* @return Method returns {@code true} if sequence has been removed and {@code false} if it's not cached.
* @throws GridException If removing failed.
*/
public final boolean removeSequence(String name) throws GridException {
waitInitialization();
checkTransactionalWithNear();
try {
GridCacheInternal key = new GridCacheInternalKeyImpl(name);
return removeInternal(key, GridCacheAtomicSequenceValue.class);
}
catch (Exception e) {
throw new GridException("Failed to remove sequence by name: " + name, e);
}
}
/**
* Gets an atomic long from cache or creates one if it's not cached.
*
* @param name Name of atomic long.
* @param initVal Initial value for atomic long. If atomic long already cached, {@code initVal}
* will be ignored.
* @param create If {@code true} atomic long will be created in case it is not in cache.
* @return Atomic long.
* @throws GridException If loading failed.
*/
public final GridCacheAtomicLong atomicLong(final String name, final long initVal,
final boolean create) throws GridException {
waitInitialization();
checkTransactionalWithNear();
final GridCacheInternalKey key = new GridCacheInternalKeyImpl(name);
try {
// Check type of structure received by key from local cache.
GridCacheAtomicLong atomicLong = cast(dsMap.get(key), GridCacheAtomicLong.class);
if (atomicLong != null)
return atomicLong;
return CU.outTx(new Callable<GridCacheAtomicLong>() {
@Override
public GridCacheAtomicLong call() throws Exception {
try (GridCacheTx tx = CU.txStartInternal(cctx, dsView, PESSIMISTIC, REPEATABLE_READ)) {
GridCacheAtomicLongValue val = cast(dsView.get(key),
GridCacheAtomicLongValue.class);
// Check that atomic long hasn't been created in other thread yet.
GridCacheAtomicLongEx a = cast(dsMap.get(key), GridCacheAtomicLongEx.class);
if (a != null) {
assert val != null;
return a;
}
if (val == null && !create)
return null;
if (val == null) {
val = new GridCacheAtomicLongValue(initVal);
dsView.putx(key, val);
}
a = new GridCacheAtomicLongImpl(name, key, atomicLongView, cctx);
dsMap.put(key, a);
tx.commit();
return a;
}
catch (Error | Exception e) {
dsMap.remove(key);
U.error(log, "Failed to make atomic long: " + name, e);
throw e;
}
}
}, cctx);
}
catch (Exception e) {
throw new GridException("Failed to get atomic long by name: " + name, e);
}
}
/**
* Removes atomic long from cache.
*
* @param name Atomic long name.
* @return Method returns {@code true} if atomic long has been removed and {@code false} if it's not cached.
* @throws GridException If removing failed.
*/
public final boolean removeAtomicLong(String name) throws GridException {
waitInitialization();
checkTransactionalWithNear();
try {
GridCacheInternal key = new GridCacheInternalKeyImpl(name);
return removeInternal(key, GridCacheAtomicLongValue.class);
}
catch (Exception e) {
throw new GridException("Failed to remove atomic long by name: " + name, e);
}
}
/**
* Gets an atomic reference from cache or creates one if it's not cached.
*
* @param name Name of atomic reference.
* @param initVal Initial value for atomic reference. If atomic reference already cached, {@code initVal}
* will be ignored.
* @param create If {@code true} atomic reference will be created in case it is not in cache.
* @return Atomic reference.
* @throws GridException If loading failed.
*/
@SuppressWarnings("unchecked")
public final <T> GridCacheAtomicReference<T> atomicReference(final String name, final T initVal,
final boolean create) throws GridException {
waitInitialization();
checkTransactionalWithNear();
final GridCacheInternalKey key = new GridCacheInternalKeyImpl(name);
try {
// Check type of structure received by key from local cache.
GridCacheAtomicReference atomicRef = cast(dsMap.get(key), GridCacheAtomicReference.class);
if (atomicRef != null)
return atomicRef;
return CU.outTx(new Callable<GridCacheAtomicReference<T>>() {
@Override
public GridCacheAtomicReference<T> call() throws Exception {
try (GridCacheTx tx = CU.txStartInternal(cctx, dsView, PESSIMISTIC, REPEATABLE_READ)) {
GridCacheAtomicReferenceValue val = cast(dsView.get(key),
GridCacheAtomicReferenceValue.class);
// Check that atomic reference hasn't been created in other thread yet.
GridCacheAtomicReferenceEx ref = cast(dsMap.get(key),
GridCacheAtomicReferenceEx.class);
if (ref != null) {
assert val != null;
return ref;
}
if (val == null && !create)
return null;
if (val == null) {
val = new GridCacheAtomicReferenceValue(initVal);
dsView.putx(key, val);
}
ref = new GridCacheAtomicReferenceImpl(name, key, atomicRefView, cctx);
dsMap.put(key, ref);
tx.commit();
return ref;
}
catch (Error | Exception e) {
dsMap.remove(key);
U.error(log, "Failed to make atomic reference: " + name, e);
throw e;
}
}
}, cctx);
}
catch (Exception e) {
throw new GridException("Failed to get atomic reference by name: " + name, e);
}
}
/**
* Removes atomic reference from cache.
*
* @param name Atomic reference name.
* @return Method returns {@code true} if atomic reference has been removed and {@code false} if it's not cached.
* @throws GridException If removing failed.
*/
public final boolean removeAtomicReference(String name) throws GridException {
waitInitialization();
checkTransactionalWithNear();
try {
GridCacheInternal key = new GridCacheInternalKeyImpl(name);
return removeInternal(key, GridCacheAtomicReferenceValue.class);
}
catch (Exception e) {
throw new GridException("Failed to remove atomic reference by name: " + name, e);
}
}
/**
* Gets an atomic stamped from cache or creates one if it's not cached.
*
* @param name Name of atomic stamped.
* @param initVal Initial value for atomic stamped. If atomic stamped already cached, {@code initVal}
* will be ignored.
* @param initStamp Initial stamp for atomic stamped. If atomic stamped already cached, {@code initStamp}
* will be ignored.
* @param create If {@code true} atomic stamped will be created in case it is not in cache.
* @return Atomic stamped.
* @throws GridException If loading failed.
*/
@SuppressWarnings("unchecked")
public final <T, S> GridCacheAtomicStamped<T, S> atomicStamped(final String name, final T initVal,
final S initStamp, final boolean create) throws GridException {
waitInitialization();
checkTransactionalWithNear();
final GridCacheInternalKeyImpl key = new GridCacheInternalKeyImpl(name);
try {
// Check type of structure received by key from local cache.
GridCacheAtomicStamped atomicStamped = cast(dsMap.get(key), GridCacheAtomicStamped.class);
if (atomicStamped != null)
return atomicStamped;
return CU.outTx(new Callable<GridCacheAtomicStamped<T, S>>() {
@Override
public GridCacheAtomicStamped<T, S> call() throws Exception {
try (GridCacheTx tx = CU.txStartInternal(cctx, dsView, PESSIMISTIC, REPEATABLE_READ)) {
GridCacheAtomicStampedValue val = cast(dsView.get(key),
GridCacheAtomicStampedValue.class);
// Check that atomic stamped hasn't been created in other thread yet.
GridCacheAtomicStampedEx stmp = cast(dsMap.get(key),
GridCacheAtomicStampedEx.class);
if (stmp != null) {
assert val != null;
return stmp;
}
if (val == null && !create)
return null;
if (val == null) {
val = new GridCacheAtomicStampedValue(initVal, initStamp);
dsView.putx(key, val);
}
stmp = new GridCacheAtomicStampedImpl(name, key, atomicStampedView, cctx);
dsMap.put(key, stmp);
tx.commit();
return stmp;
}
catch (Error | Exception e) {
dsMap.remove(key);
U.error(log, "Failed to make atomic stamped: " + name, e);
throw e;
}
}
}, cctx);
}
catch (Exception e) {
throw new GridException("Failed to get atomic stamped by name: " + name, e);
}
}
/**
* Removes atomic stamped from cache.
*
* @param name Atomic stamped name.
* @return Method returns {@code true} if atomic stamped has been removed and {@code false} if it's not cached.
* @throws GridException If removing failed.
*/
public final boolean removeAtomicStamped(String name) throws GridException {
waitInitialization();
checkTransactionalWithNear();
try {
GridCacheInternal key = new GridCacheInternalKeyImpl(name);
return removeInternal(key, GridCacheAtomicStampedValue.class);
}
catch (Exception e) {
throw new GridException("Failed to remove atomic stamped by name: " + name, e);
}
}
/**
* Gets a queue from cache or creates one if it's not cached.
*
* @param name Name of queue.
* @param cap Max size of queue.
* @param colloc Collocation flag.
* @param create If {@code true} queue will be created in case it is not in cache.
* @return Instance of queue.
* @throws GridException If failed.
*/
public final <T> GridCacheQueue<T> queue(final String name, final int cap, boolean colloc,
final boolean create) throws GridException {
waitInitialization();
checkSupportsQueue();
// Non collocated mode enabled only for PARTITIONED cache.
final boolean collocMode = cctx.cache().configuration().getCacheMode() != PARTITIONED || colloc;
if (cctx.atomic())
return queue0(name, cap, collocMode, create);
return CU.outTx(new Callable<GridCacheQueue<T>>() {
@Override public GridCacheQueue<T> call() throws Exception {
return queue0(name, cap, collocMode, create);
}
}, cctx);
}
/**
* Gets or creates queue.
*
* @param name Queue name.
* @param cap Capacity.
* @param colloc Collocation flag.
* @param create If {@code true} queue will be created in case it is not in cache.
* @return Queue.
* @throws GridException If failed.
*/
@SuppressWarnings({"unchecked", "NonPrivateFieldAccessedInSynchronizedContext"})
private <T> GridCacheQueue<T> queue0(final String name, final int cap, boolean colloc, final boolean create)
throws GridException {
GridCacheQueueHeaderKey key = new GridCacheQueueHeaderKey(name);
GridCacheQueueHeader header;
if (create) {
header = new GridCacheQueueHeader(GridUuid.randomUuid(), cap, colloc, 0, 0, null);
GridCacheQueueHeader old = queueHdrView.putIfAbsent(key, header);
if (old != null) {
if (old.capacity() != cap || old.collocated() != colloc)
throw new GridException("Failed to create queue, queue with the same name but different " +
"configuration already exists [name=" + name + ']');
header = old;
}
}
else
header = queueHdrView.get(key);
if (header == null)
return null;
if (queueQryGuard.compareAndSet(false, true)) {
queueQry = (GridCacheContinuousQueryAdapter)cctx.cache().queries().createContinuousQuery();
queueQry.filter(new QueueHeaderPredicate());
queueQry.callback(new GridBiPredicate<UUID, Collection<Map.Entry>>() {
@Override public boolean apply(UUID id, Collection<Map.Entry> entries) {
if (!busyLock.enterBusy())
return false;
try {
for (Map.Entry e : entries) {
GridCacheQueueHeaderKey key = (GridCacheQueueHeaderKey)e.getKey();
GridCacheQueueHeader hdr = (GridCacheQueueHeader)e.getValue();
for (final GridCacheQueueProxy queue : queuesMap.values()) {
if (queue.name().equals(key.queueName())) {
if (hdr == null) {
/*
* Potentially there can be queues with the same names, need to check that
* queue was really removed.
*/
cctx.closures().callLocalSafe(new Callable<Void>() {
@Override public Void call() throws Exception {
if (!busyLock.enterBusy())
return null;
try {
queue.size();
}
catch (GridCacheDataStructureRemovedRuntimeException ignore) {
queuesMap.remove(queue.delegate().id());
}
finally {
busyLock.leaveBusy();
}
return null;
}
}, false);
}
else
queue.delegate().onHeaderChanged(hdr);
}
}
}
return true;
}
finally {
busyLock.leaveBusy();
}
}
});
queueQry.execute(cctx.isLocal() || cctx.isReplicated() ? cctx.grid().forLocal() : null, true);
}
GridCacheQueueProxy queue = queuesMap.get(header.id());
if (queue == null) {
queue = new GridCacheQueueProxy(cctx, cctx.atomic() ? new GridAtomicCacheQueueImpl<>(name, header, cctx) :
new GridTransactionalCacheQueueImpl<>(name, header, cctx));
GridCacheQueueProxy old = queuesMap.putIfAbsent(header.id(), queue);
if (old != null)
queue = old;
}
return queue;
}
/**
* Removes queue from cache.
*
* @param name Queue name.
* @param batchSize Batch size.
* @return Method returns {@code true} if queue has been removed and {@code false} if it's not cached.
* @throws GridException If removing failed.
*/
public final boolean removeQueue(final String name, final int batchSize) throws GridException {
waitInitialization();
checkSupportsQueue();
if (cctx.atomic())
return removeQueue0(name, batchSize);
return CU.outTx(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
return removeQueue0(name, batchSize);
}
}, cctx);
}
/**
* @param name Queue name.
* @param batchSize Batch size.
* @return {@code True} if queue was removed.
* @throws GridException If failed.
*/
private boolean removeQueue0(String name, final int batchSize) throws GridException {
GridCacheQueueHeader hdr = queueHdrView.remove(new GridCacheQueueHeaderKey(name));
if (hdr == null)
return false;
if (hdr.empty())
return true;
GridCacheQueueAdapter.removeKeys(cctx.cache(), hdr.id(), name, hdr.collocated(), hdr.head(), hdr.tail(),
batchSize);
return true;
}
/**
* Gets or creates count down latch. If count down latch is not found in cache,
* it is created using provided name and count parameter.
* <p>
*
* @param name Name of the latch.
* @param cnt Initial count.
* @param autoDel {@code True} to automatically delete latch from cache when
* its count reaches zero.
* @param create If {@code true} latch will be created in case it is not in cache,
* if it is {@code false} all parameters except {@code name} are ignored.
* @return Count down latch for the given name or {@code null} if it is not found and
* {@code create} is false.
* @throws GridException If operation failed.
*/
public GridCacheCountDownLatch countDownLatch(final String name, final int cnt, final boolean autoDel,
final boolean create) throws GridException {
A.ensure(cnt >= 0, "count can not be negative");
waitInitialization();
checkTransactionalWithNear();
final GridCacheInternalKey key = new GridCacheInternalKeyImpl(name);
try {
// Check type of structure received by key from local cache.
GridCacheCountDownLatch latch = cast(dsMap.get(key), GridCacheCountDownLatch.class);
if (latch != null)
return latch;
return CU.outTx(new Callable<GridCacheCountDownLatch>() {
@Override public GridCacheCountDownLatch call() throws Exception {
try (GridCacheTx tx = CU.txStartInternal(cctx, dsView, PESSIMISTIC, REPEATABLE_READ)) {
GridCacheCountDownLatchValue val = cast(dsView.get(key),
GridCacheCountDownLatchValue.class);
// Check that count down hasn't been created in other thread yet.
GridCacheCountDownLatchEx latch = cast(dsMap.get(key), GridCacheCountDownLatchEx.class);
if (latch != null) {
assert val != null;
return latch;
}
if (val == null && !create)
return null;
if (val == null) {
val = new GridCacheCountDownLatchValue(cnt, autoDel);
dsView.putx(key, val);
}
latch = new GridCacheCountDownLatchImpl(name, val.get(), val.initialCount(),
val.autoDelete(), key, cntDownLatchView, cctx);
dsMap.put(key, latch);
tx.commit();
return latch;
}
catch (Error | Exception e) {
dsMap.remove(key);
U.error(log, "Failed to create count down latch: " + name, e);
throw e;
}
}
}, cctx);
}
catch (Exception e) {
throw new GridException("Failed to get count down latch by name: " + name, e);
}
}
/**
* Removes count down latch from cache.
*
* @param name Name of the latch.
* @return Count down latch for the given name.
* @throws GridException If operation failed.
*/
public boolean removeCountDownLatch(final String name) throws GridException {
waitInitialization();
checkTransactionalWithNear();
try {
return CU.outTx(
new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
GridCacheInternal key = new GridCacheInternalKeyImpl(name);
try (GridCacheTx tx = CU.txStartInternal(cctx, dsView, PESSIMISTIC, REPEATABLE_READ)) {
// Check correctness type of removable object.
GridCacheCountDownLatchValue val =
cast(dsView.get(key), GridCacheCountDownLatchValue.class);
if (val != null) {
if (val.get() > 0) {
throw new GridException("Failed to remove count down latch " +
"with non-zero count: " + val.get());
}
dsView.removex(key);
tx.commit();
}
else
tx.setRollbackOnly();
return val != null;
}
catch (Error | Exception e) {
U.error(log, "Failed to remove data structure: " + key, e);
throw e;
}
}
},
cctx
);
}
catch (Exception e) {
throw new GridException("Failed to remove count down latch by name: " + name, e);
}
}
/**
* Remove internal entry by key from cache.
*
* @param key Internal entry key.
* @param cls Class of object which will be removed. If cached object has different type exception will be thrown.
* @return Method returns true if sequence has been removed and false if it's not cached.
* @throws GridException If removing failed or class of object is different to expected class.
*/
private <R> boolean removeInternal(final GridCacheInternal key, final Class<R> cls) throws GridException {
return CU.outTx(
new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
try (GridCacheTx tx = CU.txStartInternal(cctx, dsView, PESSIMISTIC, REPEATABLE_READ)) {
// Check correctness type of removable object.
R val = cast(dsView.get(key), cls);
if (val != null) {
dsView.removex(key);
tx.commit();
}
else
tx.setRollbackOnly();
return val != null;
}
catch (Error | Exception e) {
U.error(log, "Failed to remove data structure: " + key, e);
throw e;
}
}
},
cctx
);
}
/**
* Transaction committed callback for transaction manager.
*
* @param tx Committed transaction.
*/
public void onTxCommitted(GridCacheTxEx<K, V> tx) {
if (!cctx.isDht() && tx.internal() && (!cctx.isColocated() || cctx.isReplicated())) {
try {
waitInitialization();
}
catch (GridException e) {
U.error(log, "Failed to wait for manager initialization.", e);
return;
}
Collection<GridCacheTxEntry<K, V>> entries = tx.writeEntries();
if (log.isDebugEnabled())
log.debug("Committed entries: " + entries);
for (GridCacheTxEntry<K, V> entry : entries) {
// Check updated or created GridCacheInternalKey keys.
if ((entry.op() == CREATE || entry.op() == UPDATE) && entry.key() instanceof GridCacheInternalKey) {
GridCacheInternal key = (GridCacheInternal)entry.key();
if (entry.value() instanceof GridCacheCountDownLatchValue) {
// Notify latch on changes.
GridCacheRemovable latch = dsMap.get(key);
GridCacheCountDownLatchValue val = (GridCacheCountDownLatchValue)entry.value();
if (latch instanceof GridCacheCountDownLatchEx) {
GridCacheCountDownLatchEx latch0 = (GridCacheCountDownLatchEx)latch;
latch0.onUpdate(val.get());
if (val.get() == 0 && val.autoDelete()) {
entry.cached().markObsolete(cctx.versions().next());
dsMap.remove(key);
latch.onRemoved();
}
}
else if (latch != null) {
U.error(log, "Failed to cast object " +
"[expected=" + GridCacheCountDownLatch.class.getSimpleName() +
", actual=" + latch.getClass() + ", value=" + latch + ']');
}
}
}
// Check deleted GridCacheInternal keys.
if (entry.op() == DELETE && entry.key() instanceof GridCacheInternal) {
GridCacheInternal key = (GridCacheInternal)entry.key();
// Entry's val is null if entry deleted.
GridCacheRemovable obj = dsMap.remove(key);
if (obj != null)
obj.onRemoved();
}
}
}
}
/**
* @throws GridException If thread is interrupted or manager
* was not successfully initialized.
*/
private void waitInitialization() throws GridException {
if (initLatch.getCount() > 0)
U.await(initLatch);
if (!initFlag)
throw new GridException("DataStructures manager was not properly initialized for cache: " +
cctx.cache().name());
}
/**
* @return {@code True} if cache is transactional with near cache enabled.
*/
private boolean transactionalWithNear() {
return cctx.transactional() && (CU.isNearEnabled(cctx) || cctx.isReplicated() || cctx.isLocal());
}
/**
* @return {@code True} if {@link GridCacheQueue} can be used with current cache configuration.
*/
private boolean supportsQueue() {
return !(cctx.atomic() && !cctx.isLocal() && cctx.config().getAtomicWriteOrderMode() == CLOCK);
}
/**
* @throws GridException If {@link GridCacheQueue} can not be used with current cache configuration.
*/
private void checkSupportsQueue() throws GridException {
if (cctx.atomic() && !cctx.isLocal() && cctx.config().getAtomicWriteOrderMode() == CLOCK)
throw new GridException("GridCacheQueue can not be used with ATOMIC cache with CLOCK write order mode" +
" (change write order mode to PRIMARY in configuration)");
}
/**
* @throws GridException If cache is not transactional with near cache enabled.
*/
private void checkTransactionalWithNear() throws GridException {
if (cctx.atomic())
throw new GridException("Data structures require GridCacheAtomicityMode.TRANSACTIONAL atomicity mode " +
"(change atomicity mode from ATOMIC to TRANSACTIONAL in configuration)");
if (!cctx.isReplicated() && !cctx.isLocal() && !CU.isNearEnabled(cctx))
throw new GridException("Cache data structures can not be used with near cache disabled on cache: " +
cctx.cache().name());
}
/**
* Gets a set from cache or creates one if it's not cached.
*
* @param name Set name.
* @param collocated Collocation flag.
* @param create If {@code true} set will be created in case it is not in cache.
* @return Set instance.
* @throws GridException If failed.
*/
@Nullable public <T> GridCacheSet<T> set(final String name, boolean collocated, final boolean create)
throws GridException {
waitInitialization();
// Non collocated mode enabled only for PARTITIONED cache.
final boolean collocMode = cctx.cache().configuration().getCacheMode() != PARTITIONED || collocated;
if (cctx.atomic())
return set0(name, collocMode, create);
return CU.outTx(new Callable<GridCacheSet<T>>() {
@Nullable @Override public GridCacheSet<T> call() throws Exception {
return set0(name, collocMode, create);
}
}, cctx);
}
/**
* Removes set.
*
* @param name Set name.
* @return {@code True} if set was removed.
* @throws GridException If failed.
*/
public boolean removeSet(final String name) throws GridException {
waitInitialization();
if (cctx.atomic())
return removeSet0(name);
return CU.outTx(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
return removeSet0(name);
}
}, cctx);
}
/**
* Entry update callback.
*
* @param key Key.
* @param rmv {@code True} if entry was removed.
*/
public void onEntryUpdated(K key, boolean rmv) {
if (key instanceof GridCacheSetItemKey)
onSetItemUpdated((GridCacheSetItemKey)key, rmv);
}
/**
* Partition evicted callback.
*
* @param part Partition number.
*/
public void onPartitionEvicted(int part) {
GridCacheAffinityManager aff = cctx.affinity();
for (GridConcurrentHashSet<GridCacheSetItemKey> set : setDataMap.values()) {
Iterator<GridCacheSetItemKey> iter = set.iterator();
while (iter.hasNext()) {
GridCacheSetItemKey key = iter.next();
if (aff.partition(key) == part)
iter.remove();
}
}
}
/**
* @param id Set ID.
* @return Data for given set.
*/
@Nullable public GridConcurrentHashSet<GridCacheSetItemKey> setData(GridUuid id) {
return setDataMap.get(id);
}
/**
* @param key Set item key.
* @param rmv {@code True} if item was removed.
*/
private void onSetItemUpdated(GridCacheSetItemKey key, boolean rmv) {
GridConcurrentHashSet<GridCacheSetItemKey> set = setDataMap.get(key.setId());
if (set == null) {
if (rmv)
return;
GridConcurrentHashSet<GridCacheSetItemKey> old = setDataMap.putIfAbsent(key.setId(),
set = new GridConcurrentHashSet<>());
if (old != null)
set = old;
}
if (rmv)
set.remove(key);
else
set.add(key);
}
/**
* @param name Name of set.
* @param collocated Collocation flag.
* @param create If {@code true} set will be created in case it is not in cache.
* @return Set.
* @throws GridException If failed.
*/
@SuppressWarnings("unchecked")
@Nullable private <T> GridCacheSet<T> set0(String name, boolean collocated, boolean create) throws GridException {
GridCacheSetHeaderKey key = new GridCacheSetHeaderKey(name);
GridCacheSetHeader hdr;
GridCacheAdapter cache = cctx.cache();
if (create) {
hdr = new GridCacheSetHeader(GridUuid.randomUuid(), collocated);
GridCacheSetHeader old = retryPutIfAbsent(cache, key, hdr);
if (old != null)
hdr = old;
}
else
hdr = (GridCacheSetHeader)cache.get(key);
if (hdr == null)
return null;
GridCacheSetProxy<T> set = setsMap.get(hdr.id());
if (set == null) {
GridCacheSetProxy<T> old = setsMap.putIfAbsent(hdr.id(),
set = new GridCacheSetProxy<>(cctx, new GridCacheSetImpl<T>(cctx, name, hdr)));
if (old != null)
set = old;
}
return set;
}
/**
* @param name Set name.
* @return {@code True} if set was removed.
* @throws GridException If failed.
*/
@SuppressWarnings("unchecked")
private boolean removeSet0(String name) throws GridException {
GridCacheSetHeaderKey key = new GridCacheSetHeaderKey(name);
GridCache cache = cctx.cache();
GridCacheSetHeader hdr = retryRemove(cache, key);
if (hdr == null)
return false;
if (!cctx.isLocal()) {
while (true) {
long topVer = cctx.topologyVersionFuture().get();
Collection<GridNode> nodes = CU.affinityNodes(cctx, topVer);
try {
cctx.closures().callAsyncNoFailover(BROADCAST,
new BlockSetCallable(cctx.name(), hdr.id()),
nodes,
true).get();
}
catch (GridTopologyException e) {
if (log.isDebugEnabled())
log.debug("BlockSet job failed, will retry: " + e);
continue;
}
try {
cctx.closures().callAsyncNoFailover(BROADCAST,
new RemoveSetDataCallable(cctx.name(), hdr.id(), topVer),
nodes,
true).get();
}
catch (GridTopologyException e) {
if (log.isDebugEnabled())
log.debug("RemoveSetData job failed, will retry: " + e);
continue;
}
if (cctx.topologyVersionFuture().get() == topVer)
break;
}
}
else {
blockSet(hdr.id());
removeSetData(hdr.id(), 0);
}
return true;
}
/**
* @param setId Set ID.
*/
@SuppressWarnings("unchecked")
private void blockSet(GridUuid setId) {
GridCacheSetProxy set = setsMap.remove(setId);
if (set != null)
set.blockOnRemove();
}
/**
* @param setId Set ID.
* @param topVer Topology version.
* @throws GridException If failed.
*/
@SuppressWarnings("unchecked")
private void removeSetData(GridUuid setId, long topVer) throws GridException {
boolean local = cctx.isLocal();
GridCacheAffinityManager aff = cctx.affinity();
if (!local) {
aff.affinityReadyFuture(topVer).get();
cctx.preloader().syncFuture().get();
}
GridConcurrentHashSet<GridCacheSetItemKey> set = setDataMap.get(setId);
if (set == null)
return;
GridCache cache = cctx.cache();
final int BATCH_SIZE = 100;
Collection<GridCacheSetItemKey> keys = new ArrayList<>(BATCH_SIZE);
for (GridCacheSetItemKey key : set) {
if (!local && !aff.primary(cctx.localNode(), key, topVer))
continue;
keys.add(key);
if (keys.size() == BATCH_SIZE) {
retryRemove(cache, keys);
keys.clear();
}
}
if (!keys.isEmpty())
retryRemove(cache, keys);
setDataMap.remove(setId);
}
/**
* @param cache Cache.
* @param keys Keys to remove.
* @throws GridException If failed.
*/
@SuppressWarnings("unchecked")
private void retryRemove(GridCache cache, Collection<GridCacheSetItemKey> keys) throws GridException {
int cnt = 0;
while (true) {
try {
cache.removeAll(keys);
break;
}
catch (GridCacheTxRollbackException | GridCachePartialUpdateException | GridTopologyException e) {
if (cnt++ == 3)
throw e;
else if (log.isDebugEnabled())
log.debug("Failed to remove set items, will retry [err=" + e + ']');
}
}
}
/**
* @param cache Cache.
* @param key Key.
* @param val Value.
* @throws GridException If failed.
* @return Previous value.
*/
@SuppressWarnings("unchecked")
@Nullable private <T> T retryPutIfAbsent(GridCache cache, Object key, T val) throws GridException {
int cnt = 0;
while (true) {
try {
return (T)cache.putIfAbsent(key, val);
}
catch (GridCacheTxRollbackException | GridCachePartialUpdateException | GridTopologyException e) {
if (cnt++ == 3)
throw e;
else if (log.isDebugEnabled())
log.debug("Failed to create cache item, will retry [err=" + e + ']');
}
}
}
/**
* @param cache Cache.
* @param key Key to remove.
* @throws GridException If failed.
* @return Removed value.
*/
@SuppressWarnings("unchecked")
@Nullable private <T> T retryRemove(GridCache cache, Object key) throws GridException {
int cnt = 0;
while (true) {
try {
return (T)cache.remove(key);
}
catch (GridCacheTxRollbackException | GridCachePartialUpdateException | GridTopologyException e) {
if (cnt++ == 3)
throw e;
else if (log.isDebugEnabled())
log.debug("Failed to remove cache item, will retry [err=" + e + ']');
}
}
}
/**
* Tries to cast the object to expected type.
*
* @param obj Object which will be casted.
* @param cls Class
* @param <R> Type of expected result.
* @return Object has casted to expected type.
* @throws GridException If {@code obj} has different to {@code cls} type.
*/
@SuppressWarnings("unchecked")
@Nullable private <R> R cast(@Nullable Object obj, Class<R> cls) throws GridException {
if (obj == null)
return null;
if (cls.isInstance(obj))
return (R)obj;
else
throw new GridException("Failed to cast object [expected=" + cls + ", actual=" + obj.getClass() + ']');
}
/** {@inheritDoc} */
@Override public void printMemoryStats() {
X.println(">>> ");
X.println(">>> Data structure manager memory stats [grid=" + cctx.gridName() + ", cache=" + cctx.name() + ']');
X.println(">>> dsMapSize: " + dsMap.size());
}
/**
* Predicate for queue continuous query.
*/
private static class QueueHeaderPredicate implements GridBiPredicate, Externalizable {
private static final long serialVersionUID = 0L;
/**
* Required by {@link Externalizable}.
*/
public QueueHeaderPredicate() {
// No-op.
}
/** {@inheritDoc} */
@Override public boolean apply(Object key, Object val) {
return key instanceof GridCacheQueueHeaderKey;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) {
// No-op.
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) {
// No-op.
}
}
/**
* Waits for completion of all started set operations and blocks all subsequent operations.
*/
@GridInternal
private static class BlockSetCallable implements Callable<Void>, Externalizable {
private static final long serialVersionUID = -8892474927216478231L;
/** Injected grid instance. */
@GridInstanceResource
private Grid grid;
private String cacheName;
private GridUuid setId;
/**
* Required by {@link Externalizable}.
*/
public BlockSetCallable() {
// No-op.
}
/**
* @param cacheName Cache name.
* @param setId Set ID.
*/
private BlockSetCallable(String cacheName, GridUuid setId) {
this.cacheName = cacheName;
this.setId = setId;
}
/** {@inheritDoc} */
@Override public Void call() throws GridException {
GridCacheAdapter cache = ((GridKernal)grid).context().cache().internalCache(cacheName);
assert cache != null;
cache.context().dataStructures().blockSet(setId);
return null;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeString(out, cacheName);
U.writeGridUuid(out, setId);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
cacheName = U.readString(in);
setId = U.readGridUuid(in);
}
/** {@inheritDoc} */
@Override public String toString() {
return "BlockSetCallable [setId=" + setId + ']';
}
}
/**
* Removes set items.
*/
@GridInternal
private static class RemoveSetDataCallable implements Callable<Void>, Externalizable {
private static final long serialVersionUID = 5053205121218843148L;
/** Injected grid instance. */
@GridInstanceResource
private Grid grid;
private String cacheName;
private GridUuid setId;
private long topVer;
/**
* Required by {@link Externalizable}.
*/
public RemoveSetDataCallable() {
// No-op.
}
/**
* @param cacheName Cache name.
* @param setId Set ID.
* @param topVer Topology version.
*/
private RemoveSetDataCallable(String cacheName, GridUuid setId, long topVer) {
this.cacheName = cacheName;
this.setId = setId;
this.topVer = topVer;
}
/** {@inheritDoc} */
@Override public Void call() throws GridException {
GridCacheAdapter cache = ((GridKernal)grid).context().cache().internalCache(cacheName);
assert cache != null;
cache.context().dataStructures().removeSetData(setId, topVer);
return null;
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeString(out, cacheName);
U.writeGridUuid(out, setId);
out.writeLong(topVer);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
cacheName = U.readString(in);
setId = U.readGridUuid(in);
topVer = in.readLong();
}
/** {@inheritDoc} */
@Override public String toString() {
return "RemoveSetCallable [setId=" + setId + ']';
}
}
}
|
package net.nemerosa.ontrack.extension.issues.support;
import net.nemerosa.ontrack.extension.api.model.IssueChangeLogExportRequest;
import net.nemerosa.ontrack.extension.issues.IssueServiceExtension;
import net.nemerosa.ontrack.extension.issues.export.ExportFormat;
import net.nemerosa.ontrack.extension.issues.export.ExportedIssues;
import net.nemerosa.ontrack.extension.issues.export.IssueExportService;
import net.nemerosa.ontrack.extension.issues.export.IssueExportServiceFactory;
import net.nemerosa.ontrack.extension.issues.model.Issue;
import net.nemerosa.ontrack.extension.issues.model.IssueServiceConfiguration;
import net.nemerosa.ontrack.extension.support.AbstractExtension;
import net.nemerosa.ontrack.model.extension.ExtensionFeature;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static net.nemerosa.ontrack.extension.issues.support.IssueServiceUtils.groupIssues;
/**
* Convenient implementation for most of the issue services.
*/
public abstract class AbstractIssueServiceExtension extends AbstractExtension implements IssueServiceExtension {
private final String id;
private final String name;
private final IssueExportServiceFactory issueExportServiceFactory;
/**
* Constructor.
*
* @param id The unique ID for this service.
* @param name The display name for this service.
* @param issueExportServiceFactory Factory to get export services
*/
protected AbstractIssueServiceExtension(ExtensionFeature extensionFeature, String id, String name, IssueExportServiceFactory issueExportServiceFactory) {
super(extensionFeature);
this.id = id;
this.name = name;
this.issueExportServiceFactory = issueExportServiceFactory;
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public boolean containsIssueKey(IssueServiceConfiguration issueServiceConfiguration, String key, Set<String> keys) {
return keys.contains(key);
}
/**
* Export of both text and HTML by default.
*/
@Override
public List<ExportFormat> exportFormats(IssueServiceConfiguration issueServiceConfiguration) {
return issueExportServiceFactory.getIssueExportServices().stream()
.map(IssueExportService::getExportFormat)
.collect(Collectors.toList());
}
@Override
public ExportedIssues exportIssues(IssueServiceConfiguration issueServiceConfiguration, List<? extends Issue> issues, IssueChangeLogExportRequest request) {
// Grouping of issues (or not)
Map<String, List<Issue>> groupedIssues = groupIssues(
issueServiceConfiguration,
issues,
request,
this::getIssueTypes
);
// Export service
IssueExportService exportService = issueExportServiceFactory.getIssueExportService(request.getFormat());
// Exporting
return exportService.export(
this,
issueServiceConfiguration,
groupedIssues
);
}
@Override
public String getMessageRegex(IssueServiceConfiguration issueServiceConfiguration, Issue issue) {
String displayKey = issue.getDisplayKey();
return "(?:\\s|^)(" + displayKey + ")(?:[^\\d]|$)";
}
protected abstract Set<String> getIssueTypes(IssueServiceConfiguration issueServiceConfiguration, Issue issue);
}
|
package org.sonatype.guice.bean.locators;
import java.lang.annotation.Annotation;
import javax.inject.Provider;
import org.sonatype.inject.BeanEntry;
import org.sonatype.inject.Description;
import com.google.inject.Binding;
import com.google.inject.Scopes;
/**
* Lazy {@link BeanEntry} backed by a qualified {@link Binding} and an assigned rank.
*/
final class LazyBeanEntry<Q extends Annotation, T>
implements BeanEntry<Q, T>
{
// Implementation fields
private final Q qualifier;
final Binding<T> binding;
private final Provider<T> provider;
private final int rank;
// Constructors
@SuppressWarnings( "unchecked" )
LazyBeanEntry( final Q qualifier, final Binding<T> binding, final int rank )
{
if ( null != qualifier && com.google.inject.name.Named.class == qualifier.annotationType() )
{
this.qualifier = (Q) new JsrNamed( (com.google.inject.name.Named) qualifier );
}
else
{
this.qualifier = qualifier;
}
this.binding = binding;
this.rank = rank;
if ( Scopes.isSingleton( binding ) )
{
this.provider = binding.getProvider();
}
else
{
// use Guice's singleton logic to get lazy-loading without introducing extra locks
this.provider = Scopes.SINGLETON.scope( binding.getKey(), binding.getProvider() );
}
}
// Public methods
public Q getKey()
{
return qualifier;
}
public T getValue()
{
return provider.get();
}
public T setValue( final T value )
{
throw new UnsupportedOperationException();
}
public Provider<T> getProvider()
{
return binding.getProvider();
}
public String getDescription()
{
final Object source = binding.getSource();
if ( source instanceof BeanDescription )
{
return ( (BeanDescription) source ).getDescription();
}
final Class<T> clazz = getImplementationClass();
if ( null != clazz )
{
final Description description = clazz.getAnnotation( Description.class );
if ( null != description )
{
return description.value();
}
}
return null;
}
@SuppressWarnings( "unchecked" )
public Class<T> getImplementationClass()
{
return (Class<T>) binding.acceptTargetVisitor( ImplementationVisitor.THIS );
}
public Object getSource()
{
return binding.getSource();
}
public int getRank()
{
return rank;
}
@Override
public String toString()
{
final StringBuilder buf = new StringBuilder().append( getKey() ).append( '=' );
try
{
buf.append( getValue() );
}
catch ( final Throwable e )
{
buf.append( e );
}
return buf.toString();
}
// Implementation types
/**
* Implementation of @{@link javax.inject.Named} that can also act like @{@link com.google.inject.name.Named}.
*/
private static final class JsrNamed
implements com.google.inject.name.Named, javax.inject.Named
{
// Implementation fields
private final String value;
// Constructors
JsrNamed( final com.google.inject.name.Named named )
{
value = named.value();
}
// Public methods
public String value()
{
return value;
}
public Class<? extends Annotation> annotationType()
{
return javax.inject.Named.class;
}
@Override
public int hashCode()
{
return 127 * "value".hashCode() ^ value.hashCode();
}
@Override
public boolean equals( final Object rhs )
{
if ( this == rhs )
{
return true;
}
if ( rhs instanceof com.google.inject.name.Named )
{
return value.equals( ( (com.google.inject.name.Named) rhs ).value() );
}
if ( rhs instanceof javax.inject.Named )
{
return value.equals( ( (javax.inject.Named) rhs ).value() );
}
return false;
}
@Override
public String toString()
{
return "@" + javax.inject.Named.class.getName() + "(value=" + value + ")";
}
}
}
|
package pl.softwaremill.common.test.web.jboss;
import org.apache.commons.io.FileUtils;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import pl.softwaremill.common.test.web.selenium.ServerProperties;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @author maciek
* @author Pawel Wrzeszcz
* @author Jaroslaw Kijanowski
* @author Pawel Stawicki
*/
public abstract class AbstractJBossRunner {
private String serverHome;
private String configuration;
private boolean running;
private int portset;
private String additionalSystemProperties;
private int asVersion;
private boolean secured;
private String username;
private String password;
Process jbossProcess;
protected final static SysoutLog log = new SysoutLog();
private static final String STARTED_LOG_MESSAGE = "Started in";
private boolean deploymentComplete = false;
private static final int MILLISECONDS_IN_MINUTE = 60 * 1000;
protected abstract ServerProperties getServerProperties();
protected abstract Deployment[] getDeployments();
private Process tailProcess;
@BeforeSuite
public void start() throws Exception {
loadProperties();
scheduleTimeout();
undeploy(); // Clean old deployments
startServerIfNeeded();
deploy();
}
@AfterSuite(alwaysRun = true)
public void shutdown() throws Exception {
undeploy();
if (!running) {
log.info("Stopping JBoss server");
shutdownServer();
log.info("JBoss Server stopped");
}
publishLog();
}
private void loadProperties() {
ServerProperties serverProperties = getServerProperties();
this.serverHome = serverProperties.getServerHome();
this.configuration = serverProperties.getConfiguration();
this.running = serverProperties.isRunning();
this.portset = serverProperties.getPortset();
this.additionalSystemProperties = serverProperties.getAdditionalSystemProperties();
this.asVersion = serverProperties.getAsVersion();
this.secured = serverProperties.isSecured();
this.username = serverProperties.getUsername();
this.password = serverProperties.getPassword();
}
private void startServerIfNeeded() throws Exception {
if (!running) {
log.info("Starting JBoss server");
startServer();
log.info("JBoss started");
}
}
protected void startServer() throws Exception {
jbossProcess = Runtime.getRuntime().exec(new String[]{serverHome + createRunScript(), "-c", configuration,
createPortSetCommand(), additionalSystemProperties});
waitFor(jbossProcess, STARTED_LOG_MESSAGE);
tailProcess = jbossProcess;
}
private String createPortSetCommand() {
if (portset <= 0) {
return "";
}
return "-Djboss.service.binding.set=ports-0" + portset;
}
private String createRunScript() {
if (winSystem()) {
return "/bin/run.bat";
}
return "/bin/run.sh";
}
private boolean winSystem() {
String osName = System.getProperty("os.name");
return osName != null && osName.indexOf("Windows") != -1;
}
private void waitFor(Process process, String message) {
log.info("Waiting for message: [" + message + "]");
Scanner scanner = new Scanner(process.getInputStream()).useDelimiter(message);
scanner.next();
}
private Process getTailProcess() throws IOException {
if (tailProcess == null) {
// this happens when jboss was already started
tailProcess = Runtime.getRuntime().exec(
new String[]{"tail", "-f", getServerLogPath()});
}
return tailProcess;
}
protected String getServerLogPath() {
return serverHome + "/server/" + configuration + "/log/server.log";
}
protected void shutdownServer() throws IOException, InterruptedException {
List<String> paramList = new ArrayList<String>();
// bin/shutdown.{sh, bat}
paramList.add(getServerProperties().getServerHome() + createShutdownScript());
if(asVersion == 5){
// JBoss5
paramList.add("--server=localhost:1" + getServerProperties().getPortset() + "99");
} else {
// JBoss6 and above
paramList.add("--host=localhost");
paramList.add("--port=1" + getServerProperties().getPortset() + "90");
}
// shutdown
paramList.add("-S");
if(secured){
paramList.add("-u " + username);
paramList.add("-p " + password);
}
final Process shutdownProcess = Runtime.getRuntime().exec(paramList.toArray(new String[0]));
if (winSystem()) {
PrintWriter writer = new PrintWriter(shutdownProcess.getOutputStream());
try {
//On windows, user needs to press any key on the console
//for the process to exit. Wait a bit for message "Press any key"
waitFor(shutdownProcess, "Press any key to continue");
writer.write("y");
writer.flush();
} finally {
writer.close();
}
}
shutdownProcess.waitFor();
if (shutdownProcess.exitValue() != 0) {
log.info("Failed to stop JBoss");
} else {
//Make sure jboss shuts down before leaving this method.
jbossProcess.waitFor();
}
}
private String createShutdownScript() {
if (winSystem()) {
return "/bin/shutdown.bat";
}
return "/bin/shutdown.sh";
}
private void deploy() throws Exception {
for (Deployment deployment : getDeployments()) {
deployment.deploy(getDeployDir());
if (deployment.getWaitForMessage() != null) {
// waitFor(jbossProcess, deployment.getWaitForMessage());
waitFor(getTailProcess(), deployment.getWaitForMessage());
} else {
Thread.sleep(deployment.getWaitMillis());
}
}
deploymentComplete = true;
// close the tail process so it doesn't overload
tailProcess.getInputStream().close();
}
private void undeploy() throws Exception {
for (Deployment deployment : getDeployments()) {
deployment.undeploy(getDeployDir());
}
}
public String getDeployDir() {
return serverHome + "/server/" + configuration + "/deploy/";
}
protected static class SysoutLog {
public void info(String msg) {
System.out.println("--- " + msg);
}
}
private void scheduleTimeout() {
new Thread(
new Runnable() {
@Override
public void run() {
try {
Thread.sleep(((long) getServerProperties().getDeploymentTimeoutMinutes()) * MILLISECONDS_IN_MINUTE);
if (!deploymentComplete) {
System.out.println("Timeout, shutting down JBoss");
shutdown();
throw new RuntimeException("Timeout");
}
} catch (InterruptedException e) {
// do nothing
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
).start();
}
protected void publishLog() throws IOException {
File tmpLogFile = File.createTempFile("jboss_log", ".txt");
File log = new File(getServerLogPath());
FileUtils.copyFile(log, tmpLogFile);
System.out.println("##teamcity[publishArtifacts '" + tmpLogFile.getAbsolutePath() + "']");
deleteLog();
}
private void deleteLog() {
boolean deleted = new File(getServerLogPath()).delete();
if (!deleted) {
log.info("Unable to delete JBoss log");
}
}
}
|
package org.elasticsearch.xpack.security.transport.filter;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.http.HttpServerTransport;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
import org.elasticsearch.test.SecurityIntegTestCase;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.xpack.core.common.socket.SocketAccess;
import org.junit.BeforeClass;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.Matchers.is;
// no client nodes, no transport clients, as they all get rejected on network connections
@ClusterScope(scope = Scope.SUITE, numDataNodes = 0, numClientNodes = 0, transportClientRatio = 0.0)
public class IpFilteringIntegrationTests extends SecurityIntegTestCase {
private static int randomClientPort;
@BeforeClass
public static void getRandomPort() {
randomClientPort = randomIntBetween(49000, 65500); // ephemeral port
}
@Override
protected boolean addMockHttpTransport() {
return false; // enable http
}
@Override
protected Settings nodeSettings(int nodeOrdinal) {
String randomClientPortRange = randomClientPort + "-" + (randomClientPort+100);
return Settings.builder().put(super.nodeSettings(nodeOrdinal))
.put("transport.profiles.client.port", randomClientPortRange)
// make sure this is "localhost", no matter if ipv4 or ipv6, but be consistent
.put("transport.profiles.client.bind_host", "localhost")
.put("transport.profiles.client.xpack.security.filter.deny", "_all")
.put(IPFilter.TRANSPORT_FILTER_DENY_SETTING.getKey(), "_all")
.build();
}
public void testThatIpFilteringIsIntegratedIntoNettyPipelineViaHttp() throws Exception {
TransportAddress transportAddress =
randomFrom(internalCluster().getDataNodeInstance(HttpServerTransport.class).boundAddress().boundAddresses());
try (Socket socket = new Socket()){
trySocketConnection(socket, transportAddress.address());
assertThat(socket.isClosed(), is(true));
}
}
public void testThatIpFilteringIsNotAppliedForDefaultTransport() throws Exception {
Client client = internalCluster().transportClient();
assertGreenClusterState(client);
}
public void testThatIpFilteringIsAppliedForProfile() throws Exception {
try (Socket socket = new Socket()){
trySocketConnection(socket, getProfileAddress("client"));
assertThat(socket.isClosed(), is(true));
}
}
@SuppressForbidden(reason = "Allow opening socket for test")
private void trySocketConnection(Socket socket, InetSocketAddress address) throws IOException {
logger.info("connecting to {}", address);
SocketAccess.doPrivileged(() -> socket.connect(address, 500));
assertThat(socket.isConnected(), is(true));
try (OutputStream os = socket.getOutputStream()) {
os.write("fooooo".getBytes(StandardCharsets.UTF_8));
os.flush();
}
}
private static InetSocketAddress getProfileAddress(String profile) {
TransportAddress transportAddress =
randomFrom(internalCluster().getInstance(Transport.class).profileBoundAddresses().get(profile).boundAddresses());
return transportAddress.address();
}
}
|
package com.bluesnap.android.demoapp.BlueSnapCheckoutUITests.WebViewUITests;
import android.support.test.espresso.web.webdriver.DriverAtoms;
import android.support.test.espresso.web.webdriver.Locator;
import android.util.Log;
import com.bluesnap.android.demoapp.BlueSnapCheckoutUITests.CheckoutEspressoBasedTester;
import com.bluesnap.android.demoapp.BuildConfig;
import com.bluesnap.android.demoapp.R;
import com.bluesnap.android.demoapp.TestUtils;
import com.bluesnap.android.demoapp.TestingShopperCheckoutRequirements;
import com.bluesnap.androidapi.Constants;
import com.bluesnap.androidapi.http.BlueSnapHTTPResponse;
import com.bluesnap.androidapi.http.CustomHTTPParams;
import com.bluesnap.androidapi.http.HTTPOperationController;
import com.bluesnap.androidapi.models.SdkRequest;
import com.bluesnap.androidapi.models.SdkResult;
import com.bluesnap.androidapi.services.BSPaymentRequestException;
import com.bluesnap.androidapi.services.BlueSnapService;
import junit.framework.Assert;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.web.assertion.WebViewAssertions.webMatches;
import static android.support.test.espresso.web.model.Atoms.getCurrentUrl;
import static android.support.test.espresso.web.sugar.Web.onWebView;
import static android.support.test.espresso.web.webdriver.DriverAtoms.clearElement;
import static android.support.test.espresso.web.webdriver.DriverAtoms.findElement;
import static android.support.test.espresso.web.webdriver.DriverAtoms.webClick;
import static com.bluesnap.android.demoapp.DemoToken.SANDBOX_URL;
import static com.bluesnap.androidapi.utils.JsonParser.getOptionalString;
import static java.lang.Thread.sleep;
import static junit.framework.Assert.fail;
import static org.hamcrest.CoreMatchers.containsString;
public class PayPalWebViewTests extends CheckoutEspressoBasedTester {
private static final String TAG = PayPalWebViewTests.class.getSimpleName();
private BlueSnapService blueSnapService = BlueSnapService.getInstance();
private List<CustomHTTPParams> sahdboxHttpHeaders = uIAutoTestingBlueSnapService.getHttpParamsForSandboxTests();
private final String SANDBOX_RETRIEVE_PAYPAL_TRANSACTION = "alt-transactions/";
private final String SANDBOX_PAYPAL_EMAIL = BuildConfig.BS_PAYPAL_EMAIL;
private final String SANDBOX_PAYPAL_PASSWORD = BuildConfig.BS_PAYPAL_PASSWORD;
private String payPalInvoiceId;
private String retrieveTransactionResponse;
// @Rule
// public ActivityTestRule<WebViewActivity> mActivityRule =
// new ActivityTestRule<WebViewActivity>(WebViewActivity.class,
// false, false) {
// @Override
// protected void afterActivityLaunched() {
// onWebView().forceJavascriptEnabled();
protected void payPalCheckoutSetup() throws BSPaymentRequestException, InterruptedException, JSONException {
payPalCheckoutSetup("USD", checkoutCurrency);
}
protected void payPalCheckoutSetup(String merchantStoreCurrency, String checkoutCurrency) throws BSPaymentRequestException, InterruptedException, JSONException {
SdkRequest sdkRequest = new SdkRequest(purchaseAmount, checkoutCurrency);
uIAutoTestingBlueSnapService.setSdk(sdkRequest, shopperCheckoutRequirements);
uIAutoTestingBlueSnapService.setupAndLaunch(sdkRequest, merchantStoreCurrency);
}
public PayPalWebViewTests() {
shopperCheckoutRequirements = new TestingShopperCheckoutRequirements(false, false, false);
}
void payPalBasicTransaction() throws InterruptedException {
payPalBasicTransaction(true, checkoutCurrency, purchaseAmount);
}
public void payPalBasicTransaction(boolean pressPayPalButton, String checkoutCurrency, double purchaseAmount) throws InterruptedException {
loadPayPalWebView(pressPayPalButton);
loginToPayPal();
submitPayPalPayment();
SdkResult sdkResult = blueSnapService.getSdkResult();
//wait for transaction to finish
while ((payPalInvoiceId = sdkResult.getPaypalInvoiceId()) == null)
sleep(5000);
//verify transaction status
retrievePayPalTransaction(checkoutCurrency, purchaseAmount);
}
void loadPayPalWebView() throws InterruptedException {
loadPayPalWebView(true);
}
void loadPayPalWebView(boolean pressPayPalButton) throws InterruptedException {
if (pressPayPalButton)
onView(withId(R.id.payPalButton)).perform(click());
//wait for web to load
sleep(20000);
//verify that paypal url opened up
onWebView().check(webMatches(getCurrentUrl(), containsString(Constants.getPaypalSandUrl())));
// onWebView().forceJavascriptEnabled();
}
public void loginToPayPal() throws InterruptedException {
try {
// onWebView()
// .check(webContent(hasElementWithId("email")));
onWebView()
.withElement(findElement(Locator.ID, "email")) // similar to onView(withId(...))
.perform(clearElement())
.perform(DriverAtoms.webKeys(SANDBOX_PAYPAL_EMAIL))
.withElement(findElement(Locator.ID, "btnNext"))
.perform(webClick());
sleep(6000);
} catch (Exception e) {
Log.d(TAG, "Email is already filled in");
}
try {
onWebView()
.withElement(findElement(Locator.ID, "password"))
.perform(clearElement())
.perform(DriverAtoms.webKeys(SANDBOX_PAYPAL_PASSWORD)) // Similar to perform(click())
.withElement(findElement(Locator.ID, "btnLogin"))
.perform(webClick());
} catch (Exception e) {
Log.d(TAG, "Password is already filled in");
}
//wait for login
sleep(30000);
}
public void submitPayPalPayment() throws InterruptedException {
// onWebView()
// .withElement(findElement(Locator.ID, "confirmButtonTop"))
// .perform(webClick());
onWebView()
.withElement(findElement(Locator.CLASS_NAME, "continueButton"))
.perform(webClick());
onWebView()
.withElement(findElement(Locator.CLASS_NAME, "continueButton"))
.perform(webClick());
}
public void updateCurrencyAndAmountAfterConversion(String oldCurrencyCode, String newCurrencyCode) {
checkoutCurrency = newCurrencyCode;
if (!oldCurrencyCode.equals("USD")) {
double conversionRateToUSD = blueSnapService.getsDKConfiguration().getRates().getCurrencyByCode(oldCurrencyCode).getConversionRate();
purchaseAmount = purchaseAmount / conversionRateToUSD;
}
double conversionRateFromUSD = blueSnapService.getsDKConfiguration().getRates().getCurrencyByCode(newCurrencyCode).getConversionRate();
uIAutoTestingBlueSnapService.setPurchaseAmount(uIAutoTestingBlueSnapService.getPurchaseAmount() / conversionRateFromUSD);
purchaseAmount = purchaseAmount * conversionRateFromUSD;
}
public void retrievePayPalTransaction(String checkoutCurrency, double purchaseAmount) {
retrievePayPalTransactionService(new RetrievePayPalTransactionInterface() {
@Override
public void onServiceSuccess() {
getTransactionStatus(checkoutCurrency, purchaseAmount);
}
@Override
public void onServiceFailure() {
fail("Cannot obtain transaction status from merchant server");
}
});
}
private void retrievePayPalTransactionService(final RetrievePayPalTransactionInterface retrievePayPalTransaction) {
BlueSnapHTTPResponse response = HTTPOperationController.get(SANDBOX_URL + SANDBOX_RETRIEVE_PAYPAL_TRANSACTION + payPalInvoiceId, "application/json", "application/json", sahdboxHttpHeaders);
if (response.getResponseCode() >= 200 && response.getResponseCode() < 300) {
retrieveTransactionResponse = response.getResponseString();
retrievePayPalTransaction.onServiceSuccess();
} else {
Log.e(TAG, response.getResponseCode() + " " + response.getErrorResponseString());
retrievePayPalTransaction.onServiceFailure();
}
}
private void getTransactionStatus(String checkoutCurrency, double purchaseAmount) {
try {
JSONObject jsonObject = new JSONObject(retrieveTransactionResponse);
JSONObject jsonObjectProcessingInfo = jsonObject.getJSONObject("processingInfo");
String transactionStatus = getOptionalString(jsonObjectProcessingInfo, "processingStatus");
Assert.assertEquals("PayPal transaction failed!", "SUCCESS", transactionStatus);
String transactionCurrency = getOptionalString(jsonObject, "currency");
Assert.assertEquals("Wrong transaction amount", checkoutCurrency, transactionCurrency);
String transactionAmount = getOptionalString(jsonObject, "amount");
Assert.assertEquals("Wrong transaction amount", TestUtils.round_amount(purchaseAmount), TestUtils.round_amount(Double.parseDouble(transactionAmount)));
} catch (JSONException e) {
e.printStackTrace();
fail("Error on parse transaction status");
}
}
}
|
package org.springframework.roo.addon.layers.repository;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.component.ComponentContext;
import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.customdata.taggers.CustomDataKeyDecorator;
import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails;
import org.springframework.roo.classpath.itd.AbstractItdMetadataProvider;
import org.springframework.roo.classpath.itd.ItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.classpath.layers.LayerCustomDataKeys;
import org.springframework.roo.classpath.layers.LayerTypeMatcher;
import org.springframework.roo.classpath.persistence.PersistenceMemberLocator;
import org.springframework.roo.classpath.scanner.MemberDetails;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.project.Path;
/**
* Provides the metadata for an ITD that implements a Spring Data JPA repository
*
* @author Stefan Schmidt
* @author Andrew Swan
* @since 1.2.0
*/
@Component(immediate = true)
@Service
public class RepositoryJpaMetadataProvider extends AbstractItdMetadataProvider {
// Constants
private static final JavaType ROO_REPOSITORY_JPA = new JavaType(RooRepositoryJpa.class);
// Fields
@Reference private CustomDataKeyDecorator customDataKeyDecorator;
@Reference private PersistenceMemberLocator persistenceMemberLocator;
@SuppressWarnings("unchecked")
protected void activate(final ComponentContext context) {
super.setDependsOnGovernorBeingAClass(false);
metadataDependencyRegistry.registerDependency(PhysicalTypeIdentifier.getMetadataIdentiferType(), getProvidesType());
addMetadataTrigger(ROO_REPOSITORY_JPA);
customDataKeyDecorator.registerMatchers(getClass(), new LayerTypeMatcher(LayerCustomDataKeys.LAYER_TYPE, RepositoryJpaMetadata.class, ROO_REPOSITORY_JPA, new JavaSymbolName(RooRepositoryJpa.DOMAIN_TYPE_ATTRIBUTE)));
}
protected void deactivate(final ComponentContext context) {
metadataDependencyRegistry.deregisterDependency(PhysicalTypeIdentifier.getMetadataIdentiferType(), getProvidesType());
removeMetadataTrigger(ROO_REPOSITORY_JPA);
customDataKeyDecorator.unregisterMatchers(getClass());
}
@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataId, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
final RepositoryJpaAnnotationValues annotationValues = new RepositoryJpaAnnotationValues(governorPhysicalTypeMetadata);
final ClassOrInterfaceTypeDetails coitd = (ClassOrInterfaceTypeDetails) governorPhysicalTypeMetadata.getMemberHoldingTypeDetails();
if (coitd == null) {
return null;
}
final JavaType domainType = annotationValues.getDomainType();
if (domainType == null) {
return null;
}
final JavaType idType = persistenceMemberLocator.getIdentifierType(domainType);
if (idType == null) {
return null;
}
metadataDependencyRegistry.registerDependency(PhysicalTypeIdentifier.createIdentifier(domainType, Path.SRC_MAIN_JAVA), metadataId);
final MemberDetails memberDetails = memberDetailsScanner.getMemberDetails(RepositoryJpaMetadataProvider.class.getName(), coitd);
return new RepositoryJpaMetadata(metadataId, aspectName, governorPhysicalTypeMetadata, memberDetails, idType, annotationValues);
}
public String getItdUniquenessFilenameSuffix() {
return "Jpa_Repository";
}
public String getProvidesType() {
return RepositoryJpaMetadata.getMetadataIdentiferType();
}
@Override
protected String createLocalIdentifier(final JavaType javaType, final Path path) {
return RepositoryJpaMetadata.createIdentifier(javaType, path);
}
@Override
protected String getGovernorPhysicalTypeIdentifier(final String metadataIdentificationString) {
final JavaType javaType = RepositoryJpaMetadata.getJavaType(metadataIdentificationString);
final Path path = RepositoryJpaMetadata.getPath(metadataIdentificationString);
return PhysicalTypeIdentifier.createIdentifier(javaType, path);
}
}
|
package org.openhab.binding.zwave.internal.protocol;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TooManyListenersException;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessageClass;
import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessagePriority;
import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessageType;
import org.openhab.binding.zwave.internal.protocol.NodeStage;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass.CommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClassDynamicState;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveMultiInstanceCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveWakeUpCommandClass;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveInclusionEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveInitializationCompletedEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveNetworkEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveNodeStatusEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveTransactionCompletedEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveNetworkEvent.State;
import org.openhab.binding.zwave.internal.protocol.initialization.ZWaveNodeSerializer;
import org.openhab.binding.zwave.internal.protocol.serialmessage.AddNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.AssignReturnRouteMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.AssignSucReturnRouteMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.DeleteReturnRouteMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.EnableSucMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.GetControllerCapabilitiesMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.GetSucNodeIdMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.IdentifyNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.IsFailedNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.RemoveNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.RequestNodeNeighborUpdateMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.RemoveFailedNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.RequestNodeInfoMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.GetRoutingInfoMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SendDataMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SerialApiSoftResetMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SetSucNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.ZWaveCommandProcessor;
import org.openhab.binding.zwave.internal.protocol.serialmessage.GetVersionMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.MemoryGetIdMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SerialApiGetCapabilitiesMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SerialApiGetInitDataMessageClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ZWave controller class. Implements communication with the Z-Wave
* controller stick using serial messages.
* @author Victor Belov
* @author Brian Crosby
* @author Chris Jackson
* @since 1.3.0
*/
public class ZWaveController {
private static final Logger logger = LoggerFactory.getLogger(ZWaveController.class);
private static final int QUERY_STAGE_TIMEOUT = 120000;
private static final int ZWAVE_RESPONSE_TIMEOUT = 5000; // 5000 ms ZWAVE_RESPONSE TIMEOUT
private static final int ZWAVE_RECEIVE_TIMEOUT = 1000; // 1000 ms ZWAVE_RECEIVE_TIMEOUT
private static final int INITIAL_QUEUE_SIZE = 128;
private static final long WATCHDOG_TIMER_PERIOD = 10000; // 10 seconds watchdog timer
private static final int TRANSMIT_OPTION_ACK = 0x01;
private static final int TRANSMIT_OPTION_AUTO_ROUTE = 0x04;
private static final int TRANSMIT_OPTION_EXPLORE = 0x20;
private final Map<Integer, ZWaveNode> zwaveNodes = new HashMap<Integer, ZWaveNode>();
private final ArrayList<ZWaveEventListener> zwaveEventListeners = new ArrayList<ZWaveEventListener>();
private final PriorityBlockingQueue<SerialMessage> sendQueue = new PriorityBlockingQueue<SerialMessage>(INITIAL_QUEUE_SIZE, new SerialMessage.SerialMessageComparator(this));
private ZWaveSendThread sendThread;
private ZWaveReceiveThread receiveThread;
private final Semaphore transactionCompleted = new Semaphore(1);
private volatile SerialMessage lastSentMessage = null;
private long lastMessageStartTime = 0;
private long longestResponseTime = 0;
private SerialPort serialPort;
private int zWaveResponseTimeout = ZWAVE_RESPONSE_TIMEOUT;
private Timer watchdog;
private String zWaveVersion = "Unknown";
private String serialAPIVersion = "Unknown";
private int homeId = 0;
private int ownNodeId = 0;
private int manufactureId = 0;
private int deviceType = 0;
private int deviceId = 0;
private int ZWaveLibraryType = 0;
private int sentDataPointer = 1;
private boolean setSUC = false;
private ZWaveDeviceType controllerType = ZWaveDeviceType.UNKNOWN;
private int sucID = 0;
private boolean softReset = false;
private boolean masterController = false;
private int SOFCount = 0;
private int CANCount = 0;
private int NAKCount = 0;
private int ACKCount = 0;
private int OOFCount = 0;
private AtomicInteger timeOutCount = new AtomicInteger(0);
private boolean initializationComplete = false;
private boolean isConnected;
// Constructors
/**
* Constructor. Creates a new instance of the Z-Wave controller class.
* @param serialPortName the serial port name to use for
* communication with the Z-Wave controller stick.
* @throws SerialInterfaceException when a connection error occurs.
*/
public ZWaveController(final boolean masterController, final boolean isSUC, final String serialPortName, final Integer timeout, final boolean reset)
throws SerialInterfaceException {
logger.info("Starting Z-Wave controller");
this.masterController = masterController;
this.setSUC = isSUC;
this.softReset = reset;
if(timeout != null && timeout >= 1500 && timeout <= 10000) {
zWaveResponseTimeout = timeout;
}
logger.info("Z-Wave timeout is set to {}ms. Soft reset is {}.", zWaveResponseTimeout, reset);
connect(serialPortName);
this.watchdog = new Timer(true);
this.watchdog.schedule(
new WatchDogTimerTask(serialPortName),
WATCHDOG_TIMER_PERIOD, WATCHDOG_TIMER_PERIOD);
}
// Incoming message handlers
/**
* Handles incoming Serial Messages. Serial messages can either be messages
* that are a response to our own requests, or the stick asking us information.
* @param incomingMessage the incoming message to process.
*/
private void handleIncomingMessage(SerialMessage incomingMessage) {
logger.trace("Incoming message to process");
logger.debug(incomingMessage.toString());
switch (incomingMessage.getMessageType()) {
case Request:
handleIncomingRequestMessage(incomingMessage);
break;
case Response:
handleIncomingResponseMessage(incomingMessage);
break;
default:
logger.warn("Unsupported incomingMessageType: 0x%02X", incomingMessage.getMessageType());
}
}
/**
* Handles an incoming request message.
* An incoming request message is a message initiated by a node or the controller.
* @param incomingMessage the incoming message to process.
*/
private void handleIncomingRequestMessage(SerialMessage incomingMessage) {
logger.trace("Incoming Message type = REQUEST");
ZWaveCommandProcessor processor = ZWaveCommandProcessor.getMessageDispatcher(incomingMessage.getMessageClass());
if(processor != null) {
boolean result = processor.handleRequest(this, lastSentMessage, incomingMessage);
if(processor.isTransactionComplete()) {
notifyEventListeners(new ZWaveTransactionCompletedEvent(this.lastSentMessage, result));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
}
else {
logger.warn(String.format("TODO: Implement processing of Request Message = %s (0x%02X)",
incomingMessage.getMessageClass().getLabel(),
incomingMessage.getMessageClass().getKey()));
}
}
/**
* Handles a failed SendData request. This can either be because of the stick actively reporting it
* or because of a time-out of the transaction in the send thread.
* @param originalMessage the original message that was sent
*/
private void handleFailedSendDataRequest(SerialMessage originalMessage) {
new SendDataMessageClass().handleFailedSendDataRequest(this, originalMessage);
}
/**
* Handles an incoming response message.
* An incoming response message is a response, based one of our own requests.
* @param incomingMessage the response message to process.
*/
private void handleIncomingResponseMessage(SerialMessage incomingMessage) {
logger.trace("Incoming Message type = RESPONSE");
ZWaveCommandProcessor processor = ZWaveCommandProcessor.getMessageDispatcher(incomingMessage.getMessageClass());
if(processor != null) {
boolean result = processor.handleResponse(this, lastSentMessage, incomingMessage);
if(processor.isTransactionComplete()) {
notifyEventListeners(new ZWaveTransactionCompletedEvent(this.lastSentMessage, result));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
}
else {
logger.warn(String.format("TODO: Implement processing of Response Message = %s (0x%02X)",
incomingMessage.getMessageClass().getLabel(),
incomingMessage.getMessageClass().getKey()));
}
switch (incomingMessage.getMessageClass()) {
case GetVersion:
this.zWaveVersion = ((GetVersionMessageClass)processor).getVersion();
this.ZWaveLibraryType = ((GetVersionMessageClass)processor).getLibraryType();
break;
case MemoryGetId:
this.ownNodeId = ((MemoryGetIdMessageClass)processor).getNodeId();
this.homeId = ((MemoryGetIdMessageClass)processor).getHomeId();
break;
case SerialApiGetInitData:
this.isConnected = true;
for(Integer nodeId : ((SerialApiGetInitDataMessageClass)processor).getNodes()) {
ZWaveNode node = null;
try {
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
node = nodeSerializer.DeserializeNode(nodeId);
}
catch (Exception e) {
logger.error("NODE {}: Error deserialising XML file. {}", nodeId, e.toString());
node = null;
}
String name = null;
String location = null;
// Did the node deserialise ok?
if (node != null) {
// Remember the name and location - in case we decide the file was invalid
name = node.getName();
location = node.getLocation();
// Sanity check the data from the file
if (node.getManufacturer() == Integer.MAX_VALUE ||
node.getHomeId() != this.homeId ||
node.getNodeId() != nodeId) {
logger.warn("NODE {}: Config file data is invalid, ignoring config.", nodeId);
node = null;
}
else {
// The restore was ok, but we have some work to set up the links that aren't
// made as the deserialiser doesn't call the constructor
logger.debug("NODE {}: Restored from config.", nodeId);
node.setRestoredFromConfigfile(this);
// Set the controller and node references for all command classes
for (ZWaveCommandClass commandClass : node.getCommandClasses()) {
commandClass.setController(this);
commandClass.setNode(node);
// Handle event handlers
if (commandClass instanceof ZWaveEventListener) {
this.addEventListener((ZWaveEventListener)commandClass);
}
// If this is the multi-instance class, add all command classes for the endpoints
if (commandClass instanceof ZWaveMultiInstanceCommandClass) {
for (ZWaveEndpoint endPoint : ((ZWaveMultiInstanceCommandClass) commandClass)
.getEndpoints()) {
for (ZWaveCommandClass endpointCommandClass : endPoint.getCommandClasses()) {
endpointCommandClass.setController(this);
endpointCommandClass.setNode(node);
endpointCommandClass.setEndpoint(endPoint);
// Handle event handlers
if (endpointCommandClass instanceof ZWaveEventListener) {
this.addEventListener((ZWaveEventListener)endpointCommandClass);
}
}
}
}
}
}
}
// Create a new node if it wasn't deserialised ok
if(node == null) {
node = new ZWaveNode(this.homeId, nodeId, this);
// Try to maintain the name and location (user supplied data)
// even if the XML file was considered corrupt and we reload data from the device.
node.setName(name);
node.setLocation(location);
}
if(nodeId == this.ownNodeId) {
// This is the controller node.
// We already know the device type, id, manufacturer so set it here
// It won't be set later as we probably won't request the manufacturer specific data
node.setDeviceId(this.getDeviceId());
node.setDeviceType(this.getDeviceType());
node.setManufacturer(this.getManufactureId());
}
// Place nodes in the local ZWave Controller
this.zwaveNodes.put(nodeId, node);
node.initialiseNode();
}
break;
case GetSucNodeId:
// Remember the SUC ID
this.sucID = ((GetSucNodeIdMessageClass)processor).getSucNodeId();
// If we want to be the SUC, enable it here
if(this.setSUC == true && this.sucID == 0) {
// We want to be SUC
this.enqueue(new EnableSucMessageClass().doRequest(EnableSucMessageClass.SUCType.SERVER));
this.enqueue(new SetSucNodeMessageClass().doRequest(this.ownNodeId, SetSucNodeMessageClass.SUCType.SERVER));
}
else if(this.setSUC == false && this.sucID == this.ownNodeId) {
// We don't want to be SUC, but we currently are!
// Disable SERVER functionality, and set the node to 0
this.enqueue(new EnableSucMessageClass().doRequest(EnableSucMessageClass.SUCType.NONE));
this.enqueue(new SetSucNodeMessageClass().doRequest(this.ownNodeId, SetSucNodeMessageClass.SUCType.NONE));
}
this.enqueue(new GetControllerCapabilitiesMessageClass().doRequest());
break;
case SerialApiGetCapabilities:
this.serialAPIVersion = ((SerialApiGetCapabilitiesMessageClass)processor).getSerialAPIVersion();
this.manufactureId = ((SerialApiGetCapabilitiesMessageClass)processor).getManufactureId();
this.deviceId = ((SerialApiGetCapabilitiesMessageClass)processor).getDeviceId();
this.deviceType = ((SerialApiGetCapabilitiesMessageClass)processor).getDeviceType();
this.enqueue(new SerialApiGetInitDataMessageClass().doRequest());
break;
case GetControllerCapabilities:
this.controllerType = ((GetControllerCapabilitiesMessageClass)processor).getDeviceType();
break;
default:
break;
}
}
// Controller methods
/**
* Connects to the comm port and starts send and receive threads.
* @param serialPortName the port name to open
* @throws SerialInterfaceException when a connection error occurs.
*/
public void connect(final String serialPortName)
throws SerialInterfaceException {
logger.info("Connecting to serial port {}", serialPortName);
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = portIdentifier.open("org.openhab.binding.zwave",2000);
this.serialPort = (SerialPort) commPort;
this.serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
this.serialPort.enableReceiveThreshold(1);
this.serialPort.enableReceiveTimeout(ZWAVE_RECEIVE_TIMEOUT);
this.receiveThread = new ZWaveReceiveThread();
this.receiveThread.start();
this.sendThread = new ZWaveSendThread();
this.sendThread.start();
// RXTX serial port library causes high CPU load
// Start event listener, which will just sleep and slow down event loop
serialPort.addEventListener(this.receiveThread);
serialPort.notifyOnDataAvailable(true);
logger.info("Serial port is initialized");
} catch (NoSuchPortException e) {
logger.error("Port {} does not exist", serialPortName);
throw new SerialInterfaceException(String.format("Port %s does not exist", serialPortName), e);
} catch (PortInUseException e) {
logger.error("Port {} in use.", serialPortName);
throw new SerialInterfaceException(String.format("Port %s in use.", serialPortName), e);
} catch (UnsupportedCommOperationException e) {
logger.error("Unsupported comm operation on Port {}.", serialPortName);
throw new SerialInterfaceException(String.format("Unsupported comm operation on Port %s.", serialPortName), e);
} catch (TooManyListenersException e) {
logger.error("Too many listeners on Port {}.", serialPortName);
e.printStackTrace();
}
}
/**
* Closes the connection to the Z-Wave controller.
*/
public void close() {
if (watchdog != null) {
watchdog.cancel();
watchdog = null;
}
disconnect();
// clear nodes collection and send queue
ArrayList<ZWaveEventListener> copy = new ArrayList<ZWaveEventListener>(this.zwaveEventListeners);
for (Object listener : copy.toArray()) {
if (!(listener instanceof ZWaveNode))
continue;
this.zwaveEventListeners.remove(listener);
}
this.zwaveNodes.clear();
this.sendQueue.clear();
logger.info("Stopped Z-Wave controller");
}
/**
* Disconnects from the serial interface and stops
* send and receive threads.
*/
public void disconnect() {
if (sendThread != null) {
sendThread.interrupt();
try {
sendThread.join();
} catch (InterruptedException e) {
}
sendThread = null;
}
if (receiveThread != null) {
receiveThread.interrupt();
try {
receiveThread.join();
} catch (InterruptedException e) {
}
receiveThread = null;
}
if(transactionCompleted.availablePermits() < 0)
transactionCompleted.release(transactionCompleted.availablePermits());
transactionCompleted.drainPermits();
logger.trace("Transaction completed permit count -> {}", transactionCompleted.availablePermits());
if (this.serialPort != null) {
this.serialPort.close();
this.serialPort = null;
}
logger.info("Disconnected from serial port");
}
/**
* Enqueues a message for sending on the send queue.
* @param serialMessage the serial message to enqueue.
*/
public void enqueue(SerialMessage serialMessage) {
// First try and get the node
// If we're sending to a node, then this obviously isn't to the controller, and we should
// queue anything to a battery node (ie a node supporting the WAKEUP class)!
ZWaveNode node = this.getNode(serialMessage.getMessageNode());
if (node != null) {
// Keep track of the number of packets sent to this device
node.incrementSendCount();
if (!node.isListening() && !node.isFrequentlyListening() && serialMessage.getPriority() != SerialMessagePriority.Low) {
ZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(CommandClass.WAKE_UP);
// If it's a battery operated device, check if it's awake or place in wake-up queue.
if (wakeUpCommandClass != null && !wakeUpCommandClass.processOutgoingWakeupMessage(serialMessage)) {
return;
}
}
}
// Add the message to the queue
this.sendQueue.add(serialMessage);
logger.debug("Enqueueing message. Queue length = {}", this.sendQueue.size());
}
/**
* Returns the size of the send queue.
*/
public int getSendQueueLength() {
return this.sendQueue.size();
}
/**
* Notify our own event listeners of a Z-Wave event.
* @param event the event to send.
*/
public void notifyEventListeners(ZWaveEvent event) {
logger.debug("Notifying event listeners");
ArrayList<ZWaveEventListener> copy = new ArrayList<ZWaveEventListener>(this.zwaveEventListeners);
for (ZWaveEventListener listener : copy) {
logger.trace("Notifying {}", listener.toString());
listener.ZWaveIncomingEvent(event);
}
// We also need to handle the inclusion internally within the controller
if(event instanceof ZWaveInclusionEvent) {
ZWaveInclusionEvent incEvent = (ZWaveInclusionEvent)event;
switch(incEvent.getEvent()) {
case IncludeDone:
logger.debug("NODE {}: Including node.", incEvent.getNodeId());
// First make sure this isn't an existing node
if(getNode(incEvent.getNodeId()) != null) {
logger.debug("NODE {}: Newly included node already exists - not initialising.", incEvent.getNodeId());
break;
}
// Initialise the new node
ZWaveNode node = new ZWaveNode(this.homeId, incEvent.getNodeId(), this);
this.zwaveNodes.put(incEvent.getNodeId(), node);
node.initialiseNode();
break;
case ExcludeDone:
logger.debug("NODE {}: Excluding node.", incEvent.getNodeId());
// Remove the node from the controller
if(getNode(incEvent.getNodeId()) == null) {
logger.debug("NODE {}: Excluding node that doesn't exist.", incEvent.getNodeId());
break;
}
this.zwaveNodes.remove(incEvent.getNodeId());
// Remove the XML file
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.DeleteNode(event.getNodeId());
break;
default:
break;
}
}
if(event instanceof ZWaveNetworkEvent) {
ZWaveNetworkEvent networkEvent = (ZWaveNetworkEvent)event;
switch(networkEvent.getEvent()) {
case FailedNode:
if(getNode(networkEvent.getNodeId()) == null) {
logger.debug("NODE {}: Deleting a node that doesn't exist.", networkEvent.getNodeId());
break;
}
if (networkEvent.getState() == State.Success) {
logger.warn("NODE {}: Marking node as FAILED because its on the controllers failed node list.", networkEvent.getNodeId());
getNode(networkEvent.getNodeId()).setNodeStage(NodeStage.FAILED);
ZWaveEvent zEvent = new ZWaveNodeStatusEvent(networkEvent.getNodeId(), ZWaveNodeStatusEvent.State.Failed);
this.notifyEventListeners(zEvent);
break;
}
case DeleteNode:
if(getNode(networkEvent.getNodeId()) == null) {
logger.debug("NODE {}: Deleting a node that doesn't exist.", networkEvent.getNodeId());
break;
}
this.zwaveNodes.remove(networkEvent.getNodeId());
//Remove the XML file
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.DeleteNode(event.getNodeId());
break;
default:
break;
}
}
}
/**
* Initializes communication with the Z-Wave controller stick.
*/
public void initialize() {
this.enqueue(new GetVersionMessageClass().doRequest());
this.enqueue(new MemoryGetIdMessageClass().doRequest());
this.enqueue(new SerialApiGetCapabilitiesMessageClass().doRequest());
this.enqueue(new GetSucNodeIdMessageClass().doRequest());
}
/**
* Send Identify Node message to the controller.
* @param nodeId the nodeId of the node to identify
*/
public void identifyNode(int nodeId) {
this.enqueue(new IdentifyNodeMessageClass().doRequest(nodeId));
}
/**
* Send Request Node info message to the controller.
* @param nodeId the nodeId of the node to identify
*/
public void requestNodeInfo(int nodeId) {
this.enqueue(new RequestNodeInfoMessageClass().doRequest(nodeId));
}
/**
* Checks for dead or sleeping nodes during Node initialization.
* JwS: merged checkInitComplete and checkForDeadOrSleepingNodes to prevent possibly looping nodes multiple times.
*/
public void checkForDeadOrSleepingNodes(){
int completeCount = 0;
if (zwaveNodes.isEmpty()) {
return;
}
// There are still nodes waiting to get a ping.
// So skip the dead node checking.
for (SerialMessage serialMessage : sendQueue) {
if (serialMessage.getPriority() == SerialMessagePriority.Low) {
return;
}
}
logger.debug("
for (Map.Entry<Integer, ZWaveNode> entry : zwaveNodes.entrySet()) {
logger.debug("NODE {}: In Stage {} since {} ({}s), listening={}, FLiRS={}", entry.getKey(),
entry.getValue().getNodeStage().toString(), entry.getValue().getQueryStageTimeStamp().toString(),
(Calendar.getInstance().getTimeInMillis() - entry.getValue().getQueryStageTimeStamp().getTime()) / 1000,
entry.getValue().isListening(), entry.getValue().isFrequentlyListening());
if (entry.getValue().getNodeStage() == NodeStage.EMPTYNODE) {
continue;
}
// If we've exceeded the retry time, send the Alive event which will be received in the init code
// if(Calendar.getInstance().getTimeInMillis() > (entry.getValue().getQueryStageTimeStamp().getTime() + QUERY_STAGE_RETRY)) {
// logger.debug("NODE {}: Exceeded stage retry time. Sending Alive event to kickstart initialisation.", entry.getKey());
// ZWaveNodeStatusEvent event = new ZWaveNodeStatusEvent(entry.getKey(), ZWaveNodeStatusEvent.State.Alive);
// notifyEventListeners(event);
// If we're done, or dead, or not listening, then we consider this node is done (!)
if(entry.getValue().getNodeStage() == NodeStage.DONE || entry.getValue().isDead() == true
|| (!entry.getValue().isListening() && !entry.getValue().isFrequentlyListening())) {
completeCount++;
continue;
}
// Otherwise let the node complete it's time.
if(Calendar.getInstance().getTimeInMillis() < (entry.getValue().getQueryStageTimeStamp().getTime() + QUERY_STAGE_TIMEOUT)) {
continue;
}
logger.warn("NODE {}: May be dead, setting stage to DEAD.", entry.getKey());
entry.getValue().setNodeStage(NodeStage.DEAD);
completeCount++;
}
// If all nodes are completed, then we say the binding is ready for business
if(this.zwaveNodes.size() == completeCount && initializationComplete == false) {
logger.debug("ZWave Initialisation Complete");
// We only want this event once!
initializationComplete = true;
ZWaveEvent zEvent = new ZWaveInitializationCompletedEvent(this.ownNodeId);
this.notifyEventListeners(zEvent);
// If there are DEAD nodes, send a Node Status event
// We do that here to avoid messing with the binding initialisation
for(ZWaveNode node : this.getNodes()) {
logger.debug("NODE {}: Checking completion state - {}.", node.getNodeId(), node.getNodeStage());
if (node.isDead()) {
logger.debug("NODE {}: DEAD node.", node.getNodeId());
zEvent = new ZWaveNodeStatusEvent(node.getNodeId(), ZWaveNodeStatusEvent.State.Dead);
this.notifyEventListeners(zEvent);
}
}
}
}
/**
* Polls a node for any dynamic information
* @param node
*/
public void pollNode(ZWaveNode node) {
for (ZWaveCommandClass zwaveCommandClass : node.getCommandClasses()) {
logger.trace("NODE {}: Inspecting command class {}", node.getNodeId(), zwaveCommandClass.getCommandClass().getLabel());
if (zwaveCommandClass instanceof ZWaveCommandClassDynamicState) {
logger.debug("NODE {}: Found dynamic state command class {}", node.getNodeId(), zwaveCommandClass.getCommandClass()
.getLabel());
ZWaveCommandClassDynamicState zdds = (ZWaveCommandClassDynamicState) zwaveCommandClass;
int instances = zwaveCommandClass.getInstances();
if (instances == 1) {
Collection<SerialMessage> dynamicQueries = zdds.getDynamicValues(true);
for (SerialMessage serialMessage : dynamicQueries) {
sendData(serialMessage);
}
} else {
for (int i = 1; i <= instances; i++) {
Collection<SerialMessage> dynamicQueries = zdds.getDynamicValues(true);
for (SerialMessage serialMessage : dynamicQueries) {
sendData(node.encapsulate(serialMessage, zwaveCommandClass, i));
}
}
}
} else if (zwaveCommandClass instanceof ZWaveMultiInstanceCommandClass) {
ZWaveMultiInstanceCommandClass multiInstanceCommandClass = (ZWaveMultiInstanceCommandClass) zwaveCommandClass;
for (ZWaveEndpoint endpoint : multiInstanceCommandClass.getEndpoints()) {
for (ZWaveCommandClass endpointCommandClass : endpoint.getCommandClasses()) {
logger.trace("NODE {}: Inspecting command class {} for endpoint {}", node.getNodeId(), endpointCommandClass
.getCommandClass().getLabel(), endpoint.getEndpointId());
if (endpointCommandClass instanceof ZWaveCommandClassDynamicState) {
logger.debug("NODE {}: Found dynamic state command class {}", node.getNodeId(), endpointCommandClass
.getCommandClass().getLabel());
ZWaveCommandClassDynamicState zdds2 = (ZWaveCommandClassDynamicState) endpointCommandClass;
Collection<SerialMessage> dynamicQueries = zdds2.getDynamicValues(true);
for (SerialMessage serialMessage : dynamicQueries) {
sendData(node.encapsulate(serialMessage,
endpointCommandClass, endpoint.getEndpointId()));
}
}
}
}
}
}
}
/**
* Request the node routing information.
*
* @param nodeId The address of the node to update
*/
public void requestNodeRoutingInfo(int nodeId)
{
this.enqueue(new GetRoutingInfoMessageClass().doRequest(nodeId));
}
/**
* Request the node neighbor list to be updated for the specified node.
* Once this is complete, the requestNodeRoutingInfo will be called
* automatically to update the data in the binding.
*
* @param nodeId The address of the node to update
*/
public void requestNodeNeighborUpdate(int nodeId)
{
this.enqueue(new RequestNodeNeighborUpdateMessageClass().doRequest(nodeId));
}
/**
* Puts the controller into inclusion mode to add new nodes
*/
public void requestAddNodesStart()
{
this.enqueue(new AddNodeMessageClass().doRequestStart(true));
}
/**
* Terminates the inclusion mode
*/
public void requestAddNodesStop()
{
this.enqueue(new AddNodeMessageClass().doRequestStop());
}
/**
* Puts the controller into exclusion mode to remove new nodes
*/
public void requestRemoveNodesStart()
{
this.enqueue(new RemoveNodeMessageClass().doRequestStart(true));
}
/**
* Terminates the exclusion mode
*/
public void requestRemoveNodesStop()
{
this.enqueue(new RemoveNodeMessageClass().doRequestStop());
}
/**
* Sends a request to perform a soft reset on the controller.
* This will just reset the controller - probably similar to a power cycle.
* It doesn't reinitialise the network, or change the network configuration.
*
* NOTE: At least for some (most!) sticks, this doesn't return a response.
* Therefore, the number of retries is set to 1.
* NOTE: On some (most!) ZWave-Plus sticks, this can cause the stick to hang.
*/
public void requestSoftReset()
{
SerialMessage msg = new SerialApiSoftResetMessageClass().doRequest();
msg.attempts = 1;
this.enqueue(msg);
}
/**
* Request if the node is currently marked as failed by the controller.
* @param nodeId The address of the node to check
*/
public void requestIsFailedNode(int nodeId)
{
this.enqueue(new IsFailedNodeMessageClass().doRequest(nodeId));
}
/**
* Removes a failed node from the network.
* Note that this won't remove nodes that have not failed.
* @param nodeId The address of the node to remove
*/
public void requestRemoveFailedNode(int nodeId)
{
this.enqueue(new RemoveFailedNodeMessageClass().doRequest(nodeId));
}
/**
* Delete all return nodes from the specified node. This should be performed
* before updating the routes
*
* @param nodeId
*/
public void requestDeleteAllReturnRoutes(int nodeId)
{
this.enqueue(new DeleteReturnRouteMessageClass().doRequest(nodeId));
}
/**
* Request the controller to set the return route between two nodes
*
* @param nodeId
* Source node
* @param destinationId
* Destination node
*/
public void requestAssignReturnRoute(int nodeId, int destinationId)
{
this.enqueue(new AssignReturnRouteMessageClass().doRequest(nodeId, destinationId, getCallbackId()));
}
/**
* Request the controller to set the return route from a node to the controller
*
* @param nodeId
* Source node
*/
public void requestAssignSucReturnRoute(int nodeId)
{
this.enqueue(new AssignSucReturnRouteMessageClass().doRequest(nodeId, getCallbackId()));
}
/**
* Returns the next callback ID
* @return callback ID
*/
public int getCallbackId() {
if (++sentDataPointer > 0xFF)
sentDataPointer = 1;
logger.debug("Callback ID = {}", sentDataPointer);
return sentDataPointer;
}
/**
* Transmits the SerialMessage to a single Z-Wave Node.
* Sets the transmission options as well.
* @param serialMessage the Serial message to send.
*/
public void sendData(SerialMessage serialMessage)
{
if(serialMessage == null) {
logger.error("Null message for sendData");
return;
}
if (serialMessage.getMessageClass() != SerialMessageClass.SendData) {
logger.error(String.format("Invalid message class %s (0x%02X) for sendData", serialMessage.getMessageClass().getLabel(), serialMessage.getMessageClass().getKey()));
return;
}
if (serialMessage.getMessageType() != SerialMessageType.Request) {
logger.error("Only request messages can be sent");
return;
}
serialMessage.setTransmitOptions(TRANSMIT_OPTION_ACK | TRANSMIT_OPTION_AUTO_ROUTE | TRANSMIT_OPTION_EXPLORE);
serialMessage.setCallbackId(getCallbackId());
this.enqueue(serialMessage);
}
/**
* Add a listener for Z-Wave events to this controller.
* @param eventListener the event listener to add.
*/
public void addEventListener(ZWaveEventListener eventListener) {
this.zwaveEventListeners.add(eventListener);
}
/**
* Remove a listener for Z-Wave events to this controller.
* @param eventListener the event listener to remove.
*/
public void removeEventListener(ZWaveEventListener eventListener) {
this.zwaveEventListeners.remove(eventListener);
}
/**
* Gets the API Version of the controller.
* @return the serialAPIVersion
*/
public String getSerialAPIVersion() {
return serialAPIVersion;
}
/**
* Gets the zWave Version of the controller.
* @return the zWaveVersion
*/
public String getZWaveVersion() {
return zWaveVersion;
}
/**
* Gets the Manufacturer ID of the controller.
* @return the manufactureId
*/
public int getManufactureId() {
return manufactureId;
}
/**
* Gets the device type of the controller;
* @return the deviceType
*/
public int getDeviceType() {
return deviceType;
}
/**
* Gets the device ID of the controller.
* @return the deviceId
*/
public int getDeviceId() {
return deviceId;
}
/**
* Gets the node ID of the controller.
* @return the deviceId
*/
public int getOwnNodeId() {
return ownNodeId;
}
/**
* Gets the device type of the controller.
* @return the device type
*/
public ZWaveDeviceType getControllerType() {
return controllerType;
}
/**
* Gets the networks SUC controller ID.
* @return the device id of the SUC, or 0 if none exists
*/
public int getSucId() {
return sucID;
}
/**
* Returns true if the binding is the master controller in the network.
* The master controller simply means that we get notifications.
* @return true if this is the master
*/
public boolean isMasterController() {
return masterController;
}
/**
* Gets the node object using it's node ID as key.
* Returns null if the node is not found
* @param nodeId the Node ID of the node to get.
* @return node object
*/
public ZWaveNode getNode(int nodeId) {
return this.zwaveNodes.get(nodeId);
}
/**
* Gets the node list
* @return
*/
public Collection<ZWaveNode> getNodes() {
return this.zwaveNodes.values();
}
/**
* Indicates a working connection to the
* Z-Wave controller stick and initialization complete
* @return isConnected;
*/
public boolean isConnected() {
return isConnected && initializationComplete;
}
/**
* Gets the number of Start Of Frames received.
* @return the sOFCount
*/
public int getSOFCount() {
return SOFCount;
}
/**
* Gets the number of Canceled Frames received.
* @return the cANCount
*/
public int getCANCount() {
return CANCount;
}
/**
* Gets the number of Not Acknowledged Frames received.
* @return the nAKCount
*/
public int getNAKCount() {
return NAKCount;
}
/**
* Gets the number of Acknowledged Frames received.
* @return the aCKCount
*/
public int getACKCount() {
return ACKCount;
}
/**
* Returns the number of Out of Order frames received.
* @return the oOFCount
*/
public int getOOFCount() {
return OOFCount;
}
/**
* Returns the number of Time-Outs while sending.
* @return the oOFCount
*/
public int getTimeOutCount() {
return timeOutCount.get();
}
/**
* Returns the number of frames in the transmit queue(s)
* @return
*/
public int getTxQueueLength() {
return this.sendQueue.size();
}
// Nested classes and enumerations
/**
* Z-Wave controller Send Thread. Takes care of sending all messages.
* It uses a semaphore to synchronize communication with the receiving thread.
* @author Jan-Willem Spuij
* @since 1.3.0
*/
private class ZWaveSendThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(ZWaveSendThread.class);
/**
* Run method. Runs the actual sending process.
*/
@Override
public void run() {
logger.debug("Starting Z-Wave send thread");
try {
while (!interrupted()) {
// Take the next message from the send queue
try {
lastSentMessage = sendQueue.take();
logger.debug("Took message from queue for sending. Queue length = {}", sendQueue.size());
} catch (InterruptedException e1) {
break;
}
// Check we got a message
if (lastSentMessage == null) {
continue;
}
// If it's a battery device, it needs to be awake, or we queue the frame until it is.
ZWaveNode node = getNode(lastSentMessage.getMessageNode());
if (node != null && !node.isListening() && !node.isFrequentlyListening() && lastSentMessage.getPriority() != SerialMessagePriority.Low) {
ZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(CommandClass.WAKE_UP);
// If it's a battery operated device, check if it's awake or place in wake-up queue.
if (wakeUpCommandClass != null && !wakeUpCommandClass.processOutgoingWakeupMessage(lastSentMessage)) {
continue;
}
}
// A transaction consists of 3 parts -:
// 1) We send a REQUEST to the controller.
// 2) The controller sends a RESPONSE almost immediately.
// This RESPONSE typically tells us that the message was,
// or wasn't, added to the sticks queue.
// 3) The controller sends a REQUEST once it's received
// the response from the device.
// We need to be aware that there is no synchronization of
// messages between steps 2 and 3 so we can get other messages
// received at step 3 that are not related to our original
// request.
// A transaction is completed at the completion of step 3.
// However, for some messages, there may not be a further REQUEST
// so the transaction is terminated at step 2. This is handled
// by the serial message class processor by setting
// transactionCompleted.
// Clear the semaphore used to acknowledge the completed transaction.
transactionCompleted.drainPermits();
// Send the REQUEST message TO the controller
byte[] buffer = lastSentMessage.getMessageBuffer();
logger.debug("NODE {}: Sending REQUEST Message = {}", lastSentMessage.getMessageNode(), SerialMessage.bb2hex(buffer));
lastMessageStartTime = System.currentTimeMillis();
try {
synchronized (serialPort.getOutputStream()) {
serialPort.getOutputStream().write(buffer);
serialPort.getOutputStream().flush();
}
}
catch (IOException e) {
logger.error("Got I/O exception {} during sending. exiting thread.", e.getLocalizedMessage());
break;
}
// Now wait for the RESPONSE, or REQUEST message FROM the controller
// This will terminate when the transactionCompleted flag gets set
// So, this might complete on a RESPONSE if there's an error (or no further REQUEST expected)
// or it might complete on a subsequent REQUEST.
try {
if (!transactionCompleted.tryAcquire(1, zWaveResponseTimeout, TimeUnit.MILLISECONDS)) {
timeOutCount.incrementAndGet();
// If this is a SendData message, then we need to abort
// TODO: CDJ - not according to the doc? Should check this. We don't know if this is after the response or not!
// TODO: CDJ - SendDataBort is sent if no response is received to the request!
if (lastSentMessage.getMessageClass() == SerialMessageClass.SendData) {
buffer = new SerialMessage(SerialMessageClass.SendDataAbort, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.High).getMessageBuffer();
logger.debug("NODE {}: Sending ABORT Message = {}", lastSentMessage.getMessageNode(), SerialMessage.bb2hex(buffer));
try {
synchronized (serialPort.getOutputStream()) {
serialPort.getOutputStream().write(buffer);
serialPort.getOutputStream().flush();
}
} catch (IOException e) {
logger.error("Got I/O exception {} during sending. exiting thread.", e.getLocalizedMessage());
break;
}
}
// Check if we've exceeded the number of retries.
// Requeue if we're ok, otherwise discard the message
if (--lastSentMessage.attempts >= 0) {
logger.error("NODE {}: Timeout while sending message. Requeueing - {} attempts left!",
lastSentMessage.getMessageNode(), lastSentMessage.attempts);
if (lastSentMessage.getMessageClass() == SerialMessageClass.SendData) {
handleFailedSendDataRequest(lastSentMessage);
}
else {
enqueue(lastSentMessage);
}
} else {
logger.warn("NODE {}: Too many retries. Discarding message: {}", lastSentMessage.getMessageNode(), lastSentMessage.toString());
}
continue;
}
long responseTime = System.currentTimeMillis() - lastMessageStartTime;
if(responseTime > longestResponseTime) {
longestResponseTime = responseTime;
}
logger.debug("NODE {}: Response processed after {}ms/{}ms.", lastSentMessage.getMessageNode(), responseTime, longestResponseTime);
logger.trace("Acquired. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
catch (InterruptedException e) {
break;
}
}
}
catch (Exception e) {
logger.error("Got an exception during sending. exiting thread.", e);
}
logger.debug("Stopped Z-Wave send thread");
}
}
/**
* Z-Wave controller Receive Thread. Takes care of receiving all messages.
* It uses a semaphore to synchronize communication with the sending thread.
* @author Jan-Willem Spuij
* @since 1.3.0
*/
private class ZWaveReceiveThread extends Thread implements SerialPortEventListener {
private static final int SOF = 0x01;
private static final int ACK = 0x06;
private static final int NAK = 0x15;
private static final int CAN = 0x18;
private final Logger logger = LoggerFactory.getLogger(ZWaveReceiveThread.class);
@Override
public void serialEvent(SerialPortEvent arg0) {
try {
logger.trace("RXTX library CPU load workaround, sleep forever");
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
}
}
/**
* Sends 1 byte frame response.
* @param response the response code to send.
*/
private void sendResponse(int response) {
try {
synchronized (serialPort.getOutputStream()) {
serialPort.getOutputStream().write(response);
serialPort.getOutputStream().flush();
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}
/**
* Processes incoming message and notifies event handlers.
* @param buffer the buffer to process.
*/
private void processIncomingMessage(byte[] buffer) {
SerialMessage serialMessage = new SerialMessage(buffer);
if (serialMessage.isValid) {
logger.trace("Message is valid, sending ACK");
sendResponse(ACK);
} else {
logger.error("Message is not valid, discarding");
return;
}
handleIncomingMessage(serialMessage);
}
/**
* Run method. Runs the actual receiving process.
*/
@Override
public void run() {
logger.debug("Starting Z-Wave receive thread");
try {
// Send a NAK to resynchronise communications
sendResponse(NAK);
// If we want to do a soft reset on the serial interfaces, do it here.
// It seems there's no response to this message, so sending it through
// 'normal' channels will cause a timeout.
if(softReset == true) {
try {
synchronized (serialPort.getOutputStream()) {
SerialMessage resetMsg = new SerialApiSoftResetMessageClass().doRequest();
byte[] buffer = resetMsg.getMessageBuffer();
serialPort.getOutputStream().write(buffer);
serialPort.getOutputStream().flush();
}
} catch (IOException e) {
logger.error("Error sending soft reset on initialisation: {}", e.getMessage());
}
}
while (!interrupted()) {
int nextByte;
try {
nextByte = serialPort.getInputStream().read();
if (nextByte == -1)
continue;
} catch (IOException e) {
logger.error("Got I/O exception {} during receiving. exiting thread.", e.getLocalizedMessage());
break;
}
switch (nextByte) {
case SOF:
SOFCount++;
int messageLength;
try {
messageLength = serialPort.getInputStream().read();
} catch (IOException e) {
logger.error("Got I/O exception {} during receiving. exiting thread.", e.getLocalizedMessage());
break;
}
byte[] buffer = new byte[messageLength + 2];
buffer[0] = SOF;
buffer[1] = (byte)messageLength;
int total = 0;
while (total < messageLength) {
try {
int read = serialPort.getInputStream().read(buffer, total + 2, messageLength - total);
total += (read > 0 ? read : 0);
} catch (IOException e) {
logger.error("Got I/O exception {} during receiving. exiting thread.", e.getLocalizedMessage());
return;
}
}
logger.trace("Reading message finished" );
logger.debug("Receive Message = {}", SerialMessage.bb2hex(buffer));
processIncomingMessage(buffer);
break;
case ACK:
ACKCount++;
logger.trace("Received ACK");
break;
case NAK:
NAKCount++;
logger.error("Message not acklowledged by controller (NAK), discarding");
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
break;
case CAN:
CANCount++;
logger.error("Message cancelled by controller (CAN), resending");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
enqueue(lastSentMessage);
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
break;
default:
OOFCount++;
logger.warn(String.format("Out of Frame flow. Got 0x%02X. Sending NAK.", nextByte));
sendResponse(NAK);
break;
}
}
} catch (Exception e) {
logger.error("Got an exception during receiving. exiting thread.", e);
}
logger.debug("Stopped Z-Wave receive thread");
serialPort.removeEventListener();
}
}
/**
* WatchDogTimerTask class. Acts as a watch dog and
* checks the serial threads to see whether they are
* still running.
* @author Jan-Willem Spuij
* @since 1.3.0
*/
private class WatchDogTimerTask extends TimerTask {
private final Logger logger = LoggerFactory.getLogger(WatchDogTimerTask.class);
private final String serialPortName;
/**
* Creates a new instance of the WatchDogTimerTask class.
* @param serialPortName the serial port name to reconnect to
* in case the serial threads have died.
*/
public WatchDogTimerTask(String serialPortName) {
this.serialPortName = serialPortName;
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
logger.trace("Watchdog: Checking Serial threads");
if ((receiveThread != null && !receiveThread.isAlive()) ||
(sendThread != null && !sendThread.isAlive()))
{
logger.warn("Threads not alive, respawning");
disconnect();
try {
connect(serialPortName);
} catch (SerialInterfaceException e) {
logger.error("unable to restart Serial threads: {}", e.getLocalizedMessage());
}
}
}
}
}
|
package org.eclipse.birt.chart.ui.swt.wizard.format.chart;
import java.util.List;
import org.eclipse.birt.chart.model.attribute.ColorDefinition;
import org.eclipse.birt.chart.model.attribute.FontDefinition;
import org.eclipse.birt.chart.model.attribute.Interactivity;
import org.eclipse.birt.chart.model.attribute.impl.InteractivityImpl;
import org.eclipse.birt.chart.model.layout.TitleBlock;
import org.eclipse.birt.chart.model.util.ChartDefaultValueUtil;
import org.eclipse.birt.chart.ui.extension.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.ChartCheckbox;
import org.eclipse.birt.chart.ui.swt.composites.ExternalizedTextEditorComposite;
import org.eclipse.birt.chart.ui.swt.composites.FontDefinitionComposite;
import org.eclipse.birt.chart.ui.swt.composites.TriggerDataComposite;
import org.eclipse.birt.chart.ui.swt.interfaces.ITaskPopupSheet;
import org.eclipse.birt.chart.ui.swt.wizard.format.SubtaskSheetImpl;
import org.eclipse.birt.chart.ui.swt.wizard.format.popup.InteractivitySheet;
import org.eclipse.birt.chart.ui.swt.wizard.format.popup.chart.TitleBlockSheet;
import org.eclipse.birt.chart.ui.swt.wizard.format.popup.chart.TitleTextSheet;
import org.eclipse.birt.chart.ui.util.ChartHelpContextIds;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.chart.util.TriggerSupportMatrix;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
/**
* Title subtask
*
*/
public class ChartTitleSheetImpl extends SubtaskSheetImpl implements
SelectionListener,
Listener
{
private ExternalizedTextEditorComposite txtTitle = null;
private FontDefinitionComposite fdcFont;
private ChartCheckbox btnVisible;
private ChartCheckbox btnAutoTitle;
public void createControl( Composite parent )
{
ChartUIUtil.bindHelp( parent, ChartHelpContextIds.SUBTASK_TITLE );
TitleBlock defTitle = ChartDefaultValueUtil.getDefaultValueChart( getChart() ).getTitle( );
init( );
cmpContent = new Composite( parent, SWT.NONE );
{
cmpContent.setLayout( new GridLayout( ) );
GridData gd = new GridData( GridData.FILL_BOTH );
cmpContent.setLayoutData( gd );
}
Composite cmpBasic = new Composite( cmpContent, SWT.NONE );
{
cmpBasic.setLayout( new GridLayout( 4, false ) );
GridData gd = new GridData( GridData.FILL_BOTH );
cmpBasic.setLayoutData( gd );
}
Label lblTitle = new Label( cmpBasic, SWT.NONE );
{
lblTitle.setText( Messages.getString( "ChartTitleSheetImpl.Label.ChartTitle" ) ); //$NON-NLS-1$
}
List<String> keys = null;
if ( getContext( ).getUIServiceProvider( ) != null )
{
keys = getContext( ).getUIServiceProvider( ).getRegisteredKeys( );
}
txtTitle = new ExternalizedTextEditorComposite( cmpBasic,
SWT.BORDER,
-1,
-1,
keys,
getContext( ).getUIServiceProvider( ),
getTitleText( ) );
{
GridData gdTXTTitle = new GridData( );
gdTXTTitle.widthHint = 200;
txtTitle.setLayoutData( gdTXTTitle );
txtTitle.setEnabled( isTitleEnabled( ) );
txtTitle.addListener( this );
}
btnVisible = getContext( ).getUIFactory( )
.createChartCheckbox( cmpBasic,
SWT.NONE,
defTitle.isVisible( ) );
btnVisible.setText( Messages.getString( "ChartSheetImpl.Label.Visible" ) ); //$NON-NLS-1$
GridData gd = new GridData( );
btnVisible.setLayoutData( gd );
btnVisible.setSelectionState( getChart( ).getTitle( ).isSetVisible( ) ? ( getChart( ).getTitle( )
.isVisible( ) ? ChartCheckbox.STATE_SELECTED
: ChartCheckbox.STATE_UNSELECTED )
: ChartCheckbox.STATE_GRAYED );
btnVisible.addSelectionListener( this );
boolean dynamicTitleVisible = getContext( ).getUIFactory( )
.createUIHelper( )
.isDefaultTitleSupported( );
btnAutoTitle = getContext( ).getUIFactory( )
.createChartCheckbox( cmpBasic, SWT.NONE, defTitle.isAuto( ) );
btnAutoTitle.setText( Messages.getString( "ChartTitleSheetImpl.Text.Auto" ) ); //$NON-NLS-1$
gd = new GridData( );
btnAutoTitle.setLayoutData( gd );
btnAutoTitle.setSelectionState( getChart( ).getTitle( ).isSetAuto( ) ? ( getChart( ).getTitle( )
.isAuto( ) ? ChartCheckbox.STATE_SELECTED
: ChartCheckbox.STATE_UNSELECTED )
: ChartCheckbox.STATE_GRAYED );
btnAutoTitle.setEnabled( isAutoEnabled( ) );
btnAutoTitle.setVisible( dynamicTitleVisible );
btnAutoTitle.addSelectionListener( this );
Label lblFont = new Label( cmpBasic, SWT.NONE );
lblFont.setText( Messages.getString( "LabelAttributesComposite.Lbl.Font" ) ); //$NON-NLS-1$
fdcFont = new FontDefinitionComposite( cmpBasic,
SWT.NONE,
getContext( ),
getChart( ).getTitle( ).getLabel( ).getCaption( ).getFont( ),
getChart( ).getTitle( ).getLabel( ).getCaption( ).getColor( ),
needTitleAlignment( ) );
GridData gdFDCFont = new GridData( );
// gdFDCFont.heightHint = fdcFont.getPreferredSize( ).y;
gdFDCFont.widthHint = 220;
gdFDCFont.horizontalSpan = 3;
gdFDCFont.grabExcessVerticalSpace = false;
fdcFont.setLayoutData( gdFDCFont );
fdcFont.addListener( this );
createButtonGroup( cmpContent );
updateUIState( getContext().getUIFactory( ).canEnableUI( btnVisible ) );
}
private void init( )
{
// Make it compatible with old model
if ( getChart( ).getInteractivity( ) == null )
{
Interactivity interactivity = InteractivityImpl.create( );
interactivity.eAdapters( ).addAll( getChart( ).eAdapters( ) );
getChart( ).setInteractivity( interactivity );
}
}
protected void createButtonGroup( Composite parent )
{
Composite cmp = new Composite( parent, SWT.NONE );
{
cmp.setLayout( new GridLayout( 5, false ) );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.grabExcessVerticalSpace = true;
gridData.verticalAlignment = SWT.END;
cmp.setLayoutData( gridData );
}
ITaskPopupSheet popup;
// Title Text
popup = new TitleTextSheet( Messages.getString( "ChartTitleSheetImpl.Text.TitleText" ), //$NON-NLS-1$
getContext( ) );
Button btnTitleProp = createToggleButton( cmp,
BUTTON_TEXT,
Messages.getString( "ChartTitleSheetImpl.Text.TitleText&" ), //$NON-NLS-1$
popup,
getChart( ).getTitle( ).isVisible( ) );
btnTitleProp.addSelectionListener( this );
// Title Layout
popup = new TitleBlockSheet( Messages.getString( "ChartTitleSheetImpl.Text.TitleLayout" ), //$NON-NLS-1$
getContext( ) );
Button btnBlockProp = createToggleButton( cmp,
BUTTON_LAYOUT,
Messages.getString( "ChartTitleSheetImpl.Text.Layout&" ), //$NON-NLS-1$
popup,
getChart( ).getTitle( ).isVisible( ) );
btnBlockProp.addSelectionListener( this );
// Interactivity
if ( getContext( ).isInteractivityEnabled( ) )
{
popup = new InteractivitySheet( Messages.getString( "ChartTitleSheetImpl.Label.Interactivity" ), //$NON-NLS-1$
getContext( ),
getChart( ).getTitle( ).getTriggers( ),
getChart( ).getTitle( ),
TriggerSupportMatrix.TYPE_CHARTTITLE,
TriggerDataComposite.ENABLE_SHOW_TOOLTIP_VALUE );
Button btnInteractivity = createToggleButton( cmp,
BUTTON_INTERACTIVITY,
Messages.getString( "SeriesYSheetImpl.Label.Interactivity&" ), //$NON-NLS-1$
popup,
getChart( ).getInteractivity( ).isEnable( ) );
btnInteractivity.addSelectionListener( this );
}
}
public void handleEvent( Event event )
{
if ( event.widget.equals( txtTitle ) )
{
String title = txtTitle.getText( ) ;
if ( btnAutoTitle.getSelectionState( ) == ChartCheckbox.STATE_GRAYED && (txtTitle.getText( ) == null
|| txtTitle.getText( ).trim( ).length( ) == 0 ) )
{
title = null;
}
getChart( ).getTitle( )
.getLabel( )
.getCaption( )
.setValue( title );
}
else if ( event.widget.equals( fdcFont ) )
{
if ( event.type == FontDefinitionComposite.FONT_CHANTED_EVENT )
{
getChart( ).getTitle( )
.getLabel( )
.getCaption( )
.setFont( (FontDefinition) ( (Object[]) event.data )[0] );
getChart( ).getTitle( )
.getLabel( )
.getCaption( )
.setColor( (ColorDefinition) ( (Object[]) event.data )[1] );
}
}
}
public void widgetSelected( SelectionEvent e )
{
// Detach popup dialog if there's selected popup button.
if ( detachPopup( e.widget ) )
{
return;
}
if ( isRegistered( e.widget ) )
{
attachPopup( ( (Button) e.widget ).getData( ).toString( ) );
}
if ( e.widget.equals( btnVisible ) )
{
boolean visible = btnVisible.getSelectionState( ) == ChartCheckbox.STATE_SELECTED;
if ( btnVisible.getSelectionState( ) == ChartCheckbox.STATE_GRAYED )
{
getChart( ).getTitle( ).unsetVisible( );
}
else
{
getChart( ).getTitle( ).setVisible( visible );
}
updateUIState( getContext().getUIFactory( ).canEnableUI( btnVisible ) );
if ( getToggleButtonSelection( BUTTON_TEXT )
|| getToggleButtonSelection( BUTTON_LAYOUT ) )
{
detachPopup( );
}
}
else if ( e.widget.equals( btnAutoTitle ) )
{
if ( btnAutoTitle.getSelectionState( ) == ChartCheckbox.STATE_GRAYED )
{
getChart( ).getTitle( ).unsetAuto( );
getChart( ).getTitle( )
.getLabel( )
.getCaption( )
.setValue( null );
}
else
{
getChart( ).getTitle( )
.setAuto( btnAutoTitle.getSelectionState( ) == ChartCheckbox.STATE_SELECTED );
if ( btnAutoTitle.getSelectionState( ) == ChartCheckbox.STATE_UNSELECTED )
{
getChart( ).getTitle( )
.getLabel( )
.getCaption( )
.setValue( ChartUtil.getDefaultChartTitle( getChart( ) ) );
}
}
updateTextTitleState( );
}
}
protected void updateTextTitleState( )
{
txtTitle.setEnabled( isTitleEnabled( ) );
txtTitle.setText( getTitleText( ) );
}
protected void updateUIState( boolean enabled )
{
txtTitle.setEnabled( isTitleEnabled( ) );
if ( btnAutoTitle != null )
{
btnAutoTitle.setEnabled( isAutoEnabled( ) );
}
setToggleButtonEnabled( BUTTON_TEXT, enabled );
setToggleButtonEnabled( BUTTON_LAYOUT, enabled );
}
public void widgetDefaultSelected( SelectionEvent e )
{
// TODO Auto-generated method stub
}
private boolean isAutoEnabled( )
{
return !getContext( ).getUIFactory( )
.isSetInvisible( getChart( ).getTitle( ) );
}
private boolean isTitleEnabled( )
{
return !getContext( ).getUIFactory( )
.isSetInvisible( getChart( ).getTitle( ) )
&& !isAutoTitle( );
}
protected boolean isAutoTitle( )
{
return getChart( ).getTitle( ).isSetAuto( )
&& getChart( ).getTitle( ).isAuto( );
}
protected boolean needTitleAlignment( )
{
return true;
}
private String getTitleText( )
{
if ( getChart( ).getTitle( ).isAuto( ) && getContext( ).getExtendedItem( ) != null )
{
return getContext( ).getUIFactory( )
.createUIHelper( )
.getDefaultTitle( getContext( ) );
}
String title = getChart( ).getTitle( )
.getLabel( )
.getCaption( )
.getValue( );
return ( title == null ) ? "" : title; //$NON-NLS-1$
}
}
|
package com.hserv.coordinatedentry.housingmatching.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.rest.webmvc.ResourceNotFoundException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.hserv.coordinatedentry.housingmatching.dao.RepositoryFactory;
import com.hserv.coordinatedentry.housingmatching.entity.EligibleClient;
import com.hserv.coordinatedentry.housingmatching.entity.HousingInventory;
import com.hserv.coordinatedentry.housingmatching.entity.Match;
import com.hserv.coordinatedentry.housingmatching.entity.MatchStatus;
import com.hserv.coordinatedentry.housingmatching.entity.MatchStatusLevels;
import com.hserv.coordinatedentry.housingmatching.external.HousingUnitService;
import com.hserv.coordinatedentry.housingmatching.external.NotificationService;
import com.hserv.coordinatedentry.housingmatching.external.ProjectService;
import com.hserv.coordinatedentry.housingmatching.helper.InvalidMatchStatus;
import com.hserv.coordinatedentry.housingmatching.model.ClientDEModel;
import com.hserv.coordinatedentry.housingmatching.model.MatchReservationModel;
import com.hserv.coordinatedentry.housingmatching.model.MatchStatusModel;
import com.hserv.coordinatedentry.housingmatching.service.BatchProcessService;
import com.hserv.coordinatedentry.housingmatching.service.EligibleClientService;
import com.hserv.coordinatedentry.housingmatching.service.MatchReservationsService;
import com.hserv.coordinatedentry.housingmatching.service.ServiceFactory;
import com.hserv.coordinatedentry.housingmatching.translator.MatchReservationTranslator;
import com.hserv.coordinatedentry.housingmatching.util.MatchProcessLogger;
import com.hserv.coordinatedentry.housingmatching.util.SecurityContextUtil;
import com.servinglynk.hmis.warehouse.client.search.ISearchServiceClient;
import com.servinglynk.hmis.warehouse.core.model.BaseClient;
import com.servinglynk.hmis.warehouse.core.model.BaseProject;
import com.servinglynk.hmis.warehouse.core.model.Parameter;
import com.servinglynk.hmis.warehouse.core.model.Parameters;
import com.servinglynk.hmis.warehouse.core.model.Session;
@Service
public class MatchReservationsServiceImpl implements MatchReservationsService {
@Autowired
RepositoryFactory repositoryFactory;
@Autowired
ServiceFactory serviceFactory;
@Autowired
MatchReservationTranslator matchReservationTranslator;
@Autowired
NotificationService notificationService;
@Autowired
EligibleClientService eligibleClientService;
@Autowired
HousingUnitService housingUnitService;
@Autowired
CommunityServiceLocator communityServiceLocator;
@Autowired
EligibilityValidator eligibilityValidator;
@Autowired
ISearchServiceClient searchServiceClient;
@Autowired
BatchProcessService batchProcessService;
@Autowired
MatchProcessLogger logger;
Map<Integer, Integer[]> statusMap =new HashMap<Integer,Integer[]>();
@Override
public boolean createMatchReservation(MatchReservationModel matchReservationModel) {
repositoryFactory.getMatchReservationsRepository().saveAndFlush(matchReservationTranslator.translate(matchReservationModel));
return true;
}
@Override
public boolean createMatchReservation(List<MatchReservationModel> matchReservationModels) {
Set<Match> matchReservations = matchReservationTranslator
.translates(new HashSet<MatchReservationModel>(matchReservationModels));
for (Match matchReservation : matchReservations) {
repositoryFactory.getMatchReservationsRepository().saveAndFlush(matchReservation);
}
return true;
}
@Override
public boolean deleteAll() {
repositoryFactory.getMatchReservationsRepository().deleteAll();
return true;
}
@Override
public Page<Match> findAll(String q,Pageable pageable,String projectGroupCode) {
String[] status ={};
if(q!=null)
status= q.split(",");
if(status.length>0){
return repositoryFactory.getMatchReservationsRepository().findByProgramTypeAndMatchStatusInAndDeleted(projectGroupCode,status,false,pageable);
}else{
return repositoryFactory.getMatchReservationsRepository().findByProgramTypeAndDeleted(projectGroupCode,false,pageable);
}
}
@Override
public boolean deleteByClientId(UUID clientId) {
EligibleClient client = repositoryFactory.getEligibleClientsRepository().findByClientIdAndDeleted(clientId, false);
if(client!=null)
{
List<Match> matches = repositoryFactory.getMatchReservationsRepository().findByEligibleClientAndDeleted(client, false);
repositoryFactory.getMatchReservationsRepository().delete(matches);
return true;
}
return false;
}
@Override
public MatchReservationModel findByClientId(UUID clientId) {
String projectGroup = SecurityContextUtil.getUserProjectGroup();
EligibleClient eligibleClient = repositoryFactory.getEligibleClientsRepository().findByClientIdAndProjectGroupCodeAndDeleted(clientId, projectGroup,false);
if (eligibleClient==null) throw new ResourceNotFoundException("Client not found "+clientId);
List<Match> matchs = repositoryFactory.getMatchReservationsRepository().findByEligibleClientAndDeleted(eligibleClient,false);
if(matchs.isEmpty()) throw new ResourceNotFoundException("macth reservation not found for the client "+clientId);
return matchReservationTranslator.translate(matchs.get(0));
}
@Override
public boolean updateByClientId(UUID clientId, MatchReservationModel matchReservationModel) {
EligibleClient eligibleClient = repositoryFactory.getEligibleClientsRepository().findOne(clientId);
if(eligibleClient==null)
return false;
Match matchReservations = matchReservationTranslator.translate(matchReservationModel);
matchReservations.setEligibleClient(eligibleClient);
repositoryFactory.getMatchReservationsRepository().saveAndFlush(matchReservations);
return true;
}
@Override
public void updateMatchStatus(UUID clientId, MatchStatusModel statusModel,String auditUser,Session session,String trustedApp) throws Exception {
EligibleClient client = new EligibleClient();
client.setClientId(clientId);
List<Match> matches = (List<Match>) repositoryFactory.getMatchReservationsRepository().findByEligibleClientAndDeleted(client,false);
if(matches.isEmpty()) throw new ResourceNotFoundException("No match reservation found for this client");
Match match = matches.get(0);
List<MatchStatusLevels> nextLevels = repositoryFactory.getMatchStatuLevelsRepository().findByProjectGroupCodeAndStatusCode(match.getProgramType(), match.getMatchStatus()+"");
List newStatus = new ArrayList();
for(MatchStatusLevels level : nextLevels){
newStatus.addAll(Arrays.asList(level.getNextStatusCode().split(",")));
}
if(!newStatus.contains(statusModel.getStatus()+"")){
throw new InvalidMatchStatus("Invalid status. Current status "+match.getMatchStatus());
}
MatchStatus matchStatus = new MatchStatus();
BeanUtils.copyProperties(statusModel, matchStatus,"recipients");
if(!statusModel.getRecipients().getToRecipients().isEmpty())
matchStatus.setRecipients(statusModel.getRecipients().toJSONString());
matchStatus.setClientId(clientId);
repositoryFactory.getMatchStatusRepository().save(matchStatus);
match.setMatchStatus(statusModel.getStatus());
repositoryFactory.getMatchReservationsRepository().save(match);
if(!statusModel.getRecipients().getToRecipients().isEmpty())
notificationService.notifyStatusUpdate(match, statusModel.getRecipients(),session,trustedApp);
}
public List<MatchStatusModel> getMatchStatusHistory(UUID clientId,String projectGroupCode) throws Exception {
List<MatchStatusModel> history = new ArrayList<MatchStatusModel>();
List<MatchStatus> statusHistory = repositoryFactory.getMatchStatusRepository().findByClientIdOrderByDateCreatedDesc(clientId);
for(MatchStatus matchStatus : statusHistory){
MatchStatusModel matchStatusModel = new MatchStatusModel();
BeanUtils.copyProperties(matchStatus, matchStatusModel,"recipients");
List<MatchStatusLevels> matchStatusLevels = repositoryFactory.getMatchStatuLevelsRepository().findByProjectGroupCodeAndStatusCode(projectGroupCode,(matchStatus.getStatus()+""));
if(!matchStatusLevels.isEmpty())
matchStatusModel.setStatusDescription(matchStatusLevels.get(0).getStatusDescription());
//matchStatusModel.setStatusCode(MatchStatusUpdateEnum.lookupEnum(matchStatus.getStatus()+"").getValue());
// if(matchStatus.getRecipients()!=null)
// matchStatusModel.setRecipients(objectMapper.readValue(matchStatus.getRecipients(), Recipients.class));
history.add(matchStatusModel);
}
return history;
}
public MatchStatusModel getMatchStatusById(UUID id) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
MatchStatusModel matchStatusModel = new MatchStatusModel();
MatchStatus matchStatus = repositoryFactory.getMatchStatusRepository().findOne(id);
BeanUtils.copyProperties(matchStatus, matchStatusModel,"recipients");
/* if(matchStatus.getRecipients()!=null)
matchStatusModel.setRecipients(objectMapper.readValue(matchStatus.getRecipients(), Recipients.class));*/
return matchStatusModel;
}
@Autowired
ProjectService projectService;
@Async
public void matchingProcess(Integer maxClients,Session session , String trustedAppId,UUID processId) {
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(session, ""));
logger.setProcessId(processId);
String projectGroup = session.getAccount().getProjectGroup().getProjectGroupCode();
List<HousingInventory> housingInventories = repositoryFactory.getHousingUnitsRepository().findByProjectGroupCodeAndVacantAndDeleted(projectGroup,true,false);
// match.process.housingInventories= {"step":"FETCH vacant housing units.","statusMessage":"SUCCESS - {} housing unit(s) loaded"}
logger.log("match.process.housingInventories",new Object[]{housingInventories.size()},housingInventories.size()>0 ? true :false,null,null,null);
Integer matchCount =0;
int housingUnitIndex=1;
for(HousingInventory housingInventory : housingInventories ){
logger.log("macth.process.selectedHousingUnit", new Object[]{housingUnitIndex,housingInventory.getHousingInventoryId(),housingInventory.getFamilyUnit() == true ? "FAMILY" : "SINGLE_ADULT"}, true, housingInventory.getHousingInventoryId(), null, null);
BaseProject project = projectService.getProjectInfo(housingInventory.getProjectId(), session, trustedAppId);
logger.log("match.process.project.loaded",new Object[]{project!=null? "SUCCESS":"FAILED",housingInventory.getHousingInventoryId(),project!=null? project.getProjectType(): "Project not found in HMIS"}, project!=null ? true : false,housingInventory.getHousingInventoryId(),null,null);
if(project!=null) {
List<EligibleClient> clients= new ArrayList<>();
if(housingInventory.getFamilyUnit()){
clients = eligibleClientService.getEligibleClients(project.getProjectType(),projectGroup, "FAMILY");
}else{
clients = eligibleClientService.getEligibleClients(project.getProjectType(),projectGroup, "SINGLE_ADULT");
}
logger.log("match.process.clients.loaded",new Object[]{clients.size()>0? "SUCCESS" : "FAILED",clients.size(),project.getProjectType(),housingInventory.getFamilyUnit() == true ? "FAMILY" : "SINGLE_ADULT"},clients.size()>0 ? true : false,housingInventory.getHousingInventoryId(),project.getProjectId(),null);
int clientIndex = 1;
for(EligibleClient client : clients) {
logger.log("match.process.selectedClient", new Object[]{clientIndex,client.getClientId()}, true, housingInventory.getHousingInventoryId(), project.getProjectId(), client.getClientId());
boolean validClient= false;
BaseClient baseClient = eligibleClientService.getClientInfo(client.getClientId(), trustedAppId, session.getToken());
if(baseClient!=null){
Parameters clientDEs = eligibleClientService.getClientDataElements(baseClient.getClientId(), trustedAppId, session.getToken());
ClientDEModel model = new ClientDEModel();
model.setEligibleClientService(eligibleClientService);
model.populateValues(baseClient,clientDEs);
model.populateValues(client,clientDEs);
model.populateValues(repositoryFactory.getHouseholdMembershipRepository().findByGlobalClientIdAndDeleted(baseClient.getClientId(), false),trustedAppId,session.getToken(),clientDEs);
logger.log("match.process.clientInfo.loaded",new Object[]{client.getClientId(),baseClient.getFirstName(),baseClient.getLastName(),model.getAge(),client.getCocScore(),client.getSurveyScore()},true,housingInventory.getHousingInventoryId(),project.getProjectId(),baseClient.getClientId());
Integer bedsRequired = eligibilityValidator.validateBedsAvailability(baseClient.getClientId(), housingInventory.getBedsCurrent(),housingInventory.getHousingInventoryId(),project.getProjectId());
Map<String, Object> clientDataElements = map(clientDEs.getParameters());
if(clientDataElements.get("disabilityRequired".toLowerCase())==null) clientDataElements.put("disabilityRequired".toLowerCase(), false);
if(clientDataElements.get("mentalHealthProblem".toLowerCase())==null) clientDataElements.put("mentalHealthProblem".toLowerCase(), false);
if(bedsRequired!=0) validClient = eligibilityValidator.validateProjectEligibility(clientDataElements,baseClient.getClientId() ,project.getProjectId(),housingInventory.getHousingInventoryId());
if(validClient){
this.matchClient(client, housingInventory,projectGroup);
logger.log("match.process.matchsuccess", new Object[]{housingInventory.getHousingInventoryId(),client.getClientId()}, true, housingInventory.getHousingInventoryId(),project.getProjectId(),model.getClientId());
matchCount++;
break;
}
}
clientIndex++;
}
if(matchCount==maxClients) break;
}
housingUnitIndex++;
}
batchProcessService.endBatch(processId);
}
public Map<String, Object> map(List<Parameter> parameters) {
Map<String, Object> map = new HashMap<String,Object>();
for (Parameter parameter : parameters) {
Object value = parameter.getValue();
/* if(value){
map.put(parameter.getKey(), (Boolean)value);
}else{
*/ map.put(parameter.getKey().toLowerCase(), value);
}
return map;
}
public void matchClient(EligibleClient client,HousingInventory housingInventory,String projectGroupCode){
List<Match> matches = repositoryFactory.getMatchReservationsRepository().findByEligibleClientAndDeleted(client,false);
Match match =null;
if(matches.isEmpty()) {
match = new Match();
match.setEligibleClient(client);
}else{
match = matches.get(0);
}
match.setHousingUnitId(housingInventory.getHousingInventoryId());
match.setManualMatch(false);
match.setMatchDate(new Date());
match.setMatchStatus(0);
match.setProgramType(projectGroupCode);
repositoryFactory.getMatchReservationsRepository().save(match);
client.setMatched(true);
repositoryFactory.getEligibleClientsRepository().save(client);
housingInventory.setVacant(false);
// housingInventory.setBedsCurrent(housingInventory.getBedsCurrent()-1);
repositoryFactory.getHousingUnitsRepository().save(housingInventory);
}
}
|
package org.innovateuk.ifs.form.repository;
import org.innovateuk.ifs.BaseRepositoryIntegrationTest;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.repository.CompetitionRepository;
import org.innovateuk.ifs.file.resource.FileTypeCategory;
import org.innovateuk.ifs.form.domain.FormInput;
import org.innovateuk.ifs.form.domain.FormValidator;
import org.innovateuk.ifs.form.domain.GuidanceRow;
import org.innovateuk.ifs.form.domain.Question;
import org.innovateuk.ifs.form.resource.FormInputType;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.hibernate.validator.internal.util.CollectionHelper.asSet;
import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition;
import static org.innovateuk.ifs.file.resource.FileTypeCategory.PDF;
import static org.innovateuk.ifs.file.resource.FileTypeCategory.SPREADSHEET;
import static org.innovateuk.ifs.form.builder.FormInputBuilder.newFormInput;
import static org.innovateuk.ifs.form.builder.FormValidatorBuilder.newFormValidator;
import static org.innovateuk.ifs.form.builder.GuidanceRowBuilder.newFormInputGuidanceRow;
import static org.innovateuk.ifs.form.builder.QuestionBuilder.newQuestion;
import static org.innovateuk.ifs.form.resource.FormInputScope.APPLICATION;
import static org.innovateuk.ifs.form.resource.FormInputType.FILEUPLOAD;
import static org.junit.Assert.*;
import static org.springframework.test.util.ReflectionTestUtils.getField;
/**
* Repository Integration tests for Form Inputs.
*/
public class FormInputRepositoryIntegrationTest extends BaseRepositoryIntegrationTest<FormInputRepository> {
private static final Long INACTIVE_FORM_INPUT_ID = 200L;
@Autowired
private FormInputRepository repository;
@Autowired
private QuestionRepository questionRepository;
@Autowired
private CompetitionRepository competitionRepository;
@Override
@Autowired
protected void setRepository(FormInputRepository repository) {
this.repository = repository;
}
@Test
public void test_findOne() {
FormInput input = repository.findById(1L).get();
assertEquals(Long.valueOf(1), input.getId());
assertEquals(Integer.valueOf(400), input.getWordCount());
assertEquals(FormInputType.TEXTAREA, input.getType());
assertEquals(Long.valueOf(1L), ((Competition) getField(input, "competition")).getId());
assertTrue(input.isIncludedInApplicationSummary());
assertEquals("1. What is the business opportunity that your project addresses?", input.getDescription());
}
@Test
public void test_findOne_nonExistentInput() {
assertFalse(repository.findById(Long.MAX_VALUE).isPresent());
}
@Test
public void test_findByCompetitionId() {
List<FormInput> competitionInputs = repository.findByCompetitionIdAndActiveTrueOrderByPriorityAsc(1L);
assertEquals(39, competitionInputs.size());
FormInput first = competitionInputs.get(0);
assertEquals(Long.valueOf(1), first.getId());
FormInput last = competitionInputs.get(competitionInputs.size() - 1);
assertEquals(Long.valueOf(186), last.getId());
//Assert that inactive form input is not returned.
FormInput inactive = repository.findById(INACTIVE_FORM_INPUT_ID).get();
assertThat(inactive, notNullValue());
assertThat(competitionInputs.contains(inactive), is(false));
//Assert that inactive form input is linked to the competition
assertThat(inactive.getCompetition().getId(), is(equalTo(1L)));
}
@Test
public void test_findByCompetitionId_nonExistentCompetition() {
List<FormInput> competitionInputs = repository.findByCompetitionIdAndActiveTrueOrderByPriorityAsc(999L);
assertEquals(0, competitionInputs.size());
}
@Test
public void test_findByCompetitionIdAndScope() {
List<FormInput> competitionInputs = repository.findByCompetitionIdAndScopeAndActiveTrueOrderByPriorityAsc(1L, APPLICATION);
assertEquals(16, competitionInputs.size());
FormInput first = competitionInputs.get(0);
assertEquals(Long.valueOf(1), first.getId());
FormInput last = competitionInputs.get(competitionInputs.size() - 1);
assertEquals(Long.valueOf(18), last.getId());
//Assert that inactive form input is not returned.
FormInput inactive = repository.findById(INACTIVE_FORM_INPUT_ID).get();
assertThat(inactive, notNullValue());
assertThat(competitionInputs.contains(inactive), is(false));
//Assert that inactive form input is linked to the competition and has correct scope.
assertThat(inactive.getCompetition().getId(), is(equalTo(1L)));
assertThat(inactive.getScope(), is(equalTo(APPLICATION)));
}
@Test
public void test_findByCompetitionIdAndScope_nonExistingCompetition() {
List<FormInput> competitionInputs = repository.findByCompetitionIdAndScopeAndActiveTrueOrderByPriorityAsc(999L, APPLICATION);
assertTrue(competitionInputs.isEmpty());
}
@Test
public void test_findByQuestionId() {
List<FormInput> questionInputs = repository.findByQuestionIdAndActiveTrueOrderByPriorityAsc(1L);
assertThat(questionInputs, hasSize(3));
assertEquals(Long.valueOf(1), questionInputs.get(0).getId());
assertEquals(Long.valueOf(168), questionInputs.get(1).getId());
assertEquals(Long.valueOf(169), questionInputs.get(2).getId());
//Assert that inactive form input is not returned.
FormInput inactive = repository.findById(INACTIVE_FORM_INPUT_ID).get();
assertThat(inactive, notNullValue());
assertThat(questionInputs.contains(inactive), is(false));
//Assert it is actually linked to the question we are querying for.
assertThat(inactive.getQuestion().getId(), is(equalTo(1L)));
}
@Test
public void test_findByQuestionId_nonExistingQuestion() {
List<FormInput> formInputs = repository.findByQuestionIdAndActiveTrueOrderByPriorityAsc(999L);
assertTrue(formInputs.isEmpty());
}
@Test
public void test_findByQuestionIdAndScope() {
List<FormInput> questionInputs = repository.findByQuestionIdAndScopeAndActiveTrueOrderByPriorityAsc(1L, APPLICATION);
FormInput first = questionInputs.get(0);
assertEquals(Long.valueOf(1), first.getId());
//Assert that inactive form input is not returned.
FormInput inactive = repository.findById(INACTIVE_FORM_INPUT_ID).get();
assertThat(inactive, notNullValue());
assertThat(questionInputs.contains(inactive), is(false));
//Assert it is actually linked to the question and has correct scope.
assertThat(inactive.getQuestion().getId(), is(equalTo(1L)));
assertThat(inactive.getScope(), is(equalTo(APPLICATION)));
}
@Test
public void test_findByQuestionIdAndScope_nonExistingQuestion() {
List<FormInput> questionInputs = repository.findByQuestionIdAndScopeAndActiveTrueOrderByPriorityAsc(999L, APPLICATION);
assertTrue(questionInputs.isEmpty());
}
@Test
public void test_save() {
Integer wordCount = 100;
FormInputType formInputType = FILEUPLOAD;
Question question = newQuestion().withId(1L).build();
Competition competition = newCompetition().withId(1L).build();
Set<FormValidator> inputValidators = asSet(
newFormValidator().build(),
newFormValidator().build()
);
String guidanceTitle = "Guidance title";
String guidanceAnswer = "Guidance answer";
String description = "Description";
Boolean includedInApplicationSummary = false;
Integer priority = 1;
List<GuidanceRow> guidanceRows = newFormInputGuidanceRow().withPriority(0).build(2);
Boolean isActive = true;
Set<FileTypeCategory> allowedFileTypes = asSet(PDF, SPREADSHEET);
FormInput formInput = newFormInput()
.withWordCount(wordCount)
.withType(formInputType)
.withQuestion(question)
.withCompetition(competition)
.withInputValidators(inputValidators)
.withGuidanceTitle(guidanceTitle)
.withGuidanceAnswer(guidanceAnswer)
.withDescription(description)
.withIncludedInApplicationSummary(includedInApplicationSummary)
.withPriority(priority)
.withGuidanceRows(guidanceRows)
.withActive(isActive)
.withAllowedFileTypes(allowedFileTypes)
.build();
guidanceRows.stream().forEach(gr -> gr.setFormInput(formInput));
repository.save(formInput);
FormInput savedFormInput = repository.findById(formInput.getId()).get();
assertEquals(savedFormInput.getWordCount(), wordCount);
assertEquals(savedFormInput.getType(), formInputType);
assertEquals(savedFormInput.getQuestion().getId(), question.getId());
assertEquals(savedFormInput.getCompetition().getId(), competition.getId());
assertEquals(savedFormInput.getInputValidators().size(), inputValidators.size());
assertEquals(savedFormInput.getGuidanceTitle(), guidanceTitle);
assertEquals(savedFormInput.getGuidanceAnswer(), guidanceAnswer);
assertEquals(savedFormInput.getDescription(), description);
assertEquals(savedFormInput.isIncludedInApplicationSummary(), includedInApplicationSummary);
assertEquals(savedFormInput.getPriority(), priority);
assertEquals(savedFormInput.getGuidanceRows().size(), guidanceRows.size());
assertEquals(savedFormInput.getActive(), isActive);
assertEquals(savedFormInput.getAllowedFileTypes(), allowedFileTypes);
}
}
|
package org.innovateuk.ifs.assessment.service;
import org.innovateuk.ifs.competition.resource.AssessmentPeriodResource;
import org.innovateuk.ifs.competition.resource.MilestoneResource;
import org.innovateuk.ifs.competition.service.AssessmentPeriodRestService;
import org.innovateuk.ifs.competition.service.MilestoneRestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.ZonedDateTime;
import java.time.format.TextStyle;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class AssessmentPeriodService {
@Autowired
private AssessmentPeriodRestService assessmentPeriodRestService;
@Autowired
private MilestoneRestService milestoneRestService;
public String assessmentPeriodName(long assessmentPeriodId, long competitionId) {
List<AssessmentPeriodResource> assessmentPeriods = assessmentPeriodRestService.getAssessmentPeriodByCompetitionId(competitionId).getSuccess();
if (!(assessmentPeriods.size() > 1)) {
return null;
}
List<MilestoneResource> milestones = milestoneRestService.getAllMilestonesByCompetitionId(competitionId).getSuccess();
Map<Long, List<MilestoneResource>> milestonesGroupedByAssessmentPeriodId = milestones.stream()
.filter(m -> m.getAssessmentPeriodId() != null)
.collect(Collectors.groupingBy(MilestoneResource::getAssessmentPeriodId));
int index = 1;
int assessmentPeriodNumber = -1;
for (Map.Entry<Long, List<MilestoneResource>> assessmentPeriodEntry: milestonesGroupedByAssessmentPeriodId.entrySet()) {
if (assessmentPeriodEntry.getKey().equals(assessmentPeriodId)) {
assessmentPeriodNumber = index;
break;
}
index++;
}
List<MilestoneResource> milestonesForAssessmentPeriod = milestonesGroupedByAssessmentPeriodId.get(assessmentPeriodId);
MilestoneResource first = milestonesForAssessmentPeriod.get(0);
MilestoneResource last = milestonesForAssessmentPeriod.get(milestonesForAssessmentPeriod.size() - 1);
ZonedDateTime start = first.getDate();
ZonedDateTime end = last.getDate();
if (start == null || end == null) {
return String.format("Assessment period %d", assessmentPeriodNumber);
}
if (start.getYear() == end.getYear()) {
return String.format("Assessment period %d: %s %s to %s %s %s",
assessmentPeriodNumber,
start.getDayOfMonth(),
start.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault()),
end.getDayOfMonth(),
end.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault()),
end.getYear());
}
return String.format("Assessment period %d: %s %s %s to %s %s %s",
assessmentPeriodNumber,
start.getDayOfMonth(),
start.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault()),
start.getYear(),
end.getDayOfMonth(),
end.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault()),
end.getYear());
}
}
|
package fr.opensagres.eclipse.jsbuild.internal.ui.views;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import fr.opensagres.eclipse.jsbuild.core.IJSBuildFileNode;
import fr.opensagres.eclipse.jsbuild.core.ITask;
import fr.opensagres.eclipse.jsbuild.core.JSBuildFileFactoryManager;
import fr.opensagres.eclipse.jsbuild.internal.ui.Logger;
/**
* JavaScript build file content provider.
*
*/
public class JSBuildFileContentProvider implements ITreeContentProvider {
protected static final Object[] EMPTY_ARRAY = new Object[0];
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
@Override
public void dispose() {
// do nothing
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface
* .viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// do nothing
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(Object)
*/
@Override
public Object[] getChildren(Object parentNode) {
IJSBuildFileNode buildFileNode = null;
if (parentNode instanceof IResource) {
buildFileNode = JSBuildFileFactoryManager
.tryToCreate((IResource) parentNode);
} else if (parentNode instanceof IJSBuildFileNode) {
buildFileNode = (IJSBuildFileNode) parentNode;
}
if (buildFileNode != null) {
try {
buildFileNode.getBuildFile().parseBuildFile();
} catch (CoreException e) {
Logger.logException("Error while loading tasks", e);
}
if (buildFileNode.hasChildren()) {
Collection<ITask> children = buildFileNode.getChildNodes();
return children.toArray();
}
}
/*
* else if (parentNode instanceof IAntModel) { return new Object[] {
* ((IAntModel) parentNode).getProjectNode() }; }
*/
return EMPTY_ARRAY;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(Object)
*/
@Override
public Object getParent(Object element) {
if (element instanceof IJSBuildFileNode) {
return ((IJSBuildFileNode) element).getParentNode();
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(Object)
*/
@Override
public boolean hasChildren(Object element) {
if (element instanceof IJSBuildFileNode) {
return ((IJSBuildFileNode) element).hasChildren();
}
return true;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.viewers.IStructuredContentProvider#getElements(Object)
*/
@Override
public Object[] getElements(Object inputElement) {
if (inputElement instanceof List) {
return ((List<?>) inputElement).toArray();
}
if (inputElement instanceof Object[]) {
return (Object[]) inputElement;
}
return EMPTY_ARRAY;
}
}
|
package com.rockwellcollins.atc.agree.analysis.ast;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.osate.aadl2.AadlBoolean;
import org.osate.aadl2.AadlInteger;
import org.osate.aadl2.AadlPackage;
import org.osate.aadl2.AadlReal;
import org.osate.aadl2.AnnexSubclause;
import org.osate.aadl2.BooleanLiteral;
import org.osate.aadl2.Classifier;
import org.osate.aadl2.ComponentClassifier;
import org.osate.aadl2.ComponentImplementation;
import org.osate.aadl2.ConnectedElement;
import org.osate.aadl2.Connection;
import org.osate.aadl2.ConnectionEnd;
import org.osate.aadl2.Context;
import org.osate.aadl2.DataClassifier;
import org.osate.aadl2.DataImplementation;
import org.osate.aadl2.DataPort;
import org.osate.aadl2.DataSubcomponent;
import org.osate.aadl2.DataSubcomponentType;
import org.osate.aadl2.DataType;
import org.osate.aadl2.EnumerationLiteral;
import org.osate.aadl2.EventDataPort;
import org.osate.aadl2.EventPort;
import org.osate.aadl2.Feature;
import org.osate.aadl2.FeatureGroup;
import org.osate.aadl2.FeatureGroupType;
import org.osate.aadl2.IntegerLiteral;
import org.osate.aadl2.ModalPropertyValue;
import org.osate.aadl2.NamedElement;
import org.osate.aadl2.NamedValue;
import org.osate.aadl2.Property;
import org.osate.aadl2.PropertyAssociation;
import org.osate.aadl2.PropertyConstant;
import org.osate.aadl2.PropertyExpression;
import org.osate.aadl2.RangeValue;
import org.osate.aadl2.RealLiteral;
import org.osate.aadl2.StringLiteral;
import org.osate.aadl2.Subcomponent;
import org.osate.aadl2.instance.ComponentInstance;
import org.osate.aadl2.instance.FeatureCategory;
import org.osate.aadl2.instance.FeatureInstance;
import org.osate.aadl2.modelsupport.resources.OsateResourceUtil;
import org.osate.aadl2.properties.PropertyDoesNotApplyToHolderException;
import org.osate.annexsupport.AnnexUtil;
import org.osate.xtext.aadl2.properties.util.EMFIndexRetrieval;
import org.osate.xtext.aadl2.properties.util.PropertyUtils;
import com.rockwellcollins.atc.agree.agree.AADLEnumerator;
import com.rockwellcollins.atc.agree.agree.AgreeContract;
import com.rockwellcollins.atc.agree.agree.AgreeContractSubclause;
import com.rockwellcollins.atc.agree.agree.AgreePackage;
import com.rockwellcollins.atc.agree.agree.Arg;
import com.rockwellcollins.atc.agree.agree.AssertStatement;
import com.rockwellcollins.atc.agree.agree.AssignStatement;
import com.rockwellcollins.atc.agree.agree.AssumeStatement;
import com.rockwellcollins.atc.agree.agree.AsynchStatement;
import com.rockwellcollins.atc.agree.agree.BoolLitExpr;
import com.rockwellcollins.atc.agree.agree.CalenStatement;
import com.rockwellcollins.atc.agree.agree.ConnectionStatement;
import com.rockwellcollins.atc.agree.agree.ConstStatement;
import com.rockwellcollins.atc.agree.agree.EqStatement;
import com.rockwellcollins.atc.agree.agree.EventExpr;
import com.rockwellcollins.atc.agree.agree.FloorCast;
import com.rockwellcollins.atc.agree.agree.FnCallExpr;
import com.rockwellcollins.atc.agree.agree.FnDefExpr;
import com.rockwellcollins.atc.agree.agree.GetPropertyExpr;
import com.rockwellcollins.atc.agree.agree.GuaranteeStatement;
import com.rockwellcollins.atc.agree.agree.InitialStatement;
import com.rockwellcollins.atc.agree.agree.InputStatement;
import com.rockwellcollins.atc.agree.agree.IntLitExpr;
import com.rockwellcollins.atc.agree.agree.LatchedExpr;
import com.rockwellcollins.atc.agree.agree.LatchedStatement;
import com.rockwellcollins.atc.agree.agree.LemmaStatement;
import com.rockwellcollins.atc.agree.agree.LinearizationDefExpr;
import com.rockwellcollins.atc.agree.agree.MNSynchStatement;
import com.rockwellcollins.atc.agree.agree.NamedID;
import com.rockwellcollins.atc.agree.agree.NestedDotID;
import com.rockwellcollins.atc.agree.agree.NodeBodyExpr;
import com.rockwellcollins.atc.agree.agree.NodeDefExpr;
import com.rockwellcollins.atc.agree.agree.NodeEq;
import com.rockwellcollins.atc.agree.agree.NodeLemma;
import com.rockwellcollins.atc.agree.agree.NodeStmt;
import com.rockwellcollins.atc.agree.agree.PatternStatement;
import com.rockwellcollins.atc.agree.agree.PreExpr;
import com.rockwellcollins.atc.agree.agree.PrevExpr;
import com.rockwellcollins.atc.agree.agree.PrimType;
import com.rockwellcollins.atc.agree.agree.PropertyStatement;
import com.rockwellcollins.atc.agree.agree.RealCast;
import com.rockwellcollins.atc.agree.agree.RealLitExpr;
import com.rockwellcollins.atc.agree.agree.RecordDefExpr;
import com.rockwellcollins.atc.agree.agree.RecordExpr;
import com.rockwellcollins.atc.agree.agree.RecordType;
import com.rockwellcollins.atc.agree.agree.RecordUpdateExpr;
import com.rockwellcollins.atc.agree.agree.SpecStatement;
import com.rockwellcollins.atc.agree.agree.SynchStatement;
import com.rockwellcollins.atc.agree.agree.ThisExpr;
import com.rockwellcollins.atc.agree.agree.TimeExpr;
import com.rockwellcollins.atc.agree.agree.TimeFallExpr;
import com.rockwellcollins.atc.agree.agree.TimeOfExpr;
import com.rockwellcollins.atc.agree.agree.TimeRiseExpr;
import com.rockwellcollins.atc.agree.agree.util.AgreeSwitch;
import com.rockwellcollins.atc.agree.analysis.Activator;
import com.rockwellcollins.atc.agree.analysis.AgreeCalendarUtils;
import com.rockwellcollins.atc.agree.analysis.AgreeException;
import com.rockwellcollins.atc.agree.analysis.AgreeLogger;
import com.rockwellcollins.atc.agree.analysis.AgreeTypeUtils;
import com.rockwellcollins.atc.agree.analysis.AgreeUtils;
import com.rockwellcollins.atc.agree.analysis.MNSynchronyElement;
import com.rockwellcollins.atc.agree.analysis.ast.AgreeAADLConnection.ConnectionType;
import com.rockwellcollins.atc.agree.analysis.ast.AgreeNode.TimingModel;
import com.rockwellcollins.atc.agree.analysis.ast.visitors.AgreeInlineLatchedConnections;
import com.rockwellcollins.atc.agree.analysis.ast.visitors.AgreeMakeClockedLustreNodes;
import com.rockwellcollins.atc.agree.analysis.extentions.AgreeAutomater;
import com.rockwellcollins.atc.agree.analysis.extentions.AgreeAutomaterRegistry;
import com.rockwellcollins.atc.agree.analysis.extentions.ExtensionRegistry;
import com.rockwellcollins.atc.agree.analysis.linearization.LinearizationRewriter;
import com.rockwellcollins.atc.agree.analysis.lustre.visitors.IdGatherer;
import com.rockwellcollins.atc.agree.analysis.preferences.PreferenceConstants;
import com.rockwellcollins.atc.agree.analysis.realtime.AgreeCauseEffectPattern;
import com.rockwellcollins.atc.agree.analysis.realtime.AgreePatternBuilder;
import com.rockwellcollins.atc.agree.analysis.realtime.AgreePatternTranslator;
import com.rockwellcollins.atc.agree.analysis.realtime.AgreePeriodicPattern;
import com.rockwellcollins.atc.agree.analysis.realtime.AgreeSporadicPattern;
import jkind.lustre.BinaryExpr;
import jkind.lustre.BinaryOp;
import jkind.lustre.BoolExpr;
import jkind.lustre.CastExpr;
import jkind.lustre.Equation;
import jkind.lustre.Expr;
import jkind.lustre.IdExpr;
import jkind.lustre.IfThenElseExpr;
import jkind.lustre.IntExpr;
import jkind.lustre.NamedType;
import jkind.lustre.Node;
import jkind.lustre.NodeCallExpr;
import jkind.lustre.RealExpr;
import jkind.lustre.RecordAccessExpr;
import jkind.lustre.TupleExpr;
import jkind.lustre.Type;
import jkind.lustre.UnaryExpr;
import jkind.lustre.UnaryOp;
import jkind.lustre.VarDecl;
import jkind.lustre.builders.NodeBuilder;
public class AgreeASTBuilder extends AgreeSwitch<Expr> {
public static final String clockIDSuffix = "___CLOCK_";
public static final String eventSuffix = "___EVENT_";
public static final String dotChar = "__";
public static final String unspecifiedAadlPropertyPrefix = "_unspec_property_";
public static List<Node> globalNodes;
private static Set<Type> globalTypes;
private static Map<NamedElement, String> typeMap;
private static Map<String, AgreeVar> timeOfVarMap;
private static Map<String, AgreeVar> timeRiseVarMap;
private static Map<String, AgreeVar> timeFallVarMap;
// TODO: a number of the maps in this class are static but appear to more
// appropriately and more safely be instance variables.
private static Map<String, String> renamings;
private static Map<String, EObject> refMap;
private static Map<String, GetPropertyExpr> unspecifiedAadlProperties;
private ComponentInstance curInst; // used for Get_Property Expressions
private boolean isMonolithic = false;
private LinearizationRewriter linearizationRewriter = new LinearizationRewriter();
static class GatheredVariablesAndConstraints {
public List<AgreeVar> variables = new ArrayList<>();
public List<AgreeStatement> assertions = new ArrayList<>();
public List<AgreeStatement> obligations = new ArrayList<>();
public void addAllTo(List<AgreeVar> variables, List<AgreeStatement> assertions,
List<AgreeStatement> obligations) {
variables.addAll(this.variables);
assertions.addAll(this.assertions);
obligations.addAll(this.obligations);
}
}
public AgreeProgram getAgreeProgram(ComponentInstance compInst, boolean isMonolithic) {
boolean containsRTPatterns = false;
this.isMonolithic = isMonolithic;
globalNodes = new ArrayList<>();
globalTypes = new HashSet<>();
typeMap = new HashMap<>();
renamings = new HashMap<>();
refMap = new HashMap<>();
AgreeNode topNode = getAgreeNode(compInst, true);
List<AgreeNode> agreeNodes = gatherNodes(topNode);
// have to convert the types. The reason we use Record types in the
// first place rather than the more general types is so we can check set
// containment easily
AgreeProgram program = new AgreeProgram(agreeNodes, new ArrayList<>(globalNodes), new ArrayList<>(globalTypes),
topNode);
// if there are any patterns in the AgreeProgram we need to inline them
program = AgreePatternTranslator.translate(program);
containsRTPatterns = program.containsRealTimePatterns;
program = AgreeInlineLatchedConnections.translate(program);
program = AgreeMakeClockedLustreNodes.translate(program);
// go through the extension registries and transform the program
AgreeAutomaterRegistry aAReg = (AgreeAutomaterRegistry) ExtensionRegistry
.getRegistry(ExtensionRegistry.AGREE_AUTOMATER_EXT_ID);
List<AgreeAutomater> automaters = aAReg.getAgreeAutomaters();
for (AgreeAutomater aa : automaters) {
program = aa.transform(program);
}
program.containsRealTimePatterns(containsRTPatterns);
return program;
}
private List<AgreeNode> gatherNodes(AgreeNode node) {
List<AgreeNode> nodes = new ArrayList<>();
for (AgreeNode subNode : node.subNodes) {
nodes.addAll(gatherNodes(subNode));
nodes.add(subNode);
}
return nodes;
}
private AgreeNode getAgreeNode(ComponentInstance compInst, boolean isTop) {
List<AgreeVar> inputs = new ArrayList<>();
List<AgreeVar> outputs = new ArrayList<>();
List<AgreeVar> locals = new ArrayList<>();
List<AgreeAADLConnection> aadlConnections = new ArrayList<>();
List<AgreeOverriddenConnection> userDefinedConections = new ArrayList<>();
List<AgreeConnection> connections = new ArrayList<>();
List<AgreeNode> subNodes = new ArrayList<>();
List<AgreeStatement> assertions = new ArrayList<>();
List<AgreeStatement> assumptions = new ArrayList<>();
List<AgreeStatement> guarantees = new ArrayList<>();
List<AgreeStatement> lemmas = new ArrayList<>();
List<AgreeEquation> localEquations = new ArrayList<>();
List<AgreeStatement> patternProps = Collections.emptyList();
timeOfVarMap = new HashMap<>();
timeRiseVarMap = new HashMap<>();
timeFallVarMap = new HashMap<>();
unspecifiedAadlProperties = new HashMap<>();
Expr clockConstraint = new BoolExpr(true);
Expr initialConstraint = new BoolExpr(true);
String id = compInst.getName();
AgreeVar clockVar = new AgreeVar(id + clockIDSuffix, NamedType.BOOL, compInst.getSubcomponent(), compInst,
null);
EObject reference = isTop ? compInst.getComponentClassifier() : compInst.getSubcomponent();
TimingModel timing = null;
boolean foundSubNode = false;
boolean hasDirectAnnex = false;
boolean hasSubcomponents = false;
ComponentClassifier compClass = compInst.getComponentClassifier();
if (compClass instanceof ComponentImplementation && (isTop || isMonolithic)) {
AgreeContractSubclause annex = getAgreeAnnex(compClass);
for (ComponentInstance subInst : compInst.getComponentInstances()) {
hasSubcomponents = true;
curInst = subInst;
AgreeNode subNode = getAgreeNode(subInst, false);
if (subNode != null) {
foundSubNode = true;
subNodes.add(subNode);
}
}
boolean latched = false;
if (annex != null) {
hasDirectAnnex = true;
AgreeContract contract = (AgreeContract) annex.getContract();
curInst = compInst;
assertions.addAll(getAssertionStatements(contract.getSpecs()));
getEquationStatements(contract.getSpecs()).addAllTo(locals, assertions, guarantees);
assertions.addAll(getPropertyStatements(contract.getSpecs()));
assertions.addAll(getAssignmentStatements(contract.getSpecs()));
userDefinedConections.addAll(getConnectionStatements(contract.getSpecs()));
lemmas.addAll(getLemmaStatements(contract.getSpecs()));
addLustreNodes(contract.getSpecs());
gatherLustreTypes(contract.getSpecs());
// the clock constraints contain other nodes that we add
clockConstraint = getClockConstraint(contract.getSpecs(), subNodes);
timing = getTimingModel(contract.getSpecs());
outputs.addAll(getEquationVars(contract.getSpecs(), compInst));
for (SpecStatement spec : contract.getSpecs()) {
if (spec instanceof LatchedStatement) {
latched = true;
break;
}
}
}
aadlConnections.addAll(getConnections(((ComponentImplementation) compClass).getAllConnections(), compInst,
subNodes, latched));
connections.addAll(filterConnections(aadlConnections, userDefinedConections));
// make compClass the type so we can get it's other contract
// elements
compClass = ((ComponentImplementation) compClass).getType();
} else if (compClass instanceof ComponentImplementation) {
compClass = ((ComponentImplementation) compClass).getType();
}
curInst = compInst;
if (timing == null) {
timing = TimingModel.SYNC;
}
AgreeContractSubclause annex = getAgreeAnnex(compClass);
if (annex != null) {
hasDirectAnnex = true;
AgreeContract contract = (AgreeContract) annex.getContract();
// this makes files for monolithic verification a bit smaller
if (isTop || !hasSubcomponents) {
assumptions.addAll(getAssumptionStatements(contract.getSpecs()));
guarantees.addAll(getGuaranteeStatements(contract.getSpecs()));
}
// we count eqstatements with expressions as assertions
getEquationStatements(contract.getSpecs()).addAllTo(locals, assertions, guarantees);
assertions.addAll(getPropertyStatements(contract.getSpecs()));
outputs.addAll(getEquationVars(contract.getSpecs(), compInst));
getAgreeInputVars(contract.getSpecs(), compInst).addAllTo(inputs, assumptions, guarantees);
initialConstraint = getInitialConstraint(contract.getSpecs());
addLustreNodes(contract.getSpecs());
gatherLustreTypes(contract.getSpecs());
}
gatherUnspecifiedAadlProperties(unspecifiedAadlProperties, typeMap, globalTypes, inputs, assumptions,
guarantees);
if (!(foundSubNode || hasDirectAnnex)) {
return null;
}
gatherOutputsInputsAndTypes(outputs, inputs, compInst.getFeatureInstances(), typeMap, globalTypes, assumptions, guarantees);
// verify that every variable that is reasoned about is
// in a component containing an annex
assertReferencedSubcomponentHasAnnex(compInst, inputs, outputs, subNodes, assertions, lemmas);
AgreeNodeBuilder builder = new AgreeNodeBuilder(id);
builder.addInput(inputs);
builder.addOutput(outputs);
builder.addLocal(locals);
builder.addLocalEquation(localEquations);
builder.addConnection(connections);
builder.addSubNode(subNodes);
builder.addAssertion(assertions);
builder.addAssumption(assumptions);
builder.addGuarantee(guarantees);
builder.addLemma(lemmas);
builder.addPatternProp(patternProps);
builder.setClockConstraint(clockConstraint);
builder.setInitialConstraint(initialConstraint);
builder.setClockVar(clockVar);
builder.setReference(reference);
builder.setTiming(timing);
builder.setCompInst(compInst);
builder.addTimeOf(timeOfVarMap);
builder.addTimeRise(timeRiseVarMap);
builder.addTimeFall(timeFallVarMap);
AgreeNode result = builder.build();
renamings.put(id, compInst.getName());
refMap.put(id, compInst);
return linearizationRewriter.visit(result);
}
private List<AgreeConnection> filterConnections(List<AgreeAADLConnection> aadlConnections,
List<AgreeOverriddenConnection> userDefinedConections) {
List<AgreeConnection> conns = new ArrayList<>();
// TODO right now for event ports this will copy an overridden
// connection twice
for (AgreeAADLConnection aadlConn : aadlConnections) {
EObject aadlRef = aadlConn.reference;
AgreeConnection replacementConn = aadlConn;
for (AgreeOverriddenConnection agreeConn : userDefinedConections) {
EObject agreeRef = agreeConn.aadlConn;
if (aadlRef == agreeRef) {
replacementConn = agreeConn;
break;
}
}
conns.add(replacementConn);
}
// throw errors for non-override connections with multiple fanin
Set<AgreeVar> destinations = new HashSet<>();
for (AgreeConnection conn : conns) {
if (conn instanceof AgreeAADLConnection) {
AgreeAADLConnection aadlConn = (AgreeAADLConnection) conn;
if (!destinations.add(aadlConn.destinationVarName)) {
String message = "Multiple connections to feature '" + aadlConn.destinationVarName + "'. Remove "
+ "the additional AADL connections or override them with a connection statement "
+ "in the AGREE annex.";
throw new AgreeException(message);
}
}
}
return conns;
}
private GatheredVariablesAndConstraints getAgreeInputVars(List<SpecStatement> specs, ComponentInstance compInst) {
GatheredVariablesAndConstraints result = new GatheredVariablesAndConstraints();
for (SpecStatement spec : specs) {
if (spec instanceof InputStatement) {
EList<Arg> args = ((InputStatement) spec).getLhs();
List<VarDecl> vars = agreeVarsFromArgs(args, compInst);
for (VarDecl var : vars) {
result.variables.add((AgreeVar) var);
}
result.assertions.addAll(getVariableRangeConstraints(args, spec));
}
}
return result;
}
private void assertReferencedSubcomponentHasAnnex(ComponentInstance compInst, List<AgreeVar> inputs,
List<AgreeVar> outputs, List<AgreeNode> subNodes, List<AgreeStatement> assertions,
List<AgreeStatement> lemmas) {
Set<String> allExprIds = new HashSet<>();
for (AgreeStatement statement : assertions) {
allExprIds.addAll(gatherStatementIds(statement));
}
for (AgreeStatement statement : lemmas) {
allExprIds.addAll(gatherStatementIds(statement));
}
for (String idStr : allExprIds) {
if (idStr.contains(dotChar) && !(idStr.endsWith(AgreePatternTranslator.FALL_SUFFIX)
|| idStr.endsWith(AgreePatternTranslator.RISE_SUFFIX)
|| idStr.endsWith(AgreePatternTranslator.TIME_SUFFIX))) {
String prefix = idStr.substring(0, idStr.indexOf(dotChar));
boolean found = false;
for (AgreeVar var : inputs) {
if (var.id.startsWith(prefix + dotChar)) {
found = true;
break;
}
}
for (AgreeVar var : outputs) {
if (var.id.startsWith(prefix + dotChar)) {
found = true;
break;
}
}
for (AgreeNode subNode : subNodes) {
if (subNode.id.equals(prefix)) {
found = true;
break;
}
}
if (!found) {
throw new AgreeException(
"Variable '" + idStr.replace(dotChar, ".") + "' appears in an assertion, lemma "
+ "or equation statement in component '" + compInst.getInstanceObjectPath()
+ "' but subcomponent '" + prefix + "' does " + "not contain an AGREE annex");
}
}
}
}
private Set<String> gatherStatementIds(AgreeStatement statement) {
IdGatherer visitor = new IdGatherer();
Set<String> ids = new HashSet<>();
if (statement instanceof AgreeCauseEffectPattern) {
AgreeCauseEffectPattern pattern = (AgreeCauseEffectPattern) statement;
ids.addAll(pattern.cause.accept(visitor));
ids.addAll(pattern.effect.accept(visitor));
} else if (statement instanceof AgreePeriodicPattern) {
AgreePeriodicPattern pattern = (AgreePeriodicPattern) statement;
ids.addAll(pattern.event.accept(visitor));
} else if (statement instanceof AgreeSporadicPattern) {
AgreeSporadicPattern pattern = (AgreeSporadicPattern) statement;
ids.addAll(pattern.event.accept(visitor));
} else {
ids.addAll(statement.expr.accept(visitor));
}
return ids;
}
private List<AgreeStatement> getLemmaStatements(EList<SpecStatement> specs) {
List<AgreeStatement> lemmas = new ArrayList<>();
for (SpecStatement spec : specs) {
if (spec instanceof LemmaStatement) {
LemmaStatement lemma = (LemmaStatement) spec;
if (lemma.getExpr() != null) {
lemmas.add(new AgreeStatement(lemma.getStr(), doSwitch(lemma.getExpr()), spec));
} else {
PatternStatement pattern = lemma.getPattern();
lemmas.add(new AgreePatternBuilder(lemma.getStr(), lemma, this).doSwitch(pattern));
}
}
}
return lemmas;
}
private TimingModel getTimingModel(EList<SpecStatement> specs) {
for (SpecStatement spec : specs) {
if (spec instanceof MNSynchStatement) {
return TimingModel.ASYNC;
}
if (spec instanceof CalenStatement) {
throw new AgreeException("The use of calendar statements has been depricated");
}
if (spec instanceof AsynchStatement) {
return TimingModel.ASYNC;
}
if (spec instanceof LatchedStatement) {
return TimingModel.LATCHED;
}
if (spec instanceof SynchStatement) {
// int val = Integer.valueOf(((SynchStatement) spec).getVal());
// if (val != 0) {
// return TimingModel.ASYNC;
return TimingModel.ASYNC;
}
}
return TimingModel.SYNC;
}
private List<AgreeVar> getEquationVars(EList<SpecStatement> specs, ComponentInstance compInst) {
List<AgreeVar> agreeVars = new ArrayList<>();
for (SpecStatement spec : specs) {
if (spec instanceof EqStatement) {
EList<Arg> args = ((EqStatement) spec).getLhs();
List<VarDecl> vars = agreeVarsFromArgs(args, compInst);
for (VarDecl var : vars) {
agreeVars.add((AgreeVar) var);
}
} else if (spec instanceof PropertyStatement) {
agreeVars.add(new AgreeVar(((PropertyStatement) spec).getName(), NamedType.BOOL, spec, compInst, null));
}
}
return agreeVars;
}
private void gatherOutputsInputsAndTypes(List<AgreeVar> outputs, List<AgreeVar> inputs,
EList<FeatureInstance> features, Map<NamedElement, String> typeMap, Set<Type> typeExpressions,
List<AgreeStatement> assumptions, List<AgreeStatement> guarantees) {
for (FeatureInstance feature : features) {
featureToAgreeVars(outputs, inputs, feature, typeMap, typeExpressions, assumptions, guarantees);
}
}
private void featureToAgreeVars(List<AgreeVar> outputs, List<AgreeVar> inputs, FeatureInstance feature,
Map<NamedElement, String> typeMap, Set<Type> typeExpressions, List<AgreeStatement> assumptions,
List<AgreeStatement> guarantees) {
switch (feature.getCategory()) {
case FEATURE_GROUP:
List<AgreeVar> newInputs = new ArrayList<>();
List<AgreeVar> newOutputs = new ArrayList<>();
gatherOutputsInputsAndTypes(newOutputs, newInputs, feature.getFeatureInstances(), typeMap, typeExpressions,
assumptions, guarantees);
for (AgreeVar agreeVar : newInputs) {
String newName = feature.getName() + dotChar + agreeVar.id;
inputs.add(new AgreeVar(newName, agreeVar.type, feature.getFeature(), feature.getComponentInstance(),
feature));
}
for (AgreeVar agreeVar : newOutputs) {
String newName = feature.getName() + dotChar + agreeVar.id;
outputs.add(new AgreeVar(newName, agreeVar.type, feature.getFeature(), feature.getComponentInstance(),
feature));
}
return;
case DATA_PORT:
case EVENT_PORT:
case EVENT_DATA_PORT:
portToAgreeVar(outputs, inputs, feature, typeMap, typeExpressions, assumptions, guarantees);
return;
case DATA_ACCESS:
break;
default:
break; // TODO: handle other types
}
return;
}
private void portToAgreeVar(List<AgreeVar> outputs, List<AgreeVar> inputs, FeatureInstance feature,
Map<NamedElement, String> typeMap, Set<Type> typeExpressions, List<AgreeStatement> assumptions,
List<AgreeStatement> guarantees) {
DataSubcomponentType dataClass;
Feature dataFeature = feature.getFeature();
if (dataFeature instanceof DataPort) {
DataPort dataPort = (DataPort) dataFeature;
dataClass = dataPort.getDataFeatureClassifier();
} else if (dataFeature instanceof EventDataPort) {
EventDataPort eventDataPort = (EventDataPort) dataFeature;
dataClass = eventDataPort.getDataFeatureClassifier();
} else {
dataClass = null;
}
String name = feature.getName();
boolean isEvent = feature.getCategory() == FeatureCategory.EVENT_DATA_PORT
|| feature.getCategory() == FeatureCategory.EVENT_PORT;
if (isEvent) {
AgreeVar var = new AgreeVar(name + eventSuffix, NamedType.BOOL, feature.getFeature(),
feature.getComponentInstance(), feature);
switch (feature.getDirection()) {
case IN:
inputs.add(var);
break;
case OUT:
outputs.add(var);
break;
default:
throw new AgreeException(
"Unable to reason about bi-directional event port: " + dataFeature.getQualifiedName());
}
}
if (dataClass == null) {
// we do not reason about this type
return;
}
Type type = AgreeTypeUtils.getType(dataClass, typeMap, typeExpressions);
if (type == null) {
// we do not reason about this type
return;
}
AgreeVar agreeVar = new AgreeVar(name, type, feature.getFeature(), feature.getComponentInstance(), feature);
switch (feature.getDirection()) {
case IN:
inputs.add(agreeVar);
if (dataClass instanceof DataClassifier) {
List<Expr> constraints = getDataClassifierRangeConstraintExprs(name, (DataClassifier) dataClass);
if (!constraints.isEmpty()) {
assumptions.add(getDataClassifierTypePredicate(feature.getName(), constraints, dataFeature));
}
}
break;
case OUT:
outputs.add(agreeVar);
if (dataClass instanceof DataClassifier) {
List<Expr> constraints = getDataClassifierRangeConstraintExprs(name, (DataClassifier) dataClass);
if (!constraints.isEmpty()) {
guarantees.add(getDataClassifierTypePredicate(feature.getName(), constraints, dataFeature));
}
}
break;
default:
throw new AgreeException(
"Unable to reason about bi-directional event port: " + dataFeature.getQualifiedName());
}
}
private static AgreeStatement getDataClassifierTypePredicate(String name, List<Expr> constraints,
EObject reference) {
// must have reference so we don't throw them away later
return new AgreeStatement("Type predicate on '" + name + "'",
constraints.stream().reduce(new BoolExpr(true), (a, b) -> new BinaryExpr(a, BinaryOp.AND, b)),
reference);
}
private List<AgreeAADLConnection> getConnections(EList<Connection> connections, ComponentInstance compInst,
List<AgreeNode> subNodes, boolean latched) {
// Set<AgreeVar> destinationSet = new HashSet<>();
Property commTimingProp = EMFIndexRetrieval.getPropertyDefinitionInWorkspace(OsateResourceUtil.getResourceSet(),
"Communication_Properties::Timing");
List<AgreeAADLConnection> agreeConns = new ArrayList<>();
for (Connection conn : connections) {
ConnectedElement absConnDest = conn.getDestination();
ConnectedElement absConnSour = conn.getSource();
boolean delayed = false;
try {
EnumerationLiteral lit = PropertyUtils.getEnumLiteral(conn, commTimingProp);
delayed = lit.getName().equals("delayed");
} catch (PropertyDoesNotApplyToHolderException e) {
delayed = false;
}
Context destContext = absConnDest.getContext();
Context sourContext = absConnSour.getContext();
// only make connections to things that have annexs
if (destContext != null && destContext instanceof Subcomponent) {
ComponentInstance subInst = compInst.findSubcomponentInstance((Subcomponent) destContext);
if (!AgreeUtils.containsTransitiveAgreeAnnex(subInst, isMonolithic)) {
continue;
}
}
if (sourContext != null && sourContext instanceof Subcomponent) {
ComponentInstance subInst = compInst.findSubcomponentInstance((Subcomponent) sourContext);
if (!AgreeUtils.containsTransitiveAgreeAnnex(subInst, isMonolithic)) {
continue;
}
}
AgreeNode sourceNode = agreeNodeFromNamedEl(subNodes, sourContext);
AgreeNode destNode = agreeNodeFromNamedEl(subNodes, destContext);
ConnectionEnd destPort = absConnDest.getConnectionEnd();
ConnectionEnd sourPort = absConnSour.getConnectionEnd();
if (sourPort instanceof DataSubcomponent || destPort instanceof DataSubcomponent) {
AgreeLogger.logWarning("unable to reason about connection '" + conn.getName()
+ "' because it connects to a data subcomponent");
continue;
}
// weirdness with feature groups
String sourPrefix = null;
if (sourContext instanceof FeatureGroup) {
sourPrefix = sourContext.getName();
}
String destPrefix = null;
if (destContext instanceof FeatureGroup) {
destPrefix = destContext.getName();
}
List<AgreeVar> sourVars = getAgreePortNames(sourPort, sourPrefix,
sourceNode == null ? null : sourceNode.compInst);
List<AgreeVar> destVars = getAgreePortNames(destPort, destPrefix,
destNode == null ? null : destNode.compInst);
if (sourVars.size() != destVars.size()) {
throw new AgreeException("The number of AGREE variables differ for connection '"
+ conn.getQualifiedName()
+ "'. Do the types of the source and destination differ? Perhaps one is an implementation and the other is a type?");
}
for (int i = 0; i < sourVars.size(); i++) {
AgreeVar sourVar = sourVars.get(i);
AgreeVar destVar = destVars.get(i);
if (!matches((ConnectionEnd) sourVar.reference, (ConnectionEnd) destVar.reference)) {
AgreeLogger.logWarning(
"Connection '" + conn.getName() + "' has ports '" + sourVar.id.replace(dotChar, ".")
+ "' and '" + destVar.id.replace(dotChar, ".") + "' of differing type");
continue;
}
if (!sourVar.type.equals(destVar.type)) {
throw new AgreeException("Type mismatch during connection generation");
}
ConnectionType connType;
if (sourVar.id.endsWith(eventSuffix)) {
connType = ConnectionType.EVENT;
} else {
connType = ConnectionType.DATA;
}
AgreeAADLConnection agreeConnection = new AgreeAADLConnection(sourceNode, destNode, sourVar, destVar,
connType, latched, delayed, conn);
agreeConns.add(agreeConnection);
}
}
return agreeConns;
}
private Type getConnectionEndType(ConnectionEnd port) {
DataSubcomponentType dataClass = getConnectionEndDataClass(port);
if (dataClass == null) {
return null;
}
return AgreeTypeUtils.getType(dataClass, typeMap, globalTypes);
}
private List<AgreeVar> getAgreePortNames(ConnectionEnd port, String prefix, ComponentInstance compInst) {
String portName = port.getName();
List<AgreeVar> subVars = new ArrayList<>();
// if the port is a datasubcomponent then it is a member
// of a record type. Otherwise it is the first member of a feature group
if (prefix == null) {
prefix = "";
} else if (port instanceof DataSubcomponent) {
prefix = prefix + ".";
} else {
prefix = prefix + dotChar;
}
if (port instanceof FeatureGroup) {
FeatureGroup featGroup = (FeatureGroup) port;
FeatureGroupType featType = featGroup.getFeatureGroupType();
for (FeatureGroup subFeatGroup : featType.getOwnedFeatureGroups()) {
subVars.addAll(getAgreePortNames(subFeatGroup, null, compInst));
}
for (DataPort subPort : featType.getOwnedDataPorts()) {
subVars.addAll(getAgreePortNames(subPort, null, compInst));
}
for (EventDataPort subPort : featType.getOwnedEventDataPorts()) {
subVars.addAll(getAgreePortNames(subPort, null, compInst));
}
for (EventPort subPort : featType.getOwnedEventPorts()) {
subVars.addAll(getAgreePortNames(subPort, null, compInst));
}
List<AgreeVar> prefixedStrs = new ArrayList<>();
for (AgreeVar subVar : subVars) {
prefixedStrs.add(
new AgreeVar(prefix + portName + dotChar + subVar.id, subVar.type, subVar.reference, compInst));
}
subVars = prefixedStrs;
}
if (port instanceof DataPort || port instanceof EventDataPort || port instanceof DataSubcomponent) {
Type type = getConnectionEndType(port);
if (type != null) {
subVars.add(new AgreeVar(prefix + portName, type, port, compInst));
}
}
if (port instanceof EventDataPort || port instanceof EventPort) {
subVars.add(new AgreeVar(prefix + portName + eventSuffix, NamedType.BOOL, port, compInst));
}
return subVars;
}
private DataSubcomponentType getConnectionEndDataClass(ConnectionEnd port) {
DataSubcomponentType dataClass = null;
if (port instanceof DataPort) {
DataPort dataPort = (DataPort) port;
dataClass = dataPort.getDataFeatureClassifier();
} else if (port instanceof EventDataPort) {
EventDataPort eventDataPort = (EventDataPort) port;
dataClass = eventDataPort.getDataFeatureClassifier();
} else if (port instanceof DataSubcomponent) {
dataClass = ((DataSubcomponent) port).getDataSubcomponentType();
}
if (dataClass == null) {
AgreeLogger.logWarning("Unable to determine the type of port '" + port + "'");
}
return dataClass;
}
private boolean matches(ConnectionEnd a, ConnectionEnd b) {
if (a instanceof EventDataPort ^ b instanceof EventDataPort) {
return false;
}
return true;
}
private AgreeNode agreeNodeFromNamedEl(List<AgreeNode> nodes, NamedElement comp) {
if (comp == null) {
return null;
}
for (AgreeNode node : nodes) {
if (comp.getName().equals(node.id)) {
return node;
}
}
return null;
}
private Expr getInitialConstraint(EList<SpecStatement> specs) {
for (SpecStatement spec : specs) {
if (spec instanceof InitialStatement) {
return doSwitch(((InitialStatement) spec).getExpr());
}
}
return new BoolExpr(true);
}
private Expr getClockConstraint(EList<SpecStatement> specs, List<AgreeNode> subNodes) {
// NOTE: we generate the constraint that "someone ticks" during the
// lustre generation
for (SpecStatement spec : specs) {
if (spec instanceof MNSynchStatement) {
return getMNSynchConstraint((MNSynchStatement) spec);
}
if (spec instanceof CalenStatement) {
throw new AgreeException("The use of calendar statements has been depricated");
}
if (spec instanceof AsynchStatement) {
return new BoolExpr(true);
}
if (spec instanceof LatchedStatement) {
return new BoolExpr(true);
}
if (spec instanceof SynchStatement) {
return getSynchConstraint((SynchStatement) spec, subNodes);
}
}
return new BoolExpr(true);
}
private Expr getSynchConstraint(SynchStatement spec, List<AgreeNode> subNodes) {
int val1 = Integer.decode(spec.getVal());
if (val1 == 0) {
return new BoolExpr(true);
}
List<Expr> clockIds = new ArrayList<>();
Expr clockAssertion;
for (AgreeNode subNode : subNodes) {
clockIds.add(new IdExpr(subNode.clockVar.id));
}
String dfaPrefix = AgreeTypeUtils.getObjectLocationPrefix(spec);
if (spec.getVal2() == null) {
Node dfaNode = AgreeCalendarUtils.getDFANode(dfaPrefix + "__DFA_NODE", val1);
Node calNode = AgreeCalendarUtils.getCalendarNode(dfaPrefix + "__CALENDAR_NODE", dfaNode.id,
clockIds.size());
// we do not need to make copies of the nodes if they exist
if (!nodeNameExists(dfaNode.id)) {
if (nodeNameExists(calNode.id)) {
throw new AgreeException("The calander node should not exist if the dfa node does not exist");
}
addToNodeList(dfaNode);
addToNodeList(calNode);
}
clockAssertion = new NodeCallExpr(calNode.id, clockIds);
} else {
int val2 = Integer.decode(spec.getVal2());
String nodeName = "__calendar_node_" + val1 + "_" + val2;
nodeName = dfaPrefix + nodeName;
Node calNode = AgreeCalendarUtils.getMNCalendar(nodeName, val1, val2);
if (!nodeNameExists(calNode.id)) {
addToNodeList(calNode);
}
clockAssertion = new BoolExpr(true);
int i, j;
for (i = 0; i < clockIds.size(); i++) {
Expr clock1 = clockIds.get(i);
for (j = i + 1; j < clockIds.size(); j++) {
Expr clock2 = clockIds.get(j);
NodeCallExpr nodeCall = new NodeCallExpr(nodeName, clock1, clock2);
clockAssertion = new BinaryExpr(clockAssertion, BinaryOp.AND, nodeCall);
nodeCall = new NodeCallExpr(nodeName, clock2, clock1);
clockAssertion = new BinaryExpr(clockAssertion, BinaryOp.AND, nodeCall);
}
}
}
return clockAssertion;
}
private Expr getMNSynchConstraint(MNSynchStatement sync) {
Set<String> nodeNames = new HashSet<>();
Expr clockAssertion = new BoolExpr(true);
for (int i = 0; i < sync.getComp1().size(); i++) {
Subcomponent maxComp = (Subcomponent) sync.getComp1().get(i);
Subcomponent minComp = (Subcomponent) sync.getComp2().get(i);
Expr maxClock = new IdExpr(maxComp.getName() + clockIDSuffix);
Expr minClock = new IdExpr(minComp.getName() + clockIDSuffix);
int max = Integer.valueOf(sync.getMax().get(i));
int min = Integer.valueOf(sync.getMin().get(i));
MNSynchronyElement elem = new MNSynchronyElement(maxClock, minClock, max, min);
String nodeName = "__calendar_node_" + elem.max + "_" + elem.min;
nodeName = AgreeTypeUtils.getObjectLocationPrefix(sync) + nodeName;
if (!nodeNames.contains(nodeName)) {
nodeNames.add(nodeName);
Node calNode = AgreeCalendarUtils.getMNCalendar(nodeName, elem.max, elem.min);
addToNodeList(calNode);
}
NodeCallExpr nodeCall = new NodeCallExpr(nodeName, elem.maxClock, elem.minClock);
clockAssertion = new BinaryExpr(clockAssertion, BinaryOp.AND, nodeCall);
nodeCall = new NodeCallExpr(nodeName, elem.minClock, elem.maxClock);
clockAssertion = new BinaryExpr(clockAssertion, BinaryOp.AND, nodeCall);
}
return clockAssertion;
}
private List<Type> gatherLustreTypes(EList<SpecStatement> specs) {
List<Type> types = new ArrayList<>();
for (SpecStatement spec : specs) {
if (spec instanceof RecordDefExpr) {
// this will record them to the global types
AgreeTypeUtils.getType((NamedElement) spec, typeMap, globalTypes);
}
}
return types;
}
private List<Node> addLustreNodes(EList<SpecStatement> specs) {
List<Node> nodes = new ArrayList<>();
for (SpecStatement spec : specs) {
if (spec instanceof NodeDefExpr || spec instanceof FnDefExpr) {
doSwitch(spec);
}
}
return nodes;
}
public VarDecl agreeVarFromArg(Arg arg, ComponentInstance compInst) {
NamedType type = getNamedType(AgreeTypeUtils.getTypeName(arg.getType(), typeMap, globalTypes));
return new AgreeVar(arg.getName(), type, arg, compInst, null);
}
// MWW: made this public.
public List<VarDecl> agreeVarsFromArgs(EList<Arg> args, ComponentInstance compInst) {
List<VarDecl> agreeVars = new ArrayList<>();
for (Arg arg : args) {
agreeVars.add(agreeVarFromArg(arg, compInst));
}
return agreeVars;
}
private List<AgreeStatement> getAssertionStatements(EList<SpecStatement> specs) {
List<AgreeStatement> asserts = new ArrayList<>();
for (SpecStatement spec : specs) {
if (spec instanceof AssertStatement) {
AssertStatement assertState = (AssertStatement) spec;
String str = assertState.getStr();
if (assertState.getExpr() != null) {
asserts.add(new AgreeStatement(str, doSwitch(assertState.getExpr()), assertState));
} else {
PatternStatement pattern = assertState.getPattern();
asserts.add(new AgreePatternBuilder(str, assertState, this).doSwitch(pattern));
}
}
}
return asserts;
}
private List<AgreeOverriddenConnection> getConnectionStatements(EList<SpecStatement> specs) {
List<AgreeOverriddenConnection> conns = new ArrayList<>();
for (SpecStatement spec : specs) {
if (spec instanceof ConnectionStatement) {
Expr expr = doSwitch(((ConnectionStatement) spec).getExpr());
Connection conn = (Connection) ((ConnectionStatement) spec).getConn();
AgreeOverriddenConnection agreeConn = new AgreeOverriddenConnection(new AgreeStatement("", expr, spec),
conn);
conns.add(agreeConn);
}
}
return conns;
}
private List<AgreeStatement> getAssignmentStatements(EList<SpecStatement> specs) {
List<AgreeStatement> assigns = new ArrayList<>();
for (SpecStatement spec : specs) {
if (spec instanceof AssignStatement) {
Expr expr = doSwitch(((AssignStatement) spec).getExpr());
expr = new BinaryExpr(new IdExpr(((AssignStatement) spec).getId().getBase().getName()), BinaryOp.EQUAL,
expr);
assigns.add(new AgreeStatement("", expr, spec));
}
}
return assigns;
}
private List<AgreeStatement> getPropertyStatements(EList<SpecStatement> specs) {
List<AgreeStatement> props = new ArrayList<>();
for (SpecStatement spec : specs) {
if (spec instanceof PropertyStatement) {
Expr expr = doSwitch(((PropertyStatement) spec).getExpr());
expr = new BinaryExpr(new IdExpr(((PropertyStatement) spec).getName()), BinaryOp.EQUAL, expr);
props.add(new AgreeStatement("", expr, spec));
}
}
return props;
}
private GatheredVariablesAndConstraints getEquationStatements(EList<SpecStatement> specs) {
GatheredVariablesAndConstraints result = new GatheredVariablesAndConstraints();
for (SpecStatement spec : specs) {
if (spec instanceof EqStatement) {
EqStatement eq = (EqStatement) spec;
EList<Arg> lhs = eq.getLhs();
if (eq.getExpr() != null) {
Expr expr = doSwitch(eq.getExpr());
if (lhs.size() != 1) {
List<Expr> ids = new ArrayList<>();
for (Arg arg : lhs) {
ids.add(new IdExpr(arg.getName()));
}
TupleExpr tuple = new TupleExpr(ids);
expr = new BinaryExpr(tuple, BinaryOp.EQUAL, expr);
} else {
expr = new BinaryExpr(new IdExpr(lhs.get(0).getName()), BinaryOp.EQUAL, expr);
}
result.assertions.add(new AgreeStatement("", expr, spec));
}
result.obligations.addAll(getVariableRangeConstraints(lhs, eq));
}
}
return result;
}
private List<Expr> getDataClassifierRangeConstraintExprs(String name, DataClassifier dataClassifier) {
List<Expr> constraints = new ArrayList<>();
if (dataClassifier instanceof DataType) {
if (hasIntegerRangeProperty(dataClassifier)) {
for (PropertyAssociation pa : getIntegerRangePropertyAssociations(dataClassifier)) {
for (ModalPropertyValue pv : pa.getOwnedValues()) {
PropertyExpression propExpr = pv.getOwnedValue();
if (propExpr instanceof RangeValue) {
RangeValue rangeValue = (RangeValue) propExpr;
IdExpr id = new IdExpr(name);
List<Expr> boundExprs = new ArrayList<>();
try {
double min = rangeValue.getMinimumValue().getScaledValue();
Expr lowVal = new IntExpr(BigDecimal.valueOf(min).toBigInteger());
boundExprs.add(new BinaryExpr(lowVal, BinaryOp.LESSEQUAL, id));
} catch (Exception e) {
System.out.println("Could not find value for " + name + " lower bound.");
}
try {
double max = rangeValue.getMaximumValue().getScaledValue();
Expr highVal = new IntExpr(BigDecimal.valueOf(max).toBigInteger());
boundExprs.add(new BinaryExpr(id, BinaryOp.LESSEQUAL, highVal));
} catch (Exception e) {
System.out.println("Could not find value for " + name + " upper bound.");
}
if (boundExprs.size() == 2) {
constraints.add(new BinaryExpr(boundExprs.get(0), BinaryOp.AND, boundExprs.get(1)));
} else if (boundExprs.size() == 1) {
constraints.add(boundExprs.get(0));
}
}
}
}
} else if (hasRealRangeProperty(dataClassifier)) {
for (PropertyAssociation pa : getRealRangePropertyAssociations(dataClassifier)) {
for (ModalPropertyValue pv : pa.getOwnedValues()) {
PropertyExpression propExpr = pv.getOwnedValue();
if (propExpr instanceof RangeValue) {
RangeValue rangeValue = (RangeValue) propExpr;
IdExpr id = new IdExpr(name);
List<Expr> boundExprs = new ArrayList<>();
try {
double min = rangeValue.getMinimumValue().getScaledValue();
Expr lowVal = new RealExpr(BigDecimal.valueOf(min));
boundExprs.add(new BinaryExpr(lowVal, BinaryOp.LESSEQUAL, id));
} catch (Exception e) {
System.out.println("Could not find value for " + name + " lower bound.");
}
try {
double max = rangeValue.getMaximumValue().getScaledValue();
Expr highVal = new RealExpr(BigDecimal.valueOf(max));
boundExprs.add(new BinaryExpr(id, BinaryOp.LESSEQUAL, highVal));
} catch (Exception e) {
System.out.println("Could not find value for " + name + " upper bound.");
}
if (boundExprs.size() == 2) {
constraints.add(new BinaryExpr(boundExprs.get(0), BinaryOp.AND, boundExprs.get(1)));
} else if (boundExprs.size() == 1) {
constraints.add(boundExprs.get(0));
}
}
}
}
}
} else if (dataClassifier instanceof DataImplementation) {
constraints.addAll(((DataImplementation) dataClassifier).getAllSubcomponents().stream()
.filter(sub -> sub.getSubcomponentType() instanceof DataClassifier)
.map(sub -> getDataClassifierRangeConstraintExprs(name + "." + sub.getName(),
(DataClassifier) sub.getSubcomponentType()))
.flatMap(List::stream).collect(Collectors.toList()));
}
return constraints;
}
private List<Expr> getVariableRangeConstraintExprs(String name, com.rockwellcollins.atc.agree.agree.Type type) {
List<Expr> result = new ArrayList<>();
if (type instanceof PrimType) {
PrimType primType = (PrimType) type;
String lowStr = primType.getRangeLow();
String highStr = primType.getRangeHigh();
if (lowStr != null && highStr != null) {
IdExpr id = new IdExpr(name);
int lowSign = primType.getLowNeg() == null ? 1 : -1;
int highSign = primType.getHighNeg() == null ? 1 : -1;
Expr lowVal = null;
Expr highVal = null;
switch (primType.getString()) {
case "int":
long lowl = Long.valueOf(lowStr) * lowSign;
long highl = Long.valueOf(highStr) * highSign;
lowVal = new IntExpr(BigInteger.valueOf(lowl));
highVal = new IntExpr(BigInteger.valueOf(highl));
break;
case "real":
double lowd = Double.valueOf(lowStr) * lowSign;
double highd = Double.valueOf(highStr) * highSign;
lowVal = new RealExpr(BigDecimal.valueOf(lowd));
highVal = new RealExpr(BigDecimal.valueOf(highd));
break;
default:
throw new AgreeException("Unhandled type '" + primType.getString() + "' in ranged type");
}
Expr lowBound = new BinaryExpr(lowVal, BinaryOp.LESSEQUAL, id);
Expr highBound = new BinaryExpr(id, BinaryOp.LESSEQUAL, highVal);
result.add(new BinaryExpr(lowBound, BinaryOp.AND, highBound));
}
} else if (type instanceof RecordType) {
RecordType recType = (RecordType) type;
NamedElement recordTypeName = AgreeUtils.getFinalNestId(recType.getRecord());
if (recordTypeName instanceof DataClassifier) {
result.addAll(getDataClassifierRangeConstraintExprs(name, (DataClassifier) recordTypeName));
} else if (recordTypeName instanceof RecordDefExpr) {
result.addAll(((RecordDefExpr) recordTypeName).getArgs().stream()
.map(arg -> getVariableRangeConstraintExprs(name + "." + arg.getName(), arg.getType()))
.flatMap(List::stream).collect(Collectors.toList()));
}
}
return result;
}
private List<AgreeStatement> getVariableRangeConstraints(List<Arg> args, EObject reference) {
List<AgreeStatement> constraints = new ArrayList<>();
for (Arg arg : args) {
List<Expr> argConstraints = getVariableRangeConstraintExprs(arg.getName(), arg.getType());
if (!argConstraints.isEmpty()) {
constraints.add(new AgreeStatement("Type predicate on '" + arg.getName() + "'", argConstraints.stream()
.reduce(new BoolExpr(true), (a, b) -> new BinaryExpr(a, BinaryOp.AND, b)), reference));
}
}
return constraints;
}
private static boolean hasIntegerRangeProperty(Classifier classifier) {
return classifier.getAllPropertyAssociations().stream()
.anyMatch(pa -> "Integer_Range".equals(pa.getProperty().getName()));
}
private static boolean hasRealRangeProperty(Classifier classifier) {
return classifier.getAllPropertyAssociations().stream()
.anyMatch(pa -> "Real_Range".equals(pa.getProperty().getName()));
}
private static List<PropertyAssociation> getIntegerRangePropertyAssociations(
Classifier classifier) {
return classifier.getAllPropertyAssociations().stream()
.filter(pa -> "Integer_Range".equals(pa.getProperty().getName())).collect(Collectors.toList());
}
private static List<PropertyAssociation> getRealRangePropertyAssociations(Classifier classifier) {
return classifier.getAllPropertyAssociations().stream()
.filter(pa -> "Real_Range".equals(pa.getProperty().getName())).collect(Collectors.toList());
}
private List<AgreeStatement> getAssumptionStatements(EList<SpecStatement> specs) {
List<AgreeStatement> assumptions = new ArrayList<>();
for (SpecStatement spec : specs) {
if (spec instanceof AssumeStatement) {
AssumeStatement assumption = (AssumeStatement) spec;
String str = assumption.getStr();
if (assumption.getExpr() != null) {
assumptions.add(new AgreeStatement(str, doSwitch(assumption.getExpr()), assumption));
} else {
PatternStatement pattern = assumption.getPattern();
assumptions.add(new AgreePatternBuilder(str, assumption, this).doSwitch(pattern));
}
}
}
return assumptions;
}
private List<AgreeStatement> getGuaranteeStatements(EList<SpecStatement> specs) {
List<AgreeStatement> guarantees = new ArrayList<>();
for (SpecStatement spec : specs) {
if (spec instanceof GuaranteeStatement) {
GuaranteeStatement guarantee = (GuaranteeStatement) spec;
String str = guarantee.getStr();
if (guarantee.getExpr() != null) {
guarantees.add(new AgreeStatement(str, doSwitch(guarantee.getExpr()), guarantee));
} else {
PatternStatement pattern = guarantee.getPattern();
guarantees.add(new AgreePatternBuilder(str, guarantee, this).doSwitch(pattern));
}
}
}
return guarantees;
}
private AgreeContractSubclause getAgreeAnnex(ComponentClassifier comp) {
for (AnnexSubclause annex : AnnexUtil.getAllAnnexSubclauses(comp,
AgreePackage.eINSTANCE.getAgreeContractSubclause())) {
if (annex instanceof AgreeContractSubclause) {
// in newer versions of osate the annex this returns annexes in
// the type
// as well as the implementation. We want the annex in the
// specific component
EObject container = annex.eContainer();
while (!(container instanceof ComponentClassifier)) {
container = container.eContainer();
}
if (container == comp) {
return (AgreeContractSubclause) annex;
}
}
}
return null;
}
private static NamedType getNamedType(String name) {
if (name == null) {
return null;
}
switch (name) {
case "bool":
return NamedType.BOOL;
case "real":
return NamedType.REAL;
case "int":
return NamedType.INT;
default:
return new NamedType(name);
}
}
// BEGIN CASE EXPRESSION STATEMENTS
@Override
public Expr caseRecordUpdateExpr(RecordUpdateExpr upExpr) {
EList<NamedElement> args = upExpr.getArgs();
EList<com.rockwellcollins.atc.agree.agree.Expr> argExprs = upExpr.getArgExpr();
Expr lustreExpr = doSwitch(upExpr.getRecord());
for (int i = 0; i < args.size(); i++) {
com.rockwellcollins.atc.agree.agree.Expr argExpr = argExprs.get(i);
NamedElement arg = args.get(i);
Expr lustreArgExpr = doSwitch(argExpr);
lustreExpr = new jkind.lustre.RecordUpdateExpr(lustreExpr, arg.getName(), lustreArgExpr);
}
return lustreExpr;
}
@Override
public Expr caseTimeOfExpr(TimeOfExpr timeExpr) {
NestedDotID nestId = timeExpr.getId();
NamedElement namedEl = nestId.getBase();
String idStr = namedEl.getName();
AgreeVar var = timeOfVarMap.get(idStr);
if (var == null) {
String varStr = idStr + AgreePatternTranslator.TIME_SUFFIX;
var = new AgreeVar(varStr, NamedType.REAL, namedEl);
timeOfVarMap.put(idStr, var);
}
return new IdExpr(var.id);
}
@Override
public Expr caseTimeRiseExpr(TimeRiseExpr timeExpr) {
NestedDotID nestId = timeExpr.getId();
NamedElement namedEl = nestId.getBase();
String idStr = namedEl.getName();
AgreeVar var = timeRiseVarMap.get(idStr);
if (var == null) {
String varStr = idStr + AgreePatternTranslator.RISE_SUFFIX;
var = new AgreeVar(varStr, NamedType.REAL, namedEl);
timeRiseVarMap.put(idStr, var);
}
return new IdExpr(var.id);
}
@Override
public Expr caseTimeFallExpr(TimeFallExpr timeExpr) {
NestedDotID nestId = timeExpr.getId();
NamedElement namedEl = nestId.getBase();
String idStr = namedEl.getName();
AgreeVar var = timeFallVarMap.get(idStr);
if (var == null) {
String varStr = idStr + AgreePatternTranslator.FALL_SUFFIX;
var = new AgreeVar(varStr, NamedType.REAL, namedEl);
timeFallVarMap.put(idStr, var);
}
return new IdExpr(var.id);
}
@Override
public Expr caseRecordExpr(RecordExpr recExpr) {
EList<NamedElement> agreeArgs = recExpr.getArgs();
EList<com.rockwellcollins.atc.agree.agree.Expr> agreeArgExprs = recExpr.getArgExpr();
Map<String, Expr> argExprMap = new HashMap<>();
for (int i = 0; i < agreeArgs.size(); i++) {
NamedElement agreeArg = agreeArgs.get(i);
com.rockwellcollins.atc.agree.agree.Expr agreeExpr = agreeArgExprs.get(i);
Expr lustreExpr = doSwitch(agreeExpr);
String argName = agreeArg.getName();
argExprMap.put(argName, lustreExpr);
}
NestedDotID recId = recExpr.getRecord();
while (recId.getSub() != null) {
recId = recId.getSub();
}
String recName = AgreeTypeUtils.getIDTypeStr(recId.getBase());
return new jkind.lustre.RecordExpr(recName, argExprMap);
}
@Override
public Expr caseFloorCast(FloorCast floor) {
Expr expr = doSwitch(floor.getExpr());
Expr castExpr = new CastExpr(NamedType.INT, expr);
return castExpr;
}
@Override
public Expr caseRealCast(RealCast real) {
Expr expr = doSwitch(real.getExpr());
Expr castExpr = new CastExpr(NamedType.REAL, expr);
return castExpr;
}
/*
* @Override
* public Expr caseBinaryNonLinearExpr(com.rockwellcollins.atc.agree.agree.BinaryNonLinearExpr expr) {
* Expr leftExpr = doSwitch(expr.getLeft());
* Expr rightExpr = doSwitch(expr.getRight());
* String op = expr.getOp();
* BinaryOp binOp = null;
* switch (op) {
* case "pow": binOp = BinaryOp.POW; break;
* case "arctan2" : binOp = BinaryOp.ARCTAN2; break;
* }
* assert (binOp != null);
* BinaryExpr binExpr = new BinaryExpr(leftExpr, binOp, rightExpr);
*
* return binExpr;
* }
*
* @Override
* public Expr caseUnaryNonLinearExpr(com.rockwellcollins.atc.agree.agree.UnaryNonLinearExpr expr) {
* Expr sub = doSwitch(expr.getExpr());
* String op = expr.getOp();
* UnaryOp unyOp = null;
* switch (op) {
* case "exp": unyOp = UnaryOp.EXP; break;
* case "log": unyOp = UnaryOp.LOG; break;
* case "sqrt": unyOp = UnaryOp.SQRT; break;
* case "sin": unyOp = UnaryOp.SIN; break;
* case "cos": unyOp = UnaryOp.COS; break;
* case "tan": unyOp = UnaryOp.TAN; break;
* case "asin":
* case "arcsin": unyOp = UnaryOp.ARCSIN; break;
* case "acos":
* case "arccos": unyOp = UnaryOp.ARCCOS; break;
* case "atan":
* case "arctan": unyOp = UnaryOp.ARCTAN; break;
* case "sinh" : unyOp = UnaryOp.SINH; break;
* case "cosh" : unyOp = UnaryOp.COSH; break;
* case "tanh" : unyOp = UnaryOp.TANH; break;
* case "matan":
* case "marctan": unyOp = UnaryOp.MATAN; break;
* }
* assert (unyOp != null);
* UnaryExpr unyExpr = new UnaryExpr(unyOp, sub);
*
* return unyExpr;
*
* }
*/
@Override
public Expr caseBinaryExpr(com.rockwellcollins.atc.agree.agree.BinaryExpr expr) {
Expr leftExpr = doSwitch(expr.getLeft());
Expr rightExpr = doSwitch(expr.getRight());
String op = expr.getOp();
BinaryOp binOp = null;
switch (op) {
case "+":
binOp = BinaryOp.PLUS;
break;
case "-":
binOp = BinaryOp.MINUS;
break;
case "*":
binOp = BinaryOp.MULTIPLY;
break;
case "/":
binOp = BinaryOp.DIVIDE;
break;
case "mod":
binOp = BinaryOp.MODULUS;
break;
case "div":
binOp = BinaryOp.INT_DIVIDE;
break;
case "<=>":
case "=":
binOp = BinaryOp.EQUAL;
break;
case "!=":
case "<>":
binOp = BinaryOp.NOTEQUAL;
break;
case ">":
binOp = BinaryOp.GREATER;
break;
case "<":
binOp = BinaryOp.LESS;
break;
case ">=":
binOp = BinaryOp.GREATEREQUAL;
break;
case "<=":
binOp = BinaryOp.LESSEQUAL;
break;
case "or":
binOp = BinaryOp.OR;
break;
case "and":
binOp = BinaryOp.AND;
break;
case "xor":
binOp = BinaryOp.XOR;
break;
case "=>":
binOp = BinaryOp.IMPLIES;
break;
case "->":
binOp = BinaryOp.ARROW;
break;
}
assert (binOp != null);
BinaryExpr binExpr = new BinaryExpr(leftExpr, binOp, rightExpr);
return binExpr;
}
@Override
public Expr caseBoolLitExpr(BoolLitExpr expr) {
return new BoolExpr(expr.getVal().getValue());
}
@Override
public Expr caseFnCallExpr(FnCallExpr expr) {
NestedDotID dotId = expr.getFn();
NamedElement namedEl = AgreeUtils.getFinalNestId(dotId);
String fnName = AgreeTypeUtils.getNodeName(namedEl);
boolean found = false;
for (Node node : globalNodes) {
if (node.id.equals(fnName)) {
found = true;
break;
}
}
if (!found) {
NestedDotID fn = expr.getFn();
doSwitch(AgreeUtils.getFinalNestId(fn));
// for dReal integration
if (fnName.substring(0, 7).equalsIgnoreCase("dreal__")) {
fnName = namedEl.getName();
}
}
List<Expr> argResults = new ArrayList<>();
for (com.rockwellcollins.atc.agree.agree.Expr argExpr : expr.getArgs()) {
argResults.add(doSwitch(argExpr));
}
NodeCallExpr nodeCall = new NodeCallExpr(fnName, argResults);
return nodeCall;
}
@Override
public Expr caseFnDefExpr(FnDefExpr expr) {
String nodeName = AgreeTypeUtils.getNodeName(expr);
for (Node node : globalNodes) {
if (node.id.equals(nodeName)) {
return null;
}
}
List<VarDecl> inputs = agreeVarsFromArgs(expr.getArgs(), null);
Expr bodyExpr = doSwitch(expr.getExpr());
NamedType outType = getNamedType(AgreeTypeUtils.getTypeName(expr.getType(), typeMap, globalTypes));
VarDecl outVar = new VarDecl("_outvar", outType);
List<VarDecl> outputs = Collections.singletonList(outVar);
Equation eq = new Equation(new IdExpr("_outvar"), bodyExpr);
List<Equation> eqs = Collections.singletonList(eq);
NodeBuilder builder = new NodeBuilder(nodeName);
builder.addInputs(inputs);
builder.addOutputs(outputs);
builder.addEquations(eqs);
Node node = builder.build();
addToNodeList(node);
return null;
}
@Override
public Expr caseLinearizationDefExpr(LinearizationDefExpr expr) {
NodeDefExpr linearization = linearizationRewriter.addLinearization(expr);
caseNodeDefExpr(linearization);
return null;
}
@Override
public Expr caseNodeDefExpr(NodeDefExpr expr) {
String nodeName = AgreeTypeUtils.getNodeName(expr);
for (Node node : globalNodes) {
if (node.id.equals(nodeName)) {
return null;
}
}
List<VarDecl> inputs = agreeVarsFromArgs(expr.getArgs(), null);
List<VarDecl> outputs = agreeVarsFromArgs(expr.getRets(), null);
NodeBodyExpr body = expr.getNodeBody();
List<VarDecl> internals = agreeVarsFromArgs(body.getLocs(), null);
List<Equation> eqs = new ArrayList<>();
List<String> props = new ArrayList<>();
// TODO are node lemmas depricated?
String lemmaName = "__nodeLemma";
int lemmaIndex = 0;
for (NodeStmt stmt : body.getStmts()) {
if (stmt instanceof NodeLemma) {
NodeLemma nodeLemma = (NodeLemma) stmt;
String propName = lemmaName + lemmaIndex++;
IdExpr eqId = new IdExpr(propName);
internals.add(new VarDecl(eqId.id, NamedType.BOOL));
Expr eqExpr = doSwitch(nodeLemma.getExpr());
Equation eq = new Equation(eqId, eqExpr);
eqs.add(eq);
props.add(eqId.id);
} else if (stmt instanceof NodeEq) {
eqs.add(nodeEqToEq((NodeEq) stmt));
}
}
// nodeLemmaNames.put(nodeName, lemmaNames);
NodeBuilder builder = new NodeBuilder(nodeName);
builder.addInputs(inputs);
builder.addOutputs(outputs);
builder.addLocals(internals);
builder.addEquations(eqs);
builder.addProperties(props);
Node n = builder.build();
addToNodeList(n);
return null;
}
// helper method for above
private Equation nodeEqToEq(NodeEq nodeEq) {
Expr expr = doSwitch(nodeEq.getExpr());
List<IdExpr> ids = new ArrayList<>();
for (Arg arg : nodeEq.getLhs()) {
ids.add(new IdExpr(arg.getName()));
}
Equation eq = new Equation(ids, expr);
return eq;
}
@Override
public Expr caseGetPropertyExpr(GetPropertyExpr expr) {
NamedElement propName = expr.getProp();
PropertyExpression propVal;
if (propName instanceof Property) {
NamedElement compName = AgreeTypeUtils.namedElFromId(expr.getComponent(), curInst);
Property prop = (Property) propName;
propVal = AgreeUtils.getPropExpression(compName, prop);
if (propVal == null) {
if (Activator.getDefault().getPreferenceStore()
.getBoolean(PreferenceConstants.PREF_UNSPECIFIED_AADL_PROPERTIES)) {
String propInputName = unspecifiedAadlPropertyPrefix + compName.getName() + dotChar
+ prop.getName();
unspecifiedAadlProperties.put(propInputName, expr);
return new IdExpr(propInputName);
} else {
throw new AgreeException("Could not locate property value '" + prop.getFullName()
+ "' in component '" + compName.getName() + "'. Is it possible "
+ "that a 'this' statement is used in a context in which it wasn't supposed to?"
+ " Analysis of unspecified AADL properties as inputs may be enabled in the AGREE preferences.");
}
}
} else {
propVal = AgreeUtils.getPropExpression((PropertyConstant) propName);
if (propVal == null) {
throw new AgreeException("Could not locate property value '" + propName.getFullName());
}
}
Expr res = null;
if (propVal != null) {
if (propVal instanceof StringLiteral) {
// StringLiteral value = (StringLiteral) propVal;
// nodeStr += value.getValue() + ")";
throw new AgreeException(
"Property value for '" + propName.getFullName() + "' cannot be of string type");
} else if (propVal instanceof NamedValue) {
// NamedValue namedVal = (NamedValue) propVal;
// AbstractNamedValue absVal = namedVal.getNamedValue();
// assert (absVal instanceof EnumerationLiteral);
// EnumerationLiteral enVal = (EnumerationLiteral) absVal;
throw new AgreeException(
"Property value for '" + propName.getFullName() + "' cannot be of enumeration type");
} else if (propVal instanceof BooleanLiteral) {
BooleanLiteral value = (BooleanLiteral) propVal;
res = new BoolExpr(value.getValue());
} else if (propVal instanceof IntegerLiteral) {
IntegerLiteral value = (IntegerLiteral) propVal;
res = new IntExpr(BigInteger.valueOf((long) value.getScaledValue()));
} else {
assert (propVal instanceof RealLiteral);
RealLiteral value = (RealLiteral) propVal;
res = new RealExpr(BigDecimal.valueOf(value.getValue()));
}
}
assert (res != null);
return res;
}
private void gatherUnspecifiedAadlProperties(Map<String, GetPropertyExpr> unspecifiedAadlProperties,
Map<NamedElement, String> typeMap, Set<Type> globalTypes, List<AgreeVar> inputs,
List<AgreeStatement> assumptions,
List<AgreeStatement> guarantees) {
for (Entry<String, GetPropertyExpr> entry : unspecifiedAadlProperties.entrySet()) {
String propInputName = entry.getKey();
GetPropertyExpr expr = entry.getValue();
Property prop = (Property) expr.getProp();
Expr propInputIdExpr = new IdExpr(propInputName);
Type type;
Expr bound = null;
if (prop.getReferencedPropertyType() instanceof AadlBoolean) {
type = NamedType.BOOL;
} else if (prop.getReferencedPropertyType() instanceof AadlInteger) {
AadlInteger aadlInteger = (AadlInteger) prop.getReferencedPropertyType();
type = NamedType.INT;
if (aadlInteger.getRange() != null) {
PropertyExpression lowerBound = aadlInteger.getRange().getLowerBound();
PropertyExpression upperBound = aadlInteger.getRange().getUpperBound();
Expr lowVal = new IntExpr(
BigDecimal.valueOf(((IntegerLiteral) lowerBound).getScaledValue()).toBigInteger());
Expr highVal = new IntExpr(
BigDecimal.valueOf(((IntegerLiteral) upperBound).getScaledValue()).toBigInteger());
Expr lowBound = new BinaryExpr(lowVal, BinaryOp.LESSEQUAL, propInputIdExpr);
Expr highBound = new BinaryExpr(propInputIdExpr, BinaryOp.LESSEQUAL, highVal);
bound = new BinaryExpr(lowBound, BinaryOp.AND, highBound);
}
} else if (prop.getReferencedPropertyType() instanceof AadlReal) {
AadlReal aadlReal = (AadlReal) prop.getReferencedPropertyType();
type = NamedType.REAL;
if (aadlReal.getRange() != null) {
PropertyExpression lowerBound = aadlReal.getRange().getLowerBound();
PropertyExpression upperBound = aadlReal.getRange().getUpperBound();
Expr lowVal = new RealExpr(BigDecimal.valueOf(((RealLiteral) lowerBound).getValue()));
Expr highVal = new RealExpr(BigDecimal.valueOf(((RealLiteral) upperBound).getValue()));
Expr lowBound = new BinaryExpr(lowVal, BinaryOp.LESSEQUAL, propInputIdExpr);
Expr highBound = new BinaryExpr(propInputIdExpr, BinaryOp.LESSEQUAL, highVal);
bound = new BinaryExpr(lowBound, BinaryOp.AND, highBound);
}
} else {
throw new AgreeException(
"Could not locate property value '\" + prop.getFullName() + \"' in component '\"\n"
+ "// + compName.getName() + \"'. Analysis on abstract values not supported for "
+ "AADL property type " + prop.getReferencedPropertyType() + ".");
}
// NamedType type = getNamedType(AgreeTypeUtils.getTypeName(arg.getType(), typeMap, globalTypes));
AgreeVar propInputVar = new AgreeVar(propInputName, type, expr, curInst, null);
Expr constraint = getUnchangingConstraintExpr(propInputIdExpr);
if (bound != null) {
constraint = new BinaryExpr(constraint, BinaryOp.AND, bound);
}
inputs.add(propInputVar);
assumptions.add(new AgreeStatement("", constraint, prop));
}
}
private static Expr getUnchangingConstraintExpr(Expr expr) {
return new BinaryExpr(new BoolExpr(true), BinaryOp.ARROW,
new BinaryExpr(expr, BinaryOp.EQUAL, new UnaryExpr(UnaryOp.PRE, expr)));
}
@Override
public Expr caseThisExpr(ThisExpr expr) {
throw new AgreeException("A 'this' expression should never be called in a case statement");
}
@Override
public Expr caseIfThenElseExpr(com.rockwellcollins.atc.agree.agree.IfThenElseExpr expr) {
Expr condExpr = doSwitch(expr.getA());
Expr thenExpr = doSwitch(expr.getB());
Expr elseExpr = doSwitch(expr.getC());
Expr result = new IfThenElseExpr(condExpr, thenExpr, elseExpr);
return result;
}
@Override
public Expr caseIntLitExpr(IntLitExpr expr) {
return new IntExpr(BigInteger.valueOf(Integer.parseInt(expr.getVal())));
}
@Override
public Expr caseNestedDotID(NestedDotID id) {
String jKindVar = "";
String aadlVar = "";
NamedElement base = id.getBase();
while (id.getSub() != null
&& (base instanceof FeatureGroup || base instanceof AadlPackage || base instanceof Subcomponent)) {
jKindVar += base.getName() + dotChar;
aadlVar += base.getName() + ".";
id = id.getSub();
base = id.getBase();
}
NamedElement namedEl = id.getBase();
String tag = id.getTag();
if (tag != null) {
switch (tag) {
case "_CLK":
IdExpr clockId = new IdExpr(namedEl.getName() + clockIDSuffix);
return clockId;
default:
throw new AgreeException("use of uknown tag: '" + tag + "' in expression: '" + aadlVar + tag + "'");
}
}
Expr result;
if (namedEl instanceof ConstStatement) {
// evaluate the constant
result = doSwitch(((ConstStatement) namedEl).getExpr());
} else if (namedEl instanceof NamedID) {
// Enumeration types get lifted to Lustre global types; accordingly
// lift the enumerators to global
jKindVar = namedEl.getName();
result = new IdExpr(jKindVar);
} else {
jKindVar = jKindVar + namedEl.getName();
result = new IdExpr(jKindVar);
}
// this is a record accessrecord
while (id.getSub() != null) {
id = id.getSub();
namedEl = id.getBase();
result = new RecordAccessExpr(result, namedEl.getName());
}
return result;
}
@Override
public Expr caseAADLEnumerator(AADLEnumerator aadlEnum) {
String typeStr = AgreeTypeUtils.getIDTypeStr(
com.rockwellcollins.atc.agree.validation.AgreeJavaValidator.getFinalNestId(aadlEnum.getEnumType()));
return new IdExpr(typeStr.replace("__", "_") + "_" + aadlEnum.getValue());
}
@Override
public Expr casePreExpr(PreExpr expr) {
Expr res = doSwitch(expr.getExpr());
return new UnaryExpr(UnaryOp.PRE, res);
}
@Override
public Expr caseEventExpr(EventExpr expr) {
IdExpr nestIdExpr = (IdExpr) doSwitch(expr.getId());
String eventStr = nestIdExpr.id + eventSuffix;
return new IdExpr(eventStr);
}
@Override
public Expr caseLatchedExpr(LatchedExpr expr) {
IdExpr nestIdExpr = (IdExpr) doSwitch(expr.getExpr());
String latchedStr = nestIdExpr.id + AgreeInlineLatchedConnections.LATCHED_SUFFIX;
return new IdExpr(latchedStr);
}
@Override
public Expr casePrevExpr(PrevExpr expr) {
Expr delayExpr = doSwitch(expr.getDelay());
Expr initExpr = doSwitch(expr.getInit());
Expr preExpr = new UnaryExpr(UnaryOp.PRE, delayExpr);
Expr res = new BinaryExpr(initExpr, BinaryOp.ARROW, preExpr);
return res;
}
@Override
public Expr caseRealLitExpr(RealLitExpr expr) {
return new RealExpr(BigDecimal.valueOf(Double.parseDouble(expr.getVal())));
}
@Override
public Expr caseTimeExpr(TimeExpr time) {
return AgreePatternTranslator.timeExpr;
}
@Override
public Expr caseUnaryExpr(com.rockwellcollins.atc.agree.agree.UnaryExpr expr) {
Expr subExpr = doSwitch(expr.getExpr());
Expr res = null;
switch (expr.getOp()) {
case "-":
res = new UnaryExpr(UnaryOp.NEGATIVE, subExpr);
break;
case "not":
res = new UnaryExpr(UnaryOp.NOT, subExpr);
break;
default:
assert (false);
}
return res;
}
private static void addToNodeList(Node node) {
for (Node inList : globalNodes) {
if (inList.id.equals(node.id)) {
throw new AgreeException("AGREE AST generator tried adding multiple nodes of name '" + node.id + "'");
}
}
globalNodes.add(node);
}
private static boolean nodeNameExists(String name) {
for (Node inList : globalNodes) {
if (inList.id.equals(name)) {
return true;
}
}
return false;
}
}
|
package org.safehaus.subutai.ui.commandrunner;
import com.google.common.base.Strings;
import com.vaadin.server.ThemeResource;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.*;
import org.safehaus.subutai.api.agentmanager.AgentManager;
import org.safehaus.subutai.api.commandrunner.*;
import org.safehaus.subutai.server.ui.component.AgentTree;
import org.safehaus.subutai.shared.protocol.Agent;
import org.safehaus.subutai.shared.protocol.Disposable;
import org.safehaus.subutai.shared.protocol.Response;
import org.safehaus.subutai.shared.protocol.Util;
import org.safehaus.subutai.shared.protocol.enums.RequestType;
import org.safehaus.subutai.shared.protocol.settings.Common;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Command Runner UI - Terminal
*/
public class TerminalForm extends CustomComponent implements Disposable {
final CommandRunner commandRunner;
final AgentManager agentManager;
private volatile int taskCount = 0;
private ExecutorService executor;
private AgentTree agentTree;
private TerminalControl commandOutputTxtArea;
private TextField programTxtFld, workDirTxtFld, timeoutTxtFld;
private ComboBox requestTypeCombo;
private Label indicator;
private VerticalLayout controls;
public TerminalForm(final CommandRunner commandRunner, final AgentManager agentManager) {
this.commandRunner = commandRunner;
this.agentManager = agentManager;
executor = Executors.newCachedThreadPool();
setSizeFull();
HorizontalSplitPanel horizontalSplit = new HorizontalSplitPanel();
horizontalSplit.setSplitPosition(20, Unit.PERCENTAGE);
horizontalSplit.setSizeFull();
agentTree = new AgentTree(agentManager);
horizontalSplit.setFirstComponent(agentTree);
HorizontalSplitPanel gridLayout = new HorizontalSplitPanel();
gridLayout.setSizeFull();
gridLayout.setSplitPosition(80, Unit.PERCENTAGE);
commandOutputTxtArea = new TerminalControl(this);
controls = new VerticalLayout();
controls.setSpacing(true);
controls.setMargin(true);
initProgram();
initCommand();
initTimeout();
initRequestType();
initIndicator();
gridLayout.setFirstComponent(commandOutputTxtArea);
gridLayout.setSecondComponent(controls);
horizontalSplit.setSecondComponent(gridLayout);
setCompositionRoot(horizontalSplit);
}
private void initProgram() {
Label programLbl = new Label("Program");
programTxtFld = new TextField();
programTxtFld.setId("pwd");
programTxtFld.setValue("pwd");
programTxtFld.setWidth(200, Unit.PIXELS);
controls.addComponent(programLbl);
controls.addComponent(programTxtFld);
}
private void initCommand() {
Label workDirLbl = new Label("Cwd");
workDirTxtFld = new TextField();
workDirTxtFld.setValue("/");
controls.addComponent(workDirLbl);
controls.addComponent(workDirTxtFld);
}
private void initTimeout() {
Label timeoutLbl = new Label("Timeout");
timeoutTxtFld = new TextField();
timeoutTxtFld.setId("timeout_txt");
timeoutTxtFld.setValue("30");
timeoutTxtFld.setWidth(30, Unit.PIXELS);
controls.addComponent(timeoutLbl);
controls.addComponent(timeoutTxtFld);
}
private void initRequestType() {
Label requestTypeLabel = new Label("Req Type");
controls.addComponent(requestTypeLabel);
requestTypeCombo = new ComboBox(null,
Arrays.asList(RequestType.EXECUTE_REQUEST, RequestType.TERMINATE_REQUEST, RequestType.PS_REQUEST));
requestTypeCombo.setImmediate(true);
requestTypeCombo.setTextInputAllowed(false);
requestTypeCombo.setNullSelectionAllowed(false);
requestTypeCombo.setValue(RequestType.EXECUTE_REQUEST);
requestTypeCombo.setWidth(200, Unit.PIXELS);
controls.addComponent(requestTypeCombo);
}
private void initIndicator() {
indicator = new Label();
indicator.setId("terminal_indicator");
indicator.setIcon(new ThemeResource("img/spinner.gif"));
indicator.setContentMode(ContentMode.HTML);
indicator.setHeight(11, Unit.PIXELS);
indicator.setWidth(50, Unit.PIXELS);
indicator.setVisible(false);
controls.addComponent(indicator);
}
public void sendCommand(String command) {
Set<Agent> agents = checkAgents();
if (agents != null && validateInputs(command)) {
RequestBuilder requestBuilder = new RequestBuilder(command);
if (requestTypeCombo.getValue() == RequestType.TERMINATE_REQUEST) {
requestBuilder.withPid(Integer.valueOf(programTxtFld.getValue()));
requestBuilder.withType(RequestType.TERMINATE_REQUEST);
} else if (requestTypeCombo.getValue() == RequestType.PS_REQUEST) {
requestBuilder.withType(RequestType.PS_REQUEST);
}
requestBuilder.withTimeout(Integer.valueOf(timeoutTxtFld.getValue()));
requestBuilder.withCwd(workDirTxtFld.getValue());
// getUI().setPollInterval(Common.REFRESH_UI_SEC * 1000);
createCommand(requestBuilder, agents);
}
}
private Set<Agent> checkAgents() {
Set<Agent> agents = agentTree.getSelectedAgents();
if (agents.isEmpty()) {
agents = null;
show("Please, select nodes\\n");
}
return agents;
}
private boolean validateInputs(String command) {
if (Strings.isNullOrEmpty(command)) {
show("Please, enter command\\n");
return false;
}
if (Strings.isNullOrEmpty(timeoutTxtFld.getValue()) || !Util.isNumeric(timeoutTxtFld.getValue())) {
show("Please, enter integer timeout value\\n");
return false;
} else {
int timeout = Integer.valueOf(timeoutTxtFld.getValue());
if (timeout <= 0 || timeout > Common.MAX_COMMAND_TIMEOUT_SEC) {
show("Please, enter timeout value between 0 and " + Common.MAX_COMMAND_TIMEOUT_SEC + "\\n");
}
}
if (Strings.isNullOrEmpty(workDirTxtFld.getValue())) {
show("Please, enter working directory\\n");
return false;
}
return true;
}
private void createCommand(RequestBuilder requestBuilder, Set<Agent> agents) {
final Command command = commandRunner.createCommand(requestBuilder, agents);
final String[] output = {""};
indicator.setVisible(true);
taskCount++;
executor.execute(new Runnable() {
public void run() {
commandRunner.runCommand(command, new CommandCallback() {
@Override
public void onResponse(Response response, AgentResult agentResult, Command command) {
Agent agent = agentManager.getAgentByUUID(response.getUuid());
String host = agent == null ? String.format("Offline[%s]", response.getUuid()) :
agent.getHostname();
StringBuilder out = new StringBuilder("");
if (!Strings.isNullOrEmpty(response.getStdOut())) {
out.append(response.getStdOut());
}
if (!Strings.isNullOrEmpty(response.getStdErr())) {
out.append(response.getStdErr());
}
output[0] += out.toString();
// getUI().setPollInterval(Common.REFRESH_UI_SEC * 60000);
}
});
taskCount
if (taskCount == 0) {
show(output[0]);
indicator.setVisible(false);
}
}
});
}
private void show(String notification) {
commandOutputTxtArea.setOutputPrompt(notification);
}
public void dispose() {
agentTree.dispose();
executor.shutdown();
}
}
|
package com.esri.samples.localserver.local_server_dynamic_workspace_raster;
import java.io.File;
import java.util.Arrays;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import com.esri.arcgisruntime.layers.ArcGISMapImageLayer;
import com.esri.arcgisruntime.layers.ArcGISMapImageSublayer;
import com.esri.arcgisruntime.layers.RasterSublayerSource;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.localserver.DynamicWorkspace;
import com.esri.arcgisruntime.localserver.LocalMapService;
import com.esri.arcgisruntime.localserver.LocalServer;
import com.esri.arcgisruntime.localserver.LocalServerStatus;
import com.esri.arcgisruntime.localserver.RasterWorkspace;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.MapView;
public class LocalServerDynamicWorkspaceRasterSample extends Application {
private MapView mapView;
private static LocalServer server = LocalServer.INSTANCE;
@Override
public void start(Stage stage) throws Exception {
try {
// create stack pane and application scene
StackPane stackPane = new StackPane();
Scene scene = new Scene(stackPane);
scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
// set title, size, and add scene to stage
stage.setTitle("Dynamic workspaces: raster");
stage.setWidth(800);
stage.setHeight(700);
stage.setScene(scene);
stage.show();
// create Add Raster button
Button addButton = new Button("Choose Raster");
addButton.setMaxSize(150, 25);
addButton.setDisable(false);
// choose the file, then start the Local Server instance and the local map service...
addButton.setOnAction(e -> {
if (LocalServer.INSTANCE.checkInstallValid()) {
// Browse to the raster file
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Image Files", "*.tif"));
fileChooser.setInitialDirectory(new File("./samples-data/raster/"));
File selectedFile = fileChooser.showOpenDialog(stage);
if(selectedFile != null){
String fileName = selectedFile.getName();
String path = selectedFile.getParent();
startLocalService(fileName, path);
}
}else {
Platform.runLater(() -> {
Alert dialog = new Alert(AlertType.INFORMATION);
dialog.setHeaderText("Local Server Load Error");
dialog.setContentText("Local Server install path couldn't be located.");
dialog.showAndWait();
Platform.exit();
});
}
});
// create a map and add it to a map view
ArcGISMap map = new ArcGISMap(Basemap.createTopographic());
mapView = new MapView();
mapView.setMap(map);
// add the map view and control panel to stack pane...
stackPane.getChildren().addAll(mapView, addButton);
StackPane.setAlignment(addButton, Pos.TOP_LEFT);
StackPane.setMargin(addButton, new Insets(10, 0, 0, 10));
} catch (Exception e) {
// on any error, display the stack trace
e.printStackTrace();
}
}
/** Start the LocalServer and the LocalMapService
*
* @param fileName
* @param path
*/
private void startLocalService(String fileName, String path) {
// start local server
server.startAsync();
server.addStatusChangedListener(status -> {
if (server.getStatus() == LocalServerStatus.STARTED) {
// start a service from the blank MPK...
String mapServiceURL = "./samples-data/local_server/mpk_blank.mpk";
LocalMapService localMapService = new LocalMapService(mapServiceURL);
// Can't add a dynamic workspace to a running service, so do that first...
RasterWorkspace rasterWorkspace = new RasterWorkspace("raster_wkspc", path);
RasterSublayerSource source = new RasterSublayerSource(rasterWorkspace.getId(),fileName);
ArcGISMapImageSublayer imageSublayer = new ArcGISMapImageSublayer(0, source);
Iterable<DynamicWorkspace> dynamicWorkspaces = Arrays.asList(rasterWorkspace);
localMapService.setDynamicWorkspaces(dynamicWorkspaces);
localMapService.addStatusChangedListener(event -> {
if (event.getNewStatus() == LocalServerStatus.STARTED){
// Now, we're ready to add the raster layer...
// create a map image layer using url
ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer(localMapService.getUrl());
// Add the sub layer to the image layer
imageLayer.addDoneLoadingListener(() -> {
if (imageLayer.getLoadStatus() == LoadStatus.LOADED && imageLayer.getFullExtent() != null) {
imageLayer.getSublayers().add(imageSublayer);
}
});
imageLayer.loadAsync();
//add the image layer to map. Clear any previous layers...
mapView.getMap().getOperationalLayers().clear();
mapView.getMap().getOperationalLayers().add(imageLayer);
}
});
localMapService.startAsync();
}
});
}
/**
* Stops and releases all resources used in application.
*/
@Override
public void stop() throws Exception {
if (mapView != null) {
mapView.dispose();
}
}
/**
* Opens and runs application.
*
* @param args arguments passed to this application
*/
public static void main(String[] args) {
Application.launch(args);
}
}
|
package com.daeliin.components.security.membership.notifications;
import com.daeliin.components.core.mail.Mail;
import com.daeliin.components.core.mail.MailBuildingException;
import com.daeliin.components.core.mail.Mailing;
import com.daeliin.components.security.credentials.account.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
@Slf4j
@Service
@Profile("mail")
public class MailingMembershipNotifications implements MembershipNotifications {
@Value("${daeliin.mail.from}")
private String from;
@Inject
protected Mailing mails;
@Inject
protected MessageSource messages;
@Async
@Override
public void signUp(final Account account) {
Map<String, String> parameters = addAccountParameters(account);
try {
Mail mail =
Mail.builder()
.from(from)
.to(account.email)
.subject(messages.getMessage("membership.mail.signup.subject", null, Locale.getDefault()))
.templateName("signUp")
.parameters(parameters)
.build();
mails.send(mail);
} catch (MailBuildingException e) {
log.error(String.format("Sign up mail for account %s was invalid", account), e);
}
}
@Async
@Override
public void activate(final Account account) {
Map<String, String> parameters = addAccountParameters(account);
try {
Mail mail =
Mail.builder()
.from(from)
.to(account.email)
.subject(messages.getMessage("membership.mail.activate.subject", null, Locale.getDefault()))
.templateName("activate")
.parameters(parameters)
.build();
mails.send(mail);
} catch (MailBuildingException e) {
log.error(String.format("Activate mail for account %s was invalid", account), e);
}
}
@Async
@Override
public void newPassword(final Account account) {
Map<String, String> parameters = addAccountParameters(account);
try {
Mail mail =
Mail.builder()
.from(from)
.to(account.email)
.subject(messages.getMessage("membership.mail.newPassword.subject", null, Locale.getDefault()))
.templateName("newPassword")
.parameters(parameters)
.build();
mails.send(mail);
} catch (MailBuildingException e) {
log.error(String.format("New password mail for account %s was invalid", account), e);
}
}
@Async
@Override
public void resetPassword(final Account account) {
Map<String, String> parameters = addAccountParameters(account);
try {
Mail mail =
Mail.builder()
.from(from)
.to(account.email)
.subject(messages.getMessage("membership.mail.resetPassword.subject", null, Locale.getDefault()))
.templateName("resetPassword")
.parameters(parameters)
.build();
mails.send(mail);
} catch (MailBuildingException e) {
log.error(String.format("Reset password mail for account %s was invalid", account), e);
}
}
private Map<String, String> addAccountParameters(final Account account) {
Map<String, String> accountParameters = new HashMap<>();
accountParameters.put("userName", account.username);
accountParameters.put("userEmail", account.email);
accountParameters.put("userToken", account.token);
return accountParameters;
}
}
|
package org.carlspring.strongbox.controllers.configuration;
import org.carlspring.strongbox.config.IntegrationTest;
import org.carlspring.strongbox.providers.layout.Maven2LayoutProvider;
import org.carlspring.strongbox.rest.common.RestAssuredBaseTest;
import org.carlspring.strongbox.storage.MutableStorage;
import org.carlspring.strongbox.storage.repository.MutableRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.HttpServerErrorException;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertNotNull;
import static org.carlspring.strongbox.controllers.configuration.ProxyConfigurationControllerTestIT.createProxyConfiguration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Pablo Tirado
*/
@IntegrationTest
@RunWith(SpringRunner.class)
public class StoragesConfigurationControllerTestIT
extends RestAssuredBaseTest
{
@Test
public void testAddGetStorage()
{
String storageId = "storage1";
MutableStorage storage1 = new MutableStorage("storage1");
String url = getContextBaseUrl() + "/api/configuration/strongbox/storages";
logger.debug("Using storage class " + storage1.getClass()
.getName());
given().contentType(MediaType.APPLICATION_XML_VALUE)
.body(storage1)
.when()
.put(url)
.prettyPeek()
.then()
.statusCode(200);
MutableRepository r1 = new MutableRepository("repository0");
r1.setAllowsRedeployment(true);
r1.setSecured(true);
r1.setStorage(storage1);
r1.setLayout(Maven2LayoutProvider.ALIAS);
MutableRepository r2 = new MutableRepository("repository1");
r2.setAllowsForceDeletion(true);
r2.setTrashEnabled(true);
r2.setStorage(storage1);
r2.setProxyConfiguration(createProxyConfiguration());
r2.setLayout(Maven2LayoutProvider.ALIAS);
addRepository(r1);
addRepository(r2);
MutableStorage storage = getStorage(storageId);
assertNotNull("Failed to get storage (" + storageId + ")!", storage);
assertFalse("Failed to get storage (" + storageId + ")!", storage.getRepositories().isEmpty());
assertTrue("Failed to get storage (" + storageId + ")!",
storage.getRepositories().get("repository0").allowsRedeployment());
assertTrue("Failed to get storage (" + storageId + ")!",
storage.getRepositories().get("repository0").isSecured());
assertTrue("Failed to get storage (" + storageId + ")!",
storage.getRepositories().get("repository1").allowsForceDeletion());
assertTrue("Failed to get storage (" + storageId + ")!",
storage.getRepositories().get("repository1").isTrashEnabled());
assertNotNull("Failed to get storage (" + storageId + ")!",
storage.getRepositories().get("repository1").getProxyConfiguration().getHost());
assertEquals("Failed to get storage (" + storageId + ")!",
"localhost",
storage.getRepositories().get("repository1").getProxyConfiguration().getHost());
deleteRepository(storageId, "repository0");
deleteRepository(storageId, "repository1");
}
private MutableStorage getStorage(String storageId)
{
String url = getContextBaseUrl() + "/api/configuration/strongbox/storages/" + storageId;
return given().contentType(MediaType.TEXT_PLAIN_VALUE)
.accept(MediaType.APPLICATION_XML_VALUE)
.when()
.get(url)
.as(MutableStorage.class);
}
private int addRepository(MutableRepository repository)
{
String url;
if (repository == null)
{
logger.error("Unable to add non-existing repository.");
throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
"Unable to add non-existing repository.");
}
if (repository.getStorage() == null)
{
logger.error("Storage associated with repo is null.");
throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
"Storage associated with repo is null.");
}
try
{
url = getContextBaseUrl() + "/api/configuration/strongbox/storages/" + repository.getStorage().getId() +
"/" +
repository.getId();
}
catch (RuntimeException e)
{
logger.error("Unable to create web resource.", e);
throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
}
int status = given().contentType(MediaType.APPLICATION_XML_VALUE)
.body(repository)
.when()
.put(url)
.then()
.statusCode(200)
.extract()
.statusCode();
return status;
}
private void deleteRepository(String storageId,
String repositoryId)
{
String url = getContextBaseUrl() + String.format("/api/configuration/strongbox/storages/%s/%s",
storageId,
repositoryId);
given().contentType(MediaType.APPLICATION_JSON_VALUE)
.when()
.delete(url)
.then()
.statusCode(200);
}
@Test
public void testCreateAndDeleteStorage()
{
final String storageId = "storage2";
final String repositoryId1 = "repository0";
final String repositoryId2 = "repository1";
MutableStorage storage2 = new MutableStorage(storageId);
String url = getContextBaseUrl() + "/api/configuration/strongbox/storages";
given().contentType(MediaType.APPLICATION_XML_VALUE)
.body(storage2)
.when()
.put(url)
.peek() // Use peek() to print the ouput
.then()
.statusCode(200);
MutableRepository r1 = new MutableRepository(repositoryId1);
r1.setAllowsRedeployment(true);
r1.setSecured(true);
r1.setStorage(storage2);
r1.setProxyConfiguration(createProxyConfiguration());
r1.setLayout(Maven2LayoutProvider.ALIAS);
MutableRepository r2 = new MutableRepository(repositoryId2);
r2.setAllowsRedeployment(true);
r2.setSecured(true);
r2.setStorage(storage2);
r2.setLayout(Maven2LayoutProvider.ALIAS);
addRepository(r1);
addRepository(r2);
url = getContextBaseUrl() + "/api/configuration/strongbox/proxy-configuration";
given().accept(MediaType.APPLICATION_JSON_VALUE)
.params("storageId", storageId, "repositoryId", repositoryId1)
.when()
.get(url)
.peek() // Use peek() to print the ouput
.then()
.statusCode(200)
.extract();
MutableStorage storage = getStorage(storageId);
assertNotNull("Failed to get storage (" + storageId + ")!", storage);
assertFalse("Failed to get storage (" + storageId + ")!", storage.getRepositories().isEmpty());
url = getContextBaseUrl() + "/api/configuration/strongbox/storages/" + storageId + "/" + repositoryId1;
logger.debug(url);
given().contentType(MediaType.TEXT_PLAIN_VALUE)
.param("force", true)
.when()
.delete(url)
.peek() // Use peek() to print the ouput
.then()
.statusCode(200);
url = getContextBaseUrl() + "/api/configuration/strongbox/storages/" + storageId + "/" + repositoryId1;
logger.debug(storageId);
logger.debug(repositoryId1);
given().contentType(MediaType.TEXT_PLAIN_VALUE)
.when()
.get(url)
.peek() // Use peek() to print the ouput
.then()
.statusCode(404);
deleteRepository(storageId, repositoryId2);
}
}
|
package org.xwiki.tool.extension.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Model;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.DefaultProjectBuildingRequest;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.project.ProjectBuildingResult;
import org.xwiki.component.embed.EmbeddableComponentManager;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.util.DefaultParameterizedType;
import org.xwiki.extension.Extension;
import org.xwiki.extension.MutableExtension;
import org.xwiki.extension.internal.ExtensionUtils;
import org.xwiki.extension.internal.converter.ExtensionIdConverter;
import org.xwiki.extension.repository.internal.ExtensionSerializer;
import org.xwiki.extension.repository.internal.local.DefaultLocalExtension;
import org.xwiki.properties.converter.Converter;
import org.xwiki.tool.extension.ExtensionOverride;
/**
* Base class for Maven plugins manipulating extensions.
*
* @version $Id$
* @since 8.4RC1
*/
public abstract class AbstractExtensionMojo extends AbstractMojo
{
/**
* The current Maven session being executed.
*/
@Parameter(defaultValue = "${session}", required = true, readonly = true)
protected MavenSession session;
/**
* Project builder -- builds a model from a pom.xml.
*/
@Component
protected ProjectBuilder projectBuilder;
@Parameter
protected List<ExtensionOverride> extensionOverrides;
protected ExtensionSerializer extensionSerializer;
protected Converter<Extension> extensionConverter;
protected void initializeComponents() throws MojoExecutionException
{
// Initialize ComponentManager
EmbeddableComponentManager componentManager = new EmbeddableComponentManager();
componentManager.initialize(this.getClass().getClassLoader());
// Initialize components
try {
this.extensionSerializer = componentManager.getInstance(ExtensionSerializer.class);
this.extensionConverter =
componentManager.getInstance(new DefaultParameterizedType(null, Converter.class, Extension.class));
} catch (ComponentLookupException e) {
throw new MojoExecutionException("Failed to load components", e);
}
}
protected MavenProject getMavenProject(Artifact artifact) throws MojoExecutionException
{
try {
ProjectBuildingRequest request = new DefaultProjectBuildingRequest(this.session.getProjectBuildingRequest())
// We don't want to execute any plugin here
.setProcessPlugins(false)
// It's not this plugin job to validate this pom.xml
.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL)
// Use the repositories configured for the built project instead of the default Maven ones
.setRemoteRepositories(this.session.getCurrentProject().getRemoteArtifactRepositories());
// Note: build() will automatically get the POM artifact corresponding to the passed artifact.
ProjectBuildingResult result = this.projectBuilder.build(artifact, request);
return result.getProject();
} catch (ProjectBuildingException e) {
throw new MojoExecutionException(String.format("Failed to build project for [%s]", artifact), e);
}
}
protected Extension toExtension(Artifact artifact) throws MojoExecutionException
{
MavenProject mavenProject = getMavenProject(artifact);
return toExtension(mavenProject.getModel());
}
protected Extension toExtension(Model model)
{
return this.extensionConverter.convert(Extension.class, model);
}
protected void saveExtension(File path, Artifact artifact)
throws MojoExecutionException, IOException, ParserConfigurationException, TransformerException
{
// Get MavenProject instance
MavenProject mavenProject = getMavenProject(artifact);
saveExtension(path, mavenProject.getModel());
}
protected void saveExtension(File path, Model model)
throws IOException, ParserConfigurationException, TransformerException
{
// Get Extension instance
Extension mavenExtension = this.extensionConverter.convert(Extension.class, model);
MutableExtension mutableExtension;
if (mavenExtension instanceof MutableExtension) {
mutableExtension = (MutableExtension) mavenExtension;
} else {
mutableExtension = new DefaultLocalExtension(null, mavenExtension);
}
if (!path.exists()) {
// Apply overrides
override(mutableExtension);
// Save the Extension descriptor
try (FileOutputStream stream = new FileOutputStream(path)) {
this.extensionSerializer.saveExtensionDescriptor(mavenExtension, stream);
}
}
}
protected void override(MutableExtension extension)
{
if (this.extensionOverrides != null) {
for (ExtensionOverride extensionOverride : this.extensionOverrides) {
String id = extensionOverride.get(Extension.FIELD_ID);
if (id != null) {
// Override features
String featuresString = extensionOverride.get(Extension.FIELD_FEATURES);
if (featuresString != null) {
Collection<String> features = ExtensionUtils.importPropertyStringList(featuresString, true);
extension.setExtensionFeatures(
ExtensionIdConverter.toExtensionIdList(features, extension.getId().getVersion()));
}
}
}
}
}
protected void saveExtension(Artifact artifact, File directory) throws MojoExecutionException
{
// Get path
File path = new File(directory, artifact.getArtifactId() + '-' + artifact.getBaseVersion() + ".xed");
try {
saveExtension(path, artifact);
} catch (Exception e) {
throw new MojoExecutionException("Failed to write descriptor for artifact [" + artifact + "]", e);
}
}
protected void saveExtensions(Collection<Artifact> artifacts, File directory, String type)
throws MojoExecutionException
{
// Register dependencies
for (Artifact artifact : artifacts) {
if (!artifact.isOptional()) {
if (type == null || type.equals(artifact.getType())) {
saveExtension(artifact, directory);
}
}
}
}
}
|
package com.verce.forwardmodelling;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.io.BufferedInputStream;
import java.io.File;
import java.net.*;
import javax.net.ssl.HttpsURLConnection;
import java.util.zip.*;
import java.util.TimeZone;
import java.util.Enumeration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Properties;
import java.util.Collections;
import java.util.Comparator;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.Format;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.xml.bind.DatatypeConverter;
import java.security.PrivateKey;
import java.security.KeyFactory;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItem;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.repository.model.Folder;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.CharPool;
import com.liferay.portal.kernel.util.HttpUtil;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.servlet.ServletResponseUtil;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil;
import com.liferay.portlet.documentlibrary.DuplicateFileException;
import com.liferay.util.bridges.mvc.MVCPortlet;
import hu.sztaki.lpds.pgportal.services.asm.ASMJob;
import hu.sztaki.lpds.pgportal.services.asm.ASMService;
import hu.sztaki.lpds.pgportal.services.asm.ASMWorkflow;
import hu.sztaki.lpds.pgportal.services.asm.beans.ASMRepositoryItemBean;
import hu.sztaki.lpds.pgportal.services.asm.beans.WorkflowInstanceBean;
import hu.sztaki.lpds.pgportal.services.asm.beans.RunningJobDetailsBean;
import hu.sztaki.lpds.pgportal.services.asm.beans.ASMResourceBean;
import hu.sztaki.lpds.pgportal.services.asm.constants.RepositoryItemTypeConstants;
import hu.sztaki.lpds.pgportal.services.asm.constants.DownloadTypeConstants;
import hu.sztaki.lpds.pgportal.service.base.data.WorkflowData;
import hu.sztaki.lpds.pgportal.service.base.PortalCacheService;
import hu.sztaki.lpds.dcibridge.client.ResourceConfigurationFace;
import hu.sztaki.lpds.information.local.InformationBase;
import hu.sztaki.lpds.pgportal.service.workflow.RealWorkflowUtils;
import hu.sztaki.lpds.wfs.com.WorkflowConfigErrorBean;
import hu.sztaki.lpds.pgportal.services.asm.constants.StatusConstants;
import hu.sztaki.lpds.information.com.ServiceType;
import hu.sztaki.lpds.wfs.com.RepositoryWorkflowBean;
import hu.sztaki.lpds.repository.service.veronica.commons.RepositoryFileUtils;
import hu.sztaki.lpds.wfs.inf.PortalWfsClient;
import hu.sztaki.lpds.storage.inf.PortalStorageClient;
import hu.sztaki.lpds.pgportal.services.asm.exceptions.upload.*;
import com.verce.forwardmodelling.Constants;
import org.json.*;
public class ForwardPortlet extends MVCPortlet{
ASMService asm_service = null;
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException, IOException
{
System.out.println("
if(resourceRequest.getResourceID().equals("uploadFile"))
uploadFile(resourceRequest, resourceResponse);
else if(resourceRequest.getResourceID().equals("submit"))
submitSimulationWorkflow(resourceRequest, resourceResponse);
else if(resourceRequest.getResourceID().equals("submitDownloadWorkflow"))
submitDownloadWorkflow(resourceRequest, resourceResponse);
else if(resourceRequest.getResourceID().equals("submitProcessingWorkflow"))
submitProcessingWorkflow(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("downloadOutput"))
downloadOutput(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("deleteWorkflow"))
deleteWorkflow(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("meshVelocityModelUpload"))
meshVelocityModelUpload(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("downloadMeshDetails"))
downloadMeshDetails(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("downloadVelocityModelDetails"))
downloadVelocityModelDetails(resourceRequest, resourceResponse);
else if (resourceRequest.getResourceID().equals("getWorkflowList"))
getWorkflowList(resourceRequest, resourceResponse);
}
public JSONObject getProvenanceWorkflows(ResourceRequest req, ResourceResponse res) {
// int offset = Integer.parseInt(ParamUtil.getString(req, "start"));
// int limit = Integer.parseInt(ParamUtil.getString(req, "limit"));
int offset = 0;
int limit = 1000;
JSONObject jsonObject = new JSONObject();
try {
String username = PortalUtil.getUser(req).getScreenName();
HttpServletRequest servletRequest = PortalUtil.getHttpServletRequest(req);
String url = PortalUtil.getPortalURL(servletRequest) + "/j2ep-1.0/prov/workflow/user/"+username+"?start="+offset+"&limit="+limit;
System.out.println("Fetching provenance workflows from " + url);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
InputStream response = connection.getInputStream();
String jsonString = inputStreamToString(response);
jsonObject = new JSONObject(jsonString);
} catch (Exception e) {
System.out.println("ERROR: Failed to get provenance workflows - " + e.getMessage());
}
return jsonObject;
}
public void getWorkflowList(ResourceRequest req, ResourceResponse res) {
int offset = Integer.parseInt(ParamUtil.getString(req, "start"));
int limit = Integer.parseInt(ParamUtil.getString(req, "limit"));
String filterString = ParamUtil.getString(req, "filter");
HashMap<String, String> filters = new HashMap<String, String>();
if (filterString != null && !"".equals(filterString)) {
JSONArray filterList = new JSONArray(filterString);
for (int ii = 0; ii < filterList.length(); ii++) {
JSONObject filter = filterList.getJSONObject(ii);
filters.put(filter.getString("property"), filter.getString("value"));
}
}
System.out.println("Fetching runs " + offset + " - " + (offset + limit) + " of user " + req.getRemoteUser() + " with filters: " + filters);
try{
asm_service = ASMService.getInstance();
ArrayList<ASMWorkflow> importedWfs = asm_service.getASMWorkflows(req.getRemoteUser());
String type = filters.get("prov:type");
if (type != null) {
java.util.Iterator<ASMWorkflow> iter = importedWfs.iterator();
while (iter.hasNext()) {
ASMWorkflow workflow = iter.next();
// remove those workflows that begin with a prefix that doesn't match type
if (workflow.getWorkflowName().indexOf(type + "_") >= 0) {
} else if (
workflow.getWorkflowName().indexOf("simulation_") >= 0
|| workflow.getWorkflowName().indexOf("download_") >= 0
|| workflow.getWorkflowName().indexOf("processing_") >= 0
|| workflow.getWorkflowName().indexOf("misfit_") >= 0
) {
iter.remove();
}
}
}
Collections.sort(importedWfs, new Comparator<ASMWorkflow>() {
// sort by date from the workflow name in reverse order
public int compare(ASMWorkflow wf1, ASMWorkflow wf2) {
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd-hhmmss");
try {
Date wf2date = ft.parse(wf2.getWorkflowName().substring(wf2.getWorkflowName().lastIndexOf("_")+1));
Date wf1date = ft.parse(wf1.getWorkflowName().substring(wf1.getWorkflowName().lastIndexOf("_")+1));
return wf2date.compareTo(wf1date);
} catch (Exception e) {
System.out.println(e);
return 0;
}
}
});
JSONObject provWorkflows = getProvenanceWorkflows(req, res);
JSONArray list = provWorkflows.optJSONArray("runIds");
JSONObject result = new JSONObject();
JSONArray array = new JSONArray();
result.put("list", array);
result.put("totalCount", importedWfs.size());
for(int ii = offset; ii < Math.min(offset + limit, importedWfs.size()); ii++) {
ASMWorkflow wf = importedWfs.get(ii);
if (wf == null) {
System.out.println("**** Workflow null");
break;
}
//wf.getWorkflowName() is formated: (submitedName+RandomID)_YYYY-MM-DD-TTTTTT
//wfDate is YYYY-MM-DD
//wfDate2 is YYYY-MM-DD-TTTTTT (used to sort the results)
//wfName is submitedName+RandomID
String wfDate = wf.getWorkflowName().substring(wf.getWorkflowName().lastIndexOf("_")+1, wf.getWorkflowName().lastIndexOf("-"));
String wfDate2 = wf.getWorkflowName().substring(wf.getWorkflowName().lastIndexOf("_")+1);
String wfName = wf.getWorkflowName().substring(0,wf.getWorkflowName().lastIndexOf("_"));
String status = wf.getStatusbean().getStatus();
// only fetch status for runs that are not already stopped
if (!status.equals("ERROR") && !status.equals("FINISHED") && !status.equals("WORKFLOW_SUSPENDING")) {
WorkflowInstanceBean wfIB = asm_service.getDetails(req.getRemoteUser(), wf.getWorkflowName());
HashMap<String,String> statuses = new HashMap();
if (wfIB != null) {
StatusConstants statusConstants = new StatusConstants();
for (RunningJobDetailsBean job : wfIB.getJobs()) {
if (job.getInstances().size() <= 0) {
statuses.put(job.getName(), "UNKNOWN");
continue;
}
statuses.put(job.getName(), statusConstants.getStatus(job.getInstances().get(0).getStatus()));
}
System.out.println(statuses);
}
String computeStatus = statuses.containsKey("COMPUTE") ? statuses.get("COMPUTE") : statuses.containsKey("Job0") ? statuses.get("Job0") : null;
String stageOutStatus = statuses.containsKey("STAGEOUT") ? statuses.get("STAGEOUT") : statuses.containsKey("Job1") ? statuses.get("Job1") : null;
if (statuses.containsValue("ERROR")) {
status = "ERROR";
} else if (computeStatus == null || "UNKNOWN".equals(computeStatus)) {
status = "INIT";
} else if ("PENDING".equals(computeStatus) || "INIT".equals(computeStatus)) {
status = "PENDING";
} else if ("RUNNING".equals(stageOutStatus)) {
status = "STAGE OUT";
} else if ("FINISHED".equals(stageOutStatus)) {
status = "FINISHED";
} else if ("RUNNING".equals(computeStatus)) {
status = "RUNNING";
} else {
// Fallback to overall workflow status
System.out.println("FALLBACK to workflow status");
}
}
JSONObject object = new JSONObject();
object
.put("name", wfName)
.put("desc", wf.getSubmissionText())
.put("status", status)
.put("date", wfDate)
.put("date2", wfDate2)
.put("workflowId", wf.getWorkflowName());
for (int jj = 0; jj < list.length(); ++jj) {
JSONObject provWorkflow = list.getJSONObject(jj);
if (!provWorkflow.getString("_id").equals(wfName)) {
continue;
}
object
.put("workflowName", provWorkflow.optString("workflowName"))
.put("grid", provWorkflow.optString("grid"))
.put("resourceType", provWorkflow.optString("resourceType"))
.put("resource", provWorkflow.optString("resource"))
.put("queue", provWorkflow.optString("queue"));
}
array.put(object);
}
HttpServletResponse response = PortalUtil.getHttpServletResponse(res);
PrintWriter out = response.getWriter();
out.print(result.toString());
out.flush();
out.close();
}
catch(Exception e)
{
System.out.println("[ForwardModellingPortlet.getWorkflowList] Could not update the workflow list");
e.printStackTrace();
}
}
public void updateWorkflowDescription(ActionRequest req, ActionResponse res)
{
asm_service = ASMService.getInstance();
String begName = ParamUtil.getString(req, "workflowId");
String newText = ParamUtil.getString(req, "newText");
ArrayList<ASMWorkflow> importedWfs;
importedWfs = asm_service.getASMWorkflows(req.getRemoteUser());
for(ASMWorkflow wf : importedWfs)
{
if(wf.getWorkflowName().startsWith(begName))
{
wf.setSubmissionText(newText);
System.out.println("[ForwardModellingPortlet.updateWorkflowDescription] Description in workflow "+begName+" has been updated to "+newText+" by user "+req.getRemoteUser());
return;
}
}
System.out.println("[ForwardModellingPortlet.updateWorkflowDescription] Error! Workflow "+begName+" could not be found");
}
private void deleteWorkflow(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
{
String userId = resourceRequest.getRemoteUser();
try{
asm_service = ASMService.getInstance();
String wfId = ParamUtil.getString(resourceRequest, "workflowId");
String encryptedIrodsSession = ParamUtil.getString(resourceRequest, "encryptedIrodsSession");
String irodsSession = decryptIrodsSession(encryptedIrodsSession);
asm_service.abort(userId, wfId); //TODO: fixme!
asm_service.DeleteWorkflow(userId, wfId);
System.out.println("[ForwardModellingPortlet.delete] workflow "+wfId+" has been deleted by user "+userId);
deleteFromIrods(irodsSession);
}
catch(Exception e)
{
catchError(e, resourceResponse, "500", "[ForwardModellingPortlet.delete] Exception catched!! User :"+userId);
}
}
private void deleteFromIrods(String irodsSession) {
String url = "https://dir-irods.epcc.ed.ac.uk/irodsweb/services/delete.php";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String ruri = "jonas.UEDINZone@dir-irods.epcc.ed.ac.uk:1247/UEDINZone/home/jonas";
String files = "Newfile.txt";
// String dirs[] = "";
try {
String query = String.format("ruri=%s&files[]=%s", // or &dirs[]=%s
URLEncoder.encode(ruri, charset),
URLEncoder.encode(files, charset));
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
connection.setRequestProperty("Cookie", "PHPSESSID="+irodsSession);
OutputStream output = connection.getOutputStream();
output.write(query.getBytes(charset));
InputStream response = connection.getInputStream();
System.out.println(inputStreamToString(response));
} catch(Exception e) {
System.out.println(e);
}
}
private String decryptIrodsSession(String encryptedIrodsSession) {
byte[] irodsSession = null;
try {
byte[] keyBytes = DatatypeConverter.parseBase64Binary("MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQDxmcVFGI9PMO5Z\n0Ukw5POpT0N8izhMM3zWYG9rfhJ48Gcbwr20P+obK7pUTLhkswReW62foY1SHY6c\nf50jL5MFXVCrg4Hxby0Vx49P4nBz66Kr4bAB1W1NuMTB1qTReGmNu0EQ70u2JlLO\nEBBwbOTv72zBssEBQRNy8q+Jo5b5BDjQ+0rpVwfD3J7fQ8wurAPklB6ekXK8jelx\nyKulJvUSPGjo9B+LbH+FLvQmZqdRP97MHzCc63nPxXHpV+y5Jr8crP8SEtkfy+9U\nSfTdnBkeFpvp6Ucje8KPBm6EHK4SShohjxKgzR0uXvar9NFMnukLO9lmc6yXxGWo\n1E9H980/b4vOR5I4Ts+XGY3oA3J9N8hIVJg4pvYUES8+UpDVoYsIgXTStQhvjL/5\n87n3td6YtZZPANDU+a4XSWIoGlhmeLUeNgaf4BGfH2icp5rGax2wyc2G4M7+4F7w\nDmnNgHR63GGDR86CU5kmSsO/vd1lm1eZAbiQKurscPh1PS3mwwvEmfQVXPDO+o8T\nns7+Z0SVRRLdEe+B9fR0YrAdIYM+mMWz+QLmXbFbN+WMghRWJQYCL4GvMNv5RvRZ\nnUKyiHziSEGkLDvJWkKp1QdlOVs80vq1g0Gsfmgs5oeGRVMctvrcrkbd5N0MJtXz\nW1FmisvDirFGpSYFZB2hIgiVna2stQIDAQABAoICAGdAODZXUKefWb2423ax4hAx\nd736IY0vU+KqQ/PEZVCaLPaIO1qVFg+WmIL+Zq9icjOBKqpV+HdnelMXlqg65LIe\nNyOViCsOQE5WgsC5HSXtRg/+26Fs/NGCbVQJz1ZWB4YyyJPcMJcfubOm2d+yKgUA\nZZJCOom2rgEqBirkZtj1HPLy8gjW0NK7ronsB47KpL9DLfLGZip+241tHS3vgDzS\n5GLqMbD8JWNdtanTpR3sFeNWUQg++kf5Mb1vfhOCo5o1tKycsX4NQbLcCHHNDE73\nippkv6pCcdt9/C0ptJrMYG6HHobqIdZ3byP99JSyNRY/9aD7Pn99x5RnZ5pyJJxr\nErhm+ds4L9hVPHo3C5yhbtj+73MaEGA21UrKqCD9aTi6XDSONNAA4AxA89IxNh0m\n/PSGSPEBkrSA1mvqyRVC6yL+pWVKXVhgXr+dlP42Lwsm+OpHPb95aQMDu+6NuOiu\n5HSjHF5MvF3NvO1sZ7/DKBUyFOIcKAYrPSIyQvUn6ifKqMC047MxQqBBHb445iVk\nhtmvBjzX/BYD8W37S7dszGeA4L6ZAfqnG469Pu38vxDIZ5aGATL5CrikS2yjd501\nmxIgXVlpHPbvAyMbKt78ykHJFXIJMeFiDviT4Jg48JzITSYOuTK2dHFGdZDnPJIG\nFiqXweRgTrEVaZ6wpOIBAoIBAQD7RIcOmt5vCqXsKATg4J9LLqkZGe77LcvzkN7V\nU26BqHIayWxSwXv5l0C/HK2a/S8+3Oak/qaTDeINlgoqZPPB9dch6Yd6LNApep1W\nqQZTSJbU3VmOQgNtrpaeD2+Kof9mBECWVUhmjE3u5TB45HF1gtGSwvtunLl/KL4M\ncbdoXiyrVCNIWIhVTxfIVG/le7VEslfsVDk+NeYY5OHp115XoZq3PrB64vKCr0pC\nMfkSLTSnlF29bq6GGAl1/ZiIbNyx9bsreQQpDN5yDVxs/v1vkWSmXUg0uYfJ8bOp\ngInjh9keRqECC/jEyASJNFizPXnFdTra/EW6wlw7+1CcvMTRAoIBAQD2JqJRJiEK\nJuu4SSfDrWZ4TesnPAVJxGKqjCaZzckOrmU6+Hr7dIXXBArfpWCUoDO+4Fl8PLn3\nvS6MDvrmnmgl0NiTMjEK1TVaMBmHAzEcUWWCict73UgpH6x2SRbe3edkZwbPccFD\nv5rqzEAQ73udwKrSrbymkZignaaGKuWe+vWOrw0VgVCeLVLkUSz5hL2uzqh79t7a\neALq4vp2Gh55/rGq/JeiTrRhEJ7jQpABiz43fU4b+cAX+E2tHnwRIl6HYIhzWQUK\nsJDaSvYFfLGuWZuQHwHOEf6A+nzPglI+yOFCjA/hbyb7nkcy3Uwr0L6YVf+GMRih\ngSIziVHs8jKlAoIBAAcM+jk3sUwuYU+KI/DnfLDQY2BX8PPNai6wfwA/chdjUahc\nxJRh54eubduvA1QZDK1X54TzvFreBdzZu/lKkeh8bIgAFJQiE8lGLooS/iFyJQFe\nILg0NAJs5r8Ssc+TEiabsfBF/l0aTMmKVtzdlC12+UiD/igxb6cYzpRs0He2RMyd\n9Mt/6Ht0V7eAXw9ydDi0RHFWP7D2NDm4mnpEV9pfp4bC1JLuMV3na08GNfYDnLmj\nGSpKo80ReZp8/j29yEeaHKFwqOQ5/zf2FgTc9uGdk9RzQ6ZvGldZV/BGshfXZQlL\ndBMpoNZswmvTMzX8YKFg08D3WUGPWKU6PR3Y0jECggEBAJVR4m1vv+M0sRHd7u1Z\nJywbuGbYliyloWTsGA59M1ZgnLAlRBV+HiLNJPt+ixQeCsXjuuUOwZFzheUYwUNd\nHLiz9G12qSF1LSREwXeRjB0tk3KYvIOrPLcVq70loWYZHuFdTlhRHXhHp2Z/+O1N\nGaQc2INtOV+iOwBUIkyJgTnr60JfFoTRKWKLBBnU1H+Y8qg0XSi2HYJSAxMSFfXG\n6m3+/zBGgoXHUM0BFCGwo0MMgPWQYe2+l7Tyv8whDgom20ksWhn/CnvtmDGT/6Jc\nfjzRxviqlqG3cLg1O7l1yQalPWDtLkUG9JL29SH59Ncvji9DG/r/lX2DpIe26aff\nVLECggEAenj0YmvnybT1/kkTP4eys5bbBxaIA1Tb+HPL5OcgUMTF4tRXKfk3cI2W\nfKcmoOdGnvC8NL5FKSe6JRB8QmzrxiStgvDOZb0cL4UkUw2MHJthkOXPNsIJUVAc\nAAwsrUfJvNP6lWSpcrsi4tbo8aTID+ZHzFmVWst9urxkolI9gAVBMPorX/8OVPmL\n3nIUVMJhL9nIHlAUVEMXTDvygbT/pdRPLO9IdMDkNYSYpE4GUN5gmWEIo1wPMnB6\n25ry4acPP9GnD2SNhL2bOfNiEqqrtnPKZRSWgLI220V7BimIE9Vq/cGkvOlhqUX5\nb4O58E4g/r0nGSYFpU1lqdDFUBSSqg==");
// decrypt the text using the private key
PrivateKey privateKey =
KeyFactory.getInstance("RSA").generatePrivate(new java.security.spec.PKCS8EncodedKeySpec(keyBytes));
final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] input = DatatypeConverter.parseBase64Binary(encryptedIrodsSession);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayInputStream inStream = new ByteArrayInputStream(input);
CipherInputStream cipherInputStream = new CipherInputStream(inStream, cipher);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = cipherInputStream.read(buf)) >= 0) {
outputStream.write(buf, 0, bytesRead);
}
irodsSession = outputStream.toByteArray();
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(irodsSession);
}
private void submitDownloadWorkflow(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
try {
User u = PortalUtil.getUser(resourceRequest);
String userSN = u.getScreenName();
String userId = u.getUserId()+"";
String workflowId = ParamUtil.getString(resourceRequest, "workflowId");
String ownerId = ParamUtil.getString(resourceRequest, "ownerId");
System.out.println(workflowId + " / " + ownerId);
JSONObject config = new JSONObject(resourceRequest.getParameterValues("config")[0]);
config.put("user_name", userSN);
config.put("user_id", userId);
System.out.println(config);
String runId = config.getString("runId");
String submitMessage = "Download workflow for " + config.getString("simulationRunId");
String importedWfId = importWorkflow(userId, ownerId, workflowId, runId);
File solverFile = FileUtil.createTempFile();
FileUtil.write(solverFile, config.toString());
// TODO check port numbers
asm_service.placeUploadedFile(userId, solverFile, importedWfId, "Job0", "2");
// stagein => Sync for final workflow
asm_service.placeUploadedFile(userId, solverFile, importedWfId, "sync", "0");
Vector<WorkflowConfigErrorBean> errorVector = checkCredentialErrors(userId, importedWfId);
if(errorVector!=null && !errorVector.isEmpty())
{
for (WorkflowConfigErrorBean err : errorVector) {
System.out.println("[ForwardModellingPortlet.submitSolver] Alert '"+err.getErrorID()+"'! JobName: " + err.getJobName() + " userSN: "+userSN+", runId: "+runId);
if(err.getErrorID().contains("noproxy") || err.getErrorID().contains("proxyexpired"))
{
catchError(null, resourceResponse, "401", "[ForwardModellingPortlet.submitSolver] Credential Error! Submission stoped");
return;
}
}
}
asm_service.submit(userId, importedWfId, submitMessage, "Never");
} catch (Exception e) {
e.printStackTrace();
}
}
private void submitProcessingWorkflow(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
try {
User u = PortalUtil.getUser(resourceRequest);
String userSN = u.getScreenName();
String userId = u.getUserId()+"";
String workflowId = ParamUtil.getString(resourceRequest, "workflowId");
String ownerId = ParamUtil.getString(resourceRequest, "ownerId");
System.out.println(workflowId + " / " + ownerId);
JSONObject stations = new JSONObject(resourceRequest.getParameterValues("stations")[0]);
JSONObject pes = new JSONObject(resourceRequest.getParameterValues("PEs")[0]);
System.out.println(stations);
System.out.println(pes);
// String runId = config.getString("runId");
// String submitMessage = "Download workflow for " + config.getString("simulationRunId");
// String importedWfId = importWorkflow(userId, ownerId, workflowId, runId);
// File solverFile = FileUtil.createTempFile();
// FileUtil.write(solverFile, config.toString());
// // TODO check port numbers
// asm_service.placeUploadedFile(userId, solverFile, importedWfId, "Job0", "2");
// // stagein => Sync for final workflow
// asm_service.placeUploadedFile(userId, solverFile, importedWfId, "sync", "0");
// Vector<WorkflowConfigErrorBean> errorVector = checkCredentialErrors(userId, importedWfId);
// if(errorVector!=null && !errorVector.isEmpty())
// for (WorkflowConfigErrorBean err : errorVector) {
// System.out.println("[ForwardModellingPortlet.submitSolver] Alert '"+err.getErrorID()+"'! JobName: " + err.getJobName() + " userSN: "+userSN+", runId: "+runId);
// if(err.getErrorID().contains("noproxy") || err.getErrorID().contains("proxyexpired"))
// catchError(null, resourceResponse, "401", "[ForwardModellingPortlet.submitSolver] Credential Error! Submission stoped");
// return;
// asm_service.submit(userId, importedWfId, submitMessage, "Never");
} catch (Exception e) {
e.printStackTrace();
}
}
private Vector<WorkflowConfigErrorBean> checkCredentialErrors(String userId, String importedWfId) throws Exception {
WorkflowData wfData = PortalCacheService.getInstance().getUser(userId).getWorkflow(importedWfId);
ResourceConfigurationFace rc=(ResourceConfigurationFace)InformationBase.getI().getServiceClient("resourceconfigure", "portal");
List resources = rc.get();
Vector<WorkflowConfigErrorBean> errorVector = (Vector<WorkflowConfigErrorBean>)RealWorkflowUtils.getInstance().getWorkflowConfigErrorVector(resources, userId, wfData);
if(errorVector!=null && !errorVector.isEmpty()) {
return errorVector;
}
return null;
}
private void submitSimulationWorkflow(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException, IOException
{
try {
asm_service = ASMService.getInstance();
User u = PortalUtil.getUser(resourceRequest);
String userSN = u.getScreenName();
String userId = u.getUserId()+"";
String solverType = ParamUtil.getString(resourceRequest, "solver");
String[] jsonContentArray = resourceRequest.getParameterValues("jsonObject");
String workflowId = ParamUtil.getString(resourceRequest, "workflowId");
String workflowName = ParamUtil.getString(resourceRequest, "workflowName");
String ownerId = ParamUtil.getString(resourceRequest, "ownerId");
String stationUrl = ParamUtil.getString(resourceRequest, "stationUrl");
String eventUrl = ParamUtil.getString(resourceRequest, "eventUrl");
String[] runIds = resourceRequest.getParameterValues("runId");
String stFileType = ParamUtil.getString(resourceRequest, "stationType");
String jobName = "Job0";
String submitMessage = ParamUtil.getString(resourceRequest, "submitMessage");
String nProc = ParamUtil.getString(resourceRequest, "nProc");
boolean eventDLFile = eventUrl.contains("documents");
boolean stationDLFile = stationUrl.contains("documents");
File stationFile = null;
File eventFile = null;
String stPublicPath;
String evPublicPath;
long groupId = PortalUtil.getScopeGroupId(resourceRequest);
long repositoryId = DLFolderConstants.getDataRepositoryId(groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(groupId);
Format formatter = new SimpleDateFormat("yyyyMMddHHmm");
String portalUrl = PortalUtil.getPortalURL(resourceRequest);
String currentURL = PortalUtil.getCurrentURL(resourceRequest);
String portal = currentURL.substring(0, currentURL.substring(1).indexOf("/")+1);
portalUrl += portal;
String portalUrl2 = PortalUtil.getPortalURL(resourceRequest);
if(portalUrl2.equals("http://localhost:8081")) {
portalUrl2 = "http://localhost:8080"; //TODO: careful
}
// System.out.println("Try to fetch workflow zip from repository for workflow with ID: " + workflowId);
String job0bin = "";
Date job0binModified = new Date(0L);
// Hashtable hsh = new Hashtable();
// ServiceType st = InformationBase.getI().getService("wfs", "portal", hsh, new Vector());
// PortalWfsClient wfsClient = (PortalWfsClient) Class.forName(st.getClientObject()).newInstance();
// wfsClient.setServiceURL(st.getServiceUrl());
// wfsClient.setServiceID(st.getServiceID());
// RepositoryWorkflowBean bean = new RepositoryWorkflowBean();
// bean.setId(Long.parseLong(workflowId));
// bean.setWorkflowType(RepositoryItemTypeConstants.Application);
// Vector wfList = wfsClient.getRepositoryItems(bean);
// if (wfList == null) {
// throw new Exception("Not valid wf list !");
// for (Object wfBeanObject : wfList) {
// RepositoryWorkflowBean wfBean = (RepositoryWorkflowBean) wfBeanObject;
// String relativePath = wfBean.getZipRepositoryPath();
// String fullPath = new String(RepositoryFileUtils.getInstance().getRepositoryDir() + relativePath);
// ZipFile zipFile = new ZipFile(fullPath);
// Enumeration<? extends ZipEntry> entries = zipFile.entries();
// while (entries.hasMoreElements()) {
// ZipEntry entry = (ZipEntry) entries.nextElement();
// System.out.println(entry.getName());
// if (entry.getName().indexOf("Job0/execute.bin") >= 0) {
// job0bin = inputStreamToString(zipFile.getInputStream(entry));
// job0binModified = new Date(entry.getTime());
// // System.out.println(job0bin);
// break;
// zipFile.close();
if(!stationDLFile) //1a. create StationFile and store it
{
stationFile = FileUtil.createTempFile();
URL wsUrl = new URL(portalUrl2+stationUrl);
FileUtil.write(stationFile, wsUrl.openStream());
String stFileName = "stations_"+runIds[0];
stPublicPath = addFileToDL(stationFile, stFileName, groupId, userSN, Constants.WS_TYPE);
stPublicPath = portalUrl + stPublicPath;
System.out.println("[ForwardModellingPortlet.submitSolver] Stations file created in the document library by "+userSN+", accessible in: "+stPublicPath);
stFileType = Constants.STXML_TYPE;
}
else //1b. Retrieve StationFile
{
String[] urlParts = stationUrl.split("/");
long folderId = Long.parseLong(urlParts[urlParts.length - 2]);
String stFileName = urlParts[urlParts.length - 1];
FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, stFileName);
stationFile = DLFileEntryLocalServiceUtil.getFile(fileEntry.getUserId(), fileEntry.getFileEntryId(), fileEntry.getVersion(), false);
stPublicPath = stationUrl;
}
if(!eventDLFile) //2a. create EventFile and store it
{
eventFile = FileUtil.createTempFile();
URL wsUrl = new URL(portalUrl2+eventUrl);
FileUtil.write(eventFile, wsUrl.openStream());
String evFileName = "events_"+runIds[0];
evPublicPath = addFileToDL(eventFile, evFileName, groupId, userSN, Constants.WS_TYPE);
evPublicPath = portalUrl + evPublicPath;
System.out.println("[ForwardModellingPortlet.submitSolver] Events file created in the document library by "+userSN+", accessible in: "+evPublicPath);
}
else //2b. Retrieve EventFile
{
String[] urlParts = eventUrl.split("/");
long folderId = Long.parseLong(urlParts[urlParts.length - 2]);
String evFileName = urlParts[urlParts.length - 1];
FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, evFileName);
eventFile = DLFileEntryLocalServiceUtil.getFile(fileEntry.getUserId(), fileEntry.getFileEntryId(), fileEntry.getVersion(), false);
evPublicPath = eventUrl;
}
//3. Generate zip file
String zipName = runIds[0]+".zip";
createZipFile("temp/"+zipName);
File tempZipFile = new File("temp/"+zipName);
String zipPublicPath = addFileToDL(tempZipFile, zipName, groupId, userSN, Constants.ZIP_TYPE);
zipPublicPath = portalUrl + zipPublicPath;
System.out.println("[ForwardModellingPortlet.submitSolver] Zip file created in the document library by "+userSN+", accessible in: "+zipPublicPath);
for(int i=0;i<jsonContentArray.length;i++)
{
String jsonContent = jsonContentArray[i];
//4. Import the workflow
String importedWfId = importWorkflow(userId, ownerId, workflowId, runIds[i]);
//5. Create the solver file and store it
File solverFile = FileUtil.createTempFile();
FileUtil.write(solverFile, jsonContent);
String fileName = solverType+"_"+runIds[i]+".json";
String publicPath = addFileToDL(solverFile, fileName, groupId, userSN, Constants.SOLVER_TYPE);
publicPath = portalUrl + publicPath;
System.out.println("[ForwardModellingPortlet.submitSolver] Solver file created in the document library by "+userSN+", accessible in: "+publicPath);
//6. Upload files
asm_service.placeUploadedFile(userId, stationFile, importedWfId, jobName, "0");
asm_service.placeUploadedFile(userId, eventFile, importedWfId, jobName, "1");
asm_service.placeUploadedFile(userId, solverFile, importedWfId, jobName, "2");
asm_service.placeUploadedFile(userId, tempZipFile, importedWfId, jobName, "3");
try {
asm_service.placeUploadedFile(userId, solverFile, importedWfId, "sync", "0");
} catch (Upload_GeneralException exception) {
System.out.println("*** Port 0 on job Sync doesn't exist.");
}
//8. Change number of MPI nodes
if(solverType.toLowerCase().contains(Constants.SPECFEM_TYPE))
{
System.out.println("[ForwardModellingPortlet.submitSolver] Set number of processors to "+nProc+", by "+userSN);
asm_service.setJobAttribute(userId, importedWfId, jobName, "gt5.keycount", nProc);
}
//TODO: we should check just once
Vector<WorkflowConfigErrorBean> errorVector = checkCredentialErrors(userId, importedWfId);
if(errorVector!=null && !errorVector.isEmpty())
{
for (WorkflowConfigErrorBean er : errorVector) {
System.out.println("[ForwardModellingPortlet.submitSolver] Alert '"+er.getErrorID()+"'! userSN: "+userSN+", runId: "+runIds[i]);
if(er.getErrorID().contains("noproxy") || er.getErrorID().contains("proxyexpired"))
{
catchError(null, resourceResponse, "401", "[ForwardModellingPortlet.submitSolver] Credential Error! Submission stoped");
return;
}
}
}
asm_service.submit(userId, importedWfId, submitMessage, "Never");
// Log resource information
ASMResourceBean resourceBean = asm_service.getResource(userId, importedWfId, jobName);
System.out.println("RESOURCE type: " + resourceBean.getType() + ", grid: " + resourceBean.getGrid() + ", resource: " + resourceBean.getResource() + ", queue: " + resourceBean.getQueue());
//10. Add run info in the Provenance Repository
saveSimulationProvenance(userSN, runIds[i], submitMessage, workflowName, workflowId, importedWfId, stPublicPath, evPublicPath, publicPath, zipPublicPath, stFileType, job0bin, job0binModified, resourceBean.getType(), resourceBean.getGrid(), resourceBean.getResource(), resourceBean.getQueue());
System.out.println("[ForwardModellingPortlet.submitSolver] Submission finished: "+userSN+", "+runIds[i]+", "+submitMessage+", "+workflowId+", "+importedWfId);
}
tempZipFile.delete();
}
catch (Exception e)
{
catchError(e, resourceResponse, "500", "[ForwardModellingPortlet.submitSolver] Exception catched!");
}
}
public void downloadOutput(ResourceRequest resourceRequest,
ResourceResponse resourceResponse)
{
asm_service = ASMService.getInstance();
String userId = resourceRequest.getRemoteUser();
String wfId = ParamUtil.getString(resourceRequest, "workflowId");
resourceResponse.setContentType("application/zip");
resourceResponse.setProperty("Content-Disposition", "attachment; filename=\"logs.zip\"");
try{
asm_service.getWorkflowOutputs(userId, wfId, resourceResponse);
}
catch(Exception e)
{
System.out.println("[ForwardModellingPortlet.downloadOutput] Exception caught!!");
e.printStackTrace();
// TODO send error to client
}
}
private void meshVelocityModelUpload(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
try {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(resourceRequest);
String meshURL = uploadRequest.getParameter("mesh-link");
if (uploadRequest.getFileName("mesh-file") != null && uploadRequest.getFileName("mesh-file").length() > 0) {
meshURL = saveFileUpload(resourceRequest, uploadRequest.getFileAsStream("mesh-file"), uploadRequest.getFileName("mesh-file"), "mesh");
}
System.out.println(meshURL);
if (meshURL == null || meshURL.equals("")) {
resourceResponse.getWriter().write("{ success: false, errors: { \"mesh-file\": \"No mesh file or URL included or included file too large.\" } }");
return;
}
String velocityModelURL = uploadRequest.getParameter("velocity-model-link");
if (uploadRequest.getFileName("velocity-model-file") != null && uploadRequest.getFileName("velocity-model-file").length() > 0) {
velocityModelURL = saveFileUpload(resourceRequest, uploadRequest.getFileAsStream("velocity-model-file"), uploadRequest.getFileName("velocity-model-file"), "velocitymodel");
}
System.out.println(velocityModelURL);
if (velocityModelURL == null || velocityModelURL.equals("")) {
resourceResponse.getWriter().write("{ success: false, errors: { \"velocity-model-file\": \"No velocity model file or URL included or included file too large.\" } }");
return;
}
String minLat = uploadRequest.getParameter("min_lat");
String maxLat = uploadRequest.getParameter("max_lat");
String minLon = uploadRequest.getParameter("min_lon");
String maxLon = uploadRequest.getParameter("max_lon");
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", "25");
Session session = Session.getInstance(props);
try {
Message message = new MimeMessage(session);
message.setFrom(InternetAddress.parse("admin@verce.eu")[0]);
// message.setReplyTo(InternetAddress.parse(PortalUtil.getUser(resourceRequest).getDisplayEmailAddress()));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("spinuso@knmi.nl, emanuele.casarotti@ingv.it, federica.magnoni@ingv.it, " + PortalUtil.getUser(resourceRequest).getDisplayEmailAddress()));
message.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse("jonas.matser@knmi.nl"));
message.setSubject("VERCE: Mesh and velocity model submitted");
message.setText(
"User " + PortalUtil.getUser(resourceRequest).getScreenName() + " has submitted a new mesh and velocity model for review.\n" +
"\n" +
"The mesh and velocity model are available at the following links.\n" +
"Mesh: " + meshURL + "\n" +
"Velocity Model: " + velocityModelURL + "\n" +
"\n" +
"The bounds for the mesh are:\n" +
"Minimum latitude: " + minLat + "\n" +
"Maximum latitude: " + maxLat + "\n" +
"Minimum longitude: " + minLon + "\n" +
"Maximum longitude: " + maxLon + "\n" +
"\n" +
"The user also added the following note:\n" +
HtmlUtil.escape(uploadRequest.getParameter("note"))
);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
resourceResponse.getWriter().write("{ success: true }");
} catch (Exception e) {
System.out.println(e);
catchError(e, resourceResponse, "500", e.getMessage());
}
}
private void uploadFile(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
{
resourceResponse.setContentType("text/html");
try {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(resourceRequest);
InputStream inputStream = uploadRequest.getFileAsStream("form-file");
if(inputStream == null){
throw new Exception("[ForwardModellingPortlet.uploadFile] ERROR: FileInput \"form-file\" not found in request.");
}
String name = ParamUtil.getString(uploadRequest, "name");
String filetype = ParamUtil.getString(uploadRequest, "filetype");
String publicPath = saveFileUpload(resourceRequest, inputStream, name, filetype);
String successString = " {'success':'true', 'path':'"+publicPath+"'}";
resourceResponse.getWriter().write(successString);
} catch (Exception e) {
catchError(e, resourceResponse, "500", e.getMessage());
}
}
private String saveFileUpload(ResourceRequest resourceRequest, InputStream inputStream, String name, String filetype)
throws Exception
{
if(PortalUtil.getUser(resourceRequest)==null)
throw new Exception("[ForwardModellingPortlet.uploadFile] No user logged in!");
String userSN = PortalUtil.getUser(resourceRequest).getScreenName();
long groupId = PortalUtil.getScopeGroupId(resourceRequest);
File file = FileUtil.createTempFile(inputStream);
if (file.length() < 1)
{
throw new Exception("[ForwardModellingPortlet.uploadFile] Failed!! The file is empty. User: "+userSN);
}
String publicPath = addFileToDL(file, name, groupId, userSN, filetype);
String portalUrl = PortalUtil.getPortalURL(resourceRequest);
String currentURL = PortalUtil.getCurrentURL(resourceRequest);
String portal = currentURL.substring(0, currentURL.substring(1).indexOf("/")+1);
portalUrl += portal;
publicPath = portalUrl+publicPath;
System.out.println("[ForwardModellingPortlet.uploadFile] File created in the document library by user "+userSN+", accessible in: "+publicPath);
return publicPath;
}
private String inputStreamToString(InputStream inputStream) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
StringBuilder stringBuilder = new StringBuilder();
char[] buffer = new char[1024];
int charsRead = 0;
while ((charsRead = inputStreamReader.read(buffer)) > 0) {
stringBuilder.append(buffer, 0, charsRead);
};
inputStream.close();
return stringBuilder.toString();
}
private void downloadMeshDetails(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
try {
String solverName = ParamUtil.getString(resourceRequest, "solver");
String meshName = ParamUtil.getString(resourceRequest, "meshName");
URL url = new URL("http://localhost:8080/j2ep-1.0/prov/solver/" + solverName);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
if(con.getResponseCode()!=200) {
System.out.println("[ForwardModellingPortlet.downloadMeshDetails] Error: " + con.getResponseCode());
return;
}
String input = inputStreamToString(con.getInputStream());
JSONObject jsonObject = new JSONObject(input);
JSONArray meshes = jsonObject.getJSONArray("meshes");
JSONObject mesh = null;
for (int ii = 0; ii < meshes.length(); ii++) {
mesh = meshes.getJSONObject(ii);
if (mesh.getString("name").equals(meshName)) {
break;
}
}
if (mesh == null) {
System.out.println("[ForwardModellingPortlet.downloadMeshDetails] Error: Mesh " + meshName + " not found for solver " + solverName);
return;
}
String details = mesh.getString("details");
resourceResponse.setContentType("application/text");
resourceResponse.setProperty("Content-Disposition", "attachment; filename=\"mesh-details.txt\"");
resourceResponse.getWriter().write(details);
} catch (Exception e) {
System.out.println("[ForwardModellingPortlet.downloadMeshDetails] Error: " + e.getStackTrace());
}
}
private void downloadVelocityModelDetails(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
try {
String solverName = ParamUtil.getString(resourceRequest, "solver");
String meshName = ParamUtil.getString(resourceRequest, "meshName");
String velocityModelName = ParamUtil.getString(resourceRequest, "velocityModelName");
URL url = new URL("http://localhost:8080/j2ep-1.0/prov/solver/" + solverName);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
if(con.getResponseCode()!=200)
System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: " + con.getResponseCode());
InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream());
StringBuilder stringBuilder = new StringBuilder();
char[] buffer = new char[1024];
int charsRead = 0;
while ((charsRead = inputStreamReader.read(buffer)) > 0) {
stringBuilder.append(buffer, 0, charsRead);
};
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
JSONArray meshes = jsonObject.getJSONArray("meshes");
JSONObject mesh = null;
for (int ii = 0; ii < meshes.length(); ii++) {
mesh = meshes.getJSONObject(ii);
if (mesh.getString("name").equals(meshName)) {
break;
}
}
if (mesh == null) {
System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: Mesh " + meshName + " not found for solver " + solverName);
return;
}
JSONArray velocityModels = mesh.getJSONArray("velmod");
JSONObject velocityModel = null;
for (int ii = 0; ii < velocityModels.length(); ii++) {
velocityModel = velocityModels.getJSONObject(ii);
if (velocityModel.getString("name").equals(velocityModelName)) {
break;
}
}
if (velocityModel == null) {
System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: Velocity Model " + velocityModelName + " not found for Mesh " + meshName + " and solver " + solverName);
return;
}
String details = velocityModel.getString("details");
resourceResponse.setContentType("application/text");
resourceResponse.setProperty("Content-Disposition", "attachment; filename=\"velocitymodel-details.txt\"");
resourceResponse.getWriter().write(details);
} catch (Exception e) {
System.out.println("[ForwardModellingPortlet.downloadVelocityModelDetails] Error: " + e.getStackTrace());
}
}
private String addFileToDL(File file, String name, long groupId, String userSN, String filetype)
throws SystemException, PortalException, Exception
{
long repositoryId = DLFolderConstants.getDataRepositoryId(groupId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
String sourceFileName = file.getName();
String mimeType = "text/plain";
String description = Constants.DOC_DESC + userSN;
String changeLog = "1.0";
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(groupId);
long folderId = getFolderId(repositoryId, userSN, filetype, serviceContext);
// Search for unused file number
// Don't use recursion because of stack limit (although the algorithm shouldn't run that deep)
// Two step algorithm
// 1. Find the first n (2^m) that is not in use be an existing file
// 2. Do a binary search between 2^(m-1) and 2^m for the first non-existing filename
// Define lower and upper bounds for searching
int lowerBound = 0;
int upperBound = 0;
// define midpoint for binary search part
int mid = 0;
// keep track of if we're search upwards or in binary search
boolean up = true;
String filename = name;
do {
try {
if (up) {
filename = name + (upperBound > 0 ? "_"+upperBound : "");
} else {
filename = name + (mid > 0 ? "_"+mid : "");
}
// try if file exists
DLAppServiceUtil.getFileEntry(repositoryId, folderId, filename);
} catch (PortalException e) {
// File doesnt Exist
if (up) {
// lowest n = 2^m found that's not in use
// start binary search
up = false;
continue;
} else {
// continue binary search in [lowerbound-mid]
upperBound = mid;
mid = lowerBound + (upperBound - lowerBound) / 2;
continue;
}
}
// File exists
if (up) {
// look at next n = 2^m if it's in use
lowerBound = Math.max(upperBound, 1);
upperBound = lowerBound * 2;
} else {
// continue binary search in [mid+1-lowerbound]
lowerBound = mid + 1;
mid = lowerBound + (upperBound - lowerBound) / 2;
}
} while (lowerBound != upperBound);
// set final filename
filename = name + (lowerBound > 0 ? "_"+lowerBound : "");
DLAppServiceUtil.addFileEntry(repositoryId, folderId, sourceFileName, mimeType, filename, description, changeLog, file, serviceContext);
System.out.println("[ForwardModellingPortlet.addFileToDL] The file "+filename+" has been created.");
return "/documents/" + groupId + "/" + folderId + "/" + HttpUtil.encodeURL(HtmlUtil.unescape(filename));
}
/*
* get the folderId for the specific user following the directory structure:
* root/Forwar Modelling/userSN/station (XML)
* if it doesn't exist it is created
*/
private long getFolderId(long repositoryId, String userSN, String filetype, ServiceContext serviceContext) throws SystemException, PortalException
{
Folder folder = null;
String lastFolderName = "";
if(filetype.equals(Constants.EVENT_TYPE)) lastFolderName = Constants.EVENT_FOLDER_NAME;
if(filetype.equals(Constants.STXML_TYPE)) lastFolderName = Constants.STXML_FOLDER_NAME;
if(filetype.equals(Constants.STPOINTS_TYPE)) lastFolderName = Constants.STPOINTS_FOLDER_NAME;
if(filetype.equals(Constants.SOLVER_TYPE)) lastFolderName = Constants.SOLVER_FOLDER_NAME;
if(filetype.equals(Constants.WS_TYPE)) lastFolderName = Constants.WS_FOLDER_NAME;
if(lastFolderName.equals("")) lastFolderName = filetype;
try{
folder = DLAppServiceUtil.getFolder(repositoryId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, Constants.BASE_FOLDER_NAME);
} catch (PortalException pe) {
folder = DLAppServiceUtil.addFolder(repositoryId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, Constants.BASE_FOLDER_NAME, Constants.BASE_FOLDER_DESC, serviceContext);
}
try{
folder = DLAppServiceUtil.getFolder(repositoryId, folder.getFolderId(), userSN);
} catch (PortalException pe) {
folder = DLAppServiceUtil.addFolder(repositoryId, folder.getFolderId(), userSN, Constants.USER_FOLDER_DESC, serviceContext);
}
try{
folder = DLAppServiceUtil.getFolder(repositoryId, folder.getFolderId(), lastFolderName);
} catch (PortalException pe) {
folder = DLAppServiceUtil.addFolder(repositoryId, folder.getFolderId(), lastFolderName, "", serviceContext);
}
return folder.getFolderId();
}
private String getFileAsString(File file) throws FileNotFoundException, IOException{
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
StringBuffer sb = new StringBuffer();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
sb.append(dis.readLine() + "\n");
}
fis.close();
bis.close();
dis.close();
return sb.toString();
}
private static final byte[] BUFFER = new byte[4096 * 1024];
private static void copy(InputStream input, OutputStream output) throws IOException
{
int bytesRead;
while ((bytesRead = input.read(BUFFER))!= -1) {
output.write(BUFFER, 0, bytesRead);
}
}
private void createZipFile(String fileName) throws IOException
{
ZipFile zipFile = new ZipFile("data/verce-hpc-pe.zip");
ZipOutputStream append = new ZipOutputStream(new FileOutputStream(fileName));
// copy contents from existing war
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
append.putNextEntry(e);
if (!e.isDirectory()) {
copy(zipFile.getInputStream(e), append);
}
append.closeEntry();
}
// close
zipFile.close();
append.close();
System.out.println("[ForwardModellingPortlet.createZipFile] File created in the server file system: "+fileName);
}
private void createMeshModelZipFile(String fileName, String meshFileName, String modelFileName) throws IOException
{
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName));
zos.putNextEntry(new ZipEntry("meshfile"));
copy(new FileInputStream(meshFileName), zos);
zos.closeEntry();
zos.putNextEntry(new ZipEntry("modelfile"));
copy(new FileInputStream(modelFileName), zos);
zos.closeEntry();
zos.close();
}
private void saveSimulationProvenance(String userSN, String runId, String submitMessage, String wfName, String wfId, String asmRunId,
String stationUrl, String eventUrl, String solverUrl, String zipUrl, String stationFileType, String job0bin, Date job0binModified, String resourceType, String grid, String resource, String queue) {
String runType = "workflow_run";
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
if(stationFileType.equals(Constants.STPOINTS_TYPE)) stationFileType = Constants.MIMETYPE_PLAIN;
if(stationFileType.equals(Constants.STXML_TYPE)) stationFileType = Constants.MIMETYPE_XML;
JSONObject params = new JSONObject();
params.put("username", userSN)
.put("_id", runId)
.put("type", runType)
.put("prov:type", "simulation")
.put("description", submitMessage)
.put("workflowName", wfName)
.put("workflowId", wfId)
.put("system_id", asmRunId)
.put("startTime", nowAsISO)
.put("job0bin", job0bin)
.put("job0binModified", new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ").format(job0binModified))
.put("resourceType", resourceType)
.put("grid", grid)
.put("resource", resource)
.put("queue", queue);
JSONArray input = new JSONArray();
input.put(new JSONObject().put("mime-type", stationFileType).put("name",Constants.ST_INPUT_NAME).put("url", stationUrl))
.put(new JSONObject().put("mime-type", Constants.MIMETYPE_XML).put("name",Constants.EVENT_INPUT_NAME).put("url", eventUrl))
.put(new JSONObject().put("mime-type", Constants.MIMETYPE_JSON).put("name",Constants.SOLVER_INPUT_NAME).put("url", solverUrl))
.put(new JSONObject().put("mime-type", Constants.MIMETYPE_ZIP).put("name",Constants.ZIP_INPUT_NAME).put("url", zipUrl));
params.put("input", input);
updateProvenanceRepository(params);
}
private void updateProvenanceRepository(JSONObject params) {
try{
//TODO: put the url in a properties file
URL url = new URL("http://localhost:8080/j2ep-1.0/prov/workflow/insert");
//HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
con.setRequestProperty("Accept", "application/json");
// System.out.println("[updateProvenanceRepository] Params: "+params.toString());
String urlParameters = "prov="+URLEncoder.encode(params.toString(), "ISO-8859-1");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
if(con.getResponseCode()!=200)
System.out.println("[ForwardModellingPortlet.updateProvenanceRepository] Error: " + con.getResponseCode());
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("[ForwardModellingPortlet.updateProvenanceRepository] Response: "+response.toString());
}
catch(Exception e)
{
// We log the exception but continue the normal flow
System.out.println("[ForwardModellingPortlet.updateProvenanceRepository] Exception catched!!");
e.printStackTrace();
}
}
private String importWorkflow(String userId, String ownerId, String repositoryEntryId, String importedWfName) throws Exception
{
try
{
//asm_service = ASMService.getInstance();
String wfName = asm_service.ImportWorkflow(userId, importedWfName, ownerId, RepositoryItemTypeConstants.Application, repositoryEntryId);
System.out.println("[ForwardModellingPortlet.importWorkflow] Workflow "+repositoryEntryId+"("+ownerId+") with name "+importedWfName+" imported by user "+userId);
return wfName;
}
catch (Exception e) {
System.out.println("[ForwardModellingPortlet.importWorkflow] Exception catched! Could not import workflow "+repositoryEntryId+" from "+ownerId+", with name "+importedWfName);
throw e;
}
}
/*
* Sends the error through the response. Writes logMessage through the logs
* if e is not null prints the stackTrace through the logs
*/
private void catchError(Exception e, ResourceResponse res, String errorCode, String logMessage)
{
res.setContentType("text/html");
System.out.println("[ForwardModellingPortlet.catchError] Preparing response...");
try{
res.getWriter().write("{success: false, msg:\""+logMessage+"\"}"); //Submit call expects json success parameter
}catch(Exception e2)
{
System.out.println("[ForwardModellingPortlet.catchError] Could not write in response...");
}
res.setProperty(res.HTTP_STATUS_CODE, errorCode); //Ajax call expects status code
System.out.println(logMessage);
if(e!=null) e.printStackTrace();
}
}
|
package org.safehaus.subutai.impl.container;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.safehaus.subutai.api.commandrunner.Command;
import org.safehaus.subutai.api.commandrunner.RequestBuilder;
import org.safehaus.subutai.api.container.ContainerManager;
import org.safehaus.subutai.api.lxcmanager.*;
import org.safehaus.subutai.api.manager.helper.*;
import org.safehaus.subutai.impl.strategy.PlacementStrategyFactory;
import org.safehaus.subutai.shared.protocol.Agent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ContainerManagerImpl extends ContainerManagerBase {
private static final Logger logger = LoggerFactory.getLogger(ContainerManager.class);
private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
// number sequences for template names used for new clone name generation
private ConcurrentMap<String, AtomicInteger> sequences;
public void init() {
sequences = new ConcurrentHashMap<>();
}
public void destroy() {
sequences.clear();
}
@Override
public Set<Agent> clone(String groupName, String templateName, int nodesCount, Collection<Agent> hosts, PlacementStrategyENUM... strategy) {
// restrict metrics to provided hosts only
Map<Agent, ServerMetric> metrics = lxcManager.getPhysicalServerMetrics();
Iterator<Agent> it = metrics.keySet().iterator();
while(it.hasNext()) {
if(!hosts.contains(it.next())) it.remove();
}
LxcPlacementStrategy st = PlacementStrategyFactory.create(nodesCount, strategy);
try {
st.calculatePlacement(metrics);
} catch(LxcCreateException ex) {
logger.error("Failed to calculate placement", ex);
return Collections.emptySet();
}
Map<Agent, Integer> slots = st.getPlacementDistribution();
// clone specified number of instances and store their names
List<String> cloneNames = new ArrayList<>();
for(Map.Entry<Agent, Integer> e : slots.entrySet()) {
for(int i = 0; i < e.getValue(); i++) {
String name = nextHostName(templateName);
boolean b = templateManager.clone(e.getKey().getHostname(),
templateName, name);
if(b) cloneNames.add(name);
}
}
// get agents by names
Set<Agent> clones = new HashSet<>();
for(String cloneName : cloneNames) {
Agent a = agentManager.getAgentByHostname(cloneName);
if(a != null) clones.add(a);
}
boolean saved = saveNodeGroup(groupName, templateName, clones, strategy);
if(!saved) logger.error("Failed to save node group info");
return clones;
}
@Override
public boolean attachAndExecute(Agent physicalHost, String cloneName, String cmd) {
return attachAndExecute(physicalHost, cloneName, cmd, 30, TimeUnit.SECONDS);
}
@Override
public boolean attachAndExecute(Agent physicalHost, String cloneName, String cmd, long t, TimeUnit unit) {
if(cmd == null || cmd.isEmpty()) return false;
// synopsis:
// lxc-attach {-n name} [-a arch] [-e] [-s namespaces] [-R] [--keep-env] [--clear-env] [-- command]
StringBuilder sb = new StringBuilder("lxc-attach -n ");
sb.append(cloneName).append(" -- ").append(cmd);
int timeout = (int)unit.toSeconds(t);
Command comm = commandRunner.createCommand(
new RequestBuilder(sb.toString()).withTimeout(timeout),
new HashSet<>(Arrays.asList(physicalHost)));
commandRunner.runCommand(comm);
return comm.hasSucceeded();
}
private String nextHostName(String templateName) {
AtomicInteger i = sequences.putIfAbsent(templateName, new AtomicInteger());
if(i == null) i = sequences.get(templateName);
while(true) {
String name = templateName + "-" + i.incrementAndGet();
Agent a = agentManager.getAgentByHostname(name);
if(a == null) return name;
}
}
private boolean saveNodeGroup(String name, String templateName, Set<Agent> agents,
PlacementStrategyENUM... strategy) {
String cql = "INSERT INTO node_group(name, info) VALUES(?, ?)";
EnvironmentNodeGroup group = new EnvironmentNodeGroup();
group.setTemplateUsed(templateName);
Set<EnvironmentGroupInstance> instances = new HashSet<>();
for(Agent a : agents) {
EnvironmentGroupInstance gi = new EnvironmentGroupInstance();
gi.setAgent(a);
gi.setName(a.getHostname());
gi.setPlacementStrategyENUM(strategy[0]); // TODO: first value used
instances.add(gi);
}
group.setEnvironmentGroupInstanceSet(instances);
return dbManager.executeUpdate(cql, name, gson.toJson(group));
}
}
|
package org.eclipse.birt.report.designer.data.ui.dataset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.aggregation.AggregationManager;
import org.eclipse.birt.data.engine.api.aggregation.IAggrFunction;
import org.eclipse.birt.data.engine.api.aggregation.IParameterDefn;
import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil;
import org.eclipse.birt.report.designer.data.ui.property.AbstractDescriptionPropertyPage;
import org.eclipse.birt.report.designer.data.ui.util.ControlProvider;
import org.eclipse.birt.report.designer.data.ui.util.DataSetExpressionProvider;
import org.eclipse.birt.report.designer.data.ui.util.DataSetProvider;
import org.eclipse.birt.report.designer.data.ui.util.DataUtil;
import org.eclipse.birt.report.designer.data.ui.util.Utility;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionBuilder;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.AggregationArgumentHandle;
import org.eclipse.birt.report.model.api.ColumnHintHandle;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.structures.AggregationArgument;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.core.Structure;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
/**
* TODO: Please document
*
* @version $Revision$ $Date$
*/
public class DataSetComputedColumnsPage extends AbstractDescriptionPropertyPage
{
protected transient PropertyHandle computedColumns = null;
protected transient PropertyHandleTableViewer viewer = null;
private static final int COLUMN_NAME_INDEX = 0;
private static final int DATA_TYPE_INDEX = 1;
private static final int EXPRESSION_INDEX = 2;
private static final int AGGREGATION_INDEX = 3;
// private static final int ARGUMENT_INDEX = 4;
private static final int FILTER_INDEX = 5;
protected static String[] cellLabels = new String[]{
Messages.getString( "dataset.editor.title.columnName" ),//$NON-NLS-1$
Messages.getString( "dataset.editor.title.dataType" ),//$NON-NLS-1$
Messages.getString( "dataset.editor.title.expression" ),//$NON-NLS-1$
Messages.getString( "dataset.editor.title.aggrFunc" ), //$NON-NLS-1$
Messages.getString( "dataset.editor.title.aggrArgu" ), //$NON-NLS-1$
Messages.getString( "dataset.editor.title.filter" ) //$NON-NLS-1$
};
protected static String[] cellProperties = new String[]{
ComputedColumn.NAME_MEMBER,
ComputedColumn.DATA_TYPE_MEMBER,
ComputedColumn.EXPRESSION_MEMBER,
ComputedColumn.AGGREGATEON_FUNCTION_MEMBER,
ComputedColumn.ARGUMENTS_MEMBER,
ComputedColumn.FILTER_MEMBER
};
protected static IChoice[] dataTypes = DEUtil.getMetaDataDictionary( )
.getStructure( ComputedColumn.COMPUTED_COLUMN_STRUCT )
.getMember( ComputedColumn.DATA_TYPE_MEMBER )
.getAllowedChoices( )
.getChoices( );
protected static String[] dialogLabels = new String[]{
Messages.getString( "dataset.editor.inputDialog.columnName" ),//$NON-NLS-1$
Messages.getString( "dataset.editor.inputDialog.dataType" ),//$NON-NLS-1$
Messages.getString( "dataset.editor.inputDialog.expression" ),//$NON-NLS-1$
Messages.getString( "dataset.editor.inputDialog.aggrFunc" ), //$NON-NLS-1$
Messages.getString( "dataset.editor.inputDialog.aggrArgu" ), //$NON-NLS-1$
Messages.getString( "dataset.editor.inputDialog.filter" ) //$NON-NLS-1$
};
protected AggregationManager aggregationManager;
public DataSetComputedColumnsPage( )
{
super( );
try
{
aggregationManager = DataUtil.getAggregationManager( ).getInstance( );
}
catch ( BirtException e )
{
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#createPageControl(org.eclipse.swt.widgets.Composite)
*/
public Control createContents( Composite parent )
{
computedColumns = ( (DataSetHandle) getContainer( ).getModel( ) ).getPropertyHandle( DataSetHandle.COMPUTED_COLUMNS_PROP );;
createTableViewer( parent );
addListeners( );
setToolTips( );
return viewer.getControl( );
}
protected void createTableViewer( Composite parent )
{
viewer = new PropertyHandleTableViewer( parent, true, true, true );
TableColumn column = new TableColumn( viewer.getViewer( ).getTable( ),
SWT.LEFT );
column.setText( cellLabels[COLUMN_NAME_INDEX] );
column.setWidth( 150 );
column = new TableColumn( viewer.getViewer( ).getTable( ), SWT.LEFT );
column.setText( cellLabels[DATA_TYPE_INDEX] );
column.setWidth( 200 );
column = new TableColumn( viewer.getViewer( ).getTable( ), SWT.LEFT );
column.setText( cellLabels[EXPRESSION_INDEX] );
column.setWidth( 200 );
column = new TableColumn( viewer.getViewer( ).getTable( ), SWT.LEFT );
column.setText( cellLabels[AGGREGATION_INDEX] );
column.setWidth( 200 );
column = new TableColumn( viewer.getViewer( ).getTable( ), SWT.LEFT );
column.setText( cellLabels[FILTER_INDEX] );
column.setWidth( 200 );
viewer.getViewer( )
.setContentProvider( new IStructuredContentProvider( ) {
public Object[] getElements( Object inputElement )
{
ArrayList computedColumnsList = new ArrayList( 10 );
Iterator iter = computedColumns.iterator( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
computedColumnsList.add( iter.next( ) );
}
}
return computedColumnsList.toArray( );
}
public void dispose( )
{
}
public void inputChanged( Viewer viewer, Object oldInput,
Object newInput )
{
}
} );
viewer.getViewer( ).setLabelProvider( new TableProvider( ) );
viewer.getViewer( ).setInput( computedColumns );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#pageActivated()
*/
public void pageActivated( )
{
refreshColumnNames( );
getContainer( ).setMessage( Messages.getString( "dataset.editor.computedColumns" ), //$NON-NLS-1$
IMessageProvider.NONE ); // $-NON-NLS-1
// //$NON-NLS-1$
setPageProperties( );
computedColumns = ( (DataSetHandle) getContainer( ).getModel( ) ).getPropertyHandle( DataSetHandle.COMPUTED_COLUMNS_PROP );;
viewer.getViewer( ).setInput( computedColumns );
viewer.getViewer( ).getTable( ).select( 0 );
}
/**
* Refresh columns meta data
*/
private void refreshColumnNames( )
{
( (DataSetEditor) this.getContainer( ) ).getCurrentItemModel( true,
true );
}
private void addListeners( )
{
viewer.getNewButton( ).addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
doNew( );
}
} );
viewer.getEditButton( ).addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
doEdit( );
}
} );
viewer.getViewer( ).getTable( ).addMouseListener( new MouseAdapter( ) {
public void mouseDoubleClick( MouseEvent e )
{
doEdit( );
}
} );
viewer.getViewer( ).getTable( ).addKeyListener( new KeyListener( ) {
public void keyPressed( KeyEvent e )
{
}
public void keyReleased( KeyEvent e )
{
if ( e.keyCode == SWT.DEL )
{
setPageProperties( );
}
}
} );
addRemoveListeners( );
viewer.getViewer( )
.addSelectionChangedListener( new ViewerSelectionListener( ) );
}
private void addRemoveListeners( )
{
viewer.getRemoveButton( )
.addSelectionListener( new SelectionListener( ) {
public void widgetSelected( SelectionEvent e )
{
setPageProperties( );
updateColumnsOfDataSetHandle( );
}
public void widgetDefaultSelected( SelectionEvent e )
{
}
} );
viewer.getRemoveMenuItem( )
.addSelectionListener( new SelectionListener( ) {
public void widgetSelected( SelectionEvent e )
{
setPageProperties( );
updateColumnsOfDataSetHandle( );
}
public void widgetDefaultSelected( SelectionEvent e )
{
}
} );
viewer.getRemoveAllMenuItem( )
.addSelectionListener( new SelectionListener( ) {
public void widgetSelected( SelectionEvent e )
{
setPageProperties( );
updateColumnsOfDataSetHandle( );
}
public void widgetDefaultSelected( SelectionEvent e )
{
widgetSelected( e );
}
} );
}
private void doNew( )
{
doEdit( new ComputedColumn( ) );
}
private void doEdit( )
{
int index = viewer.getViewer( ).getTable( ).getSelectionIndex( );
if ( index == -1 )
return;
ComputedColumnHandle handle = (ComputedColumnHandle) viewer.getViewer( )
.getTable( )
.getItem( index )
.getData( );
doEdit( handle );
}
protected void doEdit( Object structureOrHandle )
{
ComputedColumnInputDialog dlg = new ComputedColumnInputDialog( structureOrHandle );
if ( dlg.open( ) == Window.OK )
{
updateComputedColumn( structureOrHandle );
}
}
protected void updateComputedColumn( Object structureOrHandle )
{
if ( structureOrHandle instanceof ComputedColumn )
{
try
{
computedColumns.addItem( (ComputedColumn) structureOrHandle );
viewer.getViewer( ).refresh( );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
else
{
viewer.getViewer( ).update( structureOrHandle, null );
}
if ( validateAllComputedColumns( ) )
getContainer( ).setMessage( Messages.getString( "dataset.editor.computedColumns" ), //$NON-NLS-1$
IMessageProvider.NONE );
}
protected ComputedColumn getStructure( Object structureOrHandle )
{
ComputedColumn structure = null;
if ( structureOrHandle instanceof ComputedColumn )
{
structure = (ComputedColumn) structureOrHandle;
}
else
{
structure = (ComputedColumn) ( (ComputedColumnHandle) structureOrHandle ).getStructure( );
}
return structure;
}
protected final String getTypeName( String typeDisplayName )
{
for ( int i = 0; i < dataTypes.length; i++ )
{
if ( dataTypes[i].getDisplayName( ).equals( typeDisplayName ) )
return dataTypes[i].getName( );
}
return dataTypes[0].getName( );
}
protected final String getTypeDisplayName( String typeName )
{
for ( int i = 0; i < dataTypes.length; i++ )
{
if ( dataTypes[i].getName( ).equals( typeName ) )
{
return dataTypes[i].getDisplayName( );
}
}
return typeName;
}
private void setToolTips( )
{
viewer.getNewButton( )
.setToolTipText( Messages.getString( "DataSetComputedColumnsPage.toolTipText.New" ) );//$NON-NLS-1$
viewer.getEditButton( )
.setToolTipText( Messages.getString( "DataSetComputedColumnsPage.toolTipText.Edit" ) );//$NON-NLS-1$
viewer.getRemoveButton( )
.setToolTipText( Messages.getString( "DataSetComputedColumnsPage.toolTipText.Remove" ) );//$NON-NLS-1$
viewer.getUpButton( )
.setToolTipText( Messages.getString( "DataSetComputedColumnsPage.toolTipText.Up" ) );//$NON-NLS-1$
viewer.getDownButton( )
.setToolTipText( Messages.getString( "DataSetComputedColumnsPage.toolTipText.Down" ) );//$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.dialogs.properties.AbstractDescriptionPropertyPage#getPageDescription()
*/
public String getPageDescription( )
{
return Messages.getString( "DataSetComputedColumnsPage.description" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.dialogs.properties.AbstractPropertyPage#performOk()
*/
public boolean performOk( )
{
if ( validateAllComputedColumns( ) )
{
return super.performOk( );
}
return false;
}
private class TableProvider implements ITableLabelProvider
{
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java
* .lang.Object, int)
*/
public Image getColumnImage( Object element, int columnIndex )
{
return null;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.
* lang.Object, int)
*/
public String getColumnText( Object element, int columnIndex )
{
String value = null;
ComputedColumn computedColumn = getStructure( element );
try
{
switch ( columnIndex )
{
case 0 :
{
value = computedColumn.getName( );
break;
}
case 1 :
{
value = getTypeDisplayName( computedColumn.getDataType( ) );
break;
}
case 2 :
{
// fetch the first argument as the expression value for
// backward capability
ComputedColumnHandle handle = (ComputedColumnHandle) computedColumn.getHandle( computedColumns );
Iterator iterator = handle.argumentsIterator( );
if ( iterator.hasNext( ) )
{
AggregationArgumentHandle argHandle = (AggregationArgumentHandle) iterator.next( );
value = argHandle.getValue( );
}
if ( value == null )
{
value = computedColumn.getExpression( );
}
break;
}
case 3 :
{
value = computedColumn.getAggregateFunction( );
IAggrFunction aggrFunc = aggregationManager.getAggregation( value );
value = aggrFunc != null ? aggrFunc.getDisplayName( )
: value;
break;
}
case 4 :
{
value = computedColumn.getFilterExpression( );
break;
}
}
}
catch ( Exception e )
{
ExceptionHandler.handle( e );
}
return ( value == null ? "" : value ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse
* .jface.viewers.ILabelProviderListener)
*/
public void addListener( ILabelProviderListener listener )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
*/
public void dispose( )
{
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.viewers.IBaseLabelProvider#isLabelProperty(java
* .lang.Object, java.lang.String)
*/
public boolean isLabelProperty( Object element, String property )
{
return false;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.viewers.IBaseLabelProvider#removeListener(org.eclipse
* .jface.viewers.ILabelProviderListener)
*/
public void removeListener( ILabelProviderListener listener )
{
}
}
private class ViewerSelectionListener implements ISelectionChangedListener
{
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged( SelectionChangedEvent event )
{
setPageProperties( );
}
}
/**
* Depending on the Computed the properties of various controls on this page
* are set
*/
private void setPageProperties( )
{
viewer.updateButtons( );
validateAllComputedColumns( );
}
/**
* Update the computed columns after removing an established one and cache
* the updated DataSetViewData[]
*
*/
private void updateColumnsOfDataSetHandle( )
{
DataSetHandle dataSet = ( (DataSetEditor) getContainer( ) ).getHandle( );
DataSetViewData[] items = DataSetProvider.getCurrentInstance( )
.getColumns( dataSet, false, true, true );
int inexistence = 0;
for ( int i = 0; i < items.length; i++ )
{
boolean exist = false;
if ( items[i].isComputedColumn( ) )
{
Iterator iter = computedColumns.iterator( );
while ( iter.hasNext( ) )
{
ComputedColumn computedColumn = null;
Object obj = iter.next( );
if ( obj instanceof ComputedColumnHandle )
{
computedColumn = (ComputedColumn) ( (ComputedColumnHandle) obj ).getStructure( );
}
if ( items[i].getName( ).equals( computedColumn.getName( ) ) )
{
exist = true;
}
}
if ( !exist )
{
items[i] = null;
inexistence++;
}
}
}
if ( inexistence == 0 )
return;
DataSetViewData[] existItems = new DataSetViewData[items.length
- inexistence];
int index = 0;
for ( int i = 0; i < items.length; i++ )
{
if ( items[i] != null )
{
existItems[index] = items[i];
index++;
}
}
DataSetProvider.getCurrentInstance( )
.updateColumnsOfDataSetHandle( dataSet, existItems );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#getToolTip()
*/
public String getToolTip( )
{
return Messages.getString( "DataSetComputedColumnsPage.ComputedColumns.Tooltip" ); //$NON-NLS-1$
}
public boolean canLeave( )
{
return validateAllComputedColumns( );
}
/*
* Exam whether all registered computed columns are valid. Set the message
* of dialog as appropriated
*/
private boolean validateAllComputedColumns( )
{
if ( computedColumns != null )
{
Iterator iter = computedColumns.iterator( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
Object o = iter.next( );
ComputedColumn computedColumn = null;
if ( o instanceof ComputedColumnHandle )
{
computedColumn = (ComputedColumn) ( (ComputedColumnHandle) o ).getStructure( );
}
else
{
computedColumn = (ComputedColumn) o;
}
if ( !validateSingleColumn( computedColumn ) )
return false;
}
}
}
return true;
}
/*
* Exam whether one computed column is valid or not.
*/
private boolean validateSingleColumn( ComputedColumn computedColumn )
{
if ( computedColumn.getName( ) == null
|| computedColumn.getName( ).trim( ).length( ) == 0 )
{
getContainer( ).setMessage( Messages.getFormattedString( "dataset.editor.error.missingComputedColumnName", new Object[]{computedColumn.getName( )} ), IMessageProvider.ERROR ); //$NON-NLS-1$
return false;
}
// if ( computedColumn.getExpression( ) == null
// || computedColumn.getExpression( ).trim( ).length( ) == 0 )
// if ( isFunctionCount( computedColumn.getAggregateFunction( ) ) == false )
// getContainer( ).setMessage( Messages.getFormattedString( "dataset.editor.error.missingComputedColumnExpression", new Object[]{computedColumn.getName( )} ), IMessageProvider.ERROR ); //$NON-NLS-1$
// return false;
Iterator iter = ( (DataSetHandle) getContainer( ).getModel( ) ).getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP )
.iterator( );
while ( iter.hasNext( ) )
{
ColumnHintHandle hint = (ColumnHintHandle) iter.next( );
if ( computedColumn.getName( ).equals( hint.getAlias( ) ) )
{
getContainer( ).setMessage( Messages.getFormattedString( "dataset.editor.error.computedColumnNameAlreadyUsed", new Object[]{computedColumn.getName( )} ), IMessageProvider.ERROR ); //$NON-NLS-1$
return false;
}
}
return true;
}
protected class DummyParamDefn implements IParameterDefn
{
String name;
String displayName;
String description = "";//$NON-NLS-1$
boolean isDataField;
boolean isOptional;
/**
*
* @param name
* @param displayName
* @param isOptional
* @param isDataField
*/
public DummyParamDefn( String name, String displayName,
boolean isOptional, boolean isDataField )
{
this.name = name;
this.displayName = displayName;
this.isDataField = isDataField;
this.isOptional = isOptional;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.api.aggregation.IParameterDefn#getDescription()
*/
public String getDescription( )
{
return description;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.api.aggregation.IParameterDefn#getDisplayName()
*/
public String getDisplayName( )
{
return displayName;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.api.aggregation.IParameterDefn#isDataField()
*/
public boolean isDataField( )
{
return isDataField;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.api.aggregation.IParameterDefn#isOptional()
*/
public boolean isOptional( )
{
return isOptional;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.api.aggregation.IParameterDefn#supportDataType(int)
*/
public boolean supportDataType( int dataType )
{
return true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.api.aggregation.IParameterDefn#getName()
*/
public String getName( )
{
return name;
}
}
protected class ComputedColumnInputDialog extends PropertyHandleInputDialog
{
private static final String BLANK = "";//$NON-NLS-1$
private Text txtColumnName = null;
private Combo cmbDataType = null;
private Combo cmbAggregation = null;
private Label lblFilter = null;
private Text txtFilter = null;
private Button btnFilter = null;
private String columnName = null;
private Text[] txtParams = null; // parameter controls
private IAggrFunction[] functions = null;
private Composite parameterContainer;
private Composite composite;
private String lastExpression;
private Label firstLabel;
private int maxWidth;
/**
*
* @param structureOrHandle
*/
private ComputedColumnInputDialog( Object structureOrHandle )
{
super( structureOrHandle );
populateFunctions( );
}
private void populateFunctions( )
{
List aggrList = aggregationManager.getAggregations( AggregationManager.AGGR_TABULAR );
functions = new IAggrFunction[aggrList.size( )];
aggrList.toArray( functions );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.data.ui.dataset.PropertyHandleInputDialog#createCustomControls(org.eclipse.swt.widgets.Composite)
*/
protected void createCustomControls( Composite parent )
{
this.composite = parent;
createTextCell( parent, COLUMN_NAME_INDEX );
createComboBoxCell( parent, DATA_TYPE_INDEX );
createAggrListCell( parent, AGGREGATION_INDEX );
createParameterContainer( parent );
createFilterCell( parent, FILTER_INDEX );
handleAggrSelectEvent( getStructureOrHandle() instanceof Structure );
createSpaceForResize( parent );
}
/**
* @param parent
*/
private void createSpaceForResize( Composite parent )
{
Label space = ControlProvider.createLabel( parent, null );
space.setLayoutData( ControlProvider.getGridDataWithHSpan( 3 ) );
space = ControlProvider.createLabel( parent, null );
space.setLayoutData( ControlProvider.getGridDataWithHSpan( 3 ) );
space = ControlProvider.createLabel( parent, null );
space.setLayoutData( ControlProvider.getGridDataWithHSpan( 3 ) );
space = ControlProvider.createLabel( parent, null );
space.setLayoutData( ControlProvider.getGridDataWithHSpan( 3 ) );
}
/**
*
* @param parent
*/
private void createParameterContainer( Composite parent )
{
parameterContainer = new Composite( parent, SWT.NONE );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL );
gridData.horizontalIndent = 0;
gridData.horizontalSpan = 3;
gridData.exclude = true;
parameterContainer.setLayoutData( gridData );
GridLayout layout = new GridLayout( );
// layout.horizontalSpacing = layout.verticalSpacing = 0;
layout.marginWidth = layout.marginHeight = 0;
layout.numColumns = 3;
parameterContainer.setLayout( layout );
}
/**
*
* @param parent
* @param index
*/
private void createTextCell( Composite parent, final int index )
{
firstLabel = ControlProvider.createLabel( parent,
dialogLabels[index] );
this.maxWidth = computeMaxWidth( firstLabel );
txtColumnName = ControlProvider.createText( parent,
(String) getProperty( getStructureOrHandle( ),
cellProperties[index] ) );
txtColumnName.setLayoutData( ControlProvider.getGridDataWithHSpan( 2 ) );
columnName = txtColumnName.getText( );
txtColumnName.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
validateSyntax( );
}
} );
}
/**
*
* @param parent
* @param index
*/
private void createComboBoxCell( Composite parent, final int index )
{
Label label = ControlProvider.createLabel( parent,
dialogLabels[index] );
this.maxWidth = computeMaxWidth( label );
cmbDataType = ControlProvider.createCombo( parent, SWT.READ_ONLY );
cmbDataType.setLayoutData( ControlProvider.getGridDataWithHSpan( 2 ) );
populateDataTypeComboItems( );
cmbDataType.select( Utility.findIndex( cmbDataType.getItems( ),
getTypeDisplayName( (String) getProperty( getStructureOrHandle( ),
cellProperties[index] ) ) ) );
cmbDataType.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
validateSyntax( );
}
} );
}
private void populateDataTypeComboItems( )
{
Map<String, String> indexMap = new HashMap<String, String>( );
String[] dataTypeDisplayNames = new String[dataTypes.length];
for ( int i = 0; i < dataTypes.length; i++ )
{
dataTypeDisplayNames[i] = dataTypes[i].getDisplayName( );
indexMap.put( dataTypeDisplayNames[i], dataTypes[i].getName( ) );
}
Arrays.sort( dataTypeDisplayNames );
cmbDataType.setItems( dataTypeDisplayNames );
for ( int i = 0; i < dataTypeDisplayNames.length; i++ )
{
String name = (String) indexMap.get( dataTypeDisplayNames[i] );
cmbDataType.setData( name, new Integer( i ) );
}
}
/**
*
* @param parent
* @param index
*/
private void createAggrListCell( final Composite parent, final int index )
{
Label label = ControlProvider.createLabel( parent,
dialogLabels[index] );
this.maxWidth = computeMaxWidth( label );
cmbAggregation = ControlProvider.createCombo( parent, SWT.READ_ONLY );
cmbAggregation.setLayoutData( ControlProvider.getGridDataWithHSpan( 2 ) );
cmbAggregation.add( BLANK );
cmbAggregation.setData( BLANK, new Integer( 0 ) );
for ( int i = 0; i < functions.length; i++ )
{
cmbAggregation.add( functions[i].getDisplayName( ) );
cmbAggregation.setData( functions[i].getName( ), new Integer( i + 1 ) );
}
String aggrFuncName = (String) getProperty( getStructureOrHandle( ),
cellProperties[index] );
int selectionIndex = getAggrFuncIndex( aggrFuncName );
cmbAggregation.select( selectionIndex );
cmbAggregation.setToolTipText( selectionIndex > 0
? functions[selectionIndex - 1].getDescription( ) : BLANK );
cmbAggregation.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
handleAggrSelectEvent( true );
validateSyntax( );
updateFilterUIStatus( );
}
}
);
}
private int computeMaxWidth( Label label )
{
int widthHint = label.computeSize( -1, -1 ).x
- label.getBorderWidth( );
return widthHint > this.maxWidth ? widthHint : this.maxWidth;
}
private void handleAggrSelectEvent( boolean resetDataType )
{
disposeOldParameterUI( );
IAggrFunction function = getSelectedFunction( );
IParameterDefn[] params = null;
if ( function != null )
{
params = function.getParameterDefn( );
}
else
{
params = new IParameterDefn[]{
new DummyParamDefn( cellLabels[EXPRESSION_INDEX],
dialogLabels[EXPRESSION_INDEX],
false,
true )
};
}
if ( params.length > 0 )
{
showParameterUISection( );
createParameterUISection( params );
}
else
{
hideParameterUISection( );
}
if( resetDataType )
updateDataTypeCombo( );
parameterContainer.layout( );
composite.layout( );
}
/**
* @param params
*/
private void createParameterUISection( IParameterDefn[] params )
{
txtParams = new Text[params.length];
for ( int i = 0; i < params.length; i++ )
{
IParameterDefn param = params[i];
Label paramLabel = new Label( parameterContainer, SWT.NONE
| SWT.WRAP );
paramLabel.setText( Utility.getNonNullString( param.getDisplayName( ) ) );
GridData gd = new GridData( );
this.maxWidth = computeMaxWidth( paramLabel );
gd.widthHint = this.maxWidth;
paramLabel.setLayoutData( gd );
Composite composite = ControlProvider.getDefaultComposite( parameterContainer );
if ( param.isDataField( ) )
{
String text = BLANK;
if ( lastExpression != null )
{
text = lastExpression;
}
else
{
text = (String) getProperty( getStructureOrHandle( ),
cellProperties[EXPRESSION_INDEX] );
}
txtParams[i] = ControlProvider.createText( composite, text );
final Text txtDataField = txtParams[i];
txtDataField.setLayoutData( ControlProvider.getGridDataWithHSpan( 1 ) );
txtDataField.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
lastExpression = txtDataField.getText( );
validateSyntax( );
}
} );
}
else
{
Text txtArgument = ControlProvider.createText( composite,
null );
txtArgument.setLayoutData( ControlProvider.getGridDataWithHSpan( 1 ) );
txtArgument.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
validateSyntax( );
}
} );
txtParams[i] = txtArgument;
}
txtParams[i].setToolTipText( param.getDescription( ) );
createExpressionButton( composite, txtParams[i] );
}
updateLabelWidth( );
// update parameters' values from ComputedColumnHandle
updateParametersText( params );
}
private void updateLabelWidth( )
{
GridData gd = new GridData( );
gd.widthHint = this.maxWidth;
firstLabel.setLayoutData( gd );
}
private void updateDataTypeCombo( )
{
final IAggrFunction aggrFunc = getSelectedFunction( );
if ( aggrFunc != null )
{
String dataType = DataAdapterUtil.adapterToModelDataType( aggrFunc.getDataType( ) );
cmbDataType.setText( getTypeDisplayName( dataType ) );
}
}
private void disposeOldParameterUI( )
{
Control[] children = parameterContainer.getChildren( );
for ( int i = 0; i < children.length; i++ )
{
children[i].dispose( );
}
}
private void hideParameterUISection( )
{
( (GridData) parameterContainer.getLayoutData( ) ).heightHint = 0;
}
private void showParameterUISection( )
{
( (GridData) parameterContainer.getLayoutData( ) ).exclude = false;
( (GridData) parameterContainer.getLayoutData( ) ).heightHint = SWT.DEFAULT;
}
/**
* update the arguments' UI elements from the compute column handle.
*/
private void updateParametersText( IParameterDefn[] params )
{
if ( params.length == 0 )
return;
Object handle = getStructureOrHandle( );
if ( handle instanceof ComputedColumnHandle )
{
ComputedColumnHandle cHandle = (ComputedColumnHandle) handle;
String expr = cHandle.getExpression( );
if ( expr != null )
{
txtParams[0].setText( expr );
}
else
{
Iterator itr = cHandle.argumentsIterator( );
List argHandles = new ArrayList( );
while ( itr.hasNext( ) )
{
argHandles.add( itr.next( ) );
}
int i = 0;
if ( params[0].isDataField( ) && lastExpression != null )
{
txtParams[0].setText( lastExpression );
i++;
}
for ( ; i < params.length; i++ )
{
AggregationArgumentHandle argHandle = null;
if ( i < argHandles.size( ) )
{
argHandle = (AggregationArgumentHandle) argHandles.get( i );
}
final String value = argHandle != null
? argHandle.getValue( ) : null;
txtParams[i].setText( value != null ? value : BLANK );
}
}
}
}
/**
*
* @param aggrFuncName
* @return
*/
private int getAggrFuncIndex( String aggrFuncName )
{
Integer selectionIndex = (Integer) cmbAggregation.getData( aggrFuncName != null
? aggrFuncName : BLANK );
return selectionIndex != null ? selectionIndex.intValue( ) : 0;
}
/**
* @return whether filter component should be enabled
*/
private boolean needFilter( )
{
if ( cmbAggregation.getText( ) != null
&& cmbAggregation.getText( ).trim( ).length( ) > 0 )
{
return true;
}
else
{
return false;
}
}
/**
* Update the Filter component status
*/
private void updateFilterUIStatus( )
{
if ( needFilter( ) )
{
txtFilter.setEnabled( true );
lblFilter.setEnabled( true );
btnFilter.setEnabled( true );
}
else
{
txtFilter.setText( BLANK );
txtFilter.setEnabled( false );
lblFilter.setEnabled( false );
btnFilter.setEnabled( false );
}
}
/**
*
* @param parent
* @param index
*/
private void createFilterCell( Composite parent, final int index )
{
lblFilter = ControlProvider.createLabel( parent,
dialogLabels[index] );
Composite composite = ControlProvider.getDefaultComposite( parent );
Object handle = this.getStructureOrHandle( );
if ( handle instanceof ComputedColumnHandle )
{
ComputedColumnHandle cHandle = (ComputedColumnHandle) handle;
txtFilter = ControlProvider.createText( composite,
cHandle.getFilterExpression( ) );
}
else
txtFilter = ControlProvider.createText( composite,
(String) getProperty( getStructureOrHandle( ),
cellProperties[index] ) );
txtFilter.setLayoutData( ControlProvider.getGridDataWithHSpan( 1 ) );
txtFilter.setEnabled( false );
txtFilter.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
validateSyntax( );
}
} );
SelectionAdapter listener = new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
ExpressionBuilder expressionBuilder = new ExpressionBuilder( txtFilter.getText( ) );
expressionBuilder.setExpressionProvier( new DataSetExpressionProvider( (DesignElementHandle) getContainer( ).getModel( ) ) );
String expression = txtFilter == null ? null
: txtFilter.getText( );
setExprBuilderDefaultSelection( expressionBuilder, expression );
if ( expressionBuilder.open( ) == OK )
{
txtFilter.setText( expressionBuilder.getResult( ).trim( ) );
}
}
};
btnFilter = ControlProvider.createButton( composite,
SWT.PUSH,
listener );
updateFilterUIStatus( );
}
/**
*
* @param composite
* @param text
* @return
*/
private Button createExpressionButton( Composite composite, final Text text )
{
SelectionAdapter listener = new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
ExpressionBuilder expressionBuilder = new ExpressionBuilder( text.getText( ) );
expressionBuilder.setExpressionProvier( new DataSetExpressionProvider( (DesignElementHandle) getContainer( ).getModel( ) ) );
String expression = ( txtParams.length > 0 && txtParams[0] != null )
? txtParams[0].getText( ) : null;
setExprBuilderDefaultSelection( expressionBuilder,
expression );
if ( expressionBuilder.open( ) == OK )
{
text.setText( expressionBuilder.getResult( )
.trim( ) );
}
}
};
return ControlProvider.createButton( composite, SWT.PUSH, listener );
}
/**
* Set the default selection in the expression builder
*
* @param expressionBuilder
*/
private void setExprBuilderDefaultSelection(
ExpressionBuilder expressionBuilder, String expression )
{
Object[] selection = null;
String dataSets = DataSetExpressionProvider.DATASETS;
DataSetHandle dsHandle = (DataSetHandle) getContainer( ).getModel( );
Object handle = this.getStructureOrHandle( );
if ( handle instanceof ComputedColumnHandle )
{
try
{
String columnName = ExpressionUtil.getColumnBindingName( expression );
DataSetViewData viewData = findDataSetViewData( columnName,
dsHandle );
selection = new Object[]{
dataSets, dsHandle, viewData
};
}
catch ( BirtException e )
{
selection = new Object[]{ dataSets, dsHandle };
}
}
else
{
selection = new Object[]{ dataSets, dsHandle };
}
expressionBuilder.setDefaultSelection( selection );
}
/**
* Finds the DataSetViewData instance according to the given column name
*
* @param columnName
* @param handle
* @return
*/
private DataSetViewData findDataSetViewData( String columnName,
DataSetHandle handle )
{
if ( columnName == null || columnName.trim( ).length( ) == 0 )
{
return null;
}
DataSetViewData[] items = DataSetProvider.getCurrentInstance( )
.getColumns( handle, false, true, true );
for ( int i = 0; i < items.length; i++ )
{
if ( columnName.equals( items[i].getName( ) ) )
{
return items[i];
}
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.data.ui.dataset.PropertyHandleInputDialog#validateSemantics(java.lang.Object)
*/
protected IStatus validateSemantics( Object structureOrHandle )
{
AggregationArgument aggrArgument = null;
String columnName = txtColumnName.getText( );
String dataTypeName = getTypeName( cmbDataType.getText( ) );
IAggrFunction aggrFunc = getSelectedFunction( );
try
{
String funcName = aggrFunc != null ? aggrFunc.getName( )
: BLANK;
String filter = this.txtFilter.getText( );
if ( structureOrHandle instanceof ComputedColumnHandle )
{
ComputedColumnHandle handle = (ComputedColumnHandle) structureOrHandle;
handle.setName( columnName );
handle.setDataType( dataTypeName );
handle.setAggregateFunction( funcName );
if ( aggrFunc == null )
{
handle.setExpression( txtParams[0].getText( ).trim( ) );
}
else
{
handle.setExpression( BLANK );
handle.setFilterExpression( filter );
handle.clearArgumentList( );
IParameterDefn[] params = aggrFunc.getParameterDefn( );
for ( int i = 0; i < params.length; i++ )
{
if( txtParams[i].getText( ).trim( ).length( )== 0)
continue;
aggrArgument = StructureFactory.createAggregationArgument( );
aggrArgument.setName( params[i].getName( ) );
aggrArgument.setValue( txtParams[i].getText( )
.trim( ) );
handle.addArgument( aggrArgument );
}
}
}
else if ( structureOrHandle instanceof ComputedColumn )
{
ComputedColumn handle = (ComputedColumn) structureOrHandle;
handle.setName( columnName );
handle.setDataType( dataTypeName );
handle.setAggregateFunction( funcName );
if ( aggrFunc == null )
{
handle.setExpression( txtParams[0].getText( ).trim( ) );
}
else
{
handle.setExpression( BLANK );
handle.setFilterExpression( filter );
IParameterDefn[] params = aggrFunc.getParameterDefn( );
for ( int i = 0; i < params.length; i++ )
{
if( txtParams[i].getText( ).trim( ).length( )== 0)
continue;
aggrArgument = StructureFactory.createAggregationArgument( );
aggrArgument.setName( params[i].getName( ) );
aggrArgument.setValue( txtParams[i].getText( )
.trim( ) );
handle.addArgument( aggrArgument );
}
}
updateComputedColumns( handle );
}
}
catch ( Exception e )
{
Status status = new Status( IStatus.ERROR,
ReportPlugin.REPORT_UI,
BLANK,
e );
return status;
}
return getOKStatus( );
}
/**
*
* @return
*/
private IAggrFunction getSelectedFunction( )
{
int index = cmbAggregation.getSelectionIndex( );
return index > 0 ? functions[index - 1] : null;
}
/**
* Update the computed columns after adding a new column and cache the
* updated DataSetViewData[]
*
*/
private void updateComputedColumns( ComputedColumn handle )
{
DataSetHandle dataSet = ( (DataSetEditor) getContainer( ) ).getHandle( );
DataSetViewData[] items = DataSetProvider.getCurrentInstance( )
.getColumns( dataSet, false, true, true );
int count = items.length;
DataSetViewData[] newItems = new DataSetViewData[count + 1];
System.arraycopy( items, 0, newItems, 0, count );
newItems[count] = new DataSetViewData( );
newItems[count].setName( handle.getName( ) );
newItems[count].setDataTypeName( handle.getDataType( ) );
newItems[count].setAlias( handle.getDisplayName( ) );
newItems[count].setComputedColumn( true );
newItems[count].setPosition( count + 1 );
newItems[count].setDataType( DataAdapterUtil.adaptModelDataType( handle.getDataType( ) ) );
DataSetProvider.getCurrentInstance( )
.updateColumnsOfDataSetHandle( dataSet, newItems );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.data.ui.dataset.PropertyHandleInputDialog#validateSyntax(java.lang.Object)
*/
protected IStatus validateSyntax( Object structureOrHandle )
{
// duplicated columnName check
if ( !isUniqueColumnName( ) )
return getMiscStatus( IStatus.ERROR,
Messages.getString( "DataSetComputedColumnsPage.duplicatedName" ) ); //$NON-NLS-1$
// blankProperty check
if ( isBlankProperty( txtColumnName.getText( ) ) )
return getBlankPropertyStatus( dialogLabels[COLUMN_NAME_INDEX] );
if ( isBlankProperty( cmbDataType.getText( ) ) )
return getBlankPropertyStatus( dialogLabels[DATA_TYPE_INDEX] );
// if ( expression!=null && isBlankProperty( expression.getText( ) ) )
// String funcName = getSelectedFunction( ).getName( );
// if ( isFunctionCount( funcName ) == false )
// return getBlankPropertyStatus( cellLabels[EXPRESSION_INDEX] );
// validate arguments
IAggrFunction aggrFunc = getSelectedFunction( );
if ( aggrFunc != null )
{
IParameterDefn[] paramDefns = aggrFunc.getParameterDefn( );
for ( int i = 0; i < paramDefns.length; i++ )
{
if ( !paramDefns[i].isOptional( )
&& isBlankProperty( txtParams[i].getText( ) ) )
{
return getBlankPropertyStatus( paramDefns[i].getDisplayName( ) );
}
}
}
else
{
if ( txtParams != null
&& isBlankProperty( txtParams[0].getText( ) ) )
{
return getBlankPropertyStatus( dialogLabels[EXPRESSION_INDEX] );
}
}
return getOKStatus( );
}
/**
*
* @return
*/
private final boolean isUniqueColumnName( )
{
DataSetViewData[] items = DataSetProvider.getCurrentInstance( )
.getColumns( ( (DataSetEditor) getContainer( ) ).getHandle( ),
false,
true,
true );
for ( int i = 0; i < items.length; i++ )
{
if ( !items[i].getName( ).equals( columnName ) )
{
if ( !items[i].isComputedColumn( ) )
{
if ( ( items[i].getAlias( ) != null && items[i].getAlias( )
.equals( txtColumnName.getText( ) ) )
|| ( items[i].getName( ) != null && items[i].getName( )
.equals( txtColumnName.getText( ) ) ) )
{
return false;
}
}
}
}
Iterator iter = computedColumns.iterator( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
ComputedColumnHandle handle = (ComputedColumnHandle) iter.next( );
if ( getStructure( getStructureOrHandle( ) ) != handle.getStructure( )
&& handle.getName( ).equals( txtColumnName.getText( ) ) )
{
return false;
}
}
}
Iterator iter2 = ( (DataSetHandle) getContainer( ).getModel( ) ).getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP )
.iterator( );
while ( iter2.hasNext( ) )
{
ColumnHintHandle hint = (ColumnHintHandle) iter2.next( );
if ( !hint.getColumnName( ).equals( columnName ) )
{
if ( txtColumnName.getText( ).equals( hint.getAlias( ) )
|| txtColumnName.getText( )
.equals( hint.getColumnName( ) ) )
{
return false;
}
}
}
return true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.data.ui.dataset.PropertyHandleInputDialog#rollback()
*/
protected void rollback( )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.data.ui.dataset.PropertyHandleInputDialog#getTitle()
*/
protected String getTitle( )
{
if ( this.getStructureOrHandle( ) instanceof Structure )
{
return Messages.getString( "DataSetComputedColumnsPage.InputDialog.title.New" ); //$NON-NLS-1$
}
return Messages.getString( "DataSetComputedColumnsPage.InputDialog.title.Edit" );//$NON-NLS-1$
}
}
}
|
package org.hswebframework.web.authorization.basic.aop;
import org.hswebframework.web.AopUtils;
import org.hswebframework.web.authorization.annotation.Authorize;
import org.hswebframework.web.authorization.annotation.RequiresDataAccess;
import org.hswebframework.web.authorization.annotation.RequiresExpression;
import org.hswebframework.web.authorization.basic.define.DefaultBasicAuthorizeDefinition;
import org.hswebframework.web.authorization.basic.define.EmptyAuthorizeDefinition;
import org.hswebframework.web.authorization.define.AuthorizeDefinition;
import org.hswebframework.web.boost.aop.context.MethodInterceptorContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* ,
*
* @author zhouhao
* @see AopMethodAuthorizeDefinitionParser
* @see AuthorizeDefinition
*/
public class DefaultAopMethodAuthorizeDefinitionParser implements AopMethodAuthorizeDefinitionParser {
private Map<Method, AuthorizeDefinition> cache = new ConcurrentHashMap<>();
private List<AopMethodAuthorizeDefinitionCustomizerParser> parserCustomers;
@Autowired(required = false)
public void setParserCustomers(List<AopMethodAuthorizeDefinitionCustomizerParser> parserCustomers) {
this.parserCustomers = parserCustomers;
}
@Override
public AuthorizeDefinition parse(MethodInterceptorContext paramContext) {
AuthorizeDefinition definition = cache.get(paramContext.getMethod());
if (definition != null) return definition instanceof EmptyAuthorizeDefinition ? null : definition;
if (!CollectionUtils.isEmpty(parserCustomers)) {
definition = parserCustomers.stream()
.map(customer -> customer.parse(paramContext))
.findAny().orElse(null);
if (definition != null) {
// cache.put(paramContext.getMethod(), definition);
return definition;
}
}
Authorize classAuth = AopUtils.findAnnotation(paramContext.getTarget().getClass(), Authorize.class);
Authorize methodAuth = AopUtils.findMethodAnnotation(paramContext.getTarget().getClass(), paramContext.getMethod(), Authorize.class);
RequiresDataAccess classDataAccess = AopUtils.findAnnotation(paramContext.getTarget().getClass(), RequiresDataAccess.class);
RequiresDataAccess methodDataAccess = AopUtils.findMethodAnnotation(paramContext.getTarget().getClass(), paramContext.getMethod(), RequiresDataAccess.class);
RequiresExpression expression = AopUtils.findAnnotation(paramContext.getTarget().getClass(), RequiresExpression.class);
if (classAuth == null && methodAuth == null && classDataAccess == null && methodDataAccess == null && expression == null) {
cache.put(paramContext.getMethod(), EmptyAuthorizeDefinition.instance);
return null;
}
if ((methodAuth != null && methodAuth.ignore()) || (classAuth != null && classAuth.ignore())) {
cache.put(paramContext.getMethod(), EmptyAuthorizeDefinition.instance);
return null;
}
DefaultBasicAuthorizeDefinition authorizeDefinition = new DefaultBasicAuthorizeDefinition();
if (methodAuth == null || !methodAuth.merge())
authorizeDefinition.put(classAuth);
authorizeDefinition.put(methodAuth);
authorizeDefinition.put(expression);
authorizeDefinition.put(classDataAccess);
authorizeDefinition.put(methodDataAccess);
cache.put(paramContext.getMethod(), authorizeDefinition);
return authorizeDefinition;
}
}
|
package org.tensorflow.lite;
import androidx.annotation.NonNull;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
/**
* Main driver class for the IREE Java compatibility shim. Provides model
* creation and inference for IREE compatible TFLite models.
*
* <p>This shim aims to mimic the functionality of Tensorflow Lite's
* Interpeter.java class, however, there are a few notable features IREE doesn't
* support:
*
* <ul>
* <li> Delegates and the NNAPI
* <li> Advanced interpreter options
* <li> Interrupting or canceling inference before it's complete
* <li> Tensor method signatures
* <li> Dynamic shapes
* <li> String input/output isn't supported
* <ul>
*
* <p>In addition, this compatibility shim only accepts {@link java.nio.Buffer}
* type input. Consumers with scalar and array inputs can see conversion methods
* below.
*
* <p>Example using the Interpreter with a model with a single input/output Tensor:
*
* <pre>{@code
* // Load model/initialize interpreter:
* ByteBuffer modelByteBuffer = ... load model here ....
* Interpreter interpreter = new Interpreter(modelByteBuffer);
* interpreter.allocateTensors();
*
* // Prepare inputs:
* float[] input = {1, 3};
* float[] output = new float[2];
*
* int bytesInFloat = 4;
* FloatBuffer inputBuffer = ByteBuffer.allocateDirect(bytesInFloat * input.length)
* .order(ByteOrder.nativeOrder())
* .asFloatBuffer();
* FloatBuffer outputBuffer = ByteBuffer.allocateDirect(bytesInFloat * output.length)
* .order(ByteOrder.nativeOrder())
* .asFloatBuffer();
*
* // Run inference:
* inputBuffer.put(input);
* interpreter.run(inputBuffer, outputBuffer);
* outputBuffer.get(output);
* ... process output ...
*
* // Cleanup:
* interpreter.close();
* }</pre>
*
* <p>If a model takes multiple inputs, use
* {@link #runForMultipleInputsOutputs(Buffer[], Map)}:
*
* <pre>{@code
* // Load model/initialize interpreter same as above.
*
* // Prepare inputs:
* Buffer[] inputs = {input0, input1, ...};
* Map<Integer, Buffer> indexToOutput = new HashMap<>();
* FloatBuffer ithOutput = ... allocate (native) and populate buffer ...
* indexToOutput.put(i, ithOutput);
*
* // Run inference:
* interpreter.runForMultipleInputsOutputs(inputs, indexToOutput);
*
* // Cleanup same as above.
* }</pre>
*
* <p>Orders of inputs and outputs are determined when converting TensorFlow
* model to TensorFlow Lite model with TOCO, as are the default shapes of the
* inputs.
*
* <p><b>WARNING:</b>Instances of {@link Interpreter} are <b>not</b> thread-safe.
* A {@link Interpreter} owns resources that <b>must</b> be explicitly freed by
* invoking {@link #close()}
*/
public final class Interpreter implements AutoCloseable {
private static final String TAG = Interpreter.class.getCanonicalName();
/**
* Options class for controlling runtime interpreter behavior.
*
* <p>Currently only {@link #setNumThreads(int)} is supported.
*/
public static class Options {
int numThreads = -1;
public Options() {}
/**
* Sets the number of threads to be used for ops that support multi-threading.
*
* <p>{@code numThreads} should be >= -1. Setting {@code numThreads} to 0 has the effect to
* disable multithreading, which is equivalent to setting {@code numThreads} to 1. If
* unspecified, or set to the value -1, the number of threads used will be
* implementation-defined and platform-dependent.
*/
public Options setNumThreads(int numThreads) {
this.numThreads = numThreads;
return this;
}
}
private final int inputTensorCount;
private final int outputTensorCount;
private final Tensor[] inputTensors;
private final Tensor[] outputTensors;
private final long nativeAddress;
private long inferenceDurationNanoseconds;
private boolean tensorsAllocated;
public Interpreter(@NonNull ByteBuffer modelByteBuffer, Options options)
throws IllegalArgumentException {
TensorFlowLite.init();
if (options == null) {
options = new Options();
options.setNumThreads(2);
}
nativeAddress = nativeNew(modelByteBuffer, options.numThreads);
if (nativeAddress == 0) {
throw new IllegalArgumentException("Could not create Interpreter");
}
inputTensorCount = nativeInputTensorCount();
outputTensorCount = nativeOutputTensorCount();
inputTensors = new Tensor[inputTensorCount];
outputTensors = new Tensor[outputTensorCount];
}
public void run(Buffer input, Buffer output) {
Buffer[] inputs = {input};
Map<Integer, Buffer> outputs = new HashMap<>();
outputs.put(0, output);
runForMultipleInputsOutputs(inputs, outputs);
}
public void runForMultipleInputsOutputs(
@NonNull Buffer[] inputs, @NonNull Map<Integer, Buffer> outputs) {
if (inputs == null || inputs.length == 0) {
throw new IllegalArgumentException("Input error: Inputs should not be null or empty.");
}
if (outputs == null || outputs.isEmpty()) {
throw new IllegalArgumentException("Input error: Outputs should not be null or empty.");
}
if (!tensorsAllocated) {
allocateTensors();
}
for (int i = 0; i < inputs.length; ++i) {
getInputTensor(i).copyFromBuffer(inputs[i]);
}
long inferenceStartNanos = System.nanoTime();
int status = nativeInvoke();
inferenceDurationNanoseconds = System.nanoTime() - inferenceStartNanos;
if (status != 0) {
throw new IllegalStateException(
String.format("Failed to run Interpreter. Returned status code: %d", status));
}
for (Map.Entry<Integer, Buffer> output : outputs.entrySet()) {
getOutputTensor(output.getKey()).copyToBuffer(output.getValue());
}
}
public void allocateTensors() {
if (nativeAllocateTensors() != 0) {
throw new IllegalStateException("Failed to allocate Tensors.");
}
tensorsAllocated = true;
}
public void resizeInput(int inputIndex, @NonNull int[] dims) {
if (nativeResizeInputTensor(inputIndex, dims) != 0) {
throw new IllegalArgumentException("Unable to resize to input tensor.");
}
tensorsAllocated = false;
}
/** Gets the number of input tensors. */
public int getInputTensorCount() {
return inputTensorCount;
}
public int getInputIndex(String opName) {
for (int i = 0; i < getInputTensorCount(); ++i) {
if (getInputTensor(i).name().equals(opName)) {
return i;
}
}
return -1;
}
public Tensor getInputTensor(int index) {
if (index < 0 || index >= inputTensors.length) {
throw new IllegalArgumentException(String.format("Invalid input Tensor index: %d", index));
}
if (inputTensors[index] == null) {
inputTensors[index] = Tensor.inputFromIndex(nativeAddress, index);
}
return inputTensors[index];
}
/** Gets the number of output Tensors. */
public int getOutputTensorCount() {
return outputTensorCount;
}
/** Gets index of an output given the op name of the output or -1 if not found. */
public int getOutputIndex(String opName) {
for (int i = 0; i < getOutputTensorCount(); ++i) {
if (getOutputTensor(i).name().equals(opName)) {
return i;
}
}
return -1;
}
public Tensor getOutputTensor(int index) {
if (index < 0 || index >= outputTensors.length) {
throw new IllegalArgumentException(String.format("Invalid output Tensor index: %d", index));
}
if (outputTensors[index] == null) {
outputTensors[index] = Tensor.outputFromIndex(nativeAddress, index);
}
return outputTensors[index];
}
/** Returns native inference timing, or -1 if inference isn't complete yet. */
public Long getLastNativeInferenceDurationNanoseconds() {
return inferenceDurationNanoseconds;
}
/** Release resources associated with the {@code Interpreter}. */
@Override
public void close() {
nativeFree();
}
private native long nativeNew(ByteBuffer modelByteBuffer, int numThreads);
private native void nativeFree();
private native int nativeInputTensorCount();
private native int nativeOutputTensorCount();
private native int nativeAllocateTensors();
private native int nativeResizeInputTensor(int inputIndex, int[] dims);
private native int nativeInvoke();
}
|
package bt.data.file;
import bt.data.StorageUnit;
import bt.data.Storage;
import bt.metainfo.Torrent;
import bt.metainfo.TorrentFile;
import java.io.File;
import java.nio.file.Path;
/**
* Provides file-system based storage for torrent files.
*
* <p>Information about the collection of files in a torrent is stored as a list of strings in the torrent metainfo.
* This makes it possible for malicious parties to create torrents with malformed pathnames,
* e.g. by using relative paths (. and ..), empty and invalid directory and file names, etc.
* In the worst case this can lead to loss and corruption of user data and execution of arbitrary code.
*
* <p>This storage implementation performs normalization of file paths, ensuring that:
* <ul>
* <li>all torrent files are stored inside the root directory of this storage (see {@link #FileSystemStorage(File)})</li>
* <li>all individual paths are checked for potential issues and fixed in a consistent way (see below)</li>
* </ul>
*
* <p><b>Algorithm for resolving paths:</b><br>
* 1) The following transformations are applied to each individual path element:
* <ul>
* <li>trimming whitespaces,</li>
* <li>truncating trailing dots and whitespaces recursively,</li>
* <li>substituting empty names with an underscore character
* (this also includes names that became empty after the truncation of whitespaces and dots),</li>
* <li>in case there is a leading or trailing file separator,
* it is assumed that the path starts or ends with an empty name, respectively.</li>
* </ul><br>
* 2) Normalized path elements are concatenated together using {@link File#separator} as the delimiter.
*
* <p><b>Examples:</b><br>
* {@code "a/b/c" => "a/b/c"}<br>
* {@code " a/ b /c" => "a/b/c"}<br>
* {@code ".a/.b" => ".a/.b"}<br>
* {@code "a./.b." => "a/.b"}<br>
* {@code "" => "_"}<br>
* {@code "a//b" => "a/_/b"}<br>
* {@code "." => "_"}<br>
* {@code ".." => "_"}<br>
* {@code "/" => "_/_"}<br>
* {@code "/a/b/c" => "_/a/b/c"}<br>
*
* @since 1.0
*/
public class FileSystemStorage implements Storage {
private final Path rootDirectory;
private final PathNormalizer pathNormalizer;
/**
* Create a file-system based storage inside a given directory.
*
* @param rootDirectory Root directory for this storage. All torrent files will be stored inside this directory.
* @since 1.0
*/
@Deprecated public FileSystemStorage(File rootDirectory) {
this(rootDirectory.toPath());
}
public FileSystemStorage(Path rootDirectory) {
this.rootDirectory = rootDirectory;
this.pathNormalizer = new PathNormalizer();
}
@Override
public StorageUnit getUnit(Torrent torrent, TorrentFile torrentFile) {
Path torrentDirectory;
if (torrent.getFiles().size() == 1) {
torrentDirectory = rootDirectory;
} else {
String normalizedName = pathNormalizer.normalize(torrent.getName());
torrentDirectory = rootDirectory.resolve(normalizedName);
}
String normalizedPath = pathNormalizer.normalize(torrentFile.getPathElements());
return new FileSystemStorageUnit(torrentDirectory, normalizedPath, torrentFile.getSize());
}
}
|
package com.adobe.phonegap.push;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.preference.PreferenceManager;
import android.content.SharedPreferences;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Paint;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.WearableExtender;
import android.support.v4.app.RemoteInput;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
@SuppressLint("NewApi")
public class GCMIntentService extends GcmListenerService implements PushConstants {
private static final String LOG_TAG = "Push_GCMIntentService";
private static HashMap<Integer, ArrayList<String>> messageMap = new HashMap<Integer, ArrayList<String>>();
public void setNotification(int notId, String message){
ArrayList<String> messageList = messageMap.get(notId);
if(messageList == null) {
messageList = new ArrayList<String>();
messageMap.put(notId, messageList);
}
if(message.isEmpty()){
messageList.clear();
}else{
messageList.add(message);
}
}
@Override
public void onMessageReceived(String from, Bundle extras) {
Log.d(LOG_TAG, "onMessage - from: " + from);
if (extras != null && isAvailableSender(from)) {
Context applicationContext = getApplicationContext();
SharedPreferences prefs = applicationContext.getSharedPreferences(PushPlugin.COM_ADOBE_PHONEGAP_PUSH, Context.MODE_PRIVATE);
boolean forceShow = prefs.getBoolean(FORCE_SHOW, false);
boolean clearBadge = prefs.getBoolean(CLEAR_BADGE, false);
String messageKey = prefs.getString(MESSAGE_KEY, MESSAGE);
String titleKey = prefs.getString(TITLE_KEY, TITLE);
extras = normalizeExtras(applicationContext, extras, messageKey, titleKey);
if (clearBadge) {
PushPlugin.setApplicationIconBadgeNumber(getApplicationContext(), 0);
}
// if we are in the foreground and forceShow is `false` only send data
if (!forceShow && PushPlugin.isInForeground()) {
Log.d(LOG_TAG, "foreground");
extras.putBoolean(FOREGROUND, true);
extras.putBoolean(COLDSTART, false);
PushPlugin.sendExtras(extras);
}
// if we are in the foreground and forceShow is `true`, force show the notification if the data has at least a message or title
else if (forceShow && PushPlugin.isInForeground()) {
Log.d(LOG_TAG, "foreground force");
extras.putBoolean(FOREGROUND, true);
extras.putBoolean(COLDSTART, false);
showNotificationIfPossible(applicationContext, extras);
}
// if we are not in the foreground always send notification if the data has at least a message or title
else {
Log.d(LOG_TAG, "background");
extras.putBoolean(FOREGROUND, false);
extras.putBoolean(COLDSTART, PushPlugin.isActive());
showNotificationIfPossible(applicationContext, extras);
}
}
}
/*
* Change a values key in the extras bundle
*/
private void replaceKey(Context context, String oldKey, String newKey, Bundle extras, Bundle newExtras) {
Object value = extras.get(oldKey);
if ( value != null ) {
if (value instanceof String) {
value = localizeKey(context, newKey, (String) value);
newExtras.putString(newKey, (String) value);
} else if (value instanceof Boolean) {
newExtras.putBoolean(newKey, (Boolean) value);
} else if (value instanceof Number) {
newExtras.putDouble(newKey, ((Number) value).doubleValue());
} else {
newExtras.putString(newKey, String.valueOf(value));
}
}
}
/*
* Normalize localization for key
*/
private String localizeKey(Context context, String key, String value) {
if (key.equals(TITLE) || key.equals(MESSAGE) || key.equals(SUMMARY_TEXT)) {
try {
JSONObject localeObject = new JSONObject(value);
String localeKey = localeObject.getString(LOC_KEY);
ArrayList<String> localeFormatData = new ArrayList<String>();
if (!localeObject.isNull(LOC_DATA)) {
String localeData = localeObject.getString(LOC_DATA);
JSONArray localeDataArray = new JSONArray(localeData);
for (int i = 0 ; i < localeDataArray.length(); i++) {
localeFormatData.add(localeDataArray.getString(i));
}
}
String packageName = context.getPackageName();
Resources resources = context.getResources();
int resourceId = resources.getIdentifier(localeKey, "string", packageName);
if (resourceId != 0) {
return resources.getString(resourceId, localeFormatData.toArray());
}
else {
Log.d(LOG_TAG, "can't find resource for locale key = " + localeKey);
return value;
}
}
catch(JSONException e) {
Log.d(LOG_TAG, "no locale found for key = " + key + ", error " + e.getMessage());
return value;
}
}
return value;
}
/*
* Replace alternate keys with our canonical value
*/
private String normalizeKey(String key, String messageKey, String titleKey) {
if (key.equals(BODY) || key.equals(ALERT) || key.equals(MP_MESSAGE) || key.equals(GCM_NOTIFICATION_BODY) || key.equals(TWILIO_BODY) || key.equals(messageKey)) {
return MESSAGE;
} else if (key.equals(TWILIO_TITLE) || key.equals(SUBJECT) || key.equals(titleKey)) {
return TITLE;
}else if (key.equals(MSGCNT) || key.equals(BADGE)) {
return COUNT;
} else if (key.equals(SOUNDNAME) || key.equals(TWILIO_SOUND)) {
return SOUND;
} else if (key.startsWith(GCM_NOTIFICATION)) {
return key.substring(GCM_NOTIFICATION.length()+1, key.length());
} else if (key.startsWith(GCM_N)) {
return key.substring(GCM_N.length()+1, key.length());
} else if (key.startsWith(UA_PREFIX)) {
key = key.substring(UA_PREFIX.length()+1, key.length());
return key.toLowerCase();
} else {
return key;
}
}
/*
* Parse bundle into normalized keys.
*/
private Bundle normalizeExtras(Context context, Bundle extras, String messageKey, String titleKey) {
Log.d(LOG_TAG, "normalize extras");
Iterator<String> it = extras.keySet().iterator();
Bundle newExtras = new Bundle();
while (it.hasNext()) {
String key = it.next();
Log.d(LOG_TAG, "key = " + key);
// If normalizeKeythe key is "data" or "message" and the value is a json object extract
// This is to support parse.com and other services. Issue #147 and pull #218
if (key.equals(PARSE_COM_DATA) || key.equals(MESSAGE) || key.equals(messageKey)) {
Object json = extras.get(key);
// Make sure data is json object stringified
if ( json instanceof String && ((String) json).startsWith("{") ) {
Log.d(LOG_TAG, "extracting nested message data from key = " + key);
try {
// If object contains message keys promote each value to the root of the bundle
JSONObject data = new JSONObject((String) json);
if ( data.has(ALERT) || data.has(MESSAGE) || data.has(BODY) || data.has(TITLE) ||
data.has(messageKey) || data.has(titleKey) ) {
Iterator<String> jsonIter = data.keys();
while (jsonIter.hasNext()) {
String jsonKey = jsonIter.next();
Log.d(LOG_TAG, "key = data/" + jsonKey);
String value = data.getString(jsonKey);
jsonKey = normalizeKey(jsonKey, messageKey, titleKey);
value = localizeKey(context, jsonKey, value);
newExtras.putString(jsonKey, value);
}
}
} catch( JSONException e) {
Log.e(LOG_TAG, "normalizeExtras: JSON exception");
}
} else {
String newKey = normalizeKey(key, messageKey, titleKey);
Log.d(LOG_TAG, "replace key " + key + " with " + newKey);
replaceKey(context, key, newKey, extras, newExtras);
}
} else if (key.equals(("notification"))) {
Bundle value = extras.getBundle(key);
Iterator<String> iterator = value.keySet().iterator();
while (iterator.hasNext()) {
String notifkey = iterator.next();
Log.d(LOG_TAG, "notifkey = " + notifkey);
String newKey = normalizeKey(notifkey, messageKey, titleKey);
Log.d(LOG_TAG, "replace key " + notifkey + " with " + newKey);
String valueData = value.getString(notifkey);
valueData = localizeKey(context, newKey, valueData);
newExtras.putString(newKey, valueData);
}
continue;
// In case we weren't working on the payload data node or the notification node,
// normalize the key.
// This allows to have "message" as the payload data key without colliding
// with the other "message" key (holding the body of the payload)
// See issue #1663
} else {
String newKey = normalizeKey(key, messageKey, titleKey);
Log.d(LOG_TAG, "replace key " + key + " with " + newKey);
replaceKey(context, key, newKey, extras, newExtras);
}
} // while
return newExtras;
}
private int extractBadgeCount(Bundle extras) {
int count = -1;
String msgcnt = extras.getString(COUNT);
try {
if (msgcnt != null) {
count = Integer.parseInt(msgcnt);
}
} catch (NumberFormatException e) {
Log.e(LOG_TAG, e.getLocalizedMessage(), e);
}
return count;
}
private void showNotificationIfPossible (Context context, Bundle extras) {
// Send a notification if there is a message or title, otherwise just send data
String message = extras.getString(MESSAGE);
String title = extras.getString(TITLE);
String contentAvailable = extras.getString(CONTENT_AVAILABLE);
String forceStart = extras.getString(FORCE_START);
int badgeCount = extractBadgeCount(extras);
if (badgeCount >= 0) {
Log.d(LOG_TAG, "count =[" + badgeCount + "]");
PushPlugin.setApplicationIconBadgeNumber(context, badgeCount);
}
Log.d(LOG_TAG, "message =[" + message + "]");
Log.d(LOG_TAG, "title =[" + title + "]");
Log.d(LOG_TAG, "contentAvailable =[" + contentAvailable + "]");
Log.d(LOG_TAG, "forceStart =[" + forceStart + "]");
if ((message != null && message.length() != 0) ||
(title != null && title.length() != 0)) {
Log.d(LOG_TAG, "create notification");
if(title == null || title.isEmpty()){
extras.putString(TITLE, getAppName(this));
}
createNotification(context, extras);
}
if(!PushPlugin.isActive() && "1".equals(forceStart)){
Log.d(LOG_TAG, "app is not running but we should start it and put in background");
Intent intent = new Intent(this, PushHandlerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(PUSH_BUNDLE, extras);
intent.putExtra(START_IN_BACKGROUND, true);
intent.putExtra(FOREGROUND, false);
startActivity(intent);
} else if ("1".equals(contentAvailable)) {
Log.d(LOG_TAG, "app is not running and content available true");
Log.d(LOG_TAG, "send notification event");
PushPlugin.sendExtras(extras);
}
}
public void createNotification(Context context, Bundle extras) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String appName = getAppName(this);
String packageName = context.getPackageName();
Resources resources = context.getResources();
int notId = parseInt(NOT_ID, extras);
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra(PUSH_BUNDLE, extras);
notificationIntent.putExtra(NOT_ID, notId);
int requestCode = new Random().nextInt();
PendingIntent contentIntent = PendingIntent.getActivity(this, requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent dismissedNotificationIntent = new Intent(notificationIntent);
dismissedNotificationIntent.putExtra(DISMISSED, true);
requestCode = new Random().nextInt();
PendingIntent deleteIntent = PendingIntent.getActivity(this, requestCode, dismissedNotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setWhen(System.currentTimeMillis())
.setContentTitle(fromHtml(extras.getString(TITLE)))
.setTicker(fromHtml(extras.getString(TITLE)))
.setContentIntent(contentIntent)
//.setDeleteIntent(deleteIntent)
.setAutoCancel(true);
SharedPreferences prefs = context.getSharedPreferences(PushPlugin.COM_ADOBE_PHONEGAP_PUSH, Context.MODE_PRIVATE);
String localIcon = prefs.getString(ICON, null);
String localIconColor = prefs.getString(ICON_COLOR, null);
//boolean soundOption = prefs.getBoolean(SOUND, true);
//boolean vibrateOption = prefs.getBoolean(VIBRATE, true);
Log.d(LOG_TAG, "stored icon=" + localIcon);
Log.d(LOG_TAG, "stored iconColor=" + localIconColor);
//Log.d(LOG_TAG, "stored sound=" + soundOption);
//Log.d(LOG_TAG, "stored vibrate=" + vibrateOption);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean vibrateOption = app_preferences.getBoolean("com.adobe.phonegap.push.vibration", true);
boolean soundOption = app_preferences.getBoolean("com.adobe.phonegap.push.sound", true);
boolean lightOption = app_preferences.getBoolean("com.adobe.phonegap.push.light", true);
String ringtonePath = app_preferences.getString("com.adobe.phonegap.push.ringtone", "defValue");
Log.d(LOG_TAG, "stored sound=" + soundOption);
Log.d(LOG_TAG, "stored vibrate=" + vibrateOption);
/*
* Notification Light
*/
setNotificationLight(extras, lightOption, mBuilder);
/*
* Notification Vibration
*/
setNotificationVibration(extras, vibrateOption, mBuilder);
/*
* Notification Icon Color
*
* Sets the small-icon background color of the notification.
* To use, add the `iconColor` key to plugin android options
*
*/
setNotificationIconColor(extras.getString("color"), mBuilder, localIconColor);
/*
* Notification Icon
*
* Sets the small-icon of the notification.
*
* - checks the plugin options for `icon` key
* - if none, uses the application icon
*
* The icon value must be a string that maps to a drawable resource.
* If no resource is found, falls
*
*/
setNotificationSmallIcon(context, extras, packageName, resources, mBuilder, localIcon);
/*
* Notification Large-Icon
*
* Sets the large-icon of the notification
*
* - checks the gcm data for the `image` key
* - checks to see if remote image, loads it.
* - checks to see if assets image, Loads It.
* - checks to see if resource image, LOADS IT!
* - if none, we don't set the large icon
*
*/
setNotificationLargeIcon(extras, packageName, resources, mBuilder);
/*
* Notification Sound
*/
if (soundOption) {
setNotificationSound(ringtonePath, mBuilder);
}
/*
* LED Notification
*/
setNotificationLedColor(extras, mBuilder);
/*
* Priority Notification
*/
setNotificationPriority(extras, mBuilder);
/*
* Notification message
*/
setNotificationMessage(notId, extras, mBuilder);
/*
* Notification count
*/
setNotificationCount(context, extras, mBuilder);
/*
* Notification count
*/
setVisibility(context, extras, mBuilder);
/*
* Notification add actions
*/
createActions(extras, mBuilder, resources, packageName, notId);
mNotificationManager.notify(appName, notId, mBuilder.build());
}
private void updateIntent(Intent intent, String callback, Bundle extras, boolean foreground, int notId) {
intent.putExtra(CALLBACK, callback);
intent.putExtra(PUSH_BUNDLE, extras);
intent.putExtra(FOREGROUND, foreground);
intent.putExtra(NOT_ID, notId);
}
private void createActions(Bundle extras, NotificationCompat.Builder mBuilder, Resources resources, String packageName, int notId) {
Log.d(LOG_TAG, "create actions: with in-line");
String actions = extras.getString(ACTIONS);
if (actions != null) {
try {
JSONArray actionsArray = new JSONArray(actions);
ArrayList<NotificationCompat.Action> wActions = new ArrayList<NotificationCompat.Action>();
for (int i=0; i < actionsArray.length(); i++) {
int min = 1;
int max = 2000000000;
Random random = new Random();
int uniquePendingIntentRequestCode = random.nextInt((max - min) + 1) + min;
Log.d(LOG_TAG, "adding action");
JSONObject action = actionsArray.getJSONObject(i);
Log.d(LOG_TAG, "adding callback = " + action.getString(CALLBACK));
boolean foreground = action.optBoolean(FOREGROUND, true);
boolean inline = action.optBoolean("inline", false);
Intent intent = null;
PendingIntent pIntent = null;
if (inline) {
Log.d(LOG_TAG, "Version: " + android.os.Build.VERSION.SDK_INT + " = " + android.os.Build.VERSION_CODES.M);
if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.M) {
Log.d(LOG_TAG, "push activity");
intent = new Intent(this, PushHandlerActivity.class);
} else {
Log.d(LOG_TAG, "push receiver");
intent = new Intent(this, BackgroundActionButtonHandler.class);
}
updateIntent(intent, action.getString(CALLBACK), extras, foreground, notId);
if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.M) {
Log.d(LOG_TAG, "push activity for notId " + notId);
pIntent = PendingIntent.getActivity(this, uniquePendingIntentRequestCode, intent, PendingIntent.FLAG_ONE_SHOT);
} else {
Log.d(LOG_TAG, "push receiver for notId " + notId);
pIntent = PendingIntent.getBroadcast(this, uniquePendingIntentRequestCode, intent, PendingIntent.FLAG_ONE_SHOT);
}
} else if (foreground) {
intent = new Intent(this, PushHandlerActivity.class);
updateIntent(intent, action.getString(CALLBACK), extras, foreground, notId);
pIntent = PendingIntent.getActivity(this, uniquePendingIntentRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
} else {
intent = new Intent(this, BackgroundActionButtonHandler.class);
updateIntent(intent, action.getString(CALLBACK), extras, foreground, notId);
pIntent = PendingIntent.getBroadcast(this, uniquePendingIntentRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
NotificationCompat.Action.Builder actionBuilder =
new NotificationCompat.Action.Builder(resources.getIdentifier(action.optString(ICON, ""), DRAWABLE, packageName),
action.getString(TITLE), pIntent);
RemoteInput remoteInput = null;
if (inline) {
Log.d(LOG_TAG, "create remote input");
String replyLabel = "Enter your reply here";
remoteInput =
new RemoteInput.Builder(INLINE_REPLY)
.setLabel(replyLabel)
.build();
actionBuilder.addRemoteInput(remoteInput);
}
NotificationCompat.Action wAction = actionBuilder.build();
wActions.add(actionBuilder.build());
if (inline) {
mBuilder.addAction(wAction);
} else {
mBuilder.addAction(resources.getIdentifier(action.optString(ICON, ""), DRAWABLE, packageName),
action.getString(TITLE), pIntent);
}
wAction = null;
pIntent = null;
}
mBuilder.extend(new WearableExtender().addActions(wActions));
wActions.clear();
} catch(JSONException e) {
// nope
}
}
}
private void setNotificationCount(Context context, Bundle extras, NotificationCompat.Builder mBuilder) {
int count = extractBadgeCount(extras);
if (count >= 0) {
Log.d(LOG_TAG, "count =[" + count + "]");
mBuilder.setNumber(count);
}
}
private void setVisibility(Context context, Bundle extras, NotificationCompat.Builder mBuilder) {
String visibilityStr = extras.getString(VISIBILITY);
if (visibilityStr != null) {
try {
Integer visibility = Integer.parseInt(visibilityStr);
if (visibility >= NotificationCompat.VISIBILITY_SECRET && visibility <= NotificationCompat.VISIBILITY_PUBLIC) {
mBuilder.setVisibility(visibility);
} else {
Log.e(LOG_TAG, "Visibility parameter must be between -1 and 1");
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
private void setNotificationLight(Bundle extras, Boolean lightOption, NotificationCompat.Builder mBuilder) {
if (lightOption) {
mBuilder.setDefaults(Notification.DEFAULT_LIGHTS);
}
}
private void setNotificationVibration(Bundle extras, Boolean vibrateOption, NotificationCompat.Builder mBuilder) {
String vibrationPattern = extras.getString(VIBRATION_PATTERN);
if (vibrationPattern != null) {
String[] items = vibrationPattern.replaceAll("\\[", "").replaceAll("\\]", "").split(",");
long[] results = new long[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Long.parseLong(items[i].trim());
} catch (NumberFormatException nfe) {}
}
mBuilder.setVibrate(results);
} else {
if (vibrateOption) {
mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
}
}
}
private void setNotificationMessage(int notId, Bundle extras, NotificationCompat.Builder mBuilder) {
String message = extras.getString(MESSAGE);
String style = extras.getString(STYLE, STYLE_TEXT);
if(STYLE_INBOX.equals(style)) {
setNotification(notId, message);
mBuilder.setContentText(fromHtml(message));
ArrayList<String> messageList = messageMap.get(notId);
Integer sizeList = messageList.size();
if (sizeList > 1) {
String sizeListMessage = sizeList.toString();
String stacking = sizeList + " more";
if (extras.getString(SUMMARY_TEXT) != null) {
stacking = extras.getString(SUMMARY_TEXT);
stacking = stacking.replace("%n%", sizeListMessage);
}
NotificationCompat.InboxStyle notificationInbox = new NotificationCompat.InboxStyle()
.setBigContentTitle(fromHtml(extras.getString(TITLE)))
.setSummaryText(fromHtml(stacking));
for (int i = messageList.size() - 1; i >= 0; i
notificationInbox.addLine(fromHtml(messageList.get(i)));
}
mBuilder.setStyle(notificationInbox);
} else {
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
if (message != null) {
bigText.bigText(fromHtml(message));
bigText.setBigContentTitle(fromHtml(extras.getString(TITLE)));
mBuilder.setStyle(bigText);
}
}
} else if (STYLE_PICTURE.equals(style)) {
setNotification(notId, "");
NotificationCompat.BigPictureStyle bigPicture = new NotificationCompat.BigPictureStyle();
bigPicture.bigPicture(getBitmapFromURL(extras.getString(PICTURE)));
bigPicture.setBigContentTitle(fromHtml(extras.getString(TITLE)));
bigPicture.setSummaryText(fromHtml(extras.getString(SUMMARY_TEXT)));
mBuilder.setContentTitle(fromHtml(extras.getString(TITLE)));
mBuilder.setContentText(fromHtml(message));
mBuilder.setStyle(bigPicture);
} else {
setNotification(notId, "");
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
if (message != null) {
mBuilder.setContentText(fromHtml(message));
bigText.bigText(fromHtml(message));
bigText.setBigContentTitle(fromHtml(extras.getString(TITLE)));
String summaryText = extras.getString(SUMMARY_TEXT);
if (summaryText != null) {
bigText.setSummaryText(fromHtml(summaryText));
}
mBuilder.setStyle(bigText);
}
/*
else {
mBuilder.setContentText("<missing message content>");
}
*/
}
}
/*private void setNotificationSound(Context context, Bundle extras, NotificationCompat.Builder mBuilder) {
String soundname = extras.getString(SOUNDNAME);
if (soundname == null) {
soundname = extras.getString(SOUND);
}
if (SOUND_RINGTONE.equals(soundname)) {
mBuilder.setSound(android.provider.Settings.System.DEFAULT_RINGTONE_URI);
} else if (soundname != null && !soundname.contentEquals(SOUND_DEFAULT)) {
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + context.getPackageName() + "/raw/" + soundname);
Log.d(LOG_TAG, sound.toString());
mBuilder.setSound(sound);
} else {
mBuilder.setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI);
}*/
private void setNotificationSound(String ringtonePath, NotificationCompat.Builder mBuilder) {
Uri uri = Uri.parse(ringtonePath);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), uri);
r.play();
mBuilder.setSound(null);
}
private void setNotificationLedColor(Bundle extras, NotificationCompat.Builder mBuilder) {
String ledColor = extras.getString(LED_COLOR);
if (ledColor != null) {
// Converts parse Int Array from ledColor
String[] items = ledColor.replaceAll("\\[", "").replaceAll("\\]", "").split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i].trim());
} catch (NumberFormatException nfe) {}
}
if (results.length == 4) {
mBuilder.setLights(Color.argb(results[0], results[1], results[2], results[3]), 500, 500);
} else {
Log.e(LOG_TAG, "ledColor parameter must be an array of length == 4 (ARGB)");
}
}
}
private void setNotificationPriority(Bundle extras, NotificationCompat.Builder mBuilder) {
String priorityStr = extras.getString(PRIORITY);
if (priorityStr != null) {
try {
Integer priority = Integer.parseInt(priorityStr);
if (priority >= NotificationCompat.PRIORITY_MIN && priority <= NotificationCompat.PRIORITY_MAX) {
mBuilder.setPriority(priority);
} else {
Log.e(LOG_TAG, "Priority parameter must be between -2 and 2");
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
private Bitmap getCircleBitmap(Bitmap bitmap) {
if (bitmap == null) {
return null;
}
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final int color = Color.RED;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
float cx = bitmap.getWidth()/2;
float cy = bitmap.getHeight()/2;
float radius = cx < cy ? cx : cy;
canvas.drawCircle(cx,cy,radius,paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
bitmap.recycle();
return output;
}
private void setNotificationLargeIcon(Bundle extras, String packageName, Resources resources, NotificationCompat.Builder mBuilder) {
String gcmLargeIcon = extras.getString(IMAGE); // from gcm
String imageType = extras.getString(IMAGE_TYPE, IMAGE_TYPE_SQUARE);
if (gcmLargeIcon != null && !"".equals(gcmLargeIcon)) {
if (gcmLargeIcon.startsWith("http:
Bitmap bitmap = getBitmapFromURL(gcmLargeIcon);
if (IMAGE_TYPE_SQUARE.equalsIgnoreCase(imageType)) {
mBuilder.setLargeIcon(bitmap);
} else {
Bitmap bm = getCircleBitmap(bitmap);
mBuilder.setLargeIcon(bm);
}
Log.d(LOG_TAG, "using remote large-icon from gcm");
} else {
AssetManager assetManager = getAssets();
InputStream istr;
try {
istr = assetManager.open(gcmLargeIcon);
Bitmap bitmap = BitmapFactory.decodeStream(istr);
if (IMAGE_TYPE_SQUARE.equalsIgnoreCase(imageType)) {
mBuilder.setLargeIcon(bitmap);
} else {
Bitmap bm = getCircleBitmap(bitmap);
mBuilder.setLargeIcon(bm);
}
Log.d(LOG_TAG, "using assets large-icon from gcm");
} catch (IOException e) {
int largeIconId = 0;
largeIconId = resources.getIdentifier(gcmLargeIcon, DRAWABLE, packageName);
if (largeIconId != 0) {
Bitmap largeIconBitmap = BitmapFactory.decodeResource(resources, largeIconId);
mBuilder.setLargeIcon(largeIconBitmap);
Log.d(LOG_TAG, "using resources large-icon from gcm");
} else {
Log.d(LOG_TAG, "Not setting large icon");
}
}
}
}
}
private void setNotificationSmallIcon(Context context, Bundle extras, String packageName, Resources resources, NotificationCompat.Builder mBuilder, String localIcon) {
int iconId = 0;
String icon = extras.getString(ICON);
if (icon != null && !"".equals(icon)) {
iconId = resources.getIdentifier(icon, DRAWABLE, packageName);
Log.d(LOG_TAG, "using icon from plugin options");
}
else if (localIcon != null && !"".equals(localIcon)) {
iconId = resources.getIdentifier(localIcon, DRAWABLE, packageName);
Log.d(LOG_TAG, "using icon from plugin options");
}
if (iconId == 0) {
Log.d(LOG_TAG, "no icon resource found - using application icon");
iconId = context.getApplicationInfo().icon;
}
mBuilder.setSmallIcon(iconId);
}
private void setNotificationIconColor(String color, NotificationCompat.Builder mBuilder, String localIconColor) {
int iconColor = 0;
if (color != null && !"".equals(color)) {
try {
iconColor = Color.parseColor(color);
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "couldn't parse color from android options");
}
}
else if (localIconColor != null && !"".equals(localIconColor)) {
try {
iconColor = Color.parseColor(localIconColor);
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "couldn't parse color from android options");
}
}
if (iconColor != 0) {
mBuilder.setColor(iconColor);
}
}
public Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(15000);
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static String getAppName(Context context) {
CharSequence appName = context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
return (String)appName;
}
private int parseInt(String value, Bundle extras) {
int retval = 0;
try {
retval = Integer.parseInt(extras.getString(value));
}
catch(NumberFormatException e) {
Log.e(LOG_TAG, "Number format exception - Error parsing " + value + ": " + e.getMessage());
}
catch(Exception e) {
Log.e(LOG_TAG, "Number format exception - Error parsing " + value + ": " + e.getMessage());
}
return retval;
}
private Spanned fromHtml(String source) {
if (source != null)
return Html.fromHtml(source);
else
return null;
}
private boolean isAvailableSender(String from) {
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PushPlugin.COM_ADOBE_PHONEGAP_PUSH, Context.MODE_PRIVATE);
String savedSenderID = sharedPref.getString(SENDER_ID, "");
return from.equals(savedSenderID) || from.startsWith("/topics/");
}
}
|
package com.couchbase.lite;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.util.Log;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import junit.framework.Assert;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
public class DocumentTest extends LiteTestCase {
public void testNewDocumentHasCurrentRevision() throws CouchbaseLiteException {
Document document = database.createDocument();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("foo", "foo");
properties.put("bar", Boolean.FALSE);
document.putProperties(properties);
Assert.assertNotNull(document.getCurrentRevisionId());
Assert.assertNotNull(document.getCurrentRevision());
}
public void testPutDeletedDocument() throws CouchbaseLiteException {
Document document = database.createDocument();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("foo", "foo");
properties.put("bar", Boolean.FALSE);
document.putProperties(properties);
Assert.assertNotNull(document.getCurrentRevision());
String docId = document.getId();
properties.put("_rev",document.getCurrentRevisionId());
properties.put("_deleted", true);
properties.put("mykey", "myval");
SavedRevision newRev = document.putProperties(properties);
newRev.loadProperties();
assertTrue( newRev.getProperties().containsKey("mykey") );
Assert.assertTrue(document.isDeleted());
Document fetchedDoc = database.getExistingDocument(docId);
Assert.assertNull(fetchedDoc);
// query all docs and make sure we don't see that document
database.getAllDocs(new QueryOptions());
Query queryAllDocs = database.createAllDocumentsQuery();
QueryEnumerator queryEnumerator = queryAllDocs.run();
for (Iterator<QueryRow> it = queryEnumerator; it.hasNext();) {
QueryRow row = it.next();
Assert.assertFalse(row.getDocument().getId().equals(docId));
}
}
public void testDeleteDocument() throws CouchbaseLiteException {
Document document = database.createDocument();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("foo", "foo");
properties.put("bar", Boolean.FALSE);
document.putProperties(properties);
Assert.assertNotNull(document.getCurrentRevision());
String docId = document.getId();
document.delete();
Assert.assertTrue(document.isDeleted());
Document fetchedDoc = database.getExistingDocument(docId);
Assert.assertNull(fetchedDoc);
// query all docs and make sure we don't see that document
database.getAllDocs(new QueryOptions());
Query queryAllDocs = database.createAllDocumentsQuery();
QueryEnumerator queryEnumerator = queryAllDocs.run();
for (Iterator<QueryRow> it = queryEnumerator; it.hasNext();) {
QueryRow row = it.next();
Assert.assertFalse(row.getDocument().getId().equals(docId));
}
}
public void testGetNonExistentDocument() throws CouchbaseLiteException {
assertNull(database.getExistingDocument("missing"));
Document doc = database.getDocument("missing");
assertNotNull(doc);
assertNull(database.getExistingDocument("missing"));
}
// Reproduces issue #167
public void testLoadRevisionBody() throws CouchbaseLiteException {
Document document = database.createDocument();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("foo", "foo");
properties.put("bar", Boolean.FALSE);
document.putProperties(properties);
Assert.assertNotNull(document.getCurrentRevision());
boolean deleted = false;
RevisionInternal revisionInternal = new RevisionInternal(
document.getId(),
document.getCurrentRevisionId(),
deleted
);
EnumSet<Database.TDContentOptions> contentOptions = EnumSet.of(
Database.TDContentOptions.TDIncludeAttachments,
Database.TDContentOptions.TDBigAttachmentsFollow
);
database.loadRevisionBody(revisionInternal, contentOptions);
// now lets purge the document, and then try to load the revision body again
document.purge();
boolean gotExpectedException = false;
try {
database.loadRevisionBody(revisionInternal, contentOptions);
} catch (CouchbaseLiteException e) {
if (e.getCBLStatus().getCode() == Status.NOT_FOUND) {
gotExpectedException = true;
}
}
assertTrue(gotExpectedException);
}
public void testDocumentWithRemovedProperty() {
Map<String, Object> props = new HashMap<String, Object>();
props.put("_id", "fakeid");
props.put("_removed", true);
props.put("foo", "bar");
Document doc = createDocumentWithProperties(database, props);
assertNotNull(doc);
Document docFetched = database.getDocument(doc.getId());
Map<String, Object> fetchedProps = docFetched.getCurrentRevision().getProperties();
assertNotNull(fetchedProps.get("_removed"));
assertTrue(docFetched.getCurrentRevision().isGone());
}
public void failingTestGetDocumentWithLargeJSON() {
Map<String, Object> props = new HashMap<String, Object>();
props.put("_id", "laaargeJSON");
char[] chars = new char[2500000];//~5MB
Arrays.fill(chars, 'a');
props.put("foo", new String(chars));
Document doc = createDocumentWithProperties(database, props);
assertNotNull(doc);
Document docFetched = database.getDocument(doc.getId());
Map<String, Object> fetchedProps = docFetched.getCurrentRevision().getProperties();
assertEquals(fetchedProps.get("foo"), new String(chars));
}
public void failingTestDocumentPropertiesAreImmutable() throws Exception {
String jsonString = "{\n" +
" \"name\":\"praying mantis\",\n" +
" \"wikipedia\":{\n" +
" \"behavior\":{\n" +
" \"style\":\"predatory\",\n" +
" \"attack\":\"ambush\"\n" +
" },\n" +
" \"evolution\":{\n" +
" \"ancestor\":\"proto-roaches\",\n" +
" \"cousin\":\"termite\"\n" +
" } \n" +
" } \n" +
"\n" +
"}";
Map map = (Map) Manager.getObjectMapper().readValue(jsonString, Object.class);
Document doc = createDocumentWithProperties(database, map);
boolean firstLevelImmutable = false;
Map<String, Object> props = doc.getProperties();
try {
props.put("name", "bug");
} catch (UnsupportedOperationException e) {
firstLevelImmutable = true;
}
assertTrue(firstLevelImmutable);
boolean secondLevelImmutable = false;
Map wikiProps = (Map) props.get("wikipedia");
try {
wikiProps.put("behavior", "unknown");
} catch (UnsupportedOperationException e) {
secondLevelImmutable = true;
}
assertTrue(secondLevelImmutable);
boolean thirdLevelImmutable = false;
Map evolutionProps = (Map) wikiProps.get("behavior");
try {
evolutionProps.put("movement", "flight");
} catch (UnsupportedOperationException e) {
thirdLevelImmutable = true;
}
assertTrue(thirdLevelImmutable);
}
public void failingTestProvidedMapChangesAreSafe() throws Exception {
Map<String, Object> originalProps = new HashMap<String, Object>();
Document doc = createDocumentWithProperties(database, originalProps);
Map<String, Object> nestedProps = new HashMap<String, Object>();
nestedProps.put("version", "original");
UnsavedRevision rev = doc.createRevision();
rev.getProperties().put("nested", nestedProps);
rev.save();
nestedProps.put("version", "changed");
assertEquals("original", ((Map) doc.getProperty("nested")).get("version"));
}
@JsonIgnoreProperties(ignoreUnknown = true)
static public class Foo {
private String bar;
public Foo() {
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
/**
* Assert that if you add a
* @throws Exception
*/
public void testNonPrimitiveTypesInDocument() throws Exception {
Object fooProperty;
Map<String, Object> props = new HashMap<String, Object>();
Foo foo = new Foo();
foo.setBar("basic");
props.put("foo", foo);
Document doc = createDocumentWithProperties(database, props);
fooProperty = doc.getProperties().get("foo");
assertTrue(fooProperty instanceof Map);
assertFalse(fooProperty instanceof Foo);
Document fetched = database.getDocument(doc.getId());
fooProperty = fetched.getProperties().get("foo");
assertTrue(fooProperty instanceof Map);
assertFalse(fooProperty instanceof Foo);
ObjectMapper mapper = new ObjectMapper();
Foo fooResult = mapper.convertValue(fooProperty, Foo.class);
assertEquals(foo.bar, fooResult.bar);
}
public void testDocCustomID() throws Exception {
Document document = database.getDocument("my_custom_id");
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("foo", "bar");
document.putProperties(properties);
Document documentFetched = database.getDocument("my_custom_id");
assertEquals("my_custom_id", documentFetched.getId());
assertEquals("bar", documentFetched.getProperties().get("foo"));
}
public void testGetPropertiesFromDocNotYetSaved(){
Document doc = database.createDocument();
Map<String, Object> properties = doc.getProperties();
assertNull(properties);
}
/**
* Document.update() - simple successful scenario
*/
public void testUpdate() throws Exception {
Document document = database.getDocument("testUpdate");
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("title", "testUpdate");
document.putProperties(properties);
final String title = "testUpdate - 2";
final String notes = "notes - 2";
document.update(new Document.DocumentUpdater() {
@Override
public boolean update(UnsavedRevision newRevision) {
Map<String, Object> properties = newRevision.getUserProperties();
properties.put("title", title);
properties.put("notes", notes);
newRevision.setUserProperties(properties);
return true;
}
});
Document document2 = database.getDocument("testUpdate");
assertEquals(title, document2.getProperties().get("title"));
assertEquals(notes, document2.getProperties().get("notes"));
}
/**
* Document.update() - simple scenario with failure
*/
public void testUpdateFalse() throws Exception {
Document document = database.getDocument("testUpdateFalse");
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("title", "testUpdate");
document.putProperties(properties);
final String title = "testUpdate - 2";
final String notes = "notes - 2";
document.update(new Document.DocumentUpdater() {
@Override
public boolean update(UnsavedRevision newRevision) {
Map<String, Object> properties = newRevision.getUserProperties();
properties.put("title", title);
properties.put("notes", notes);
newRevision.setUserProperties(properties);
return false;
}
});
Document document2 = database.getDocument("testUpdateFalse");
assertEquals("testUpdate", document2.getProperties().get("title"));
assertNull(document2.getProperties().get("notes"));
}
public void testUpdateConflict() throws Exception {
Document document = database.getDocument("testUpdateConflict");
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("title", "testUpdateConflict");
document.putProperties(properties);
final String title1 = "testUpdateConflict - 1";
final String text1 = "notes - 1";
final String title2 = "testUpdateConflict - 2";
final String notes2 = "notes - 2";
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
// Another thread to update document
// This thread pretends to be Pull replicator update logic
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Log.w(TAG, "Thread.run() start");
// wait till main thread finishes to create newRevision
Log.w(TAG, "Thread.run() latch1.await()");
try {
latch1.await();
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
}
Log.w(TAG, "Thread.run() exit from latch1.await()");
Document document1 = database.getDocument("testUpdateConflict");
Map<String, Object> properties1 = new HashMap<String, Object>();
properties1.put("title", title1);
properties1.put("text", text1);
try {
document1.putProperties(properties1);
} catch (CouchbaseLiteException e) {
Log.e(TAG, "[Thread.run()] " + e.getMessage());
}
Log.w(TAG, "Thread.run() latch2.countDown()");
latch2.countDown();
Log.w(TAG, "Thread.run() end");
}
});
thread.start();
// main thread to update document
document.update(new Document.DocumentUpdater() {
@Override
public boolean update(UnsavedRevision newRevision) {
Log.w(TAG, "DocumentUpdater.update() start");
// after created newRevision wait till other thread to update document.
Log.w(TAG, "DocumentUpdater.update() latch1.countDown()");
latch1.countDown();
Log.w(TAG, "DocumentUpdater.update() latch2.await()");
try {
latch2.await();
} catch (InterruptedException e) {
Log.e(TAG, "[DocumentUpdater.update()]" + e.getMessage());
}
Map<String, Object> properties2 = newRevision.getUserProperties();
properties2.put("title", title2);
properties2.put("notes", notes2);
newRevision.setUserProperties(properties2);
Log.w(TAG, "DocumentUpdater.update() end");
return true;
}
});
Document document4 = database.getDocument("testUpdateConflict");
Log.w(TAG, "" + document4.getProperties());
assertEquals(title2, document4.getProperties().get("title"));
assertEquals(notes2, document4.getProperties().get("notes"));
assertNull(notes2, document4.getProperties().get("text"));
}
}
|
package bisq.asset.coins;
import bisq.asset.Coin;
import bisq.asset.LiquidBitcoinAddressValidator;
public class TetherUSDLiquid extends Coin {
public TetherUSDLiquid() {
// If you add a new USDT variant or want to change this ticker symbol you should also look here:
// core/src/main/java/bisq/core/provider/price/PriceProvider.java:getAll()
super("Tether USD (Liquid)", "L-USDT", new LiquidBitcoinAddressValidator());
}
}
|
package soot.jimple.toolkits.pointer;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.omg.CORBA.UNKNOWN;
import soot.Local;
import soot.RefLikeType;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.CastExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.NewExpr;
import soot.jimple.ParameterRef;
import soot.jimple.Stmt;
import soot.jimple.ThisRef;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ForwardFlowAnalysis;
/** LocalMustAliasAnalysis attempts to determine if two local
* variables (at two potentially different program points) must point
* to the same object.
*
* The underlying abstraction is based on global value numbering.
*
* @author Patrick Lam
* @author Eric Bodden
* */
public class LocalMustAliasAnalysis extends ForwardFlowAnalysis<Unit,HashMap<Local,Object>>
{
public static final String UNKNOWN_LABEL = "UNKNOWN";
protected static final Object UNKNOWN = new Object() {
public String toString() { return UNKNOWN_LABEL; }
};
protected static final Object NOTHING = new Object() {
public String toString() { return "NOTHING"; }
};
protected List<Local> locals;
protected int nextNumber = 1;
public LocalMustAliasAnalysis(UnitGraph g)
{
super(g);
this.locals = new LinkedList<Local>();
for (Local l : (Collection<Local>) g.getBody().getLocals()) {
if (l.getType() instanceof RefLikeType)
this.locals.add(l);
}
doAnalysis();
}
protected void merge(HashMap<Local,Object> inMap1, HashMap<Local,Object> inMap2, HashMap<Local,Object> outMap)
{
for (Local l : locals) {
Object i1 = inMap1.get(l), i2 = inMap2.get(l);
if (i1.equals(i2))
outMap.put(l, i1);
else if (i1 == NOTHING)
outMap.put(l, i2);
else if (i2 == NOTHING)
outMap.put(l, i1);
else
outMap.put(l, UNKNOWN);
}
}
protected void flowThrough(HashMap<Local,Object> in, Unit u, HashMap<Local,Object> out) {
Stmt s = (Stmt)u;
out.clear();
out.putAll(in);
if (s instanceof DefinitionStmt) {
DefinitionStmt ds = (DefinitionStmt) s;
Value lhs = ds.getLeftOp();
Value rhs = ds.getRightOp();
if (rhs instanceof CastExpr) {
CastExpr castExpr = (CastExpr) rhs;
rhs = castExpr.getOp();
}
if (lhs instanceof Local && lhs.getType() instanceof RefLikeType) {
if (rhs instanceof Local) {
out.put((Local) lhs, in.get(rhs));
} else {
//expression could have changed, hence assign a fresh number
//(thisref and parameterref cannot actually change but whatever...)
out.put((Local) lhs, nextNumber++);
}
}
}
}
protected void copy(HashMap<Local,Object> sourceMap, HashMap<Local,Object> destMap)
{
for (Local l : (Collection<Local>) locals) {
destMap.put (l, sourceMap.get(l));
}
}
/** Initial most conservative value: has to be {@link UNKNOWN} (top). */
protected HashMap<Local,Object> entryInitialFlow()
{
HashMap<Local,Object> m = new HashMap<Local,Object>();
for (Local l : (Collection<Local>) locals) {
m.put(l, UNKNOWN);
}
return m;
}
/** Initial bottom value: objects have no definitions. */
protected HashMap<Local,Object> newInitialFlow()
{
HashMap<Local,Object> m = new HashMap<Local,Object>();
for (Local l : (Collection<Local>) locals) {
m.put(l, NOTHING);
}
return m;
}
/**
* Returns a string (natural number) representation of the instance key associated with l
* at statement s or <code>null</code> if there is no such key associated or <code>UNKNOWN</code> if
* the value of l at s is {@link #UNKNOWN}.
* @param l any local of the associated method
* @param s the statement at which to check
*/
public String instanceKeyString(Local l, Stmt s) {
Object ln = getFlowBefore(s).get(l);
if(ln==null) {
return null;
} else if(ln==UNKNOWN) {
return UNKNOWN.toString();
}
return ln.toString();
}
/**
* Returns true if this analysis has any information about local l
* at statement s (i.e. it is not {@link #UNKNOWN}).
* In particular, it is safe to pass in locals/statements that are not
* even part of the right method. In those cases <code>false</code>
* will be returned.
* Permits s to be <code>null</code>, in which case <code>false</code> will be returned.
*/
public boolean hasInfoOn(Local l, Stmt s) {
HashMap<Local,Object> flowBefore = getFlowBefore(s);
if(flowBefore==null) {
return false;
} else {
Object info = flowBefore.get(l);
return info!=null && info!=UNKNOWN;
}
}
/**
* @return true if values of l1 (at s1) and l2 (at s2) have the
* exact same object IDs, i.e. at statement s1 the variable l1 must point to the same object
* as l2 at s2.
*/
public boolean mustAlias(Local l1, Stmt s1, Local l2, Stmt s2) {
Object l1n = getFlowBefore(s1).get(l1);
Object l2n = getFlowBefore(s2).get(l2);
if (l1n == UNKNOWN || l2n == UNKNOWN)
return false;
return l1n == l2n;
}
}
|
package com.marcelherd.uebung1.model;
import static gdi.MakeItSimple.isEndOfInputFile;
import static gdi.MakeItSimple.isFilePresent;
import static gdi.MakeItSimple.isFileReadable;
import static gdi.MakeItSimple.openInputFile;
import static gdi.MakeItSimple.readLine;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import javax.activation.UnsupportedDataTypeException;
/**
* Default BTree implementation.
*
* @author Manuel Schwalm
* @author Marcel Herd
*/
public class MyBTree implements BTree {
private TreeNode root; // must be either a leaf, or have at least 2 children
private int order;
public MyBTree(int order) {
this.order = order;
this.root = new TreeNode(order);
}
/**
* {@inheritDoc}
*/
public boolean insert(Comparable o) {
if (! isEmpty()) {
if (! o.getClass().equals(root.getKeys()[0].getClass())) { // compare o's type with that of an element within the tree
if (! o.getClass().getGenericSuperclass().getTypeName().equals("java.lang.Object")) { // if o has a superclass that is not Object
if (! o.getClass().getGenericSuperclass().getTypeName().equals(root.getKeys()[0].getClass().getGenericSuperclass().getTypeName())) { // they don't share a direct superclass
return false; // o is of a different type than the existing element(s), it can not be inserted
}
}
}
}
TreeNode newNode = new TreeNode(order);
Comparable newRootKey = root.insert(o, newNode); // null if explosion was handled within the root TreeNode
if (newRootKey != null) { // explosion cascaded up to root, create new root node
TreeNode newRoot = new TreeNode(order);
newRoot.getKeys()[0] = newRootKey;
newRoot.getChildren()[0] = root;
newRoot.getChildren()[1] = newNode;
root = newRoot;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean insert(String filename) {
if (isFilePresent(filename) && isFileReadable(filename)) {
Object file = openInputFile(filename);
// read
StringBuilder sb = new StringBuilder();
while ( !isEndOfInputFile(file)) {
sb.append(readLine(file));
}
// parse
String inputData = sb.toString();
inputData = inputData.replaceAll("\\s+", ","); // normalize input
String[] inputStrings = inputData.split(","); // first string declares data type, subsequent strings are keys
if (inputStrings.length > 1) { // there are keys to insert
/*
* While it would be necessary to use reflection to fully complete the given assignment,
* it is simply not feasible. Our best bet is to implement this method for only a select few
* Comparable types.
*/
try {
Comparable[] inputValues = new Integer[inputStrings.length - 1];
for (int i = 1; i < inputStrings.length; i++) {
switch (inputStrings[0]) {
case "Integer":
inputValues[i - 1] = Integer.parseInt(inputStrings[i]);
break;
case "String":
inputValues[i - 1] = inputStrings[i];
break;
case "Double":
inputValues[i - 1] = Double.parseDouble(inputStrings[i]);
break;
case "Float":
inputValues[i - 1] = Float.parseFloat(inputStrings[i]);
break;
case "Long":
inputValues[i - 1] = Long.parseLong(inputStrings[i]);
break;
default:
throw new UnsupportedDataTypeException("Unsupported data type: " + inputStrings[0]);
}
}
for (Comparable c : inputValues) {
insert(c);
}
} catch (UnsupportedDataTypeException e) {
System.out.println(e.getMessage());
return false;
}
}
return true;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public void delete(Comparable obj) {
if (isEmpty()) return;
// 1. find node that contains obj
TreeNode target = root;
TreeNode parent = null;
while (! target.contains(obj)) {
if (target.isLeaf()) return; // element is not in tree
for (int i = 0; i < target.getKeys().length; i++) { // find subtree within node
parent = target;
if (target.getKeys()[i] == null || obj.compareTo(target.getKeys()[i]) == -1) {
target = target.getChildren()[i]; // enter left subtree
break;
}
if (obj.compareTo(target.getKeys()[i]) == 1 && i == target.getKeys().length - 1) {
target = target.getChildren()[target.getKeys().length]; // enter last subtree
break;
}
}
}
// 2. remove obj from node
if (target.isLeaf()) {
int index = target.index(obj);
target.getKeys()[index] = null; // delete element
leftShiftKeys(target, index); // shift subsequent elements to the left
if (target.size() < order) { // deficit
// 3. fix deficit
handleUnderflow(target, parent);
}
} else { // inner node
int index = target.index(obj);
parent = target;
TreeNode thatChild = target.getChildren()[index]; // subtree to the left of obj
while (! thatChild.isLeaf()) { // find the leaf that contains the next smallest element
parent = thatChild;
int treeIndex = 0;
for (int i = 1; i < thatChild.getChildren().length - 1; i++) {
if (thatChild.getChildren()[i] == null) break;
treeIndex = i;
}
thatChild = thatChild.getChildren()[treeIndex]; // until we found the leaf, always go for the subtree that is the furthest to the right
}
target.getKeys()[index] = thatChild.getMax(); // replace obj
thatChild.getKeys()[thatChild.index(thatChild.getMax())] = null; // remove replacement from leaf
leftShiftKeys(thatChild, index); // shift subsequent elements to the left
if (thatChild.size() < order) { // deficit in leaf
// 3. fix deficit
handleUnderflow(thatChild, parent);
}
}
}
/**
* Fixes underflow within node
*
* @param node - node that has a deficit
* @param parent - parent of node
*/
private void handleUnderflow(TreeNode node, TreeNode parent) {
if (parent == null) return;
int nodeIndex = 0;
for (int i = 0; i < parent.getChildren().length; i++) {
if (parent.getChildren()[i] == node) {
nodeIndex = i;
break;
}
}
TreeNode left = (nodeIndex > 0) ? parent.getChildren()[nodeIndex - 1] : null;
TreeNode right = (nodeIndex < parent.getChildren().length - 1) ? parent.getChildren()[nodeIndex + 1] : null;
if (left != null && left.size() > order) { // balance with left sibling
Comparable leftKey = left.getMax();
int leftKeyIndex = left.index(leftKey);
Comparable parentKey = parent.getKeys()[nodeIndex - 1];
int parentKeyIndex = parent.index(parentKey);
rightShiftKeys(node);
node.getKeys()[0] = parentKey;
parent.getKeys()[parentKeyIndex] = leftKey;
left.getKeys()[leftKeyIndex] = null;
} else if (right != null && right.size() > order) { // balance with right sibling
Comparable rightKey = right.getMin();
int rightKeyIndex = right.index(rightKey);
Comparable parentKey = parent.getKeys()[nodeIndex];
int parentKeyIndex = parent.index(parentKey);
node.getKeys()[node.firstAvailableIndex()] = parentKey;
parent.getKeys()[parentKeyIndex] = rightKey;
leftShiftKeys(right, rightKeyIndex);
} else {
TreeNode mergedNode = new TreeNode(order);
Comparable[] newKeys = new Comparable[2 * order];
TreeNode[] newChildren = new TreeNode[2 * order + 1];
if (left != null) { // merge with left sibling
for ( int i = 0; i < left.size(); i++) { // first, insert the keys from the left sibling
newKeys[i] = left.getKeys()[i];
}
Comparable parentKey = parent.getKeys()[nodeIndex - 1];
int parentKeyIndex = parent.index(parentKey);
newKeys[left.size()] = parentKey; // then, insert key from parent node
for (int i = 0; i < node.size(); i++) {
newKeys[i + left.size() + 1] = node.getKeys()[i]; // finally, insert the keys from this node
}
mergedNode.setKeys(newKeys);
for (int i = 0; i < left.children(); i++) {
newChildren[i] = left.getChildren()[i];
}
for (int i = 0; i < node.children(); i++) {
newChildren[i + left.children()] = node.getChildren()[i];
}
mergedNode.setChildren(newChildren);
// putting it all together
int parentIndex = parent.index(left);
parent.getChildren()[parentIndex] = mergedNode;
parent.getChildren()[parentIndex + 1] = null;
parent.getKeys()[parentKeyIndex] = null; // can cause another underflow
if (parent.size() < order) { // deficit
handleUnderflow(parent, findParent(parent, root));
}
} else { // merge with right sibling
for (int i = 0; i < node.size(); i++) {
newKeys[i] = node.getKeys()[i]; // first, insert the keys from this node
}
Comparable parentKey = parent.getKeys()[nodeIndex];
newKeys[node.size()] = parentKey; // then, insert key from parent node
for (int i = 0; i < right.size(); i++) {
newKeys[i + node.size() + 1] = right.getKeys()[i]; // finally, insert the keys from the right sibling
}
mergedNode.setKeys(newKeys);
// putting it all together
leftShiftKeys(parent, 0); // can cause another underflow
leftShiftChildren(parent);
parent.getChildren()[0] = mergedNode;
if (parent.size() < order) { // deficit
handleUnderflow(parent, findParent(parent, root));
}
}
}
}
/**
* Returns the parent of node, or null if node has no parent
*
* @param node - node, whose parent is being searched for
* @param container - node, within which the parent is being searched for
* @return the parent of node, or null if node has no parent
*/
private TreeNode findParent(TreeNode node, TreeNode container) {
if (node == root) return null;
for (TreeNode child : container.getChildren()) { // check if container is the parent of node
if (child == node) return container;
}
if (! container.isLeaf()) { // check if a child of the container is the parent of node
for (TreeNode child : container.getChildren()) {
TreeNode result = findParent(node, child);
if (result != null) return result;
}
}
return null; // could not find parent
}
/**
* Shifts all children inside the given node to the left
*
* @param node - node, whose children should be shifted to the left
*/
private void leftShiftChildren(TreeNode node) {
for (int i = 0; i < node.getChildren().length - 1; i++) {
node.getChildren()[i] = node.getChildren()[i + 1];
}
}
/**
* Shifts all keys inside the given node to the left, starting at startIndex
*
* @param node - node, whose keys are being shifted
* @param startIndex - index where the first shifted key will reside
*/
private void leftShiftKeys(TreeNode node, int startIndex) {
Comparable[] keys = node.getKeys();
for (int i = startIndex; i < keys.length - 1; i++) {
keys[i] = keys[i + 1];
}
keys[keys.length - 1] = null;
}
/**
* Shifts all keys inside node to the right
*
* @param node - node, whose keys are being shifted to the right
*/
private void rightShiftKeys(TreeNode node) {
for (int i = node.getKeys().length - 1; i > 0; i
node.getKeys()[i] = node.getKeys()[i - 1];
}
node.getKeys()[0] = null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(Comparable o) {
return contains(o, root);
}
/**
* Returns true if this tree contains the specified element.
*
* @param o - element whose presence in this tree is to be tested
* @param node - node, within which element is being searched for
* @return true if this tree contains the specified element
*/
private boolean contains(Comparable o, TreeNode node) {
if (node == null) return false;
for (int i = 0; i < node.getKeys().length; i++) { // check current node
if (node.getKeys()[i] != null && o.compareTo(node.getKeys()[i]) == 0) {
return true;
}
}
for (int i = 0; i < node.getChildren().length; i++) { // check children
if (contains(o, node.getChildren()[i])) return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return size(root);
}
/**
* Returns the number of elements in the given node.
*
* @param node - node, of which the number of elements should be computed
* @return the number of elements in the given node
*/
private int size(TreeNode node) {
int size = 0;
for (Comparable key : node.getKeys()) {
if (key != null) size++;
}
for (TreeNode child : node.getChildren()) {
if (child != null) size += size(child);
}
return size;
}
/**
* {@inheritDoc}
*/
@Override
public int height() {
int height = 1;
TreeNode child = root;
while ((child = child.getChildren()[0]) != null) height++; // all leaves are on the same level, therefore it is sufficient to check the height of any subtree
return height;
}
/**
* {@inheritDoc}
*/
@Override
public Comparable getMax() {
if (isEmpty()) return null;
TreeNode child = root;
while (! child.isLeaf()) {
for (int i = child.getChildren().length - 1; i >= 0; i--) { // find node that contains the largest keys
if (child.getChildren()[i] != null) {
child = child.getChildren()[i];
break;
}
}
}
Comparable max = null;
for (int i = child.getKeys().length - 1; i >= 0; i
max = child.getKeys()[i];
if (max != null) break;
}
return max;
}
/**
* {@inheritDoc}
*/
@Override
public Comparable getMin() {
if (isEmpty()) return null;
TreeNode child = root;
while (! child.isLeaf()) {
child = child.getChildren()[0];
}
return child.getKeys()[0];
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
return root.getKeys()[0] == null;
}
/**
* {@inheritDoc}
*/
@Override
public void addAll(BTree otherTree) {
addAll(((MyBTree) otherTree).getRoot());
}
/**
* Inserts all elements in node into this tree.
*
* @param node - the node, of which all elements should be inserted into this tree
*/
private void addAll(TreeNode node) {
if (node == null) return;
for (int i = 0; i < node.getKeys().length; i++) {
if (node.getKeys()[i] != null) insert(node.getKeys()[i]);
addAll(node.getChildren()[i]);
}
addAll(node.getChildren()[node.getChildren().length - 1]);
}
/**
* {@inheritDoc}
*/
@Override
public void printInOrder() {
printInOrder(root);
System.out.println();
}
/**
* Prints all elements in node using InOrder-Traversal.
*
* @param node - the node, of which all elements should be printed
*/
private void printInOrder(TreeNode node) {
if (node == null) return;
for (int i = 0; i < node.getKeys().length; i++) {
printInOrder(node.getChildren()[i]);
if (node.getKeys()[i] != null) System.out.print(node.getKeys()[i] + " ");
}
printInOrder(node.getChildren()[node.getChildren().length - 1]);
}
/**
* {@inheritDoc}
*/
@Override
public void printPreOrder() {
printPreOrder(root);
System.out.println();
}
/**
* Prints all elements in node using PreOrder-Traversal.
*
* @param node - the node, of which all elements should be printed
*/
private void printPreOrder(TreeNode node) {
if (node == null) return;
for (int i = 0; i < node.getKeys().length; i++) {
if (node.getKeys()[i] != null) System.out.print(node.getKeys()[i] + " ");
printPreOrder(node.getChildren()[i]);
}
printPreOrder(node.getChildren()[node.getChildren().length - 1]);
}
/**
* {@inheritDoc}
*/
@Override
public void printPostOrder() {
printPostOrder(root);
System.out.println();
}
/**
* Prints all elements in node using PostOrder-Traversal.
*
* @param node - the node, of which all elements should be printed
*/
private void printPostOrder(TreeNode node) {
if (node == null) return;
for (int i = 0; i < node.getKeys().length; i++) {
printPostOrder(node.getChildren()[i]);
}
printPostOrder(node.getChildren()[node.getChildren().length - 1]);
for (int i = 0; i < node.getKeys().length; i++) {
if (node.getKeys()[i] != null) System.out.print(node.getKeys()[i] + " ");
}
}
/**
* {@inheritDoc}
*/
@Override
public void printLevelOrder() {
if (! isEmpty()) {
Queue<Comparable> queue = new LinkedList<Comparable>();
for (Comparable key : root.getKeys()) { // root keys
if (key != null) queue.offer(key);
}
if (! root.isLeaf()) { // root has children
addKeysLevelOrder(root.getChildren(), queue);
}
while (! queue.isEmpty()) {
System.out.print(queue.poll() + " ");
}
}
}
/**
* Traverses the children in level order and appends their keys to the queue.
*
* @param children - tree nodes, that are to be traversed
* @param queue - queue, to which the keys are added
*/
private void addKeysLevelOrder(TreeNode[] children, Queue<Comparable> queue) {
for (TreeNode child : children) {
if (child != null) {
Comparable[] keys = child.getKeys();
for (Comparable key : keys) {
if (key != null) queue.add(key);
}
}
}
for (TreeNode child : children) {
if (child != null && ! child.isLeaf()) {
addKeysLevelOrder(child.getChildren(), queue);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public BTree clone() {
MyBTree newTree = new MyBTree(order);
TreeNode newTreeRoot = new TreeNode(root);
newTree.setRoot(newTreeRoot);
return newTree;
}
public TreeNode getRoot() {
return root;
}
public void setRoot(TreeNode root) {
this.root = root;
}
}
|
package com.assylias.jbloomberg;
import com.assylias.bigblue.utils.TypedObject;
import com.bloomberglp.blpapi.CorrelationID;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class EventsManagerTest {
private EventsManager em;
private CountDownLatch latch;
private final AtomicInteger countEvent = new AtomicInteger();
private volatile DataChangeEvent evt;
private CorrelationID id;
private RealtimeField field;
private String ticker;
@BeforeMethod(groups = "unit")
public void beforeMethod() {
em = new ConcurrentConflatedEventsManager();
id = new CorrelationID(0);
field = RealtimeField.ASK;
ticker = "TICKER";
}
@Test(groups = "unit")
public void testFire_FieldNotRegistered() throws Exception {
DataChangeListener lst = getDataChangeListener(1);
em.addEventListener(ticker, id, field, lst);
em.fireEvent(id, RealtimeField.ASK_ALL_SESSION, 1234);
assertFalse(latch.await(10, TimeUnit.MILLISECONDS));
}
@Test(groups = "unit")
public void testFire_Ok() throws Exception {
DataChangeListener lst = getDataChangeListener(1);
em.addEventListener(ticker, id, field, lst);
em.fireEvent(id, field, 1234);
assertTrue(latch.await(10, TimeUnit.MILLISECONDS));
assertEquals(evt.getDataName(), "ASK");
assertNull(evt.getOldValue());
assertEquals(evt.getNewValue().asInt(), 1234);
}
@Test(groups = "unit")
public void testFire_SameValueTwiceSentOnce() throws Exception {
DataChangeListener lst = getDataChangeListener(2);
em.addEventListener(ticker, id, field, lst);
em.fireEvent(id, field, 1234);
em.fireEvent(id, field, 1234);
assertFalse(latch.await(10, TimeUnit.MILLISECONDS)); //second event not sent to listener
assertEquals(evt.getDataName(), "ASK");
assertNull(evt.getOldValue());
assertEquals(evt.getNewValue().asInt(), 1234);
}
//TODO: it seems that the order of events is not preseved which could be an issue in case of two successive
//data points on the same security
//The problem is that the current setup does not allow to strongly guarantee the order and the solution is probably
//to have a single queue but that may prove to be an issue performance wise if some listeners do a lot of work with new data...
@Test(groups = "unit", enabled = false, invocationCount = 20, threadPoolSize = 2)
public void testFire_2Listeners() throws Exception {
CountDownLatch latch = new CountDownLatch(4);
String ticker = "" + new Random().nextDouble();
List<DataChangeEvent> events = new CopyOnWriteArrayList<>();
DataChangeListener lst1 = getDataChangeListener(latch, events);
DataChangeListener lst2 = getDataChangeListener(latch, events);
em.addEventListener(ticker, id, field, lst1);
em.addEventListener(ticker, id, field, lst2);
em.fireEvent(id, field, 1);
em.fireEvent(id, field, 2);
assertTrue(latch.await(500, TimeUnit.MILLISECONDS), msg(latch, events));
assertEquals(events.size(), 4);
assertEquals(events.get(0).getDataName(), "ASK");
assertNull(events.get(0).getOldValue(), msg(latch, events));
assertNotNull(events.get(3).getOldValue(), msg(latch, events));
assertEquals(events.get(3).getOldValue().asInt(), 1, msg(latch, events));
assertEquals(events.get(3).getNewValue().asInt(), 2, msg(latch, events));
}
private String msg(CountDownLatch latch, List<DataChangeEvent> e) {
return "latch.count = " + latch.getCount() + ", evt = " + String.valueOf(e);
}
@Test(groups = "unit")
public void test2Listeners2Securities() throws Exception {
latch = new CountDownLatch(2);
CorrelationID id1 = new CorrelationID(0);
CorrelationID id2 = new CorrelationID(1);
em.addEventListener("SEC 1", id1, field, new DataChangeListener() {
@Override
public void dataChanged(DataChangeEvent e) {
assertEquals(e.getSource(), "SEC 1");
assertEquals(e.getDataName(), field.toString());
assertEquals(e.getOldValue(), null);
assertEquals(e.getNewValue().asInt(), 123);
latch.countDown();
}
});
em.addEventListener("SEC 2", id2, field, new DataChangeListener() {
@Override
public void dataChanged(DataChangeEvent e) {
assertEquals(e.getSource(), "SEC 2");
assertEquals(e.getDataName(), field.toString());
assertEquals(e.getOldValue(), null);
assertEquals(e.getNewValue().asInt(), 456);
latch.countDown();
}
});
em.fireEvent(id1, field, 123);
em.fireEvent(id2, field, 456);
assertTrue(latch.await(100, TimeUnit.MILLISECONDS));
}
@Test(groups = "unit")
public void test1Listener2Securities() throws Exception {
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
CorrelationID id1 = new CorrelationID(0);
CorrelationID id2 = new CorrelationID(1);
DataChangeListener lst = new DataChangeListener() {
@Override
public void dataChanged(DataChangeEvent e) {
if (e.getSource().equals("SEC 1")
&& e.getDataName().equals(field.toString())
&& e.getOldValue() == null
&& e.getNewValue().asInt() == 123) {
latch1.countDown();
} else if (e.getSource().equals("SEC 2")
&& e.getDataName().equals(field.toString())
&& e.getOldValue() == null
&& e.getNewValue().asInt() == 456) {
latch2.countDown();
} else {
fail("Unexpected event received: " + e);
}
}
};
em.addEventListener("SEC 1", id1, field, lst);
em.addEventListener("SEC 2", id2, field, lst);
em.fireEvent(id1, field, 123);
em.fireEvent(id2, field, 456);
assertTrue(latch1.await(100, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(100, TimeUnit.MILLISECONDS));
}
@Test(groups = "unit")
public void testFire_Concurrent() throws Exception {
final int NUM_EVENTS = 10_000;
final int NUM_THREADS = 100;
final int NUM_PER_THREAD = NUM_EVENTS / NUM_THREADS;
final DataChangeEvent[] events = new DataChangeEvent[NUM_EVENTS];
latch = new CountDownLatch(NUM_EVENTS);
countEvent.set(0);
DataChangeListener lst = new DataChangeListener() {
@Override
public void dataChanged(DataChangeEvent e) {
events[countEvent.getAndIncrement()] = e;
latch.countDown();
}
};
em.addEventListener(ticker, id, field, lst);
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
final int start = i * NUM_PER_THREAD;
Runnable r = new Runnable() {
@Override
public void run() {
for (int i = start; i < start + NUM_PER_THREAD; i++) {
em.fireEvent(id, field, i);
}
}
};
executor.submit(r);
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
assertTrue(latch.await(1, TimeUnit.SECONDS), "latch at " + latch.getCount());
Set<TypedObject> newValues = new HashSet<>();
Set<TypedObject> oldValues = new HashSet<>();
for (DataChangeEvent e : events) {
assertEquals(e.getSource(), ticker);
assertEquals(e.getDataName(), "ASK");
newValues.add(e.getNewValue());
oldValues.add(e.getOldValue());
}
assertEquals(newValues.size(), NUM_EVENTS);
assertEquals(oldValues.size(), NUM_EVENTS); //including null
}
@Test(groups = "unit")
public void testFire_Performance() throws Exception {
final int NUM_EVENTS = 1_000_000;
final int NUM_THREADS = 1;
final int NUM_PER_THREAD = NUM_EVENTS / NUM_THREADS;
countEvent.set(0);
DataChangeListener lst = new DataChangeListener() {
@Override
public void dataChanged(DataChangeEvent e) {
countEvent.getAndIncrement();
}
};
em.addEventListener(ticker, id, field, lst);
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
final int start = i * NUM_PER_THREAD;
Runnable r = new Runnable() {
@Override
public void run() {
for (int i = start; i < start + NUM_PER_THREAD; i++) {
em.fireEvent(id, field, i);
}
}
};
executor.submit(r);
}
long start = System.nanoTime();
executor.shutdown();
executor.awaitTermination(60, TimeUnit.SECONDS);
long time = (System.nanoTime() - start) / 1_000_000;
}
private DataChangeListener getDataChangeListener(final int i) {
latch = new CountDownLatch(i);
countEvent.set(i);
return new DataChangeListener() {
@Override
public void dataChanged(DataChangeEvent e) {
if (countEvent.decrementAndGet() < 0) fail("latch already at 0");
evt = e;
latch.countDown();
}
};
}
private DataChangeListener getDataChangeListener(CountDownLatch latch, List<DataChangeEvent> evt) {
return e -> {
if (latch.getCount() == 0) fail("latch already at 0");
evt.add(e);
latch.countDown();
};
}
}
|
package src.model.dao.concrete;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import src.model.dao.interfaces.RecensioneDaoInterface;
import src.model.database.DB;
import src.model.*;
/**
*Class which contains all MySql queries to get review's informations from database
*/
public class RecensioneDao implements RecensioneDaoInterface{
private static final String
INSERT = "INSERT INTO recensione(testo, gioco, utente) VALUES (?, ?, ?);";
private static final String
DELETE = "DELETE FROM recensione WHERE id = ?;";
private static final String
ALL = "SELECT * FROM recensione;";
private static final String
ALL_NOT_APPROVED = "SELECT * FROM recensione WHERE approvazione = 0;";
private static final String
DELETE_ALL = "DELETE FROM gioco;";
private static final String
FIND_REVIEW = "SELECT * FROM recensione WHERE id = ?;";
private static final String
FIND_REVIEW_BY_USER_AND_GAME = "SELECT * from recensione WHERE utente = ? AND gioco = ?;";
/**
*Method to insert a review
*
*@param testo review's text
*@param gioco game reviewed
*@param utente user that makes review
*@throws SQLException if no database connection is found or another error occurs
*/
@Override
public void insertReview(String testo, Gioco gioco, Utente utente) throws SQLException{
Connection connection = DB.openConnection();
PreparedStatement ps = connection.prepareStatement(INSERT);
ps.setString(1, testo);
ps.setInt(2, gioco.getId());
ps.setInt(3, utente.getId());
ps.executeUpdate();
ps.close();
connection.close();
}
/**
*Method to delete a review
*
*@param recensione review to delete from database
*@throws SQLException if no database connection is found or another error occurs
*/
@Override
public void deleteReview(Recensione recensione) throws SQLException{
Connection connection = DB.openConnection();
PreparedStatement ps = connection.prepareStatement(DELETE);
ps.setInt(1, recensione.getId());
ps.executeUpdate();
ps.close();
connection.close();
}
/**
*Method to get all filtered reviews
*
*@param QUERY query to filter reviews
*@return ArrayList all filtered reviews
*@throws SQLException if no database connection is found or another error occurs
*/
public ArrayList<Recensione> filterReviews(String QUERY) throws SQLException{
ArrayList<Recensione> filtred_reviews = new ArrayList<>();
Connection connection = DB.openConnection();
Statement s = connection.createStatement();
ResultSet rset = s.executeQuery(QUERY);
while (rset.next()){
Recensione recensione = new Recensione(rset.getInt(1), rset.getInt(2), rset.getString(3), rset.getInt(4), rset.getInt(5));
filtred_reviews.add(recensione);
}
s.close();
rset.close();
connection.close();
return filtred_reviews;
}
/**
*Method to get all reviews
*
*@return ArrayList all reviews
*@throws SQLException if no database connection is found or another error occurs
*/
@Override
public ArrayList<Recensione> allReviews() throws SQLException{
return filterReviews(ALL);
}
/**
*Method to get all approved reviews
*
*@return ArrayList all filtered reviews
*@throws SQLException if no database connection is found or another error occurs
*/
@Override
public ArrayList<Recensione> allReviewsNotApproved() throws SQLException{
return filterReviews(ALL_NOT_APPROVED);
}
/**
*Method to delete all reviews
*
*@throws SQLException if no database connection is found or another error occurs
*/
@Override
public void deleteAllReviews() throws SQLException{
Connection connection = DB.openConnection();
Statement s = connection.createStatement();
s.executeUpdate(DELETE_ALL);
s.close();
connection.close();
}
/**
*Method to find a review thanks to its id
*
*@param id review's id
*@return Recensione searched review
*@throws SQLException if no database connection is found or another error occurs
*/
@Override
public Recensione findReviewById(int id) throws SQLException{
Recensione r;
Connection connection = DB.openConnection();
PreparedStatement ps = connection.prepareStatement(FIND_REVIEW);
ps.setInt(1, id);
ResultSet rset = ps.executeQuery();
if (rset.first() == false) return null;
r = new Recensione(rset.getInt(1), rset.getInt(2), rset.getString(3), rset.getInt(4), rset.getInt(5));
ps.close();
connection.close();
return r;
}
/**
*Method to find a review thanks to user and game
*
*@param utente user who made review
*@param gioco reviewed game
*@return Recensione searched review
*@throws SQLException if no database connection is found or another error occurs
*/
@Override
public Recensione findReviewByUserAndGame(Utente utente, Gioco gioco) throws SQLException{
Recensione r;
Connection connection = DB.openConnection();
PreparedStatement ps = connection.prepareStatement(FIND_REVIEW_BY_USER_AND_GAME);
ps.setInt(1, utente.getId());
ps.setInt(2, gioco.getId());
ResultSet rset = ps.executeQuery();
if (rset.first() == false) return null;
r = new Recensione(rset.getInt(1), rset.getInt(2), rset.getString(3), rset.getInt(4), rset.getInt(5));
ps.close();
connection.close();
return r;
}
}
|
package com.formulasearchengine.backend.basex;
import com.formulasearchengine.mathmlquerygenerator.NtcirPattern;
import com.formulasearchengine.mathmlquerygenerator.XQueryGenerator;
import net.xqj.basex.BaseXXQDataSource;
import org.w3c.dom.Document;
import javax.xml.xquery.*;
import java.util.List;
public class Client {
private Results results = new Results();
private Results.Run currentRun = results.new Run( "baseX" + System.currentTimeMillis(), "automated" );
private Results.Run.Result currentResult;
private Long measurement;
public String getXML () {
return results.toXML();
}
public String getCSV () {
return results.toCSV();
}
public Client (List<NtcirPattern> patterns) {
for ( NtcirPattern pattern : patterns ) {
processPattern( pattern );
}
results.addRun( currentRun );
}
public Client () {
}
private void processPattern (NtcirPattern pattern) {
currentResult = currentRun.new Result( pattern.getNum() );
basex( pattern.getxQueryExpression() );
currentRun.addResult( currentResult );
}
/**
* Connects with the BaseX database, sending the given query and saves the
* result in a list
*/
public Long basex (String query) {
try {
runQuery( query );
} catch ( XQException e ) {
e.printStackTrace();
return -1L;
}
return measurement;
}
private int runQuery (String query) throws XQException {
int score = 10;
int rank = 1;
XQConnection conn = getXqConnection();
XQPreparedExpression xqpe = conn.prepareExpression( query );
measurement = System.nanoTime();
XQResultSequence rs = xqpe.executeQuery();
measurement = System.nanoTime() - measurement;
currentResult.setTime( measurement );
while ( rs.next() ) {
currentResult.addHit( rs.getItemAsString( null ), "", score, rank );
rank++;
}
conn.close();
return rank
}
public String runMWSQuery (Document mwsQuery) {
XQueryGenerator generator = new XQueryGenerator( mwsQuery );
generator.setHeader( Benchmark.BASEX_HEADER );
generator.setFooter( Benchmark.BASEX_FOOTER );
return execute( generator.toString() );
}
public String execute (String query) {
currentResult = currentRun.new Result( "" );
try {
runQuery( query );
if ( currentResult.size() > 0 ) {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<results xmlns=\"http://ntcir-math.nii.ac.jp/\" total=\""+ currentResult.size() +"\">\n"
+ currentResult.toXML() + "</results>\n";
} else {
return "Query executed successful, but result set was empty.";
}
} catch ( Exception e ) {
return "Query :\n" + query + "\n\n failed " + e.getLocalizedMessage();
}
}
private static XQConnection getXqConnection () throws XQException {
XQDataSource xqs = new BaseXXQDataSource();
xqs.setProperty( "serverName", "localhost" );
xqs.setProperty( "port", "1984" );
xqs.setProperty( "databaseName", "math" );
return xqs.getConnection( "admin", "admin" );
}
}
|
package mil.nga.geopackage.test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.imageio.ImageIO;
import mil.nga.geopackage.BoundingBox;
import mil.nga.geopackage.GeoPackage;
import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.attributes.AttributesColumn;
import mil.nga.geopackage.attributes.AttributesDao;
import mil.nga.geopackage.attributes.AttributesRow;
import mil.nga.geopackage.attributes.AttributesTable;
import mil.nga.geopackage.core.contents.Contents;
import mil.nga.geopackage.core.contents.ContentsDao;
import mil.nga.geopackage.core.contents.ContentsDataType;
import mil.nga.geopackage.core.srs.SpatialReferenceSystem;
import mil.nga.geopackage.core.srs.SpatialReferenceSystemDao;
import mil.nga.geopackage.db.GeoPackageDataType;
import mil.nga.geopackage.extension.CrsWktExtension;
import mil.nga.geopackage.extension.GeometryExtensions;
import mil.nga.geopackage.extension.WebPExtension;
import mil.nga.geopackage.extension.coverage.CoverageDataPng;
import mil.nga.geopackage.extension.coverage.CoverageDataTiff;
import mil.nga.geopackage.extension.coverage.GriddedCoverage;
import mil.nga.geopackage.extension.coverage.GriddedCoverageDao;
import mil.nga.geopackage.extension.coverage.GriddedCoverageDataType;
import mil.nga.geopackage.extension.coverage.GriddedCoverageEncodingType;
import mil.nga.geopackage.extension.coverage.GriddedTile;
import mil.nga.geopackage.extension.coverage.GriddedTileDao;
import mil.nga.geopackage.extension.index.FeatureTableIndex;
import mil.nga.geopackage.features.columns.GeometryColumns;
import mil.nga.geopackage.features.columns.GeometryColumnsDao;
import mil.nga.geopackage.features.user.FeatureColumn;
import mil.nga.geopackage.features.user.FeatureDao;
import mil.nga.geopackage.features.user.FeatureRow;
import mil.nga.geopackage.features.user.FeatureTable;
import mil.nga.geopackage.geom.GeoPackageGeometryData;
import mil.nga.geopackage.io.GeoPackageIOUtils;
import mil.nga.geopackage.manager.GeoPackageManager;
import mil.nga.geopackage.metadata.Metadata;
import mil.nga.geopackage.metadata.MetadataDao;
import mil.nga.geopackage.metadata.MetadataScopeType;
import mil.nga.geopackage.metadata.reference.MetadataReference;
import mil.nga.geopackage.metadata.reference.MetadataReferenceDao;
import mil.nga.geopackage.metadata.reference.ReferenceScopeType;
import mil.nga.geopackage.projection.Projection;
import mil.nga.geopackage.projection.ProjectionConstants;
import mil.nga.geopackage.projection.ProjectionFactory;
import mil.nga.geopackage.projection.ProjectionTransform;
import mil.nga.geopackage.schema.columns.DataColumns;
import mil.nga.geopackage.schema.columns.DataColumnsDao;
import mil.nga.geopackage.schema.constraints.DataColumnConstraintType;
import mil.nga.geopackage.schema.constraints.DataColumnConstraints;
import mil.nga.geopackage.schema.constraints.DataColumnConstraintsDao;
import mil.nga.geopackage.tiles.TileBoundingBoxUtils;
import mil.nga.geopackage.tiles.TileGenerator;
import mil.nga.geopackage.tiles.TileGrid;
import mil.nga.geopackage.tiles.features.DefaultFeatureTiles;
import mil.nga.geopackage.tiles.features.FeatureTileGenerator;
import mil.nga.geopackage.tiles.features.FeatureTiles;
import mil.nga.geopackage.tiles.matrix.TileMatrix;
import mil.nga.geopackage.tiles.matrix.TileMatrixDao;
import mil.nga.geopackage.tiles.matrixset.TileMatrixSet;
import mil.nga.geopackage.tiles.matrixset.TileMatrixSetDao;
import mil.nga.geopackage.tiles.user.TileDao;
import mil.nga.geopackage.tiles.user.TileRow;
import mil.nga.geopackage.tiles.user.TileTable;
import mil.nga.geopackage.user.ContentValues;
import mil.nga.wkb.geom.CircularString;
import mil.nga.wkb.geom.CompoundCurve;
import mil.nga.wkb.geom.CurvePolygon;
import mil.nga.wkb.geom.Geometry;
import mil.nga.wkb.geom.GeometryEnvelope;
import mil.nga.wkb.geom.GeometryType;
import mil.nga.wkb.geom.LineString;
import mil.nga.wkb.geom.MultiLineString;
import mil.nga.wkb.geom.MultiPolygon;
import mil.nga.wkb.geom.Point;
import mil.nga.wkb.geom.Polygon;
import mil.nga.wkb.util.GeometryEnvelopeBuilder;
/**
* Creates an example GeoPackage file
*
* @author osbornb
*/
public class GeoPackageExample {
private static final String GEOPACKAGE_FILE = "example.gpkg";
private static final boolean FEATURES = true;
private static final boolean TILES = true;
private static final boolean ATTRIBUTES = true;
private static final boolean SCHEMA = true;
private static final boolean NON_LINEAR_GEOMETRY_TYPES = true;
private static final boolean WEBP = true;
private static final boolean CRS_WKT = true;
private static final boolean METADATA = true;
private static final boolean COVERAGE_DATA = true;
private static final boolean GEOMETRY_INDEX = true;
private static final boolean FEATURE_TILE_LINK = true;
private static final String ID_COLUMN = "id";
private static final String GEOMETRY_COLUMN = "geometry";
private static final String TEXT_COLUMN = "text";
private static final String REAL_COLUMN = "real";
private static final String BOOLEAN_COLUMN = "boolean";
private static final String BLOB_COLUMN = "blob";
private static final String INTEGER_COLUMN = "integer";
private static final String TEXT_LIMITED_COLUMN = "text_limited";
private static final String BLOB_LIMITED_COLUMN = "blob_limited";
private static final String DATE_COLUMN = "date";
private static final String DATETIME_COLUMN = "datetime";
public static void main(String[] args) throws SQLException, IOException {
System.out.println("Creating: " + GEOPACKAGE_FILE);
GeoPackage geoPackage = createGeoPackage();
System.out.println("CRS WKT Extension: " + CRS_WKT);
if (CRS_WKT) {
createCrsWktExtension(geoPackage);
}
System.out.println("Features: " + FEATURES);
if (FEATURES) {
createFeatures(geoPackage);
System.out.println("Schema Extension: " + SCHEMA);
if (SCHEMA) {
createSchemaExtension(geoPackage);
}
System.out.println("Geometry Index Extension: " + GEOMETRY_INDEX);
if (GEOMETRY_INDEX) {
createGeometryIndexExtension(geoPackage);
}
System.out.println("Feature Tile Link Extension: "
+ FEATURE_TILE_LINK);
if (FEATURE_TILE_LINK) {
createFeatureTileLinkExtension(geoPackage);
}
System.out.println("Non-Linear Geometry Types Extension: "
+ NON_LINEAR_GEOMETRY_TYPES);
if (NON_LINEAR_GEOMETRY_TYPES) {
createNonLinearGeometryTypesExtension(geoPackage);
}
} else {
System.out.println("Schema Extension: " + FEATURES);
System.out.println("Geometry Index Extension: " + FEATURES);
System.out.println("Feature Tile Link Extension: " + FEATURES);
System.out.println("Non-Linear Geometry Types Extension: "
+ FEATURES);
}
System.out.println("Tiles: " + TILES);
if (TILES) {
createTiles(geoPackage);
System.out.println("WebP Extension: " + WEBP);
if (WEBP) {
createWebPExtension(geoPackage);
}
} else {
System.out.println("WebP Extension: " + TILES);
}
System.out.println("Attributes: " + ATTRIBUTES);
if (ATTRIBUTES) {
createAttributes(geoPackage);
}
System.out.println("Metadata: " + METADATA);
if (METADATA) {
createMetadataExtension(geoPackage);
}
System.out.println("Coverage Data: " + METADATA);
if (COVERAGE_DATA) {
createCoverageDataExtension(geoPackage);
}
System.out.println("Created: " + geoPackage.getPath());
}
private static GeoPackage createGeoPackage() {
File file = new File(GEOPACKAGE_FILE);
if (file.exists()) {
file.delete();
}
GeoPackageManager.create(file);
GeoPackage geoPackage = GeoPackageManager.open(file);
return geoPackage;
}
private static void createFeatures(GeoPackage geoPackage)
throws SQLException {
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.getOrCreateCode(
ProjectionConstants.AUTHORITY_EPSG,
(long) ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
geoPackage.createGeometryColumnsTable();
Point point1 = new Point(-104.801918, 39.720014);
String point1Name = "BIT Systems";
createFeatures(geoPackage, srs, "point1", GeometryType.POINT, point1,
point1Name);
Point point2 = new Point(-77.196736, 38.753370);
String point2Name = "NGA";
createFeatures(geoPackage, srs, "point2", GeometryType.POINT, point2,
point2Name);
LineString line1 = new LineString();
String line1Name = "East Lockheed Drive";
line1.addPoint(new Point(-104.800614, 39.720721));
line1.addPoint(new Point(-104.802174, 39.720726));
line1.addPoint(new Point(-104.802584, 39.720660));
line1.addPoint(new Point(-104.803088, 39.720477));
line1.addPoint(new Point(-104.803474, 39.720209));
createFeatures(geoPackage, srs, "line1", GeometryType.LINESTRING,
line1, line1Name);
LineString line2 = new LineString();
String line2Name = "NGA";
line2.addPoint(new Point(-77.196650, 38.756501));
line2.addPoint(new Point(-77.196414, 38.755979));
line2.addPoint(new Point(-77.195518, 38.755208));
line2.addPoint(new Point(-77.195303, 38.755272));
line2.addPoint(new Point(-77.195351, 38.755459));
line2.addPoint(new Point(-77.195863, 38.755697));
line2.addPoint(new Point(-77.196328, 38.756069));
line2.addPoint(new Point(-77.196568, 38.756526));
createFeatures(geoPackage, srs, "line2", GeometryType.LINESTRING,
line2, line2Name);
Polygon polygon1 = new Polygon();
String polygon1Name = "BIT Systems";
LineString ring1 = new LineString();
ring1.addPoint(new Point(-104.802246, 39.720343));
ring1.addPoint(new Point(-104.802246, 39.719753));
ring1.addPoint(new Point(-104.802183, 39.719754));
ring1.addPoint(new Point(-104.802184, 39.719719));
ring1.addPoint(new Point(-104.802138, 39.719694));
ring1.addPoint(new Point(-104.802097, 39.719691));
ring1.addPoint(new Point(-104.802096, 39.719648));
ring1.addPoint(new Point(-104.801646, 39.719648));
ring1.addPoint(new Point(-104.801644, 39.719722));
ring1.addPoint(new Point(-104.801550, 39.719723));
ring1.addPoint(new Point(-104.801549, 39.720207));
ring1.addPoint(new Point(-104.801648, 39.720207));
ring1.addPoint(new Point(-104.801648, 39.720341));
ring1.addPoint(new Point(-104.802246, 39.720343));
polygon1.addRing(ring1);
createFeatures(geoPackage, srs, "polygon1", GeometryType.POLYGON,
polygon1, polygon1Name);
Polygon polygon2 = new Polygon();
String polygon2Name = "NGA Visitor Center";
LineString ring2 = new LineString();
ring2.addPoint(new Point(-77.195299, 38.755159));
ring2.addPoint(new Point(-77.195203, 38.755080));
ring2.addPoint(new Point(-77.195410, 38.754930));
ring2.addPoint(new Point(-77.195350, 38.754884));
ring2.addPoint(new Point(-77.195228, 38.754966));
ring2.addPoint(new Point(-77.195135, 38.754889));
ring2.addPoint(new Point(-77.195048, 38.754956));
ring2.addPoint(new Point(-77.194986, 38.754906));
ring2.addPoint(new Point(-77.194897, 38.754976));
ring2.addPoint(new Point(-77.194953, 38.755025));
ring2.addPoint(new Point(-77.194763, 38.755173));
ring2.addPoint(new Point(-77.194827, 38.755224));
ring2.addPoint(new Point(-77.195012, 38.755082));
ring2.addPoint(new Point(-77.195041, 38.755104));
ring2.addPoint(new Point(-77.195028, 38.755116));
ring2.addPoint(new Point(-77.195090, 38.755167));
ring2.addPoint(new Point(-77.195106, 38.755154));
ring2.addPoint(new Point(-77.195205, 38.755233));
ring2.addPoint(new Point(-77.195299, 38.755159));
polygon2.addRing(ring2);
createFeatures(geoPackage, srs, "polygon2", GeometryType.POLYGON,
polygon2, polygon2Name);
List<Geometry> geometries1 = new ArrayList<>();
List<String> geometries1Names = new ArrayList<>();
geometries1.add(point1);
geometries1Names.add(point1Name);
geometries1.add(line1);
geometries1Names.add(line1Name);
geometries1.add(polygon1);
geometries1Names.add(polygon1Name);
createFeatures(geoPackage, srs, "geometry1", GeometryType.GEOMETRY,
geometries1, geometries1Names);
List<Geometry> geometries2 = new ArrayList<>();
List<String> geometries2Names = new ArrayList<>();
geometries2.add(point2);
geometries2Names.add(point2Name);
geometries2.add(line2);
geometries2Names.add(line2Name);
geometries2.add(polygon2);
geometries2Names.add(polygon2Name);
createFeatures(geoPackage, srs, "geometry2", GeometryType.GEOMETRY,
geometries2, geometries2Names);
}
private static void createFeatures(GeoPackage geoPackage,
SpatialReferenceSystem srs, String tableName, GeometryType type,
Geometry geometry, String name) throws SQLException {
List<Geometry> geometries = new ArrayList<>();
geometries.add(geometry);
List<String> names = new ArrayList<>();
names.add(name);
createFeatures(geoPackage, srs, tableName, type, geometries, names);
}
private static void createFeatures(GeoPackage geoPackage,
SpatialReferenceSystem srs, String tableName, GeometryType type,
List<Geometry> geometries, List<String> names) throws SQLException {
GeometryEnvelope envelope = null;
for (Geometry geometry : geometries) {
if (envelope == null) {
envelope = GeometryEnvelopeBuilder.buildEnvelope(geometry);
} else {
GeometryEnvelopeBuilder.buildEnvelope(geometry, envelope);
}
}
ContentsDao contentsDao = geoPackage.getContentsDao();
Contents contents = new Contents();
contents.setTableName(tableName);
contents.setDataType(ContentsDataType.FEATURES);
contents.setIdentifier(tableName);
contents.setDescription("example: " + tableName);
contents.setMinX(envelope.getMinX());
contents.setMinY(envelope.getMinY());
contents.setMaxX(envelope.getMaxX());
contents.setMaxY(envelope.getMaxY());
contents.setSrs(srs);
List<FeatureColumn> columns = new ArrayList<FeatureColumn>();
int columnNumber = 0;
columns.add(FeatureColumn.createPrimaryKeyColumn(columnNumber++,
ID_COLUMN));
columns.add(FeatureColumn.createGeometryColumn(columnNumber++,
GEOMETRY_COLUMN, type, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, TEXT_COLUMN,
GeoPackageDataType.TEXT, false, ""));
columns.add(FeatureColumn.createColumn(columnNumber++, REAL_COLUMN,
GeoPackageDataType.REAL, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, BOOLEAN_COLUMN,
GeoPackageDataType.BOOLEAN, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, BLOB_COLUMN,
GeoPackageDataType.BLOB, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, INTEGER_COLUMN,
GeoPackageDataType.INTEGER, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++,
TEXT_LIMITED_COLUMN, GeoPackageDataType.TEXT, (long) UUID
.randomUUID().toString().length(), false, null));
columns.add(FeatureColumn
.createColumn(columnNumber++, BLOB_LIMITED_COLUMN,
GeoPackageDataType.BLOB, (long) UUID.randomUUID()
.toString().getBytes().length, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, DATE_COLUMN,
GeoPackageDataType.DATE, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, DATETIME_COLUMN,
GeoPackageDataType.DATETIME, false, null));
FeatureTable table = new FeatureTable(tableName, columns);
geoPackage.createFeatureTable(table);
contentsDao.create(contents);
GeometryColumnsDao geometryColumnsDao = geoPackage
.getGeometryColumnsDao();
GeometryColumns geometryColumns = new GeometryColumns();
geometryColumns.setContents(contents);
geometryColumns.setColumnName(GEOMETRY_COLUMN);
geometryColumns.setGeometryType(type);
geometryColumns.setSrs(srs);
geometryColumns.setZ((byte) 0);
geometryColumns.setM((byte) 0);
geometryColumnsDao.create(geometryColumns);
FeatureDao dao = geoPackage.getFeatureDao(geometryColumns);
for (int i = 0; i < geometries.size(); i++) {
Geometry geometry = geometries.get(i);
String name;
if (names != null) {
name = names.get(i);
} else {
name = UUID.randomUUID().toString();
}
FeatureRow newRow = dao.newRow();
GeoPackageGeometryData geometryData = new GeoPackageGeometryData(
geometryColumns.getSrsId());
geometryData.setGeometry(geometry);
newRow.setGeometry(geometryData);
newRow.setValue(TEXT_COLUMN, name);
newRow.setValue(REAL_COLUMN, Math.random() * 5000.0);
newRow.setValue(BOOLEAN_COLUMN, Math.random() < .5 ? false : true);
newRow.setValue(BLOB_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(INTEGER_COLUMN, (int) (Math.random() * 500));
newRow.setValue(TEXT_LIMITED_COLUMN, UUID.randomUUID().toString());
newRow.setValue(BLOB_LIMITED_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(DATE_COLUMN, new Date());
newRow.setValue(DATETIME_COLUMN, new Date());
dao.create(newRow);
}
}
private static void createTiles(GeoPackage geoPackage) throws IOException,
SQLException {
geoPackage.createTileMatrixSetTable();
geoPackage.createTileMatrixTable();
BoundingBox bitsBoundingBox = new BoundingBox(-11667347.997449303,
4824705.2253603265, -11666125.00499674, 4825928.217812888);
createTiles(geoPackage, "bit_systems", bitsBoundingBox, 15, 17, "png");
BoundingBox ngaBoundingBox = new BoundingBox(-8593967.964158937,
4685284.085768163, -8592744.971706374, 4687730.070673289);
createTiles(geoPackage, "nga", ngaBoundingBox, 15, 16, "png");
}
private static void createTiles(GeoPackage geoPackage, String name,
BoundingBox boundingBox, int minZoomLevel, int maxZoomLevel,
String extension) throws SQLException, IOException {
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.getOrCreateCode(
ProjectionConstants.AUTHORITY_EPSG,
(long) ProjectionConstants.EPSG_WEB_MERCATOR);
TileGrid totalTileGrid = TileBoundingBoxUtils.getTileGrid(boundingBox,
minZoomLevel);
BoundingBox totalBoundingBox = TileBoundingBoxUtils
.getWebMercatorBoundingBox(totalTileGrid, minZoomLevel);
ContentsDao contentsDao = geoPackage.getContentsDao();
Contents contents = new Contents();
contents.setTableName(name);
contents.setDataType(ContentsDataType.TILES);
contents.setIdentifier(name);
contents.setDescription(name);
contents.setMinX(totalBoundingBox.getMinLongitude());
contents.setMinY(totalBoundingBox.getMinLatitude());
contents.setMaxX(totalBoundingBox.getMaxLongitude());
contents.setMaxY(totalBoundingBox.getMaxLatitude());
contents.setSrs(srs);
TileTable tileTable = TestUtils.buildTileTable(contents.getTableName());
geoPackage.createTileTable(tileTable);
contentsDao.create(contents);
TileMatrixSetDao tileMatrixSetDao = geoPackage.getTileMatrixSetDao();
TileMatrixSet tileMatrixSet = new TileMatrixSet();
tileMatrixSet.setContents(contents);
tileMatrixSet.setSrs(contents.getSrs());
tileMatrixSet.setMinX(contents.getMinX());
tileMatrixSet.setMinY(contents.getMinY());
tileMatrixSet.setMaxX(contents.getMaxX());
tileMatrixSet.setMaxY(contents.getMaxY());
tileMatrixSetDao.create(tileMatrixSet);
TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao();
final String tilesPath = "tiles/";
for (int zoom = minZoomLevel; zoom <= maxZoomLevel; zoom++) {
final String zoomPath = tilesPath + zoom + "/";
Integer tileWidth = null;
Integer tileHeight = null;
TileGrid tileGrid = TileBoundingBoxUtils.getTileGrid(
totalBoundingBox, zoom);
TileDao dao = geoPackage.getTileDao(tileMatrixSet);
for (long x = tileGrid.getMinX(); x <= tileGrid.getMaxX(); x++) {
final String xPath = zoomPath + x + "/";
for (long y = tileGrid.getMinY(); y <= tileGrid.getMaxY(); y++) {
final String yPath = xPath + y + "." + extension;
if (TestUtils.class.getResource("/" + yPath) != null) {
File tileFile = TestUtils.getTestFile(yPath);
byte[] tileBytes = GeoPackageIOUtils
.fileBytes(tileFile);
if (tileWidth == null || tileHeight == null) {
BufferedImage tileImage = ImageIO.read(tileFile);
if (tileImage != null) {
tileHeight = tileImage.getHeight();
tileWidth = tileImage.getWidth();
}
}
TileRow newRow = dao.newRow();
newRow.setZoomLevel(zoom);
newRow.setTileColumn(x - tileGrid.getMinX());
newRow.setTileRow(y - tileGrid.getMinY());
newRow.setTileData(tileBytes);
dao.create(newRow);
}
}
}
if (tileWidth == null) {
tileWidth = 256;
}
if (tileHeight == null) {
tileHeight = 256;
}
long matrixWidth = tileGrid.getMaxX() - tileGrid.getMinX() + 1;
long matrixHeight = tileGrid.getMaxY() - tileGrid.getMinY() + 1;
double pixelXSize = (tileMatrixSet.getMaxX() - tileMatrixSet
.getMinX()) / (matrixWidth * tileWidth);
double pixelYSize = (tileMatrixSet.getMaxY() - tileMatrixSet
.getMinY()) / (matrixHeight * tileHeight);
TileMatrix tileMatrix = new TileMatrix();
tileMatrix.setContents(contents);
tileMatrix.setZoomLevel(zoom);
tileMatrix.setMatrixWidth(matrixWidth);
tileMatrix.setMatrixHeight(matrixHeight);
tileMatrix.setTileWidth(tileWidth);
tileMatrix.setTileHeight(tileHeight);
tileMatrix.setPixelXSize(pixelXSize);
tileMatrix.setPixelYSize(pixelYSize);
tileMatrixDao.create(tileMatrix);
}
}
private static void createAttributes(GeoPackage geoPackage) {
List<AttributesColumn> columns = new ArrayList<AttributesColumn>();
int columnNumber = 1;
columns.add(AttributesColumn.createColumn(columnNumber++, TEXT_COLUMN,
GeoPackageDataType.TEXT, false, ""));
columns.add(AttributesColumn.createColumn(columnNumber++, REAL_COLUMN,
GeoPackageDataType.REAL, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
BOOLEAN_COLUMN, GeoPackageDataType.BOOLEAN, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++, BLOB_COLUMN,
GeoPackageDataType.BLOB, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
INTEGER_COLUMN, GeoPackageDataType.INTEGER, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
TEXT_LIMITED_COLUMN, GeoPackageDataType.TEXT, (long) UUID
.randomUUID().toString().length(), false, null));
columns.add(AttributesColumn
.createColumn(columnNumber++, BLOB_LIMITED_COLUMN,
GeoPackageDataType.BLOB, (long) UUID.randomUUID()
.toString().getBytes().length, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++, DATE_COLUMN,
GeoPackageDataType.DATE, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
DATETIME_COLUMN, GeoPackageDataType.DATETIME, false, null));
AttributesTable attributesTable = geoPackage
.createAttributesTableWithId("attributes", columns);
AttributesDao attributesDao = geoPackage
.getAttributesDao(attributesTable.getTableName());
for (int i = 0; i < 10; i++) {
AttributesRow newRow = attributesDao.newRow();
newRow.setValue(TEXT_COLUMN, UUID.randomUUID().toString());
newRow.setValue(REAL_COLUMN, Math.random() * 5000.0);
newRow.setValue(BOOLEAN_COLUMN, Math.random() < .5 ? false : true);
newRow.setValue(BLOB_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(INTEGER_COLUMN, (int) (Math.random() * 500));
newRow.setValue(TEXT_LIMITED_COLUMN, UUID.randomUUID().toString());
newRow.setValue(BLOB_LIMITED_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(DATE_COLUMN, new Date());
newRow.setValue(DATETIME_COLUMN, new Date());
attributesDao.create(newRow);
}
}
private static void createGeometryIndexExtension(GeoPackage geoPackage) {
List<String> featureTables = geoPackage.getFeatureTables();
for (String featureTable : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(featureTable);
FeatureTableIndex featureTableIndex = new FeatureTableIndex(
geoPackage, featureDao);
featureTableIndex.index();
}
}
private static void createFeatureTileLinkExtension(GeoPackage geoPackage)
throws SQLException, IOException {
List<String> featureTables = geoPackage.getFeatureTables();
for (String featureTable : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(featureTable);
FeatureTiles featureTiles = new DefaultFeatureTiles(featureDao);
FeatureTableIndex featureIndex = new FeatureTableIndex(geoPackage,
featureDao);
featureTiles.setFeatureIndex(featureIndex);
BoundingBox boundingBox = featureDao.getBoundingBox();
Projection projection = featureDao.getProjection();
Projection requestProjection = ProjectionFactory
.getProjection(ProjectionConstants.EPSG_WEB_MERCATOR);
ProjectionTransform transform = projection
.getTransformation(requestProjection);
BoundingBox requestBoundingBox = transform.transform(boundingBox);
int zoomLevel = TileBoundingBoxUtils
.getZoomLevel(requestBoundingBox);
zoomLevel = Math.min(zoomLevel, 19);
int minZoom = zoomLevel - 2;
int maxZoom = zoomLevel + 2;
TileGenerator tileGenerator = new FeatureTileGenerator(geoPackage,
featureTable + "_tiles", featureTiles, minZoom, maxZoom,
requestBoundingBox, requestProjection);
tileGenerator.generateTiles();
}
}
private static int dataColumnConstraintIndex = 0;
private static void createSchemaExtension(GeoPackage geoPackage)
throws SQLException {
geoPackage.createDataColumnConstraintsTable();
DataColumnConstraintsDao dao = geoPackage.getDataColumnConstraintsDao();
DataColumnConstraints sampleRange = new DataColumnConstraints();
sampleRange.setConstraintName("sampleRange");
sampleRange.setConstraintType(DataColumnConstraintType.RANGE);
sampleRange.setMin(BigDecimal.ONE);
sampleRange.setMinIsInclusive(true);
sampleRange.setMax(BigDecimal.TEN);
sampleRange.setMaxIsInclusive(true);
sampleRange.setDescription("sampleRange description");
dao.create(sampleRange);
DataColumnConstraints sampleEnum1 = new DataColumnConstraints();
sampleEnum1.setConstraintName("sampleEnum");
sampleEnum1.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum1.setValue("1");
sampleEnum1.setDescription("sampleEnum description");
dao.create(sampleEnum1);
DataColumnConstraints sampleEnum3 = new DataColumnConstraints();
sampleEnum3.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum3.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum3.setValue("3");
sampleEnum3.setDescription("sampleEnum description");
dao.create(sampleEnum3);
DataColumnConstraints sampleEnum5 = new DataColumnConstraints();
sampleEnum5.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum5.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum5.setValue("5");
sampleEnum5.setDescription("sampleEnum description");
dao.create(sampleEnum5);
DataColumnConstraints sampleEnum7 = new DataColumnConstraints();
sampleEnum7.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum7.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum7.setValue("7");
sampleEnum7.setDescription("sampleEnum description");
dao.create(sampleEnum7);
DataColumnConstraints sampleEnum9 = new DataColumnConstraints();
sampleEnum9.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum9.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum9.setValue("9");
sampleEnum9.setDescription("sampleEnum description");
dao.create(sampleEnum9);
DataColumnConstraints sampleGlob = new DataColumnConstraints();
sampleGlob.setConstraintName("sampleGlob");
sampleGlob.setConstraintType(DataColumnConstraintType.GLOB);
sampleGlob.setValue("[1-2][0-9][0-9][0-9]");
sampleGlob.setDescription("sampleGlob description");
dao.create(sampleGlob);
geoPackage.createDataColumnsTable();
DataColumnsDao dataColumnsDao = geoPackage.getDataColumnsDao();
List<String> featureTables = geoPackage.getFeatureTables();
for (String featureTable : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(featureTable);
FeatureTable table = featureDao.getTable();
for (FeatureColumn column : table.getColumns()) {
if (!column.isPrimaryKey()
&& column.getDataType() == GeoPackageDataType.INTEGER) {
DataColumns dataColumns = new DataColumns();
dataColumns.setContents(featureDao.getGeometryColumns()
.getContents());
dataColumns.setColumnName(column.getName());
dataColumns.setName(featureTable);
dataColumns.setTitle("TEST_TITLE");
dataColumns.setDescription("TEST_DESCRIPTION");
dataColumns.setMimeType("TEST_MIME_TYPE");
DataColumnConstraintType constraintType = DataColumnConstraintType
.values()[dataColumnConstraintIndex];
dataColumnConstraintIndex++;
if (dataColumnConstraintIndex >= DataColumnConstraintType
.values().length) {
dataColumnConstraintIndex = 0;
}
int value = 0;
String contraintName = null;
switch (constraintType) {
case RANGE:
contraintName = sampleRange.getConstraintName();
value = 1 + (int) (Math.random() * 10);
break;
case ENUM:
contraintName = sampleEnum1.getConstraintName();
value = 1 + ((int) (Math.random() * 5) * 2);
break;
case GLOB:
contraintName = sampleGlob.getConstraintName();
value = 1000 + (int) (Math.random() * 2000);
break;
default:
throw new GeoPackageException(
"Unexpected Constraint Type: " + constraintType);
}
dataColumns.setConstraintName(contraintName);
ContentValues values = new ContentValues();
values.put(column.getName(), value);
featureDao.update(values, null, null);
dataColumnsDao.create(dataColumns);
break;
}
}
}
}
private static void createNonLinearGeometryTypesExtension(
GeoPackage geoPackage) throws SQLException {
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.getOrCreateCode(
ProjectionConstants.AUTHORITY_EPSG,
(long) ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
GeometryExtensions extensions = new GeometryExtensions(geoPackage);
String tableName = "non_linear_geometries";
List<Geometry> geometries = new ArrayList<>();
List<String> geometryNames = new ArrayList<>();
CircularString circularString = new CircularString();
circularString.addPoint(new Point(-122.358, 47.653));
circularString.addPoint(new Point(-122.348, 47.649));
circularString.addPoint(new Point(-122.348, 47.658));
circularString.addPoint(new Point(-122.358, 47.658));
circularString.addPoint(new Point(-122.358, 47.653));
for (int i = GeometryType.CIRCULARSTRING.getCode(); i <= GeometryType.SURFACE
.getCode(); i++) {
GeometryType geometryType = GeometryType.fromCode(i);
extensions.getOrCreate(tableName, GEOMETRY_COLUMN, geometryType);
Geometry geometry = null;
String name = geometryType.getName().toLowerCase();
switch (geometryType) {
case CIRCULARSTRING:
geometry = circularString;
break;
case COMPOUNDCURVE:
CompoundCurve compundCurve = new CompoundCurve();
compundCurve.addLineString(circularString);
geometry = compundCurve;
break;
case CURVEPOLYGON:
CurvePolygon<CircularString> curvePolygon = new CurvePolygon<>();
curvePolygon.addRing(circularString);
geometry = curvePolygon;
break;
case MULTICURVE:
MultiLineString multiCurve = new MultiLineString();
multiCurve.addLineString(circularString);
geometry = multiCurve;
break;
case MULTISURFACE:
MultiPolygon multiSurface = new MultiPolygon();
Polygon polygon = new Polygon();
polygon.addRing(circularString);
multiSurface.addPolygon(polygon);
geometry = multiSurface;
break;
case CURVE:
CompoundCurve curve = new CompoundCurve();
curve.addLineString(circularString);
geometry = curve;
break;
case SURFACE:
CurvePolygon<CircularString> surface = new CurvePolygon<>();
surface.addRing(circularString);
geometry = surface;
break;
default:
throw new GeoPackageException("Unexpected Geometry Type: "
+ geometryType);
}
geometries.add(geometry);
geometryNames.add(name);
}
createFeatures(geoPackage, srs, tableName, GeometryType.GEOMETRY,
geometries, geometryNames);
}
private static void createWebPExtension(GeoPackage geoPackage)
throws SQLException, IOException {
WebPExtension webpExtension = new WebPExtension(geoPackage);
String tableName = "webp_tiles";
webpExtension.getOrCreate(tableName);
geoPackage.createTileMatrixSetTable();
geoPackage.createTileMatrixTable();
BoundingBox bitsBoundingBox = new BoundingBox(-11667347.997449303,
4824705.2253603265, -11666125.00499674, 4825928.217812888);
createTiles(geoPackage, tableName, bitsBoundingBox, 15, 15, "webp");
}
private static void createCrsWktExtension(GeoPackage geoPackage)
throws SQLException {
CrsWktExtension wktExtension = new CrsWktExtension(geoPackage);
wktExtension.getOrCreate();
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.queryForOrganizationCoordsysId(
ProjectionConstants.AUTHORITY_EPSG,
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
SpatialReferenceSystem testSrs = new SpatialReferenceSystem();
testSrs.setSrsName("test");
testSrs.setSrsId(12345);
testSrs.setOrganization("test_org");
testSrs.setOrganizationCoordsysId(testSrs.getSrsId());
testSrs.setDefinition(srs.getDefinition());
testSrs.setDescription(srs.getDescription());
testSrs.setDefinition_12_063(srs.getDefinition_12_063());
srsDao.create(testSrs);
SpatialReferenceSystem testSrs2 = new SpatialReferenceSystem();
testSrs2.setSrsName("test2");
testSrs2.setSrsId(54321);
testSrs2.setOrganization("test_org");
testSrs2.setOrganizationCoordsysId(testSrs2.getSrsId());
testSrs2.setDefinition(srs.getDefinition());
testSrs2.setDescription(srs.getDescription());
srsDao.create(testSrs2);
}
private static void createMetadataExtension(GeoPackage geoPackage)
throws SQLException {
geoPackage.createMetadataTable();
MetadataDao metadataDao = geoPackage.getMetadataDao();
Metadata metadata1 = new Metadata();
metadata1.setId(1);
metadata1.setMetadataScope(MetadataScopeType.DATASET);
metadata1.setStandardUri("TEST_URI_1");
metadata1.setMimeType("text/xml");
metadata1.setMetadata("TEST METADATA 1");
metadataDao.create(metadata1);
Metadata metadata2 = new Metadata();
metadata2.setId(2);
metadata2.setMetadataScope(MetadataScopeType.FEATURE_TYPE);
metadata2.setStandardUri("TEST_URI_2");
metadata2.setMimeType("text/xml");
metadata2.setMetadata("TEST METADATA 2");
metadataDao.create(metadata2);
Metadata metadata3 = new Metadata();
metadata3.setId(3);
metadata3.setMetadataScope(MetadataScopeType.TILE);
metadata3.setStandardUri("TEST_URI_3");
metadata3.setMimeType("text/xml");
metadata3.setMetadata("TEST METADATA 3");
metadataDao.create(metadata3);
geoPackage.createMetadataReferenceTable();
MetadataReferenceDao metadataReferenceDao = geoPackage
.getMetadataReferenceDao();
MetadataReference reference1 = new MetadataReference();
reference1.setReferenceScope(ReferenceScopeType.GEOPACKAGE);
reference1.setMetadata(metadata1);
metadataReferenceDao.create(reference1);
List<String> tileTables = geoPackage.getTileTables();
if (!tileTables.isEmpty()) {
String table = tileTables.get(0);
MetadataReference reference2 = new MetadataReference();
reference2.setReferenceScope(ReferenceScopeType.TABLE);
reference2.setTableName(table);
reference2.setMetadata(metadata2);
reference2.setParentMetadata(metadata1);
metadataReferenceDao.create(reference2);
}
List<String> featureTables = geoPackage.getFeatureTables();
if (!featureTables.isEmpty()) {
String table = featureTables.get(0);
MetadataReference reference3 = new MetadataReference();
reference3.setReferenceScope(ReferenceScopeType.ROW_COL);
reference3.setTableName(table);
reference3.setColumnName(GEOMETRY_COLUMN);
reference3.setRowIdValue(1L);
reference3.setMetadata(metadata3);
metadataReferenceDao.create(reference3);
}
}
private static void createCoverageDataExtension(GeoPackage geoPackage)
throws SQLException {
createCoverageDataPngExtension(geoPackage);
createCoverageDataTiffExtension(geoPackage);
}
private static void createCoverageDataPngExtension(GeoPackage geoPackage)
throws SQLException {
BoundingBox bbox = new BoundingBox(-11667347.997449303,
4824705.2253603265, -11666125.00499674, 4825928.217812888);
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem contentsSrs = srsDao
.getOrCreateFromEpsg(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D);
SpatialReferenceSystem tileMatrixSrs = srsDao
.getOrCreateFromEpsg(ProjectionConstants.EPSG_WEB_MERCATOR);
ProjectionTransform transform = ProjectionFactory.getProjection(
ProjectionConstants.EPSG_WEB_MERCATOR).getTransformation(
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D);
BoundingBox contentsBoundingBox = transform.transform(bbox);
CoverageDataPng coverageData = CoverageDataPng
.createTileTableWithMetadata(geoPackage, "coverage_png",
contentsBoundingBox, contentsSrs.getId(), bbox,
tileMatrixSrs.getId());
TileDao tileDao = coverageData.getTileDao();
TileMatrixSet tileMatrixSet = coverageData.getTileMatrixSet();
GriddedCoverageDao griddedCoverageDao = coverageData
.getGriddedCoverageDao();
GriddedCoverage griddedCoverage = new GriddedCoverage();
griddedCoverage.setTileMatrixSet(tileMatrixSet);
griddedCoverage.setDataType(GriddedCoverageDataType.INTEGER);
griddedCoverage.setDataNull(new Double(Short.MAX_VALUE
- Short.MIN_VALUE));
griddedCoverage
.setGridCellEncodingType(GriddedCoverageEncodingType.CENTER);
griddedCoverageDao.create(griddedCoverage);
GriddedTileDao griddedTileDao = coverageData.getGriddedTileDao();
int width = 1;
int height = 1;
int tileWidth = 3;
int tileHeight = 3;
short[][] tilePixels = new short[tileHeight][tileWidth];
tilePixels[0][0] = (short) 1661.95;
tilePixels[0][1] = (short) 1665.40;
tilePixels[0][2] = (short) 1668.19;
tilePixels[1][0] = (short) 1657.18;
tilePixels[1][1] = (short) 1663.39;
tilePixels[1][2] = (short) 1669.65;
tilePixels[2][0] = (short) 1654.78;
tilePixels[2][1] = (short) 1660.31;
tilePixels[2][2] = (short) 1666.44;
byte[] imageBytes = coverageData.drawTileData(tilePixels);
TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao();
TileMatrix tileMatrix = new TileMatrix();
tileMatrix.setContents(tileMatrixSet.getContents());
tileMatrix.setMatrixHeight(height);
tileMatrix.setMatrixWidth(width);
tileMatrix.setTileHeight(tileHeight);
tileMatrix.setTileWidth(tileWidth);
tileMatrix.setPixelXSize((bbox.getMaxLongitude() - bbox
.getMinLongitude()) / width / tileWidth);
tileMatrix
.setPixelYSize((bbox.getMaxLatitude() - bbox.getMinLatitude())
/ height / tileHeight);
tileMatrix.setZoomLevel(15);
tileMatrixDao.create(tileMatrix);
TileRow tileRow = tileDao.newRow();
tileRow.setTileColumn(0);
tileRow.setTileRow(0);
tileRow.setZoomLevel(tileMatrix.getZoomLevel());
tileRow.setTileData(imageBytes);
long tileId = tileDao.create(tileRow);
GriddedTile griddedTile = new GriddedTile();
griddedTile.setContents(tileMatrixSet.getContents());
griddedTile.setTableId(tileId);
griddedTileDao.create(griddedTile);
}
private static void createCoverageDataTiffExtension(GeoPackage geoPackage)
throws SQLException {
BoundingBox bbox = new BoundingBox(-8593967.964158937,
4685284.085768163, -8592744.971706374, 4687730.070673289);
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem contentsSrs = srsDao
.getOrCreateFromEpsg(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D);
SpatialReferenceSystem tileMatrixSrs = srsDao
.getOrCreateFromEpsg(ProjectionConstants.EPSG_WEB_MERCATOR);
ProjectionTransform transform = ProjectionFactory.getProjection(
ProjectionConstants.EPSG_WEB_MERCATOR).getTransformation(
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D);
BoundingBox contentsBoundingBox = transform.transform(bbox);
CoverageDataTiff coverageData = CoverageDataTiff
.createTileTableWithMetadata(geoPackage, "coverage_tiff",
contentsBoundingBox, contentsSrs.getId(), bbox,
tileMatrixSrs.getId());
TileDao tileDao = coverageData.getTileDao();
TileMatrixSet tileMatrixSet = coverageData.getTileMatrixSet();
GriddedCoverageDao griddedCoverageDao = coverageData
.getGriddedCoverageDao();
GriddedCoverage griddedCoverage = new GriddedCoverage();
griddedCoverage.setTileMatrixSet(tileMatrixSet);
griddedCoverage.setDataType(GriddedCoverageDataType.FLOAT);
griddedCoverage.setDataNull((double) Float.MAX_VALUE);
griddedCoverage
.setGridCellEncodingType(GriddedCoverageEncodingType.CENTER);
griddedCoverageDao.create(griddedCoverage);
GriddedTileDao griddedTileDao = coverageData.getGriddedTileDao();
int width = 1;
int height = 1;
int tileWidth = 4;
int tileHeight = 4;
float[][] tilePixels = new float[tileHeight][tileWidth];
tilePixels[0][0] = 71.78f;
tilePixels[0][1] = 74.31f;
tilePixels[0][2] = 70.19f;
tilePixels[0][3] = 68.07f;
tilePixels[1][0] = 61.01f;
tilePixels[1][1] = 69.66f;
tilePixels[1][2] = 68.65f;
tilePixels[1][3] = 72.02f;
tilePixels[2][0] = 41.58f;
tilePixels[2][1] = 69.46f;
tilePixels[2][2] = 67.56f;
tilePixels[2][3] = 70.42f;
tilePixels[3][0] = 54.03f;
tilePixels[3][1] = 71.32f;
tilePixels[3][2] = 57.61f;
tilePixels[3][3] = 54.96f;
byte[] imageBytes = coverageData.drawTileData(tilePixels);
TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao();
TileMatrix tileMatrix = new TileMatrix();
tileMatrix.setContents(tileMatrixSet.getContents());
tileMatrix.setMatrixHeight(height);
tileMatrix.setMatrixWidth(width);
tileMatrix.setTileHeight(tileHeight);
tileMatrix.setTileWidth(tileWidth);
tileMatrix.setPixelXSize((bbox.getMaxLongitude() - bbox
.getMinLongitude()) / width / tileWidth);
tileMatrix
.setPixelYSize((bbox.getMaxLatitude() - bbox.getMinLatitude())
/ height / tileHeight);
tileMatrix.setZoomLevel(15);
tileMatrixDao.create(tileMatrix);
TileRow tileRow = tileDao.newRow();
tileRow.setTileColumn(0);
tileRow.setTileRow(0);
tileRow.setZoomLevel(tileMatrix.getZoomLevel());
tileRow.setTileData(imageBytes);
long tileId = tileDao.create(tileRow);
GriddedTile griddedTile = new GriddedTile();
griddedTile.setContents(tileMatrixSet.getContents());
griddedTile.setTableId(tileId);
griddedTileDao.create(griddedTile);
}
private static void createRTreeSpatialIndexExtension(GeoPackage geoPackage) {
}
}
|
package org.lwjgl;
import org.lwjgl.system.*;
import javax.annotation.*;
import java.nio.*;
import static org.lwjgl.system.CheckIntrinsics.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
/** This class is a container for architecture-independent pointer data. Its interface mirrors the {@link LongBuffer} API for convenience. */
public class PointerBuffer extends CustomBuffer<PointerBuffer> implements Comparable<PointerBuffer> {
protected PointerBuffer(long address, @Nullable ByteBuffer container, int mark, int position, int limit, int capacity) {
super(address, container, mark, position, limit, capacity);
}
public static PointerBuffer allocateDirect(int capacity) {
ByteBuffer source = BufferUtils.createByteBuffer(BufferUtils.getAllocationSize(capacity, POINTER_SHIFT));
return new PointerBuffer(memAddress(source), source, -1, 0, capacity, capacity);
}
/**
* Creates a new PointerBuffer that starts at the specified memory address and has the specified capacity.
*
* @param address the starting memory address
* @param capacity the buffer capacity, in number of pointers
*/
public static PointerBuffer create(long address, int capacity) {
return new PointerBuffer(address, null, -1, 0, capacity, capacity);
}
/**
* Creates a new PointerBuffer using the specified ByteBuffer as its pointer data source.
*
* @param source the source buffer
*/
public static PointerBuffer create(ByteBuffer source) {
int capacity = source.remaining() >> POINTER_SHIFT;
return new PointerBuffer(memAddress(source), source, -1, 0, capacity, capacity);
}
@Override
protected PointerBuffer self() {
return this;
}
@Override
public int sizeof() {
return POINTER_SIZE;
}
@Override
protected PointerBuffer newBufferInstance(long address, @Nullable ByteBuffer container, int mark, int position, int limit, int capacity) {
return new PointerBuffer(address, container, mark, position, limit, capacity);
}
/**
* Relative <i>get</i> method. Reads the pointer at this buffer's current position, and then increments the position.
*
* @return the pointer at the buffer's current position
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public long get() {
return memGetAddress(address + (nextGetIndex() << POINTER_SHIFT));
}
/**
* Convenience relative get from a source ByteBuffer.
*
* @param source the source ByteBuffer
*/
public static long get(ByteBuffer source) {
if (source.remaining() < POINTER_SIZE) {
throw new BufferUnderflowException();
}
try {
return memGetAddress(memAddress(source));
} finally {
source.position(source.position() + POINTER_SIZE);
}
}
/**
* Relative <i>put</i> method <i>(optional operation)</i>.
*
* <p>Writes the specified pointer into this buffer at the current position, and then increments the position.</p>
*
* @param p the pointer to be written
*
* @return This buffer
*
* @throws BufferOverflowException If this buffer's current position is not smaller than its limit
*/
public PointerBuffer put(long p) {
memPutAddress(address + (nextPutIndex() << POINTER_SHIFT), p);
return this;
}
/**
* Convenience relative put on a target ByteBuffer.
*
* @param target the target ByteBuffer
* @param p the pointer value to be written
*/
public static void put(ByteBuffer target, long p) {
if (target.remaining() < POINTER_SIZE) {
throw new BufferOverflowException();
}
try {
memPutAddress(memAddress(target), p);
} finally {
target.position(target.position() + POINTER_SIZE);
}
}
/**
* Absolute <i>get</i> method. Reads the pointer at the specified {@code index}.
*
* @param index the index from which the pointer will be read
*
* @return the pointer at the specified {@code index}
*
* @throws IndexOutOfBoundsException If <tt>index</tt> is negative or not smaller than the buffer's limit
*/
public long get(int index) {
return memGetAddress(address + (check(index, limit) << POINTER_SHIFT));
}
/**
* Convenience absolute get from a source ByteBuffer.
*
* @param source the source ByteBuffer
* @param index the index at which the pointer will be read
*/
public static long get(ByteBuffer source, int index) {
checkFromIndexSize(index, POINTER_SIZE, source.limit());
return memGetAddress(memAddress0(source) + index);
}
/**
* Absolute <i>put</i> method <i>(optional operation)</i>.
*
* <p>Writes the specified pointer into this buffer at the specified {@code index}.</p>
*
* @param index the index at which the pointer will be written
* @param p the pointer value to be written
*
* @return This buffer
*
* @throws IndexOutOfBoundsException If <tt>index</tt> is negative or not smaller than the buffer's limit
*/
public PointerBuffer put(int index, long p) {
memPutAddress(address + (check(index, limit) << POINTER_SHIFT), p);
return this;
}
/**
* Convenience absolute put on a target ByteBuffer.
*
* @param target the target ByteBuffer
* @param index the index at which the pointer will be written
* @param p the pointer value to be written
*/
public static void put(ByteBuffer target, int index, long p) {
checkFromIndexSize(index, POINTER_SIZE, target.limit());
memPutAddress(memAddress0(target) + index, p);
}
// -- PointerWrapper operations --
/** Puts the pointer value of the specified {@link Pointer} at the current position and then increments the position. */
public PointerBuffer put(Pointer pointer) {
put(pointer.address());
return this;
}
/** Puts the pointer value of the specified {@link Pointer} at the specified {@code index}. */
public PointerBuffer put(int index, Pointer pointer) {
put(index, pointer.address());
return this;
}
// -- Buffer address operations --
/**
* <p>Writes the address of the specified {@code buffer} into this buffer at the current position, and then increments the position.</p>
*
* @param buffer the pointer to be written
*
* @return this buffer
*
* @throws BufferOverflowException If this buffer's current position is not smaller than its limit
*/
public PointerBuffer put(ByteBuffer buffer) {
put(memAddress(buffer));
return this;
}
/**
* <p>Writes the address of the specified {@code buffer} into this buffer at the current position, and then increments the position.</p>
*
* @param buffer the pointer to be written
*
* @return this buffer
*
* @throws BufferOverflowException If this buffer's current position is not smaller than its limit
*/
public PointerBuffer put(ShortBuffer buffer) {
put(memAddress(buffer));
return this;
}
/**
* <p>Writes the address of the specified {@code buffer} into this buffer at the current position, and then increments the position.</p>
*
* @param buffer the pointer to be written
*
* @return this buffer
*
* @throws BufferOverflowException If this buffer's current position is not smaller than its limit
*/
public PointerBuffer put(IntBuffer buffer) {
put(memAddress(buffer));
return this;
}
/**
* <p>Writes the address of the specified {@code buffer} into this buffer at the current position, and then increments the position.</p>
*
* @param buffer the pointer to be written
*
* @return this buffer
*
* @throws BufferOverflowException If this buffer's current position is not smaller than its limit
*/
public PointerBuffer put(LongBuffer buffer) {
put(memAddress(buffer));
return this;
}
/**
* <p>Writes the address of the specified {@code buffer} into this buffer at the current position, and then increments the position.</p>
*
* @param buffer the pointer to be written
*
* @return this buffer
*
* @throws BufferOverflowException If this buffer's current position is not smaller than its limit
*/
public PointerBuffer put(FloatBuffer buffer) {
put(memAddress(buffer));
return this;
}
/**
* <p>Writes the address of the specified {@code buffer} into this buffer at the current position, and then increments the position.</p>
*
* @param buffer the pointer to be written
*
* @return this buffer
*
* @throws BufferOverflowException If this buffer's current position is not smaller than its limit
*/
public PointerBuffer put(DoubleBuffer buffer) {
put(memAddress(buffer));
return this;
}
/**
* <p>Writes the address of the specified {@code buffer} into this buffer at the current position, and then increments the position.</p>
*
* @param buffer the pointer to be written
*
* @return this buffer
*
* @throws BufferOverflowException If this buffer's current position is not smaller than its limit
*/
public PointerBuffer putAddressOf(CustomBuffer buffer) {
put(memAddress(buffer));
return this;
}
/** Puts the address of the specified {@code buffer} at the specified {@code index}. */
public PointerBuffer put(int index, ByteBuffer buffer) {
put(index, memAddress(buffer));
return this;
}
/** Puts the address of the specified {@code buffer} at the specified {@code index}. */
public PointerBuffer put(int index, ShortBuffer buffer) {
put(index, memAddress(buffer));
return this;
}
/** Puts the address of the specified {@code buffer} at the specified {@code index}. */
public PointerBuffer put(int index, IntBuffer buffer) {
put(index, memAddress(buffer));
return this;
}
/** Puts the address of the specified {@code buffer} at the specified {@code index}. */
public PointerBuffer put(int index, LongBuffer buffer) {
put(index, memAddress(buffer));
return this;
}
/** Puts the address of the specified {@code buffer} at the specified {@code index}. */
public PointerBuffer put(int index, FloatBuffer buffer) {
put(index, memAddress(buffer));
return this;
}
/** Puts the address of the specified {@code buffer} at the specified {@code index}. */
public PointerBuffer put(int index, DoubleBuffer buffer) {
put(index, memAddress(buffer));
return this;
}
/** Puts the address of the specified {@code buffer} at the specified {@code index}. */
public PointerBuffer putAddressOf(int index, CustomBuffer buffer) {
put(index, memAddress(buffer));
return this;
}
/**
* Reads the pointer at this buffer's current position, and then increments the position. The pointer is returned as a {@link ByteBuffer} instance that
* starts at the pointer address and has capacity equal to the specified {@code size}.
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public ByteBuffer getByteBuffer(int size) { return memByteBuffer(get(), size); }
/**
* Reads the pointer at this buffer's current position, and then increments the position. The pointer is returned as a {@link ShortBuffer} instance that
* starts at the pointer address and has capacity equal to the specified {@code size}.
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public ShortBuffer getShortBuffer(int size) { return memShortBuffer(get(), size); }
/**
* Reads the pointer at this buffer's current position, and then increments the position. The pointer is returned as a {@link IntBuffer} instance that
* starts at the pointer address and has capacity equal to the specified {@code size}.
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public IntBuffer getIntBuffer(int size) { return memIntBuffer(get(), size); }
/**
* Reads the pointer at this buffer's current position, and then increments the position. The pointer is returned as a {@link LongBuffer} instance that
* starts at the pointer address and has capacity equal to the specified {@code size}.
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public LongBuffer getLongBuffer(int size) { return memLongBuffer(get(), size); }
/**
* Reads the pointer at this buffer's current position, and then increments the position. The pointer is returned as a {@link FloatBuffer} instance that
* starts at the pointer address and has capacity equal to the specified {@code size}.
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public FloatBuffer getFloatBuffer(int size) { return memFloatBuffer(get(), size); }
/**
* Reads the pointer at this buffer's current position, and then increments the position. The pointer is returned as a {@link DoubleBuffer} instance that
* starts at the pointer address and has capacity equal to the specified {@code size}.
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public DoubleBuffer getDoubleBuffer(int size) { return memDoubleBuffer(get(), size); }
/**
* Reads the pointer at this buffer's current position, and then increments the position. The pointer is returned as a {@link PointerBuffer} instance that
* starts at the pointer address and has capacity equal to the specified {@code size}.
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public PointerBuffer getPointerBuffer(int size) { return memPointerBuffer(get(), size); }
/**
* Reads the pointer at this buffer's current position, and then increments the position. The pointer is evaluated as a null-terminated ASCII string, which
* is decoded and returned as a {@link String} instance.
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public String getStringASCII() { return memASCII(get()); }
/**
* Reads the pointer at this buffer's current position, and then increments the position. The pointer is evaluated as a null-terminated UTF-8 string, which
* is decoded and returned as a {@link String} instance.
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public String getStringUTF8() { return memUTF8(get()); }
/**
* Reads the pointer at this buffer's current position, and then increments the position. The pointer is evaluated as a null-terminated UTF-16 string,
* which is decoded and returned as a {@link String} instance.
*
* @throws BufferUnderflowException If the buffer's current position is not smaller than its limit
*/
public String getStringUTF16() { return memUTF16(get()); }
/** Returns a {@link ByteBuffer} instance that starts at the address found at the specified {@code index} and has capacity equal to the specified size. */
public ByteBuffer getByteBuffer(int index, int size) { return memByteBuffer(get(index), size); }
/** Returns a {@link ShortBuffer} instance that starts at the address found at the specified {@code index} and has capacity equal to the specified size. */
public ShortBuffer getShortBuffer(int index, int size) { return memShortBuffer(get(index), size); }
/** Returns a {@link IntBuffer} instance that starts at the address found at the specified {@code index} and has capacity equal to the specified size. */
public IntBuffer getIntBuffer(int index, int size) { return memIntBuffer(get(index), size); }
/** Returns a {@link LongBuffer} instance that starts at the address found at the specified {@code index} and has capacity equal to the specified size. */
public LongBuffer getLongBuffer(int index, int size) { return memLongBuffer(get(index), size); }
/** Returns a {@link FloatBuffer} instance that starts at the address found at the specified {@code index} and has capacity equal to the specified size. */
public FloatBuffer getFloatBuffer(int index, int size) { return memFloatBuffer(get(index), size); }
/** Returns a {@link DoubleBuffer} instance that starts at the address found at the specified {@code index} and has capacity equal to the specified size. */
public DoubleBuffer getDoubleBuffer(int index, int size) { return memDoubleBuffer(get(index), size); }
/** Returns a {@link PointerBuffer} instance that starts at the address found at the specified {@code index} and has capacity equal to the specified size. */
public PointerBuffer getPointerBuffer(int index, int size) { return memPointerBuffer(get(index), size); }
/** Decodes the ASCII string that starts at the address found at the specified {@code index}. */
public String getStringASCII(int index) { return memASCII(get(index)); }
/** Decodes the UTF-8 string that starts at the address found at the specified {@code index}. */
public String getStringUTF8(int index) { return memUTF8(get(index)); }
/** Decodes the UTF-16 string that starts at the address found at the specified {@code index}. */
public String getStringUTF16(int index) { return memUTF16(get(index)); }
// -- Bulk get operations --
/**
* Relative bulk <i>get</i> method.
*
* <p>This method transfers pointers from this buffer into the specified destination array. An invocation of this method of the form <tt>src.get(a)</tt>
* behaves in exactly the same way as the invocation
*
* <pre>
* src.get(a, 0, a.length) </pre>
*
* @return This buffer
*
* @throws BufferUnderflowException If there are fewer than <tt>length</tt> pointers remaining in this buffer
*/
public PointerBuffer get(long[] dst) {
return get(dst, 0, dst.length);
}
/**
* Relative bulk <i>get</i> method.
*
* <p>This method transfers pointers from this buffer into the specified destination array. If there are fewer pointers remaining in the buffer than are
* required to satisfy the request, that is, if <tt>length</tt> <tt>></tt> <tt>remaining()</tt>, then no pointers are transferred and a
* {@link BufferUnderflowException} is thrown.
*
* <p>Otherwise, this method copies <tt>length</tt> pointers from this buffer into the specified array, starting at the current position of this buffer and
* at the specified offset in the array. The position of this buffer is then incremented by <tt>length</tt>.
*
* <p>In other words, an invocation of this method of the form <tt>src.get(dst, off, len)</tt> has exactly the same effect as the loop</p>
*
* <pre>
* for (int i = off; i < off + len; i++)
* dst[i] = src.get(); </pre>
*
* <p>except that it first checks that there are sufficient pointers in this buffer and it is potentially much more efficient. </p>
*
* @param dst the array into which pointers are to be written
* @param offset the offset within the array of the first pointer to be written; must be non-negative and no larger than <tt>dst.length</tt>
* @param length the maximum number of pointers to be written to the specified array; must be non-negative and no larger than <tt>dst.length - offset</tt>
*
* @return This buffer
*
* @throws BufferUnderflowException If there are fewer than <tt>length</tt> pointers remaining in this buffer
* @throws IndexOutOfBoundsException If the preconditions on the <tt>offset</tt> and <tt>length</tt> parameters do not hold
*/
public PointerBuffer get(long[] dst, int offset, int length) {
if (BITS64) {
memLongBuffer(address(), remaining()).get(dst, offset, length);
position(position() + length);
} else {
get32(dst, offset, length);
}
return this;
}
private void get32(long[] dst, int offset, int length) {
checkFromIndexSize(offset, length, dst.length);
if (remaining() < length) {
throw new BufferUnderflowException();
}
for (int i = offset, end = offset + length; i < end; i++) {
dst[i] = get();
}
}
/**
* Relative bulk <i>put</i> method <i>(optional operation)</i>.
*
* <p>This method transfers the entire content of the specified source pointer array into this buffer. An invocation of this method of the form
* <tt>dst.put(a)</tt> behaves in exactly the same way as the invocation</p>
*
* <pre>
* dst.put(a, 0, a.length) </pre>
*
* @return This buffer
*
* @throws BufferOverflowException If there is insufficient space in this buffer
*/
public PointerBuffer put(long[] src) {
return put(src, 0, src.length);
}
/**
* Relative bulk <i>put</i> method <i>(optional operation)</i>.
*
* <p>This method transfers pointers into this buffer from the specified source array. If there are more pointers to be copied from the array than remain
* in this buffer, that is, if <tt>length</tt> <tt>></tt> <tt>remaining()</tt>, then no pointers are transferred and a
* {@link BufferOverflowException} is thrown.
*
* <p>Otherwise, this method copies <tt>length</tt> pointers from the specified array into this buffer, starting at the specified offset in the array and
* at the current position of this buffer. The position of this buffer is then incremented by <tt>length</tt>.</p>
*
* <p>In other words, an invocation of this method of the form <tt>dst.put(src, off, len)</tt> has exactly the same effect as the loop</p>
*
* <pre>
* for (int i = off; i < off + len; i++)
* dst.put(a[i]); </pre>
*
* <p>except that it first checks that there is sufficient space in this buffer and it is potentially much more efficient.</p>
*
* @param src the array from which pointers are to be read
* @param offset the offset within the array of the first pointer to be read; must be non-negative and no larger than <tt>array.length</tt>
* @param length the number of pointers to be read from the specified array; must be non-negative and no larger than <tt>array.length - offset</tt>
*
* @return This buffer
*
* @throws BufferOverflowException If there is insufficient space in this buffer
* @throws IndexOutOfBoundsException If the preconditions on the <tt>offset</tt> and <tt>length</tt> parameters do not hold
*/
public PointerBuffer put(long[] src, int offset, int length) {
if (BITS64) {
memLongBuffer(address(), remaining()).put(src, offset, length);
position(position() + length);
} else {
put32(src, offset, length);
}
return this;
}
private void put32(long[] src, int offset, int length) {
checkFromIndexSize(offset, length, src.length);
if (remaining() < length) {
throw new BufferOverflowException();
}
int end = offset + length;
for (int i = offset; i < end; i++) {
put(src[i]);
}
}
/**
* Returns the current hash code of this buffer.
*
* <p>The hash code of a pointer buffer depends only upon its remaining elements; that is, upon the elements from <tt>position()</tt> up to, and including,
* the element at <tt>limit()</tt> - <tt>1</tt>.</p>
*
* <p>Because buffer hash codes are content-dependent, it is inadvisable to use buffers as keys in hash maps or similar data structures unless it is known
* that their contents will not change.</p>
*
* @return the current hash code of this buffer
*/
public int hashCode() {
int h = 1;
int p = position();
for (int i = limit() - 1; i >= p; i
h = 31 * h + (int)get(i);
}
return h;
}
/**
* Tells whether or not this buffer is equal to another object.
*
* <p>Two pointer buffers are equal if, and only if,</p>
*
* <ol>
* <li>They have the same element type,</li>
* <li>They have the same number of remaining elements, and</li>
* <li>The two sequences of remaining elements, considered
* independently of their starting positions, are pointwise equal.</li>
* </ol>
*
* <p>A pointer buffer is not equal to any other type of object.</p>
*
* @param ob the object to which this buffer is to be compared
*
* @return <tt>true</tt> if, and only if, this buffer is equal to the
* given object
*/
public boolean equals(Object ob) {
if (!(ob instanceof PointerBuffer)) {
return false;
}
PointerBuffer that = (PointerBuffer)ob;
if (this.remaining() != that.remaining()) {
return false;
}
int p = this.position();
for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i
long v1 = this.get(i);
long v2 = that.get(j);
if (v1 != v2) {
return false;
}
}
return true;
}
/**
* Compares this buffer to another.
*
* <p>Two pointer buffers are compared by comparing their sequences of remaining elements lexicographically, without regard to the starting position of
* each sequence within its corresponding buffer.</p>
*
* <p>A pointer buffer is not comparable to any other type of object.</p>
*
* @return A negative integer, zero, or a positive integer as this buffer is less than, equal to, or greater than the specified buffer
*/
@Override
public int compareTo(PointerBuffer that) {
int n = this.position() + Math.min(this.remaining(), that.remaining());
for (int i = this.position(), j = that.position(); i < n; i++, j++) {
long v1 = this.get(i);
long v2 = that.get(j);
if (v1 == v2) {
continue;
}
if (v1 < v2) {
return -1;
}
return +1;
}
return this.remaining() - that.remaining();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.