input
stringlengths 20
285k
| output
stringlengths 20
285k
|
---|---|
public void onMatch(RelOptRuleCall call)
{
JoinRel joinRel = (JoinRel) call.rels[0];
RelNode leftRel = joinRel.getLeft();
RelNode rightRel = joinRel.getRight();
boolean joinTypeFeasible =
(joinRel.getJoinType() == JoinRelType.INNER) ||
(joinRel.getJoinType() == JoinRelType.LEFT);
boolean joinConditionFeasible =
joinRel.getCondition().equals(
joinRel.getCluster().getRexBuilder().makeLiteral(true));
if (!joinTypeFeasible || !joinConditionFeasible) {
return;
}
if (!joinRel.getVariablesStopped().isEmpty()) {
return;
}
boolean swapped = false;
FennelBufferRel bufRel =
bufferRight(leftRel, rightRel, joinRel.getTraits());
if (bufRel != null) {
rightRel = bufRel;
} else {
bufRel = bufferRight(rightRel, leftRel, joinRel.getTraits());
if (bufRel != null) {
swapped = true;
leftRel = rightRel;
rightRel = bufRel;
}
}
RelNode fennelLeft =
mergeTraitsAndConvert(
joinRel.getTraits(),
FennelRel.FENNEL_EXEC_CONVENTION,
leftRel);
if (fennelLeft == null) {
return;
}
RelNode fennelRight =
mergeTraitsAndConvert(
joinRel.getTraits(),
FennelRel.FENNEL_EXEC_CONVENTION,
rightRel);
if (fennelRight == null) {
return;
}
FennelCartesianProductRel productRel =
new FennelCartesianProductRel(
joinRel.getCluster(),
fennelLeft,
fennelRight,
joinRel.getJoinType(),
RelOptUtil.getFieldNameList(joinRel.getRowType()));
RelNode newRel;
if (swapped) {
final RexNode [] exps =
RelOptUtil.createSwappedJoinExprs(
productRel,
joinRel,
true);
final RexProgram program =
RexProgram.create(
productRel.getRowType(),
exps,
null,
joinRel.getRowType(),
productRel.getCluster().getRexBuilder());
newRel =
new CalcRel(
productRel.getCluster(),
RelOptUtil.clone(joinRel.getTraits()),
productRel,
joinRel.getRowType(),
program,
RelCollation.emptyList);
} else {
newRel = productRel;
}
call.transformTo(newRel);
}
| public void onMatch(RelOptRuleCall call)
{
JoinRel joinRel = (JoinRel) call.rels[0];
RelNode leftRel = joinRel.getLeft();
RelNode rightRel = joinRel.getRight();
JoinRelType joinType = joinRel.getJoinType();
boolean joinTypeFeasible = !(joinType == JoinRelType.FULL);
boolean swapped = false;
if (joinType == JoinRelType.RIGHT) {
swapped = true;
RelNode tmp = leftRel;
leftRel = rightRel;
rightRel = tmp;
joinType = JoinRelType.LEFT;
}
boolean joinConditionFeasible =
joinRel.getCondition().equals(
joinRel.getCluster().getRexBuilder().makeLiteral(true));
if (!joinTypeFeasible || !joinConditionFeasible) {
return;
}
if (!joinRel.getVariablesStopped().isEmpty()) {
return;
}
FennelBufferRel bufRel =
bufferRight(leftRel, rightRel, joinRel.getTraits());
if (bufRel != null) {
rightRel = bufRel;
} else if (!swapped) {
bufRel = bufferRight(rightRel, leftRel, joinRel.getTraits());
if (bufRel != null) {
swapped = true;
leftRel = rightRel;
rightRel = bufRel;
}
}
RelNode fennelLeft =
mergeTraitsAndConvert(
joinRel.getTraits(),
FennelRel.FENNEL_EXEC_CONVENTION,
leftRel);
if (fennelLeft == null) {
return;
}
RelNode fennelRight =
mergeTraitsAndConvert(
joinRel.getTraits(),
FennelRel.FENNEL_EXEC_CONVENTION,
rightRel);
if (fennelRight == null) {
return;
}
FennelCartesianProductRel productRel =
new FennelCartesianProductRel(
joinRel.getCluster(),
fennelLeft,
fennelRight,
joinType,
RelOptUtil.getFieldNameList(joinRel.getRowType()));
RelNode newRel;
if (swapped) {
final RexNode [] exps =
RelOptUtil.createSwappedJoinExprs(
productRel,
joinRel,
true);
final RexProgram program =
RexProgram.create(
productRel.getRowType(),
exps,
null,
joinRel.getRowType(),
productRel.getCluster().getRexBuilder());
newRel =
new CalcRel(
productRel.getCluster(),
RelOptUtil.clone(joinRel.getTraits()),
productRel,
joinRel.getRowType(),
program,
RelCollation.emptyList);
} else {
newRel = productRel;
}
call.transformTo(newRel);
}
|
private void install_tables(RandomAccessFile out, List<String> list) {
System.out.print("Trying to add data_install tables...");
try {
BufferedReader in = new BufferedReader(new FileReader("data_install.txt"));
out.seek(out.length());
String line;
Vector<Integer> patch_files = new Vector<Integer>();
Vector<String> install_files = new Vector<String>();
Vector<String> offsets = new Vector<String>();
while((line = in.readLine()) != null) {
if(!line.startsWith("#")) {
String []tokens = line.split(",");
patch_files.add(Integer.parseInt(tokens[0]));
install_files.add(tokens[1]);
offsets.add(tokens[2]);
}
}
Vector<String> install_uniq = new Vector<String>(new LinkedHashSet<String>(install_files));
writeInt(out, install_uniq.size());
int install_count = 0;
String match = install_files.firstElement();
out.write(match.getBytes());
writeInt(out, install_count);
for(String file : install_files) {
if(!match.equals(file)) {
out.write(file.getBytes());
match = file;
writeInt(out, install_count);
}
install_count++;
}
for(String trans_file : list) {
int index = patch_files.indexOf(extractNumber(trans_file));
int offset = -1;
if(index != -1) {
offset = (int)Long.parseLong(offsets.get(index),16);
} else {
System.out.println("Install info not found for " + trans_file);
}
writeInt(out, offset);
}
long filelength = out.length();
if(filelength % 16 > 0) {
filelength += 16 - (filelength % 16);
out.setLength(filelength);
}
System.out.println("OK");
} catch (FileNotFoundException e) {
System.out.println("\ndata_install.txt not found");
} catch (IOException e) {
e.printStackTrace();
}
}
| private void install_tables(RandomAccessFile out, List<String> list) {
System.out.print("Trying to add data_install tables...");
try {
BufferedReader in = new BufferedReader(new FileReader("data_install.txt"));
out.seek(out.length());
String line;
Vector<Integer> patch_files = new Vector<Integer>();
Vector<String> install_files = new Vector<String>();
Vector<String> offsets = new Vector<String>();
while((line = in.readLine()) != null) {
if(!line.startsWith("#")) {
String []tokens = line.split(",");
patch_files.add(Integer.parseInt(tokens[0]));
install_files.add(tokens[1]);
offsets.add(tokens[2]);
}
}
Vector<String> install_uniq = new Vector<String>(new LinkedHashSet<String>(install_files));
while(install_uniq.remove("NONE"));
writeInt(out, install_uniq.size());
int install_count = 0;
String match = install_files.firstElement();
out.write(match.getBytes());
writeInt(out, install_count);
for(String file : install_files) {
if(!file.equals("NONE") && !match.equals(file)) {
out.write(file.getBytes());
match = file;
writeInt(out, install_count);
}
install_count++;
}
for(String trans_file : list) {
int index = patch_files.indexOf(extractNumber(trans_file));
int offset = -1;
if(index != -1) {
offset = (int)Long.parseLong(offsets.get(index),16);
} else {
System.out.println("Install info not found for " + trans_file);
}
writeInt(out, offset);
}
long filelength = out.length();
if(filelength % 16 > 0) {
filelength += 16 - (filelength % 16);
out.setLength(filelength);
}
System.out.println("OK");
} catch (FileNotFoundException e) {
System.out.println("\ndata_install.txt not found");
} catch (IOException e) {
e.printStackTrace();
}
}
|
public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(1, true));
final CCombo combo = new CCombo(parent, SWT.None);
combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
viewer = CheckboxTableViewer.newCheckList(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
getSite().getPage().addSelectionListener("org.dawnsci.spectrum.ui.views.SpectrumView", new ISelectionListener() {
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
List<ISpectrumFile> files = SpectrumUtils.getSpectrumFilesList((IStructuredSelection)selection);
if (files.isEmpty()) {
viewer.setInput(new ArrayList<String>());
combo.removeAll();
return;
}
if (files.size() == 1) {
currentFiles = new ArrayList<ISpectrumFile>(1);
currentFiles.add((ISpectrumFile)((IStructuredSelection)selection).getFirstElement());
combo.setItems(currentFiles.get(0).getDataNames().toArray(new String[currentFiles.get(0).getDataNames().size()]));
int i = 0;
for(String name : currentFiles.get(0).getDataNames()) {
if (name.equals(currentFiles.get(0).getxDatasetName())) {
combo.select(i);
}
i++;
}
viewer.setInput(currentFiles.get(0).getDataNames());
viewer.setCheckedElements(currentFiles.get(0).getyDatasetNames().toArray());
viewer.refresh();
}
}
});
viewer.setLabelProvider(new LabelProvider());
viewer.setContentProvider(new ViewContentProvider());
viewer.addCheckStateListener(new ICheckStateListener() {
@Override
public void checkStateChanged(CheckStateChangedEvent event) {
if (event.getChecked()) {
event.getElement().toString();
if (currentFiles.get(0).contains(event.getElement().toString())) {
currentFiles.get(0).addyDatasetName(event.getElement().toString());
}
} else {
if (currentFiles.get(0).contains(event.getElement().toString())) {
currentFiles.get(0).removeyDatasetName(event.getElement().toString());
}
}
}
});
}
| public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(1, true));
final CCombo combo = new CCombo(parent, SWT.None);
combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
viewer = CheckboxTableViewer.newCheckList(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
getSite().getPage().addSelectionListener("org.dawnsci.spectrum.ui.views.SpectrumView", new ISelectionListener() {
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
List<ISpectrumFile> files = SpectrumUtils.getSpectrumFilesList((IStructuredSelection)selection);
if (files.isEmpty()) {
if (viewer == null || viewer.getTable().isDisposed()) return;
viewer.setInput(new ArrayList<String>());
combo.removeAll();
return;
}
if (files.size() == 1) {
currentFiles = new ArrayList<ISpectrumFile>(1);
currentFiles.add((ISpectrumFile)((IStructuredSelection)selection).getFirstElement());
combo.setItems(currentFiles.get(0).getDataNames().toArray(new String[currentFiles.get(0).getDataNames().size()]));
int i = 0;
for(String name : currentFiles.get(0).getDataNames()) {
if (name.equals(currentFiles.get(0).getxDatasetName())) {
combo.select(i);
}
i++;
}
viewer.setInput(currentFiles.get(0).getDataNames());
viewer.setCheckedElements(currentFiles.get(0).getyDatasetNames().toArray());
viewer.refresh();
}
}
});
viewer.setLabelProvider(new LabelProvider());
viewer.setContentProvider(new ViewContentProvider());
viewer.addCheckStateListener(new ICheckStateListener() {
@Override
public void checkStateChanged(CheckStateChangedEvent event) {
if (event.getChecked()) {
event.getElement().toString();
if (currentFiles.get(0).contains(event.getElement().toString())) {
currentFiles.get(0).addyDatasetName(event.getElement().toString());
}
} else {
if (currentFiles.get(0).contains(event.getElement().toString())) {
currentFiles.get(0).removeyDatasetName(event.getElement().toString());
}
}
}
});
}
|
private static IWeaponStats getRenamedPrintClone(final IWeaponStats stats, final String name) {
return new IWeaponStats() {
public int getAccuracy() {
return stats.getAccuracy();
}
public int getDamage() {
return stats.getDamage();
}
public ITraitType getDamageTraitType() {
return stats.getDamageTraitType();
}
public HealthType getDamageType() {
return stats.getDamageType();
}
public Integer getDefence() {
return stats.getDefence();
}
public Integer getRange() {
return stats.getRate();
}
public Integer getRate() {
return stats.getRate();
}
public int getSpeed() {
return stats.getSpeed();
}
public IIdentificate[] getTags() {
return stats.getTags();
}
public ITraitType getTraitType() {
return stats.getTraitType();
}
public boolean inflictsNoDamage() {
return stats.inflictsNoDamage();
}
public IIdentificate getName() {
return new Identificate(name);
}
};
}
| private static IWeaponStats getRenamedPrintClone(final IWeaponStats stats, final String name) {
return new IWeaponStats() {
public int getAccuracy() {
return stats.getAccuracy();
}
public int getDamage() {
return stats.getDamage();
}
public ITraitType getDamageTraitType() {
return stats.getDamageTraitType();
}
public HealthType getDamageType() {
return stats.getDamageType();
}
public Integer getDefence() {
return stats.getDefence();
}
public Integer getRange() {
return stats.getRange();
}
public Integer getRate() {
return stats.getRate();
}
public int getSpeed() {
return stats.getSpeed();
}
public IIdentificate[] getTags() {
return stats.getTags();
}
public ITraitType getTraitType() {
return stats.getTraitType();
}
public boolean inflictsNoDamage() {
return stats.inflictsNoDamage();
}
public IIdentificate getName() {
return new Identificate(name);
}
};
}
|
public void testStuff() throws Exception {
IndexAwareResourceSet set = get(IndexAwareResourceSet.class);
URI uri = URI.createURI("classpath:/" + IndexAwareResourcesetTest.class.getName().replace('.', '/')
+ ".importuritestlanguage");
System.out.println(uri);
set.getResource(uri, true);
set.getResource(URI.createURI("classpath:/" + getClass().getName().replace('.', '/')
+ ".importuritestlanguage"), true);
IIndexStore store = set.getStore();
Query createQuery = store.eObjectDAO().createQuery();
Iterator<EObjectDescriptor> result = createQuery.executeListResult().iterator();
List<String> names = new ArrayList<String>();
while (result.hasNext()) {
EObjectDescriptor next = result.next();
if (next.getName().equals("D")) {
Type obj = (Type) set.getEObject(next.getFragmentURI(), true);
assertEquals("A", obj.getExtends().getName());
}
names.add(next.getName());
}
assertTrue(names.contains("A"));
assertTrue(names.contains("B"));
assertTrue(names.contains("C"));
assertTrue(names.contains("D"));
assertEquals(4,names.size());
}
| public void testStuff() throws Exception {
IndexAwareResourceSet set = get(IndexAwareResourceSet.class);
set.setClasspathURIContext(getClass());
URI uri = URI.createURI("classpath:/" + IndexAwareResourcesetTest.class.getName().replace('.', '/')
+ ".importuritestlanguage");
System.out.println(uri);
set.getResource(uri, true);
set.getResource(URI.createURI("classpath:/" + getClass().getName().replace('.', '/')
+ ".importuritestlanguage"), true);
IIndexStore store = set.getStore();
Query createQuery = store.eObjectDAO().createQuery();
Iterator<EObjectDescriptor> result = createQuery.executeListResult().iterator();
List<String> names = new ArrayList<String>();
while (result.hasNext()) {
EObjectDescriptor next = result.next();
if (next.getName().equals("D")) {
Type obj = (Type) set.getEObject(next.getFragmentURI(), true);
assertEquals("A", obj.getExtends().getName());
}
names.add(next.getName());
}
assertTrue(names.contains("A"));
assertTrue(names.contains("B"));
assertTrue(names.contains("C"));
assertTrue(names.contains("D"));
assertEquals(4,names.size());
}
|
private void processImages() {
String title = null;
if (bundle != null && bundle.getDc() != null && bundle.getDc().getTitle() != null
&& bundle.getDc().getTitle().size() > 0) {
title = bundle.getDc().getTitle().get(0);
}
final ScanFolderAction action = new ScanFolderAction(model, inputPath, title);
final DispatchCallback<ScanFolderResult> callback = new DispatchCallback<ScanFolderResult>() {
private volatile int done = 0;
private int total = 0;
private volatile boolean isDone = false;
@Override
public void callback(final ScanFolderResult result) {
getEventBus().fireEvent(new RefreshTreeEvent(Constants.NAME_OF_TREE.INPUT_QUEUE));
ServerActionResult serverActionResult = result.getServerActionResult();
if (serverActionResult.getServerActionResult() == Constants.SERVER_ACTION_RESULT.OK) {
if (result != null && result.getToAdd() != null && !result.getToAdd().isEmpty()) {
initializeConversion(result);
} else if (result != null && result.getItems() != null && !result.getItems().isEmpty()) {
doTheRest(result.getItems());
} else {
EditorSC.operationFailed(lang, "");
}
} else {
if (serverActionResult.getServerActionResult() == Constants.SERVER_ACTION_RESULT.WRONG_FILE_NAME) {
SC.ask(lang.wrongFileName() + serverActionResult.getMessage(), new BooleanCallback() {
@Override
public void execute(Boolean value) {
if (value != null && value && result != null && result.getToAdd() != null
&& !result.getToAdd().isEmpty()) {
initializeConversion(result);
}
}
});
}
}
}
private void initializeConversion(final ScanFolderResult result) {
final DispatchCallback<InitializeConversionResult> callback =
new DispatchCallback<InitializeConversionResult>() {
@Override
public void callback(InitializeConversionResult initResult) {
if (initResult != null && initResult.isSuccess()) {
convert(result);
} else {
SC.ask("Someone else is now running the conversion task. Please wait a second. Do you want to try it again?",
new BooleanCallback() {
@Override
public void execute(Boolean value) {
if (value != null && value) {
initializeConversion(result);
}
}
});
}
}
@Override
public void callbackError(Throwable t) {
SC.say("Someone else is now running the conversion task.");
}
};
dispatcher.execute(new InitializeConversionAction(true), callback);
}
private void endConversion() {
final DispatchCallback<InitializeConversionResult> callback =
new DispatchCallback<InitializeConversionResult>() {
@Override
public void callback(InitializeConversionResult result) {
if (result != null && !result.isSuccess()) {
SC.warn("Some images were not converted.");
}
}
@Override
public void callbackError(Throwable t) {
SC.say("Someone else is now running the conversion task.");
}
};
dispatcher.execute(new InitializeConversionAction(false), callback);
}
private void convert(ScanFolderResult result) {
final List<ImageItem> itemList = result == null ? null : result.getItems();
final List<ImageItem> toAdd = result == null ? null : result.getToAdd();
if (toAdd != null && !toAdd.isEmpty()) {
SetEnabledHotKeysEvent.fire(CreateStructurePresenter.this, false);
int lastItem = toAdd.size();
boolean progressbar = lastItem > 5;
final Progressbar hBar1 = progressbar ? new Progressbar() : null;
if (progressbar) {
done = 0;
total = lastItem;
hBar1.setHeight(24);
hBar1.setVertical(false);
hBar1.setPercentDone(0);
getView().getPopupPanel().setAutoHideEnabled(false);
getView().getPopupPanel().setWidget(hBar1);
getView().getPopupPanel().setVisible(true);
getView().getPopupPanel().center();
Timer timer = new Timer() {
@Override
public void run() {
for (ImageItem item : toAdd) {
convertItem(item, hBar1, itemList);
}
}
};
timer.schedule(40);
} else {
for (ImageItem item : toAdd) {
convertItem(item, hBar1, itemList);
}
}
} else {
doTheRest(itemList);
}
}
@Override
public void callbackError(final Throwable t) {
if (t.getMessage() != null && t.getMessage().length() > 0
&& t.getMessage().charAt(0) == Constants.SESSION_EXPIRED_FLAG) {
SC.confirm(lang.sessionExpired(), new BooleanCallback() {
@Override
public void execute(Boolean value) {
if (value != null && value) {
ClientUtils.redirect(t.getMessage().substring(1));
}
}
});
} else {
SC.ask(t.getMessage() + " " + lang.mesTryAgain(), new BooleanCallback() {
@Override
public void execute(Boolean value) {
if (value != null && value) {
processImages();
}
}
});
}
getView().getPopupPanel().setAutoHideEnabled(true);
getView().getPopupPanel().setVisible(false);
getView().getPopupPanel().hide();
}
private void doTheRest(List<ImageItem> itemList) {
ScanRecord[] items = null;
if (itemList != null && itemList.size() > 0) {
items = new ScanRecord[itemList.size()];
for (int i = 0, total = itemList.size(); i < total; i++) {
items[i] =
new ScanRecord(String.valueOf(i + 1),
model,
itemList.get(i).getIdentifier(),
Constants.PAGE_TYPES.NP.toString());
}
if (config.getHostname() == null || "".equals(config.getHostname().trim())) {
EditorSC.compulsoryConfigFieldWarn(EditorClientConfiguration.Constants.HOSTNAME,
EditorSC.ConfigFieldType.STRING,
lang);
}
getView().onAddImages(DigitalObjectModel.PAGE.getValue(),
items,
config.getHostname(),
false);
getView().getTileGrid().addDropHandler(new DropHandler() {
@Override
public void onDrop(DropEvent event) {
Object draggable = EventHandler.getDragTarget();
if (draggable instanceof TreeGrid) {
ListGridRecord[] selection =
leftPresenter.getView().getSubelementsGrid().getSelectedRecords();
if (selection == null || selection.length == 0) {
event.cancel();
return;
}
for (ListGridRecord rec : selection) {
if (!DigitalObjectModel.PAGE.getValue()
.equals(rec.getAttribute(Constants.ATTR_MODEL_ID))) {
SC.say("TODO Sem muzete pretahovat jen objekty typu stranka.");
event.cancel();
return;
}
}
}
}
});
}
getView().getTileGrid().addSelectionChangedHandler(new SelectionChangedHandler() {
@Override
public void onSelectionChanged(SelectionChangedEvent event) {
if (event.getRecord().getAttributeAsString(Constants.ATTR_PARENT) != null
&& !"".equals(event.getRecord().getAttributeAsString(Constants.ATTR_PARENT))) {
Record rec = event.getRecord();
event.getRecord()
.setAttribute("__ref",
"ScanRecord [getName()="
+ rec.getAttributeAsString(Constants.ATTR_NAME)
+ ", "
+ "getModel()="
+ model
+ ", "
+ "getPicture()="
+ rec.getAttributeAsString(Constants.ATTR_PICTURE_OR_UUID)
+ ", " + "getPath()=, " + "getPageType()="
+ rec.getAttributeAsString(Constants.ATTR_TYPE)
+ "]");
event.getRecord().setAttribute(Constants.ATTR_MODEL, model);
event.getRecord().setAttribute(Constants.ATTR_PARENT, "");
}
}
});
markedRecords = new ArrayList<Record>();
getView().getTileGrid().addRecordClickHandler(new RecordClickHandler() {
@Override
public void onRecordClick(RecordClickEvent event) {
if (!isMarkingOff() && event.isAltKeyDown() && event.isCtrlKeyDown()) {
getView().addUndoRedo(getView().getTileGrid().getData(), true, false);
String isMarked =
event.getRecord()
.getAttributeAsString(Constants.ATTR_ADITIONAL_INFO_OR_OCR);
if (isMarked == null || Boolean.FALSE.toString().equals(isMarked)) {
event.getRecord().setAttribute(Constants.ATTR_ADITIONAL_INFO_OR_OCR,
Boolean.TRUE.toString());
markedRecords.add(event.getRecord());
} else {
markedRecords.remove(event.getRecord());
event.getRecord().setAttribute(Constants.ATTR_ADITIONAL_INFO_OR_OCR,
Boolean.FALSE.toString());
}
getView().getTileGrid().deselectRecord(event.getRecord());
}
}
});
getView().getPopupPanel().setAutoHideEnabled(true);
getView().getPopupPanel().setWidget(null);
getView().getPopupPanel().setVisible(false);
getView().getPopupPanel().hide();
SetEnabledHotKeysEvent.fire(CreateStructurePresenter.this, true);
}
private void convertItem(ImageItem item, final Progressbar hBar1, final List<ImageItem> itemList) {
ConvertToJPEG2000Action action = new ConvertToJPEG2000Action(item);
final DispatchCallback<ConvertToJPEG2000Result> callback =
new DispatchCallback<ConvertToJPEG2000Result>() {
@Override
public void callback(ConvertToJPEG2000Result result) {
done++;
if (hBar1 != null) {
hBar1.setPercentDone(((100 * (done + 1)) / total));
}
if (done >= total && !isDone) {
synchronized (LOCK) {
if (done >= total && !isDone) {
endConversion();
doTheRest(itemList);
isDone = true;
}
}
}
}
@Override
public void callbackError(Throwable t) {
if (!isDone) {
synchronized (LOCK) {
if (!isDone) {
endConversion();
doTheRest(itemList);
isDone = true;
}
}
}
}
};
dispatcher.execute(action, callback);
}
};
Image loader = new Image("images/loadingAnimation3.gif");
getView().getPopupPanel().setWidget(loader);
getView().getPopupPanel().setVisible(true);
getView().getPopupPanel().center();
dispatcher.execute(action, callback);
}
| private void processImages() {
String title = null;
if (bundle != null && bundle.getDc() != null && bundle.getDc().getTitle() != null
&& bundle.getDc().getTitle().size() > 0) {
title = bundle.getDc().getTitle().get(0);
}
final ScanFolderAction action = new ScanFolderAction(model, inputPath, title);
final DispatchCallback<ScanFolderResult> callback = new DispatchCallback<ScanFolderResult>() {
private volatile int done = 0;
private int total = 0;
private volatile boolean isDone = false;
@Override
public void callback(final ScanFolderResult result) {
getEventBus().fireEvent(new RefreshTreeEvent(Constants.NAME_OF_TREE.INPUT_QUEUE));
ServerActionResult serverActionResult = result.getServerActionResult();
if (serverActionResult.getServerActionResult() == Constants.SERVER_ACTION_RESULT.OK) {
if (result != null && result.getToAdd() != null && !result.getToAdd().isEmpty()) {
initializeConversion(result);
} else if (result != null && result.getItems() != null && !result.getItems().isEmpty()) {
doTheRest(result.getItems());
} else {
EditorSC.operationFailed(lang, "");
}
} else {
if (serverActionResult.getServerActionResult() == Constants.SERVER_ACTION_RESULT.WRONG_FILE_NAME) {
SC.ask(lang.wrongFileName() + serverActionResult.getMessage(), new BooleanCallback() {
@Override
public void execute(Boolean value) {
if (value != null && value && result != null && result.getToAdd() != null
&& !result.getToAdd().isEmpty()) {
initializeConversion(result);
}
}
});
}
}
}
private void initializeConversion(final ScanFolderResult result) {
final DispatchCallback<InitializeConversionResult> callback =
new DispatchCallback<InitializeConversionResult>() {
@Override
public void callback(InitializeConversionResult initResult) {
if (initResult != null && initResult.isSuccess()) {
convert(result);
} else {
SC.ask("Someone else is now running the conversion task. Please wait a second. Do you want to try it again?",
new BooleanCallback() {
@Override
public void execute(Boolean value) {
if (value != null && value) {
initializeConversion(result);
}
}
});
}
}
@Override
public void callbackError(Throwable t) {
SC.say("Someone else is now running the conversion task.");
}
};
dispatcher.execute(new InitializeConversionAction(true), callback);
}
private void endConversion() {
final DispatchCallback<InitializeConversionResult> callback =
new DispatchCallback<InitializeConversionResult>() {
@Override
public void callback(InitializeConversionResult result) {
if (result != null && !result.isSuccess()) {
SC.warn("Some images were not converted.");
}
}
@Override
public void callbackError(Throwable t) {
SC.say("Someone else is now running the conversion task.");
}
};
dispatcher.execute(new InitializeConversionAction(false), callback);
}
private void convert(ScanFolderResult result) {
final List<ImageItem> itemList = result == null ? null : result.getItems();
final List<ImageItem> toAdd = result == null ? null : result.getToAdd();
if (toAdd != null && !toAdd.isEmpty()) {
SetEnabledHotKeysEvent.fire(CreateStructurePresenter.this, false);
int lastItem = toAdd.size();
boolean progressbar = lastItem > 5;
final Progressbar hBar1 = progressbar ? new Progressbar() : null;
if (progressbar) {
done = 0;
total = lastItem;
hBar1.setHeight(24);
hBar1.setVertical(false);
hBar1.setPercentDone(0);
getView().getPopupPanel().setAutoHideEnabled(false);
getView().getPopupPanel().setWidget(hBar1);
getView().getPopupPanel().setVisible(true);
getView().getPopupPanel().center();
Timer timer = new Timer() {
@Override
public void run() {
for (ImageItem item : toAdd) {
convertItem(item, hBar1, itemList);
}
}
};
timer.schedule(40);
} else {
for (ImageItem item : toAdd) {
convertItem(item, hBar1, itemList);
}
}
} else {
doTheRest(itemList);
}
}
@Override
public void callbackError(final Throwable t) {
if (t.getMessage() != null && t.getMessage().length() > 0
&& t.getMessage().charAt(0) == Constants.SESSION_EXPIRED_FLAG) {
SC.confirm(lang.sessionExpired(), new BooleanCallback() {
@Override
public void execute(Boolean value) {
if (value != null && value) {
ClientUtils.redirect(t.getMessage().substring(1));
}
}
});
} else {
SC.ask(t.getMessage() + " " + lang.mesTryAgain(), new BooleanCallback() {
@Override
public void execute(Boolean value) {
if (value != null && value) {
processImages();
}
}
});
}
getView().getPopupPanel().setAutoHideEnabled(true);
getView().getPopupPanel().setVisible(false);
getView().getPopupPanel().hide();
}
private void doTheRest(List<ImageItem> itemList) {
ScanRecord[] items = null;
if (itemList != null && itemList.size() > 0) {
items = new ScanRecord[itemList.size()];
for (int i = 0, total = itemList.size(); i < total; i++) {
items[i] =
new ScanRecord(String.valueOf(i + 1),
model,
itemList.get(i).getIdentifier(),
Constants.PAGE_TYPES.NP.toString());
}
if (config.getHostname() == null || "".equals(config.getHostname().trim())) {
EditorSC.compulsoryConfigFieldWarn(EditorClientConfiguration.Constants.HOSTNAME,
EditorSC.ConfigFieldType.STRING,
lang);
}
getView().onAddImages(DigitalObjectModel.PAGE.getValue(),
items,
config.getHostname(),
false);
getView().getTileGrid().addDropHandler(new DropHandler() {
@Override
public void onDrop(DropEvent event) {
Object draggable = EventHandler.getDragTarget();
if (draggable instanceof TreeGrid) {
ListGridRecord[] selection =
leftPresenter.getView().getSubelementsGrid().getSelectedRecords();
if (selection == null || selection.length == 0) {
event.cancel();
return;
}
for (ListGridRecord rec : selection) {
if (!DigitalObjectModel.PAGE.getValue()
.equals(rec.getAttribute(Constants.ATTR_MODEL_ID))) {
SC.say("TODO Sem muzete pretahovat jen objekty typu stranka.");
event.cancel();
return;
}
}
}
}
});
}
getView().getTileGrid().addSelectionChangedHandler(new SelectionChangedHandler() {
@Override
public void onSelectionChanged(SelectionChangedEvent event) {
if (event.getRecord().getAttributeAsString(Constants.ATTR_PARENT) != null
&& !"".equals(event.getRecord().getAttributeAsString(Constants.ATTR_PARENT))) {
Record rec = event.getRecord();
event.getRecord()
.setAttribute("__ref",
"ScanRecord [getName()="
+ rec.getAttributeAsString(Constants.ATTR_NAME)
+ ", "
+ "getModel()="
+ model
+ ", "
+ "getPicture()="
+ rec.getAttributeAsString(Constants.ATTR_PICTURE_OR_UUID)
+ ", " + "getPath()=, " + "getPageType()="
+ rec.getAttributeAsString(Constants.ATTR_TYPE)
+ "]");
event.getRecord().setAttribute(Constants.ATTR_MODEL, model);
event.getRecord().setAttribute(Constants.ATTR_PARENT, "");
event.getRecord().setAttribute(Constants.ATTR_ADITIONAL_INFO_OR_OCR,
Boolean.FALSE);
}
}
});
markedRecords = new ArrayList<Record>();
getView().getTileGrid().addRecordClickHandler(new RecordClickHandler() {
@Override
public void onRecordClick(RecordClickEvent event) {
if (!isMarkingOff() && event.isAltKeyDown() && event.isCtrlKeyDown()) {
getView().addUndoRedo(getView().getTileGrid().getData(), true, false);
String isMarked =
event.getRecord()
.getAttributeAsString(Constants.ATTR_ADITIONAL_INFO_OR_OCR);
if (isMarked == null || Boolean.FALSE.toString().equals(isMarked)) {
event.getRecord().setAttribute(Constants.ATTR_ADITIONAL_INFO_OR_OCR,
Boolean.TRUE.toString());
markedRecords.add(event.getRecord());
} else {
markedRecords.remove(event.getRecord());
event.getRecord().setAttribute(Constants.ATTR_ADITIONAL_INFO_OR_OCR,
Boolean.FALSE.toString());
}
getView().getTileGrid().deselectRecord(event.getRecord());
}
}
});
getView().getPopupPanel().setAutoHideEnabled(true);
getView().getPopupPanel().setWidget(null);
getView().getPopupPanel().setVisible(false);
getView().getPopupPanel().hide();
SetEnabledHotKeysEvent.fire(CreateStructurePresenter.this, true);
}
private void convertItem(ImageItem item, final Progressbar hBar1, final List<ImageItem> itemList) {
ConvertToJPEG2000Action action = new ConvertToJPEG2000Action(item);
final DispatchCallback<ConvertToJPEG2000Result> callback =
new DispatchCallback<ConvertToJPEG2000Result>() {
@Override
public void callback(ConvertToJPEG2000Result result) {
done++;
if (hBar1 != null) {
hBar1.setPercentDone(((100 * (done + 1)) / total));
}
if (done >= total && !isDone) {
synchronized (LOCK) {
if (done >= total && !isDone) {
endConversion();
doTheRest(itemList);
isDone = true;
}
}
}
}
@Override
public void callbackError(Throwable t) {
if (!isDone) {
synchronized (LOCK) {
if (!isDone) {
endConversion();
doTheRest(itemList);
isDone = true;
}
}
}
}
};
dispatcher.execute(action, callback);
}
};
Image loader = new Image("images/loadingAnimation3.gif");
getView().getPopupPanel().setWidget(loader);
getView().getPopupPanel().setVisible(true);
getView().getPopupPanel().center();
dispatcher.execute(action, callback);
}
|
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mView = inflater.inflate(R.layout.select_calendars_fragment, null);
mList = (ListView)mView.findViewById(R.id.list);
if (Utils.isMultiPaneConfiguration(getActivity())) {
View v = mView.findViewById(R.id.manage_sync_set);
if (v != null) {
v.setVisibility(View.GONE);
}
}
return mView;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mView = inflater.inflate(R.layout.select_calendars_fragment, null);
mList = (ListView)mView.findViewById(R.id.list);
if (Utils.isMultiPaneConfiguration(getActivity())) {
mList.setDivider(null);
View v = mView.findViewById(R.id.manage_sync_set);
if (v != null) {
v.setVisibility(View.GONE);
}
}
return mView;
}
|
private void shareRouteToClusterMember(ComChannel pClusterMemberChannel)
{
HRMID tMemberHRMID = pClusterMemberChannel.getPeerHRMID();
if (getHierarchyLevel().getValue() == 1){
RoutingEntry tRoutingEntry = RoutingEntry.createRouteToDirectNeighbor(tMemberHRMID, 0 , 1 , RoutingEntry.INFINITE_DATARATE );
tRoutingEntry.setNextHopL2Address(pClusterMemberChannel.getPeerL2Address());
Logging.log(this, "SHARING ROUTE: " + tRoutingEntry);
mHRMController.addHRMRoute(tRoutingEntry);
synchronized (mSharedRoutes){
if (HRMConfig.Routing.AVOID_DUPLICATES_IN_ROUTING_TABLES){
boolean tRestartNeeded;
do{
tRestartNeeded = false;
for (RoutingEntry tEntry: mSharedRoutes){
if ((tEntry.getDest().equals(tRoutingEntry.getDest())) &&
(tEntry.getNextHop().equals(tRoutingEntry.getNextHop())) ){
Logging.log(this, "REMOVING DUPLICATE: " + tEntry);
mSharedRoutes.remove(tEntry);
mSharedRoutesHaveChanged = true;
tRestartNeeded = true;
break;
}
}
}while(tRestartNeeded);
}
mSharedRoutes.add(tRoutingEntry);
mSharedRoutesHaveChanged = true;
}
}else{
Logging.log(this, "IMPLEMENT ME - SHARING ROUTE TO: " + pClusterMemberChannel);
}
}
private boolean sharePhaseHasTimeout()
{
double tDesiredTimePeriod = mHRMController.getPeriodSharePhase(getHierarchyLevel().getValue() - 1);
double tTimeNextSharePhase = mTimeOfLastSharePhase + tDesiredTimePeriod;
double tCurrentSimulationTime = mHRMController.getSimulationTime();
if (HRMConfig.DebugOutput.GUI_SHOW_TIMING_ROUTE_DISTRIBUTION){
Logging.log(this, "Checking for timeout of \"share phase\": desired time period is " + tDesiredTimePeriod + ", " + tCurrentSimulationTime + " > " + tTimeNextSharePhase + "? -> " + (tCurrentSimulationTime >= tTimeNextSharePhase));
}
return (tCurrentSimulationTime >= tTimeNextSharePhase);
}
private boolean hasNewSharePhaseData()
{
boolean tResult = false;
synchronized (mSharedRoutes){
tResult = mSharedRoutesHaveChanged;
}
return tResult;
}
public void sharePhase()
{
if (sharePhaseHasTimeout()){
if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
Logging.log(this, "SHARE PHASE with cluster members on level " + (getHierarchyLevel().getValue() - 1) + "/" + (HRMConfig.Hierarchy.HEIGHT - 1));
}
mTimeOfLastSharePhase = mHRMController.getSimulationTime();
if ((!HRMConfig.Routing.PERIODIC_SHARE_PHASES) && (!hasNewSharePhaseData())){
if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
Logging.log(this, "SHARE PHASE skipped because routing data hasn't changed since last signaling round");
}
return;
}
HRMID tOwnClusterAddress = mParentCluster.getHRMID();
if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
Logging.log(this, " ..distributing as " + tOwnClusterAddress.toString() + " aggregated ROUTES among cluster members: " + mParentCluster.getComChannels());
}
synchronized (mSharedRoutes){
for(ComChannel tClusterMember : mParentCluster.getComChannels()) {
RoutingInformation tRoutingInformationPacket = new RoutingInformation(tOwnClusterAddress, tClusterMember.getPeerHRMID());
if (getHierarchyLevel().getValue() == 1){
L2Address tPhysNodeL2Address = mHRMController.getHRS().getCentralFNL2Address();
for (HRMID tHRMID : mHRMController.getOwnHRMIDs()){
RoutingEntry tRouteFromClusterMemberToHere = RoutingEntry.createRouteToDirectNeighbor(tHRMID, 0 , 1 , RoutingEntry.INFINITE_DATARATE );
tRouteFromClusterMemberToHere.setNextHopL2Address(tPhysNodeL2Address);
tRoutingInformationPacket.addRoute(tRouteFromClusterMemberToHere);
}
}else{
}
if (tRoutingInformationPacket.getRoutes().size() > 0){
tClusterMember.sendPacket(tRoutingInformationPacket);
}else{
}
}
mSharedRoutesHaveChanged = false;
}
}else{
}
}
public void reportPhase()
{
if (!getHierarchyLevel().isHighest()){
}else{
}
}
public void eventCoordinatorRoleInvalid()
{
Logging.log(this, "============ EVENT: Coordinator_Role_Invalid");
if (!getHierarchyLevel().isHighest()){
BullyLeave tBullyLeavePacket = new BullyLeave(mHRMController.getNodeName(), getPriority());
sendAllSuperiorClusters(tBullyLeavePacket, true);
}else{
Logging.log(this, "eventCoordinatorRoleInvalid() skips further signaling because hierarchy end is already reached at: " + (getHierarchyLevel().getValue() - 1));
}
Logging.log(this, "============ Destroying this coordinator now...");
mParentCluster.setCoordinator(null);
mHRMController.unregisterCoordinator(this);
}
private void sendAllSuperiorClusters(Serializable pPacket, boolean pIncludeLoopback)
{
LinkedList<ComChannel> tComChannels = getComChannels();
L2Address tLocalL2Address = mHRMController.getHRS().getCentralFNL2Address();
Logging.log(this, "Sending BROADCASTS from " + tLocalL2Address + " the packet " + pPacket + " to " + tComChannels.size() + " communication channels");
for(ComChannel tComChannel : tComChannels) {
boolean tIsLoopback = tLocalL2Address.equals(tComChannel.getPeerL2Address());
if (!tIsLoopback){
Logging.log(this, " ..to " + tComChannel);
}else{
Logging.log(this, " ..to LOOPBACK " + tComChannel);
}
if ((HRMConfig.Hierarchy.SIGNALING_INCLUDES_LOCALHOST) || (pIncludeLoopback) || (!tIsLoopback)){
tComChannel.sendPacket(pPacket);
}else{
Logging.log(this, " ..skipping " + (tIsLoopback ? "LOOPBACK CHANNEL" : ""));
}
}
}
public void eventAnnouncedAsCoordinator()
{
if (HRMConfig.Addressing.ASSIGN_AUTOMATICALLY){
Logging.log(this, "EVENT ANNOUNCED - triggering address assignment for " + getComChannels().size() + " cluster members");
signalAddressDistribution();
}
mHRMController.setSourceIntermediateCluster(this, getCluster());
if(!getHierarchyLevel().isHighest()) {
if (HRMConfig.Hierarchy.CONTINUE_AUTOMATICALLY){
Logging.log(this, "EVENT ANNOUNCED - triggering clustering of this cluster's coordinator and its neighbors");
if (!isClustered()){
cluster();
}else{
Logging.warn(this, "Clustering is already finished for this hierarchy level, skipping cluster-request");
}
}
}
}
public void cluster()
{
Logging.log(this, "\n\n\n################ CLUSTERING STARTED");
boolean tSuperiorClusterFound = false;
for(Cluster tCluster : mHRMController.getAllClusters(getHierarchyLevel())) {
if (joinSuperiorCluster(tCluster)){
tSuperiorClusterFound = true;
break;
}
}
if (!tSuperiorClusterFound){
exploreNeighborhodAndCreateSuperiorCluster();
}
}
private boolean joinSuperiorCluster(ControlEntity pSuperiorCluster)
{
Logging.log(this, "\n\n\n################ JOINING EXISTING SUPERIOR CLUSTER " + pSuperiorCluster);
return false;
}
private void eventInitialClusteringFinished()
{
mInitialClusteringFinished = true;
}
public boolean isClustered()
{
return mInitialClusteringFinished;
}
@Override
public HierarchyLevel getHierarchyLevel() {
return new HierarchyLevel(this, super.getHierarchyLevel().getValue() + 1);
}
@Override
public BullyPriority getPriority()
{
return mParentCluster.getPriority();
}
@Override
public void setPriority(BullyPriority pPriority)
{
if (!getPriority().equals(pPriority)){
Logging.err(this, "Updating Bully priority from " + getPriority() + " to " + pPriority);
}else{
Logging.log(this, "Trying to set same Bully priority " + getPriority());
}
mParentCluster.setPriority(pPriority);
}
public Cluster getCluster()
{
return mParentCluster;
}
@Override
public Long getClusterID() {
return mParentCluster.getClusterID();
}
private boolean isConnectedToNeighborCoordinator(Name pCoordinatorName)
{
boolean tResult = false;
synchronized (mConnectedNeighborCoordinators) {
tResult = mConnectedNeighborCoordinators.contains(pCoordinatorName);
}
return tResult;
}
private void registerConnectionToNeighborCoordinator(Name pCoordinatorName)
{
synchronized (mConnectedNeighborCoordinators) {
mConnectedNeighborCoordinators.add(pCoordinatorName);
}
}
private void exploreNeighborhodAndCreateSuperiorCluster()
{
Logging.log(this, "\n\n\n################ EXPLORATION STARTED on hierarchy level " + getHierarchyLevel().getValue());
if (!isClustered()){
if (!getHierarchyLevel().isHighest()){
int tMaxRadius = HRMConfig.Routing.EXPANSION_RADIUS;
Logging.log(this, "Maximum radius is " + tMaxRadius);
Long tIDFutureCluster = Cluster.createClusterID();
List<AbstractRoutingGraphNode> tNeighborClustersForClustering = mHRMController.getNeighborClustersOrderedByRadiusInARG(mParentCluster);
Logging.log(this, " ..neighborhood ordered by radius: " + tNeighborClustersForClustering);
for(int tRadius = 1; tRadius <= tMaxRadius; tRadius++) {
Logging.log(this, "\n>>> Exploring neighbors with radius (" + tRadius + "/" + tMaxRadius + ")");
List<AbstractRoutingGraphNode> tSelectedNeighborClusters = new LinkedList<AbstractRoutingGraphNode>();
List<AbstractRoutingGraphNode> tNeighborClustersForClustering_RemoveList = new LinkedList<AbstractRoutingGraphNode>();
for(AbstractRoutingGraphNode tClusterCandidate : tNeighborClustersForClustering) {
if(tClusterCandidate instanceof Cluster) {
if (tRadius == 1){
Logging.log(this, " ..[r=" + tRadius + "]: found Cluster candidate: " + tClusterCandidate);
tSelectedNeighborClusters.add(tClusterCandidate);
tNeighborClustersForClustering_RemoveList.add(tClusterCandidate);
}else{
}
} else {
if (tClusterCandidate instanceof ClusterProxy){
ClusterProxy tClusterCandidateProxy = (ClusterProxy)tClusterCandidate;
if (!isConnectedToNeighborCoordinator(tClusterCandidateProxy.getCoordinatorHostName())){
int tNeighborClusterDistance = mHRMController.getClusterDistance(tClusterCandidateProxy);
if ((tNeighborClusterDistance > 0) && (tNeighborClusterDistance <= tRadius)) {
Logging.log(this, " ..[r=" + tRadius + "]: found ClusterProxy candidate: " + tClusterCandidate);
tSelectedNeighborClusters.add(tClusterCandidateProxy);
tNeighborClustersForClustering_RemoveList.add(tClusterCandidate);
}else{
if (tNeighborClusterDistance > tRadius){
continue;
}
}
}
}else{
Logging.err(this, "Found unsupported neighbor: " + tClusterCandidate);
}
}
}
for (AbstractRoutingGraphNode tRemoveCandidate : tNeighborClustersForClustering_RemoveList){
tNeighborClustersForClustering.remove(tRemoveCandidate);
}
for(AbstractRoutingGraphNode tNeighborCluster : tSelectedNeighborClusters) {
if(tNeighborCluster instanceof ControlEntity) {
ControlEntity tNeighborClusterControlEntity = (ControlEntity)tNeighborCluster;
eventDetectedNeighborCoordinator(tNeighborClusterControlEntity, tIDFutureCluster);
}else{
Logging.err(this, "Unsupported neighbor object: " + tNeighborCluster);
}
}
}
for(Coordinator tLocalCoordinator : mHRMController.getAllCoordinators(getHierarchyLevel())) {
tLocalCoordinator.eventInitialClusteringFinished();
}
}else{
Logging.warn(this, "CLUSTERING SKIPPED, no clustering on highest hierarchy level " + getHierarchyLevel().getValue() + " needed");
}
}else{
Logging.warn(this, "Clustering was already triggered, clustering will be maintained");
}
}
private void eventDetectedNeighborCoordinator(ControlEntity pNeighborCluster, Long pIDForFutureCluster)
{
FoGEntity tFoGLayer = (FoGEntity) mHRMController.getNode().getLayer(FoGEntity.class);
L2Address tThisHostL2Address = mHRMController.getHRS().getL2AddressFor(tFoGLayer.getCentralFN());
Logging.info(this, "\n\n\n############## FOUND INFERIOR NEIGHBOR CLUSTER " + pNeighborCluster + " FOR " + tThisHostL2Address);
Name tTargetCoordinatorHostName = ((ICluster)pNeighborCluster).getCoordinatorHostName();
if(!isConnectedToNeighborCoordinator(tTargetCoordinatorHostName)) {
registerConnectionToNeighborCoordinator(tTargetCoordinatorHostName);
HierarchyLevel tTargetClusterHierLvl = new HierarchyLevel(this, pNeighborCluster.getHierarchyLevel().getValue() + 1);
ControlEntity tNeighborClusterControlEntity = (ControlEntity)pNeighborCluster;
Logging.log(this, " ..creating cluster description");
RequestClusterParticipationProperty tRequestClusterParticipationProperty = new RequestClusterParticipationProperty(pIDForFutureCluster, tTargetClusterHierLvl, pNeighborCluster.getCoordinatorID());
Logging.log(this, " ..creating new communication session");
ComSession tComSession = new ComSession(mHRMController, false, getHierarchyLevel());
Logging.log(this, " ..iterate over all coordinators on hierarchy level: " + (getHierarchyLevel().getValue() - 1));
int tKnownLocalCoordinatorsOnThisHierarchyLevel = 0;
for(Coordinator tLocalCoordinator : mHRMController.getAllCoordinators(getHierarchyLevel())) {
tKnownLocalCoordinatorsOnThisHierarchyLevel++;
Logging.log(this, " ..found [" + tKnownLocalCoordinatorsOnThisHierarchyLevel + "] : " + tLocalCoordinator);
Logging.log(this, " ..creating new communication channel");
ComChannel tComChannel = new ComChannel(mHRMController, ComChannel.Direction.OUT, tLocalCoordinator, tComSession);
tComChannel.setRemoteClusterName(new ClusterName(mHRMController, pNeighborCluster.getHierarchyLevel(), pNeighborCluster.getCoordinatorID(), pIDForFutureCluster ));
tComChannel.setPeerPriority(pNeighborCluster.getPriority());
if(tNeighborClusterControlEntity.superiorCoordinatorHostL2Address() != null) {
Cluster tCoordinatorCluster = tLocalCoordinator.getCluster();
Logging.log(this, " ..creating cluster member description for the found cluster " + tCoordinatorCluster);
ClusterMemberDescription tClusterMemberDescription = tRequestClusterParticipationProperty.addClusterMember(tCoordinatorCluster.getClusterID(), tCoordinatorCluster.getCoordinatorID(), tCoordinatorCluster.getPriority());
tClusterMemberDescription.setSourceName(mHRMController.getNodeName());
tClusterMemberDescription.setSourceL2Address(tThisHostL2Address);
for(ControlEntity tClusterMemberNeighbor: tLocalCoordinator.getCluster().getNeighborsARG()) {
ICluster tIClusterNeighbor = (ICluster)tClusterMemberNeighbor;
DiscoveryEntry tDiscoveryEntry = new DiscoveryEntry(tClusterMemberNeighbor.getCoordinatorID(), tIClusterNeighbor.getCoordinatorHostName(), tClusterMemberNeighbor.getClusterID(), tClusterMemberNeighbor.superiorCoordinatorHostL2Address(), tClusterMemberNeighbor.getHierarchyLevel());
tDiscoveryEntry.setPriority(tClusterMemberNeighbor.getPriority());
if(tLocalCoordinator.getPathToCoordinator(tLocalCoordinator.getCluster(), tIClusterNeighbor) != null) {
for(RoutingServiceLinkVector tVector : tLocalCoordinator.getPathToCoordinator(tLocalCoordinator.getCluster(), tIClusterNeighbor)) {
tDiscoveryEntry.addRoutingVectors(tVector);
}
}
tClusterMemberDescription.addDiscoveryEntry(tDiscoveryEntry);
}
}else{
Logging.err(this, "eventDetectedNeighborCoordinator() didn't found the L2Address of the coordinator for: " + tNeighborClusterControlEntity);
}
}
Description tConnectionRequirements = mHRMController.createHRMControllerDestinationDescription();
tConnectionRequirements.set(tRequestClusterParticipationProperty);
ClusterDiscovery tBigDiscovery = new ClusterDiscovery(mHRMController.getNodeName());
Connection tConnection = null;
Logging.log(this, " ..CONNECTING to: " + tTargetCoordinatorHostName + " with requirements: " + tConnectionRequirements);
tConnection = tFoGLayer.connect(tTargetCoordinatorHostName, tConnectionRequirements, mHRMController.getNode().getIdentity());
Logging.log(this, " ..connect() FINISHED");
if (tConnection != null){
mCounterOutgoingConnections++;
Logging.log(this, " ..starting this OUTGOING CONNECTION as nr. " + mCounterOutgoingConnections);
tComSession.startConnection(null, tConnection);
for(Coordinator tCoordinator : mHRMController.getAllCoordinators(new HierarchyLevel(this, getHierarchyLevel().getValue() - 1))) {
LinkedList<Integer> tCoordinatorIDs = new LinkedList<Integer>();
for(ControlEntity tNeighbor : tCoordinator.getCluster().getNeighborsARG()) {
if(tNeighbor.getHierarchyLevel().getValue() == tCoordinator.getHierarchyLevel().getValue() - 1) {
tCoordinatorIDs.add(((ICluster) tNeighbor).getCoordinatorID());
}
}
tCoordinatorIDs.add(tCoordinator.getCluster().getCoordinatorID());
if(!tTargetCoordinatorHostName.equals(mHRMController.getNodeName())) {
int tDistance = 0;
if (pNeighborCluster instanceof ClusterProxy){
ClusterProxy tClusterProxy = (ClusterProxy) pNeighborCluster;
tDistance = mHRMController.getClusterDistance(tClusterProxy);
}
NestedDiscovery tNestedDiscovery = tBigDiscovery.new NestedDiscovery(tCoordinatorIDs, pNeighborCluster.getClusterID(), pNeighborCluster.getCoordinatorID(), pNeighborCluster.getHierarchyLevel(), tDistance);
Logging.log(this, "Created " + tNestedDiscovery + " for " + pNeighborCluster);
tNestedDiscovery.setOrigin(tCoordinator.getClusterID());
tNestedDiscovery.setTargetClusterID(tNeighborClusterControlEntity.superiorCoordinatorHostL2Address().getComplexAddress().longValue());
tBigDiscovery.addNestedDiscovery(tNestedDiscovery);
}
}
tComSession.write(tBigDiscovery);
for(NestedDiscovery tDiscovery : tBigDiscovery.getDiscoveries()) {
String tClusters = new String();
for(Cluster tCluster : mHRMController.getAllClusters()) {
tClusters += tCluster + ", ";
}
String tDiscoveries = new String();
for(DiscoveryEntry tEntry : tDiscovery.getDiscoveryEntries()) {
tDiscoveries += ", " + tEntry;
}
if(tDiscovery.getNeighborRelations() != null) {
for(Tuple<ClusterName, ClusterName> tTuple : tDiscovery.getNeighborRelations()) {
if(!mHRMController.isLinkedARG(tTuple.getFirst(), tTuple.getSecond())) {
Cluster tFirstCluster = mHRMController.getClusterByID(tTuple.getFirst());
Cluster tSecondCluster = mHRMController.getClusterByID(tTuple.getSecond());
if(tFirstCluster != null && tSecondCluster != null ) {
tFirstCluster.registerNeighborARG(tSecondCluster);
Logging.log(this, "Connecting " + tFirstCluster + " with " + tSecondCluster);
} else {
Logging.warn(this, "Unable to find cluster " + tTuple.getFirst() + ":" + tFirstCluster + " or " + tTuple.getSecond() + ":" + tSecondCluster + " out of \"" + tClusters + "\", cluster discovery contained " + tDiscoveries + " and CEP is " + tComSession);
}
}
}
} else {
Logging.warn(this, tDiscovery + "does not contain any neighbor relations");
}
}
}else{
Logging.err(this, "eventDetectedNeighborCoordinator() wasn't able to connect to: " + tTargetCoordinatorHostName);
}
}else{
Logging.warn(this, "eventDetectedNeighborCoordinator() skips this connection request because there exist already a connection to: " + tTargetCoordinatorHostName);
}
}
public void eventSuperiorClusterCoordinatorAnnounced(BullyAnnounce pAnnouncePacket, ComChannel pComChannel)
{
setSuperiorCoordinator(pComChannel, pAnnouncePacket.getSenderName(), pAnnouncePacket.getCoordinatorID(), pComChannel.getPeerL2Address());
}
public void storeAnnouncement(AnnounceRemoteCluster pAnnounce)
{
Logging.log(this, "Storing " + pAnnounce);
if(mReceivedAnnouncements == null) {
mReceivedAnnouncements = new LinkedList<AnnounceRemoteCluster>();
}
pAnnounce.setNegotiatorIdentification(new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.superiorCoordinatorID(), mParentCluster.getClusterID()));
mReceivedAnnouncements.add(pAnnounce);
}
public LinkedList<Long> getBounces()
{
return mBouncedAnnounces;
}
private LinkedList<RoutingServiceLinkVector> getPathToCoordinator(ICluster pSourceCluster, ICluster pDestinationCluster)
{
List<Route> tCoordinatorPath = mHRMController.getHRS().getCoordinatorRoutingMap().getRoute(((ControlEntity)pSourceCluster).superiorCoordinatorHostL2Address(), ((ControlEntity)pDestinationCluster).superiorCoordinatorHostL2Address());
LinkedList<RoutingServiceLinkVector> tVectorList = new LinkedList<RoutingServiceLinkVector>();
if(tCoordinatorPath != null) {
for(Route tPath : tCoordinatorPath) {
tVectorList.add(new RoutingServiceLinkVector(tPath, mHRMController.getHRS().getCoordinatorRoutingMap().getSource(tPath), mHRMController.getHRS().getCoordinatorRoutingMap().getDest(tPath)));
}
}
return tVectorList;
}
@Override
public Name getCoordinatorHostName() {
return mCoordinatorName;
}
@Override
public void setCoordinatorHostName(Name pCoordName) {
mCoordinatorName = pCoordName;
}
public void eventClusterCoordinatorAnnounced(BullyAnnounce pAnnounce, ComChannel pCEP)
{
ClusterName tLocalManagedClusterName = new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.superiorCoordinatorID(), mParentCluster.getClusterID());
if(superiorCoordinatorComChannel() != null) {
if(getCoordinatorHostName() != null && !pAnnounce.getSenderName().equals(getCoordinatorHostName())) {
List<AbstractRoutingGraphLink> tRouteARG = mHRMController.getRouteARG(mParentCluster, pCEP.getRemoteClusterName());
if(tRouteARG.size() > 0) {
if(mHRMController.getOtherEndOfLinkARG(pCEP.getRemoteClusterName(), tRouteARG.get(tRouteARG.size() - 1)) instanceof Cluster) {
Logging.warn(this, "Not sending neighbor zone announce because another intermediate cluster has a shorter route to target");
if(tRouteARG != null) {
String tClusterRoute = new String();
AbstractRoutingGraphNode tRouteARGNode = mParentCluster;
for(AbstractRoutingGraphLink tConnection : tRouteARG) {
tClusterRoute += tRouteARGNode + "\n";
tRouteARGNode = mHRMController.getOtherEndOfLinkARG(tRouteARGNode, tConnection);
}
Logging.log(this, "cluster route to other entity:\n" + tClusterRoute);
}
} else {
AnnounceRemoteCluster tOldCovered = new AnnounceRemoteCluster(getCoordinatorHostName(), getHierarchyLevel(), superiorCoordinatorHostL2Address(),getCoordinatorID(), superiorCoordinatorHostL2Address().getComplexAddress().longValue());
tOldCovered.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority());
tOldCovered.setNegotiatorIdentification(tLocalManagedClusterName);
DiscoveryEntry tOldCoveredEntry = new DiscoveryEntry(mParentCluster.getCoordinatorID(), mParentCluster.getCoordinatorHostName(), mParentCluster.superiorCoordinatorHostL2Address().getComplexAddress().longValue(), mParentCluster.superiorCoordinatorHostL2Address(), mParentCluster.getHierarchyLevel());
tRouteARG = mHRMController.getRouteARG(mParentCluster, superiorCoordinatorComChannel().getRemoteClusterName());
tOldCoveredEntry.setPriority(superiorCoordinatorComChannel().getPeerPriority());
tOldCoveredEntry.setRoutingVectors(pCEP.getPath(mParentCluster.superiorCoordinatorHostL2Address()));
tOldCovered.setCoveringClusterEntry(tOldCoveredEntry);
pCEP.sendPacket(tOldCovered);
AnnounceRemoteCluster tNewCovered = new AnnounceRemoteCluster(pAnnounce.getSenderName(), getHierarchyLevel(), pCEP.getPeerL2Address(), pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address().getComplexAddress().longValue());
tNewCovered.setCoordinatorsPriority(pAnnounce.getSenderPriority());
tNewCovered.setNegotiatorIdentification(tLocalManagedClusterName);
DiscoveryEntry tCoveredEntry = new DiscoveryEntry(pAnnounce.getCoordinatorID(), pAnnounce.getSenderName(), (pCEP.getPeerL2Address()).getComplexAddress().longValue(), pCEP.getPeerL2Address(), getHierarchyLevel());
tCoveredEntry.setRoutingVectors(pCEP.getPath(pCEP.getPeerL2Address()));
tNewCovered.setCoveringClusterEntry(tCoveredEntry);
tCoveredEntry.setPriority(pAnnounce.getSenderPriority());
Logging.warn(this, "Rejecting " + (superiorCoordinatorComChannel().getPeerL2Address()).getDescr() + " in favor of " + pAnnounce.getSenderName());
tNewCovered.setRejection();
superiorCoordinatorComChannel().sendPacket(tNewCovered);
for(ComChannel tCEP : getComChannels()) {
if(pAnnounce.getCoveredNodes().contains(tCEP.getPeerL2Address())) {
tCEP.setAsParticipantOfMyCluster(true);
} else {
tCEP.setAsParticipantOfMyCluster(false);
}
}
setSuperiorCoordinatorID(pAnnounce.getCoordinatorID());
setSuperiorCoordinator(pCEP, pAnnounce.getSenderName(),pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address());
mHRMController.setClusterWithCoordinator(getHierarchyLevel(), this);
superiorCoordinatorComChannel().sendPacket(tNewCovered);
}
}
}
} else {
if (pAnnounce.getCoveredNodes() != null){
for(ComChannel tCEP : getComChannels()) {
if(pAnnounce.getCoveredNodes().contains(tCEP.getPeerL2Address())) {
tCEP.setAsParticipantOfMyCluster(true);
} else {
tCEP.setAsParticipantOfMyCluster(false);
}
}
}
setSuperiorCoordinatorID(pAnnounce.getCoordinatorID());
mHRMController.setClusterWithCoordinator(getHierarchyLevel(), this);
setSuperiorCoordinator(pCEP, pAnnounce.getSenderName(), pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address());
}
}
private ICluster addAnnouncedCluster(AnnounceRemoteCluster pAnnounce, ComChannel pCEP)
{
if(pAnnounce.getRoutingVectors() != null) {
for(RoutingServiceLinkVector tVector : pAnnounce.getRoutingVectors()) {
mHRMController.getHRS().registerRoute(tVector.getSource(), tVector.getDestination(), tVector.getPath());
}
}
ClusterProxy tCluster = null;
if(pAnnounce.isAnnouncementFromForeign())
{
Logging.log(this, " ..creating cluster proxy");
tCluster = new ClusterProxy(mParentCluster.mHRMController, pAnnounce.getCoordAddress().getComplexAddress().longValue() , new HierarchyLevel(this, super.getHierarchyLevel().getValue() + 2), pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress(), pAnnounce.getToken());
mHRMController.setSourceIntermediateCluster(tCluster, mHRMController.getSourceIntermediateCluster(this));
tCluster.setSuperiorCoordinatorID(pAnnounce.getToken());
tCluster.setPriority(pAnnounce.getCoordinatorsPriority());
} else {
Logging.log(this, "Cluster announced by " + pAnnounce + " is an intermediate neighbor ");
}
if(pAnnounce.getCoordinatorName() != null) {
mHRMController.getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress());
}
return tCluster;
}
@Override
public void handleNeighborAnnouncement(AnnounceRemoteCluster pAnnounce, ComChannel pCEP)
{
if(pAnnounce.getCoveringClusterEntry() != null) {
if(pAnnounce.isRejected()) {
Logging.log(this, "Removing " + this + " as participating CEP from " + this);
getComChannels().remove(this);
}
if(pAnnounce.getCoordinatorName() != null) {
mHRMController.getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress());
}
pCEP.handleDiscoveryEntry(pAnnounce.getCoveringClusterEntry());
}
}
@Override
public void setSuperiorCoordinator(ComChannel pCoordinatorComChannel, Name pCoordinatorName, int pCoordToken, L2Address pCoordinatorL2Address)
{
super.setSuperiorCoordinator(pCoordinatorComChannel, pCoordinatorName, pCoordToken, pCoordinatorL2Address);
Logging.log(this, "Setting channel to superior coordinator to " + pCoordinatorComChannel + " for coordinator " + pCoordinatorName + " with routing address " + pCoordinatorL2Address);
Logging.log(this, "Previous channel to superior coordinator was " + superiorCoordinatorComChannel() + " with name " + mCoordinatorName);
setSuperiorCoordinatorComChannel(pCoordinatorComChannel);
mCoordinatorName = pCoordinatorName;
synchronized(this) {
notifyAll();
}
ClusterName tLocalManagedClusterName = new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.getCoordinatorID(), mParentCluster.getClusterID());
for(AbstractRoutingGraphNode tNeighbor: mHRMController.getNeighborsARG(mParentCluster)) {
if(tNeighbor instanceof ICluster) {
for(ComChannel tComChannel : getComChannels()) {
if(((ControlEntity)tNeighbor).superiorCoordinatorHostL2Address().equals(tComChannel.getPeerL2Address()) && !tComChannel.isPartOfMyCluster()) {
Logging.info(this, "Informing " + tComChannel + " about existence of neighbor zone ");
AnnounceRemoteCluster tAnnounce = new AnnounceRemoteCluster(pCoordinatorName, getHierarchyLevel(), pCoordinatorL2Address, getCoordinatorID(), pCoordinatorL2Address.getComplexAddress().longValue());
tAnnounce.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority());
LinkedList<RoutingServiceLinkVector> tVectorList = tComChannel.getPath(pCoordinatorL2Address);
tAnnounce.setRoutingVectors(tVectorList);
tAnnounce.setNegotiatorIdentification(tLocalManagedClusterName);
tComChannel.sendPacket(tAnnounce);
}
Logging.log(this, "Informed " + tComChannel + " about new neighbor zone");
}
}
}
if(mReceivedAnnouncements != null) {
for(AnnounceRemoteCluster tAnnounce : mReceivedAnnouncements) {
superiorCoordinatorComChannel().sendPacket(tAnnounce);
}
}
}
public String toString()
{
return toLocation() + "(" + (mParentCluster != null ? "Cluster" + mParentCluster.getGUIClusterID() + ", " : "") + idToString() + ")";
}
@Override
public String toLocation()
{
String tResult = getClass().getSimpleName() + getGUICoordinatorID() + "@" + mHRMController.getNodeGUIName() + "@" + (getHierarchyLevel().getValue() - 1);
return tResult;
}
private String idToString()
{
if (getHRMID() == null){
return "ID=" + getClusterID() + ", CordID=" + getCoordinatorID() + ", NodePrio=" + getPriority().getValue();
}else{
return "HRMID=" + getHRMID().toString();
}
}
}
| private void shareRouteToClusterMember(ComChannel pClusterMemberChannel)
{
HRMID tMemberHRMID = pClusterMemberChannel.getPeerHRMID();
if (getHierarchyLevel().getValue() == 1){
RoutingEntry tRoutingEntry = RoutingEntry.createRouteToDirectNeighbor(tMemberHRMID, 0 , 1 , RoutingEntry.INFINITE_DATARATE );
tRoutingEntry.setNextHopL2Address(pClusterMemberChannel.getPeerL2Address());
Logging.log(this, "SHARING ROUTE: " + tRoutingEntry);
mHRMController.addHRMRoute(tRoutingEntry);
synchronized (mSharedRoutes){
if (HRMConfig.Routing.AVOID_DUPLICATES_IN_ROUTING_TABLES){
boolean tRestartNeeded;
do{
tRestartNeeded = false;
for (RoutingEntry tEntry: mSharedRoutes){
if ((tEntry.getDest().equals(tRoutingEntry.getDest())) &&
(tEntry.getNextHop().equals(tRoutingEntry.getNextHop())) ){
Logging.log(this, "REMOVING DUPLICATE: " + tEntry);
mSharedRoutes.remove(tEntry);
mSharedRoutesHaveChanged = true;
tRestartNeeded = true;
break;
}
}
}while(tRestartNeeded);
}
mSharedRoutes.add(tRoutingEntry);
mSharedRoutesHaveChanged = true;
}
}else{
Logging.log(this, "IMPLEMENT ME - SHARING ROUTE TO: " + pClusterMemberChannel);
}
}
private boolean sharePhaseHasTimeout()
{
double tDesiredTimePeriod = mHRMController.getPeriodSharePhase(getHierarchyLevel().getValue() - 1);
double tTimeNextSharePhase = mTimeOfLastSharePhase + tDesiredTimePeriod;
double tCurrentSimulationTime = mHRMController.getSimulationTime();
if (HRMConfig.DebugOutput.GUI_SHOW_TIMING_ROUTE_DISTRIBUTION){
Logging.log(this, "Checking for timeout of \"share phase\": desired time period is " + tDesiredTimePeriod + ", " + tCurrentSimulationTime + " > " + tTimeNextSharePhase + "? -> " + (tCurrentSimulationTime >= tTimeNextSharePhase));
}
return (tCurrentSimulationTime >= tTimeNextSharePhase);
}
private boolean hasNewSharePhaseData()
{
boolean tResult = false;
synchronized (mSharedRoutes){
tResult = mSharedRoutesHaveChanged;
}
return tResult;
}
public void sharePhase()
{
if (sharePhaseHasTimeout()){
if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
Logging.log(this, "SHARE PHASE with cluster members on level " + (getHierarchyLevel().getValue() - 1) + "/" + (HRMConfig.Hierarchy.HEIGHT - 1));
}
mTimeOfLastSharePhase = mHRMController.getSimulationTime();
if ((!HRMConfig.Routing.PERIODIC_SHARE_PHASES) && (!hasNewSharePhaseData())){
if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
Logging.log(this, "SHARE PHASE skipped because routing data hasn't changed since last signaling round");
}
return;
}
HRMID tOwnClusterAddress = mParentCluster.getHRMID();
if (HRMConfig.DebugOutput.SHOW_SHARE_PHASE){
Logging.log(this, " ..distributing as " + tOwnClusterAddress.toString() + " aggregated ROUTES among cluster members: " + mParentCluster.getComChannels());
}
synchronized (mSharedRoutes){
for(ComChannel tClusterMember : mParentCluster.getComChannels()) {
RoutingInformation tRoutingInformationPacket = new RoutingInformation(tOwnClusterAddress, tClusterMember.getPeerHRMID());
if (getHierarchyLevel().getValue() == 1){
L2Address tPhysNodeL2Address = mHRMController.getHRS().getCentralFNL2Address();
for (HRMID tHRMID : mHRMController.getOwnHRMIDs()){
RoutingEntry tRouteFromClusterMemberToHere = RoutingEntry.createRouteToDirectNeighbor(tHRMID, 0 , 1 , RoutingEntry.INFINITE_DATARATE );
tRouteFromClusterMemberToHere.setNextHopL2Address(tPhysNodeL2Address);
tRoutingInformationPacket.addRoute(tRouteFromClusterMemberToHere);
}
}else{
}
if (tRoutingInformationPacket.getRoutes().size() > 0){
tClusterMember.sendPacket(tRoutingInformationPacket);
}else{
}
}
mSharedRoutesHaveChanged = false;
}
}else{
}
}
public void reportPhase()
{
if (!getHierarchyLevel().isHighest()){
}else{
}
}
public void eventCoordinatorRoleInvalid()
{
Logging.log(this, "============ EVENT: Coordinator_Role_Invalid");
if (!getHierarchyLevel().isHighest()){
BullyLeave tBullyLeavePacket = new BullyLeave(mHRMController.getNodeName(), getPriority());
sendAllSuperiorClusters(tBullyLeavePacket, true);
}else{
Logging.log(this, "eventCoordinatorRoleInvalid() skips further signaling because hierarchy end is already reached at: " + (getHierarchyLevel().getValue() - 1));
}
Logging.log(this, "============ Destroying this coordinator now...");
mParentCluster.setCoordinator(null);
mHRMController.unregisterCoordinator(this);
}
private void sendAllSuperiorClusters(Serializable pPacket, boolean pIncludeLoopback)
{
LinkedList<ComChannel> tComChannels = getComChannels();
L2Address tLocalL2Address = mHRMController.getHRS().getCentralFNL2Address();
Logging.log(this, "Sending BROADCASTS from " + tLocalL2Address + " the packet " + pPacket + " to " + tComChannels.size() + " communication channels");
for(ComChannel tComChannel : tComChannels) {
boolean tIsLoopback = tLocalL2Address.equals(tComChannel.getPeerL2Address());
if (!tIsLoopback){
Logging.log(this, " ..to " + tComChannel);
}else{
Logging.log(this, " ..to LOOPBACK " + tComChannel);
}
if ((HRMConfig.Hierarchy.SIGNALING_INCLUDES_LOCALHOST) || (pIncludeLoopback) || (!tIsLoopback)){
tComChannel.sendPacket(pPacket);
}else{
Logging.log(this, " ..skipping " + (tIsLoopback ? "LOOPBACK CHANNEL" : ""));
}
}
}
public void eventAnnouncedAsCoordinator()
{
if (HRMConfig.Addressing.ASSIGN_AUTOMATICALLY){
Logging.log(this, "EVENT ANNOUNCED - triggering address assignment for " + getComChannels().size() + " cluster members");
signalAddressDistribution();
}
mHRMController.setSourceIntermediateCluster(this, getCluster());
if(!getHierarchyLevel().isHighest()) {
if (HRMConfig.Hierarchy.CONTINUE_AUTOMATICALLY){
Logging.log(this, "EVENT ANNOUNCED - triggering clustering of this cluster's coordinator and its neighbors");
if (!isClustered()){
cluster();
}else{
Logging.warn(this, "Clustering is already finished for this hierarchy level, skipping cluster-request");
}
}
}
}
public void cluster()
{
Logging.log(this, "\n\n\n################ CLUSTERING STARTED");
boolean tSuperiorClusterFound = false;
for(Cluster tCluster : mHRMController.getAllClusters(getHierarchyLevel())) {
if (joinSuperiorCluster(tCluster)){
tSuperiorClusterFound = true;
break;
}
}
if (!tSuperiorClusterFound){
exploreNeighborhodAndCreateSuperiorCluster();
}
}
private boolean joinSuperiorCluster(ControlEntity pSuperiorCluster)
{
Logging.log(this, "\n\n\n################ JOINING EXISTING SUPERIOR CLUSTER " + pSuperiorCluster);
return false;
}
private void eventInitialClusteringFinished()
{
mInitialClusteringFinished = true;
}
public boolean isClustered()
{
return mInitialClusteringFinished;
}
@Override
public HierarchyLevel getHierarchyLevel() {
return new HierarchyLevel(this, super.getHierarchyLevel().getValue() + 1);
}
@Override
public BullyPriority getPriority()
{
return mParentCluster.getPriority();
}
@Override
public void setPriority(BullyPriority pPriority)
{
if (!getPriority().equals(pPriority)){
Logging.err(this, "Updating Bully priority from " + getPriority() + " to " + pPriority);
}else{
Logging.log(this, "Trying to set same Bully priority " + getPriority());
}
mParentCluster.setPriority(pPriority);
}
public Cluster getCluster()
{
return mParentCluster;
}
@Override
public Long getClusterID() {
return mParentCluster.getClusterID();
}
private boolean isConnectedToNeighborCoordinator(Name pCoordinatorName)
{
boolean tResult = false;
synchronized (mConnectedNeighborCoordinators) {
tResult = mConnectedNeighborCoordinators.contains(pCoordinatorName);
}
return tResult;
}
private void registerConnectionToNeighborCoordinator(Name pCoordinatorName)
{
synchronized (mConnectedNeighborCoordinators) {
mConnectedNeighborCoordinators.add(pCoordinatorName);
}
}
private void exploreNeighborhodAndCreateSuperiorCluster()
{
Logging.log(this, "\n\n\n################ EXPLORATION STARTED on hierarchy level " + getHierarchyLevel().getValue());
if (!isClustered()){
if (!getHierarchyLevel().isHighest()){
int tMaxRadius = HRMConfig.Routing.EXPANSION_RADIUS;
Logging.log(this, "Maximum radius is " + tMaxRadius);
Long tIDFutureCluster = Cluster.createClusterID();
List<AbstractRoutingGraphNode> tNeighborClustersForClustering = mHRMController.getNeighborClustersOrderedByRadiusInARG(mParentCluster);
Logging.log(this, " ..neighborhood ordered by radius: " + tNeighborClustersForClustering);
for(int tRadius = 1; tRadius <= tMaxRadius; tRadius++) {
Logging.log(this, "\n>>> Exploring neighbors with radius (" + tRadius + "/" + tMaxRadius + ")");
List<AbstractRoutingGraphNode> tSelectedNeighborClusters = new LinkedList<AbstractRoutingGraphNode>();
List<AbstractRoutingGraphNode> tNeighborClustersForClustering_RemoveList = new LinkedList<AbstractRoutingGraphNode>();
for(AbstractRoutingGraphNode tClusterCandidate : tNeighborClustersForClustering) {
if(tClusterCandidate instanceof Cluster) {
if (tRadius == 1){
Logging.log(this, " ..[r=" + tRadius + "]: found Cluster candidate: " + tClusterCandidate);
tSelectedNeighborClusters.add(tClusterCandidate);
tNeighborClustersForClustering_RemoveList.add(tClusterCandidate);
}else{
}
} else {
if (tClusterCandidate instanceof ClusterProxy){
ClusterProxy tClusterCandidateProxy = (ClusterProxy)tClusterCandidate;
if (!isConnectedToNeighborCoordinator(tClusterCandidateProxy.getCoordinatorHostName())){
int tNeighborClusterDistance = mHRMController.getClusterDistance(tClusterCandidateProxy);
if ((tNeighborClusterDistance > 0) && (tNeighborClusterDistance <= tRadius)) {
Logging.log(this, " ..[r=" + tRadius + "]: found ClusterProxy candidate: " + tClusterCandidate);
tSelectedNeighborClusters.add(tClusterCandidateProxy);
tNeighborClustersForClustering_RemoveList.add(tClusterCandidate);
}else{
if (tNeighborClusterDistance > tRadius){
continue;
}
}
}
}else{
Logging.err(this, "Found unsupported neighbor: " + tClusterCandidate);
}
}
}
for (AbstractRoutingGraphNode tRemoveCandidate : tNeighborClustersForClustering_RemoveList){
tNeighborClustersForClustering.remove(tRemoveCandidate);
}
for(AbstractRoutingGraphNode tNeighborCluster : tSelectedNeighborClusters) {
if(tNeighborCluster instanceof ControlEntity) {
ControlEntity tNeighborClusterControlEntity = (ControlEntity)tNeighborCluster;
eventDetectedNeighborCoordinator(tNeighborClusterControlEntity, tIDFutureCluster);
}else{
Logging.err(this, "Unsupported neighbor object: " + tNeighborCluster);
}
}
}
for(Coordinator tLocalCoordinator : mHRMController.getAllCoordinators(getHierarchyLevel())) {
tLocalCoordinator.eventInitialClusteringFinished();
}
}else{
Logging.warn(this, "CLUSTERING SKIPPED, no clustering on highest hierarchy level " + getHierarchyLevel().getValue() + " needed");
}
}else{
Logging.warn(this, "Clustering was already triggered, clustering will be maintained");
}
}
private void eventDetectedNeighborCoordinator(ControlEntity pNeighborCluster, Long pIDForFutureCluster)
{
FoGEntity tFoGLayer = (FoGEntity) mHRMController.getNode().getLayer(FoGEntity.class);
L2Address tThisHostL2Address = mHRMController.getHRS().getL2AddressFor(tFoGLayer.getCentralFN());
Logging.info(this, "\n\n\n############## FOUND INFERIOR NEIGHBOR CLUSTER " + pNeighborCluster + " FOR " + tThisHostL2Address);
Name tNeighborCoordinatorHostName = ((ICluster)pNeighborCluster).getCoordinatorHostName();
if(!isConnectedToNeighborCoordinator(tNeighborCoordinatorHostName)) {
registerConnectionToNeighborCoordinator(tNeighborCoordinatorHostName);
HierarchyLevel tTargetClusterHierLvl = new HierarchyLevel(this, pNeighborCluster.getHierarchyLevel().getValue() + 1);
ControlEntity tNeighborClusterControlEntity = (ControlEntity)pNeighborCluster;
Logging.log(this, " ..creating cluster description");
RequestClusterParticipationProperty tRequestClusterParticipationProperty = new RequestClusterParticipationProperty(pIDForFutureCluster, tTargetClusterHierLvl, pNeighborCluster.getCoordinatorID());
Logging.log(this, " ..creating new communication session");
ComSession tComSession = new ComSession(mHRMController, false, getHierarchyLevel());
Logging.log(this, " ..iterate over all coordinators on hierarchy level: " + (getHierarchyLevel().getValue() - 1));
int tKnownLocalCoordinatorsOnThisHierarchyLevel = 0;
for(Coordinator tLocalCoordinator : mHRMController.getAllCoordinators(getHierarchyLevel())) {
tKnownLocalCoordinatorsOnThisHierarchyLevel++;
Logging.log(this, " ..found [" + tKnownLocalCoordinatorsOnThisHierarchyLevel + "] : " + tLocalCoordinator);
Logging.log(this, " ..creating new communication channel");
ComChannel tComChannel = new ComChannel(mHRMController, ComChannel.Direction.OUT, tLocalCoordinator, tComSession);
tComChannel.setRemoteClusterName(new ClusterName(mHRMController, pNeighborCluster.getHierarchyLevel(), pNeighborCluster.getCoordinatorID(), pIDForFutureCluster ));
tComChannel.setPeerPriority(pNeighborCluster.getPriority());
if(tNeighborClusterControlEntity.superiorCoordinatorHostL2Address() != null) {
Cluster tCoordinatorCluster = tLocalCoordinator.getCluster();
Logging.log(this, " ..creating cluster member description for the found cluster " + tCoordinatorCluster);
ClusterMemberDescription tClusterMemberDescription = tRequestClusterParticipationProperty.addClusterMember(tCoordinatorCluster.getClusterID(), tCoordinatorCluster.getCoordinatorID(), tCoordinatorCluster.getPriority());
tClusterMemberDescription.setSourceName(mHRMController.getNodeName());
tClusterMemberDescription.setSourceL2Address(tThisHostL2Address);
for(ControlEntity tClusterMemberNeighbor: tLocalCoordinator.getCluster().getNeighborsARG()) {
ICluster tIClusterNeighbor = (ICluster)tClusterMemberNeighbor;
DiscoveryEntry tDiscoveryEntry = new DiscoveryEntry(tClusterMemberNeighbor.getCoordinatorID(), tIClusterNeighbor.getCoordinatorHostName(), tClusterMemberNeighbor.getClusterID(), tClusterMemberNeighbor.superiorCoordinatorHostL2Address(), tClusterMemberNeighbor.getHierarchyLevel());
tDiscoveryEntry.setPriority(tClusterMemberNeighbor.getPriority());
if(tLocalCoordinator.getPathToCoordinator(tLocalCoordinator.getCluster(), tIClusterNeighbor) != null) {
for(RoutingServiceLinkVector tVector : tLocalCoordinator.getPathToCoordinator(tLocalCoordinator.getCluster(), tIClusterNeighbor)) {
tDiscoveryEntry.addRoutingVectors(tVector);
}
}
tClusterMemberDescription.addDiscoveryEntry(tDiscoveryEntry);
}
}else{
Logging.err(this, "eventDetectedNeighborCoordinator() didn't found the L2Address of the coordinator for: " + tNeighborClusterControlEntity);
}
}
Description tConnectionRequirements = mHRMController.createHRMControllerDestinationDescription();
tConnectionRequirements.set(tRequestClusterParticipationProperty);
ClusterDiscovery tBigDiscovery = new ClusterDiscovery(mHRMController.getNodeName());
Connection tConnection = null;
Logging.log(this, " ..CONNECTING to: " + tNeighborCoordinatorHostName + " with requirements: " + tConnectionRequirements);
tConnection = tFoGLayer.connect(tNeighborCoordinatorHostName, tConnectionRequirements, mHRMController.getNode().getIdentity());
Logging.log(this, " ..connect() FINISHED");
if (tConnection != null){
mCounterOutgoingConnections++;
Logging.log(this, " ..starting this OUTGOING CONNECTION as nr. " + mCounterOutgoingConnections);
tComSession.startConnection(null, tConnection);
for(Coordinator tCoordinator : mHRMController.getAllCoordinators(new HierarchyLevel(this, getHierarchyLevel().getValue() - 1))) {
LinkedList<Integer> tCoordinatorIDs = new LinkedList<Integer>();
for(ControlEntity tNeighbor : tCoordinator.getCluster().getNeighborsARG()) {
if(tNeighbor.getHierarchyLevel().getValue() == tCoordinator.getHierarchyLevel().getValue() - 1) {
tCoordinatorIDs.add(((ICluster) tNeighbor).getCoordinatorID());
}
}
tCoordinatorIDs.add(tCoordinator.getCluster().getCoordinatorID());
if(!tNeighborCoordinatorHostName.equals(mHRMController.getNodeName())) {
int tDistance = 0;
if (pNeighborCluster instanceof ClusterProxy){
ClusterProxy tClusterProxy = (ClusterProxy) pNeighborCluster;
tDistance = mHRMController.getClusterDistance(tClusterProxy);
}
NestedDiscovery tNestedDiscovery = tBigDiscovery.new NestedDiscovery(tCoordinatorIDs, pNeighborCluster.getClusterID(), pNeighborCluster.getCoordinatorID(), pNeighborCluster.getHierarchyLevel(), tDistance);
Logging.log(this, "Created " + tNestedDiscovery + " for " + pNeighborCluster);
tNestedDiscovery.setOrigin(tCoordinator.getClusterID());
tNestedDiscovery.setTargetClusterID(tNeighborClusterControlEntity.superiorCoordinatorHostL2Address().getComplexAddress().longValue());
tBigDiscovery.addNestedDiscovery(tNestedDiscovery);
}
}
tComSession.write(tBigDiscovery);
for(NestedDiscovery tDiscovery : tBigDiscovery.getDiscoveries()) {
String tClusters = new String();
for(Cluster tCluster : mHRMController.getAllClusters()) {
tClusters += tCluster + ", ";
}
String tDiscoveries = new String();
for(DiscoveryEntry tEntry : tDiscovery.getDiscoveryEntries()) {
tDiscoveries += ", " + tEntry;
}
if(tDiscovery.getNeighborRelations() != null) {
for(Tuple<ClusterName, ClusterName> tTuple : tDiscovery.getNeighborRelations()) {
if(!mHRMController.isLinkedARG(tTuple.getFirst(), tTuple.getSecond())) {
Cluster tFirstCluster = mHRMController.getClusterByID(tTuple.getFirst());
Cluster tSecondCluster = mHRMController.getClusterByID(tTuple.getSecond());
if(tFirstCluster != null && tSecondCluster != null ) {
tFirstCluster.registerNeighborARG(tSecondCluster);
Logging.log(this, "Connecting " + tFirstCluster + " with " + tSecondCluster);
} else {
Logging.warn(this, "Unable to find cluster " + tTuple.getFirst() + ":" + tFirstCluster + " or " + tTuple.getSecond() + ":" + tSecondCluster + " out of \"" + tClusters + "\", cluster discovery contained " + tDiscoveries + " and CEP is " + tComSession);
}
}
}
} else {
Logging.warn(this, tDiscovery + "does not contain any neighbor relations");
}
}
}else{
Logging.err(this, "eventDetectedNeighborCoordinator() wasn't able to connect to: " + tNeighborCoordinatorHostName);
}
}else{
Logging.warn(this, "eventDetectedNeighborCoordinator() skips this connection request because there exist already a connection to: " + tNeighborCoordinatorHostName);
}
}
public void eventSuperiorClusterCoordinatorAnnounced(BullyAnnounce pAnnouncePacket, ComChannel pComChannel)
{
setSuperiorCoordinator(pComChannel, pAnnouncePacket.getSenderName(), pAnnouncePacket.getCoordinatorID(), pComChannel.getPeerL2Address());
}
public void storeAnnouncement(AnnounceRemoteCluster pAnnounce)
{
Logging.log(this, "Storing " + pAnnounce);
if(mReceivedAnnouncements == null) {
mReceivedAnnouncements = new LinkedList<AnnounceRemoteCluster>();
}
pAnnounce.setNegotiatorIdentification(new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.superiorCoordinatorID(), mParentCluster.getClusterID()));
mReceivedAnnouncements.add(pAnnounce);
}
public LinkedList<Long> getBounces()
{
return mBouncedAnnounces;
}
private LinkedList<RoutingServiceLinkVector> getPathToCoordinator(ICluster pSourceCluster, ICluster pDestinationCluster)
{
List<Route> tCoordinatorPath = mHRMController.getHRS().getCoordinatorRoutingMap().getRoute(((ControlEntity)pSourceCluster).superiorCoordinatorHostL2Address(), ((ControlEntity)pDestinationCluster).superiorCoordinatorHostL2Address());
LinkedList<RoutingServiceLinkVector> tVectorList = new LinkedList<RoutingServiceLinkVector>();
if(tCoordinatorPath != null) {
for(Route tPath : tCoordinatorPath) {
tVectorList.add(new RoutingServiceLinkVector(tPath, mHRMController.getHRS().getCoordinatorRoutingMap().getSource(tPath), mHRMController.getHRS().getCoordinatorRoutingMap().getDest(tPath)));
}
}
return tVectorList;
}
@Override
public Name getCoordinatorHostName() {
return mCoordinatorName;
}
@Override
public void setCoordinatorHostName(Name pCoordName) {
mCoordinatorName = pCoordName;
}
public void eventClusterCoordinatorAnnounced(BullyAnnounce pAnnounce, ComChannel pCEP)
{
ClusterName tLocalManagedClusterName = new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.superiorCoordinatorID(), mParentCluster.getClusterID());
if(superiorCoordinatorComChannel() != null) {
if(getCoordinatorHostName() != null && !pAnnounce.getSenderName().equals(getCoordinatorHostName())) {
List<AbstractRoutingGraphLink> tRouteARG = mHRMController.getRouteARG(mParentCluster, pCEP.getRemoteClusterName());
if(tRouteARG.size() > 0) {
if(mHRMController.getOtherEndOfLinkARG(pCEP.getRemoteClusterName(), tRouteARG.get(tRouteARG.size() - 1)) instanceof Cluster) {
Logging.warn(this, "Not sending neighbor zone announce because another intermediate cluster has a shorter route to target");
if(tRouteARG != null) {
String tClusterRoute = new String();
AbstractRoutingGraphNode tRouteARGNode = mParentCluster;
for(AbstractRoutingGraphLink tConnection : tRouteARG) {
tClusterRoute += tRouteARGNode + "\n";
tRouteARGNode = mHRMController.getOtherEndOfLinkARG(tRouteARGNode, tConnection);
}
Logging.log(this, "cluster route to other entity:\n" + tClusterRoute);
}
} else {
AnnounceRemoteCluster tOldCovered = new AnnounceRemoteCluster(getCoordinatorHostName(), getHierarchyLevel(), superiorCoordinatorHostL2Address(),getCoordinatorID(), superiorCoordinatorHostL2Address().getComplexAddress().longValue());
tOldCovered.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority());
tOldCovered.setNegotiatorIdentification(tLocalManagedClusterName);
DiscoveryEntry tOldCoveredEntry = new DiscoveryEntry(mParentCluster.getCoordinatorID(), mParentCluster.getCoordinatorHostName(), mParentCluster.superiorCoordinatorHostL2Address().getComplexAddress().longValue(), mParentCluster.superiorCoordinatorHostL2Address(), mParentCluster.getHierarchyLevel());
tRouteARG = mHRMController.getRouteARG(mParentCluster, superiorCoordinatorComChannel().getRemoteClusterName());
tOldCoveredEntry.setPriority(superiorCoordinatorComChannel().getPeerPriority());
tOldCoveredEntry.setRoutingVectors(pCEP.getPath(mParentCluster.superiorCoordinatorHostL2Address()));
tOldCovered.setCoveringClusterEntry(tOldCoveredEntry);
pCEP.sendPacket(tOldCovered);
AnnounceRemoteCluster tNewCovered = new AnnounceRemoteCluster(pAnnounce.getSenderName(), getHierarchyLevel(), pCEP.getPeerL2Address(), pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address().getComplexAddress().longValue());
tNewCovered.setCoordinatorsPriority(pAnnounce.getSenderPriority());
tNewCovered.setNegotiatorIdentification(tLocalManagedClusterName);
DiscoveryEntry tCoveredEntry = new DiscoveryEntry(pAnnounce.getCoordinatorID(), pAnnounce.getSenderName(), (pCEP.getPeerL2Address()).getComplexAddress().longValue(), pCEP.getPeerL2Address(), getHierarchyLevel());
tCoveredEntry.setRoutingVectors(pCEP.getPath(pCEP.getPeerL2Address()));
tNewCovered.setCoveringClusterEntry(tCoveredEntry);
tCoveredEntry.setPriority(pAnnounce.getSenderPriority());
Logging.warn(this, "Rejecting " + (superiorCoordinatorComChannel().getPeerL2Address()).getDescr() + " in favor of " + pAnnounce.getSenderName());
tNewCovered.setRejection();
superiorCoordinatorComChannel().sendPacket(tNewCovered);
for(ComChannel tCEP : getComChannels()) {
if(pAnnounce.getCoveredNodes().contains(tCEP.getPeerL2Address())) {
tCEP.setAsParticipantOfMyCluster(true);
} else {
tCEP.setAsParticipantOfMyCluster(false);
}
}
setSuperiorCoordinatorID(pAnnounce.getCoordinatorID());
setSuperiorCoordinator(pCEP, pAnnounce.getSenderName(),pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address());
mHRMController.setClusterWithCoordinator(getHierarchyLevel(), this);
superiorCoordinatorComChannel().sendPacket(tNewCovered);
}
}
}
} else {
if (pAnnounce.getCoveredNodes() != null){
for(ComChannel tCEP : getComChannels()) {
if(pAnnounce.getCoveredNodes().contains(tCEP.getPeerL2Address())) {
tCEP.setAsParticipantOfMyCluster(true);
} else {
tCEP.setAsParticipantOfMyCluster(false);
}
}
}
setSuperiorCoordinatorID(pAnnounce.getCoordinatorID());
mHRMController.setClusterWithCoordinator(getHierarchyLevel(), this);
setSuperiorCoordinator(pCEP, pAnnounce.getSenderName(), pAnnounce.getCoordinatorID(), pCEP.getPeerL2Address());
}
}
private ICluster addAnnouncedCluster(AnnounceRemoteCluster pAnnounce, ComChannel pCEP)
{
if(pAnnounce.getRoutingVectors() != null) {
for(RoutingServiceLinkVector tVector : pAnnounce.getRoutingVectors()) {
mHRMController.getHRS().registerRoute(tVector.getSource(), tVector.getDestination(), tVector.getPath());
}
}
ClusterProxy tCluster = null;
if(pAnnounce.isAnnouncementFromForeign())
{
Logging.log(this, " ..creating cluster proxy");
tCluster = new ClusterProxy(mParentCluster.mHRMController, pAnnounce.getCoordAddress().getComplexAddress().longValue() , new HierarchyLevel(this, super.getHierarchyLevel().getValue() + 2), pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress(), pAnnounce.getToken());
mHRMController.setSourceIntermediateCluster(tCluster, mHRMController.getSourceIntermediateCluster(this));
tCluster.setSuperiorCoordinatorID(pAnnounce.getToken());
tCluster.setPriority(pAnnounce.getCoordinatorsPriority());
} else {
Logging.log(this, "Cluster announced by " + pAnnounce + " is an intermediate neighbor ");
}
if(pAnnounce.getCoordinatorName() != null) {
mHRMController.getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress());
}
return tCluster;
}
@Override
public void handleNeighborAnnouncement(AnnounceRemoteCluster pAnnounce, ComChannel pCEP)
{
if(pAnnounce.getCoveringClusterEntry() != null) {
if(pAnnounce.isRejected()) {
Logging.log(this, "Removing " + this + " as participating CEP from " + this);
getComChannels().remove(this);
}
if(pAnnounce.getCoordinatorName() != null) {
mHRMController.getHRS().mapFoGNameToL2Address(pAnnounce.getCoordinatorName(), pAnnounce.getCoordAddress());
}
pCEP.handleDiscoveryEntry(pAnnounce.getCoveringClusterEntry());
}
}
@Override
public void setSuperiorCoordinator(ComChannel pCoordinatorComChannel, Name pCoordinatorName, int pCoordToken, L2Address pCoordinatorL2Address)
{
super.setSuperiorCoordinator(pCoordinatorComChannel, pCoordinatorName, pCoordToken, pCoordinatorL2Address);
Logging.log(this, "Setting channel to superior coordinator to " + pCoordinatorComChannel + " for coordinator " + pCoordinatorName + " with routing address " + pCoordinatorL2Address);
Logging.log(this, "Previous channel to superior coordinator was " + superiorCoordinatorComChannel() + " with name " + mCoordinatorName);
setSuperiorCoordinatorComChannel(pCoordinatorComChannel);
mCoordinatorName = pCoordinatorName;
synchronized(this) {
notifyAll();
}
ClusterName tLocalManagedClusterName = new ClusterName(mHRMController, mParentCluster.getHierarchyLevel(), mParentCluster.getCoordinatorID(), mParentCluster.getClusterID());
for(AbstractRoutingGraphNode tNeighbor: mHRMController.getNeighborsARG(mParentCluster)) {
if(tNeighbor instanceof ICluster) {
for(ComChannel tComChannel : getComChannels()) {
if(((ControlEntity)tNeighbor).superiorCoordinatorHostL2Address().equals(tComChannel.getPeerL2Address()) && !tComChannel.isPartOfMyCluster()) {
Logging.info(this, "Informing " + tComChannel + " about existence of neighbor zone ");
AnnounceRemoteCluster tAnnounce = new AnnounceRemoteCluster(pCoordinatorName, getHierarchyLevel(), pCoordinatorL2Address, getCoordinatorID(), pCoordinatorL2Address.getComplexAddress().longValue());
tAnnounce.setCoordinatorsPriority(superiorCoordinatorComChannel().getPeerPriority());
LinkedList<RoutingServiceLinkVector> tVectorList = tComChannel.getPath(pCoordinatorL2Address);
tAnnounce.setRoutingVectors(tVectorList);
tAnnounce.setNegotiatorIdentification(tLocalManagedClusterName);
tComChannel.sendPacket(tAnnounce);
}
Logging.log(this, "Informed " + tComChannel + " about new neighbor zone");
}
}
}
if(mReceivedAnnouncements != null) {
for(AnnounceRemoteCluster tAnnounce : mReceivedAnnouncements) {
superiorCoordinatorComChannel().sendPacket(tAnnounce);
}
}
}
public String toString()
{
return toLocation() + "(" + (mParentCluster != null ? "Cluster" + mParentCluster.getGUIClusterID() + ", " : "") + idToString() + ")";
}
@Override
public String toLocation()
{
String tResult = getClass().getSimpleName() + getGUICoordinatorID() + "@" + mHRMController.getNodeGUIName() + "@" + (getHierarchyLevel().getValue() - 1);
return tResult;
}
private String idToString()
{
if (getHRMID() == null){
return "ID=" + getClusterID() + ", CordID=" + getCoordinatorID() + ", NodePrio=" + getPriority().getValue();
}else{
return "HRMID=" + getHRMID().toString();
}
}
}
|
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
String perms = "ultraban.fine";
if (sender instanceof Player){
player = (Player)sender;
if (Permissions.Security.permission(player, perms)){
auth = true;
}
admin = player.getName();
}else{
auth = true;
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = args[0];
if(autoComplete) p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
boolean broadcast = true;
String amt = args[1];
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
amt = combineSplit(2, args, " ");
}else{
amt = combineSplit(1, args, " ");
}
}
if(victim != null){
if(!broadcast){
String fineMsg = config.getString("messages.fineMsgVictim", "You have been fined by %admin% in the amount of %amt%!");
String idoit = victim.getName();
fineMsg = fineMsg.replaceAll("%admin%", admin);
fineMsg = fineMsg.replaceAll("%victim%", idoit);
sender.sendMessage(formatMessage(":S:" + fineMsg));
victim.sendMessage(formatMessage(fineMsg));
}
if(setupEconomy()){
double bal = economy.getBalance(p);
double amtd = Double.valueOf(amt.trim());
if(amtd > bal){
economy.withdrawPlayer(victim.getName(), bal);
}else{
economy.withdrawPlayer(victim.getName(), amtd);
}
}
log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + ".");
plugin.db.addPlayer(p, amt, admin, 0, 4);
if(broadcast){
String idoit = victim.getName();
String fineMsgAll = config.getString("messages.fineMsgBroadcast", "%victim% was fined by %admin% in the amount of %amt%!!");
fineMsgAll = fineMsgAll.replaceAll("%admin%", admin);
fineMsgAll = fineMsgAll.replaceAll("%victim%", idoit);
plugin.getServer().broadcastMessage(formatMessage(fineMsgAll));
return true;
}
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
String perms = "ultraban.fine";
if (sender instanceof Player){
player = (Player)sender;
if (Permissions.Security.permission(player, perms)){
auth = true;
}
admin = player.getName();
}else{
auth = true;
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = args[0];
if(autoComplete) p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
boolean broadcast = true;
String amt = args[1];
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
amt = combineSplit(2, args, " ");
}else{
amt = combineSplit(1, args, " ");
}
}
if(victim != null){
if(!broadcast){
String fineMsg = config.getString("messages.fineMsgVictim", "You have been fined by %admin% in the amount of %amt%!");
String idoit = victim.getName();
fineMsg = fineMsg.replaceAll("%admin%", admin);
fineMsg = fineMsg.replaceAll("%amt%", amt);
fineMsg = fineMsg.replaceAll("%victim%", idoit);
sender.sendMessage(formatMessage(":S:" + fineMsg));
victim.sendMessage(formatMessage(fineMsg));
}
if(setupEconomy()){
double bal = economy.getBalance(p);
double amtd = Double.valueOf(amt.trim());
if(amtd > bal){
economy.withdrawPlayer(victim.getName(), bal);
}else{
economy.withdrawPlayer(victim.getName(), amtd);
}
}
log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + ".");
plugin.db.addPlayer(p, amt, admin, 0, 4);
if(broadcast){
String idoit = victim.getName();
String fineMsgAll = config.getString("messages.fineMsgBroadcast", "%victim% was fined by %admin% in the amount of %amt%!!");
fineMsgAll = fineMsgAll.replaceAll("%admin%", admin);
fineMsgAll = fineMsgAll.replaceAll("%amt%", amt);
fineMsgAll = fineMsgAll.replaceAll("%victim%", idoit);
plugin.getServer().broadcastMessage(formatMessage(fineMsgAll));
return true;
}
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
|
protected void doPost(HttpServletRequest req, HttpServletResponse res) {
String resource = req.getParameter("resource");
String data = req.getParameter("data");
String format = req.getParameter("format");
String tmpPath = this.getServletContext().getRealPath("/")
+ File.separator + "tmp" + File.separator;
this.baseFilename = String.valueOf(System.currentTimeMillis());
this.inFile = tmpPath + this.baseFilename + ".svg";
this.outFile = tmpPath + this.baseFilename + ".pdf";
System.out.println(inFile);
try {
BufferedWriter out = new BufferedWriter(new FileWriter(inFile));
out.write(data);
out.close();
makePDF();
res.getOutputStream().print("./tmp/" + this.baseFilename + ".pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
| protected void doPost(HttpServletRequest req, HttpServletResponse res) {
String resource = req.getParameter("resource");
String data = req.getParameter("data");
String format = req.getParameter("format");
String tmpPath = this.getServletContext().getRealPath("/")
+ File.separator + "tmp" + File.separator;
this.baseFilename = String.valueOf(System.currentTimeMillis());
this.inFile = tmpPath + this.baseFilename + ".svg";
this.outFile = tmpPath + this.baseFilename + ".pdf";
System.out.println(inFile);
try {
BufferedWriter out = new BufferedWriter(new FileWriter(inFile));
out.write(data);
out.close();
makePDF();
res.getOutputStream().print("/oryx/tmp/" + this.baseFilename + ".pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
|
void tokenize(String pat, Vector targetStrings)
throws javax.xml.transform.TransformerException
{
m_compiler.m_currentPattern = pat;
m_patternMapSize = 0;
m_compiler.m_opMap = new OpMapVector(OpMap.MAXTOKENQUEUESIZE * 5, OpMap.BLOCKTOKENQUEUESIZE * 5, OpMap.MAPINDEX_LENGTH);
int nChars = pat.length();
int startSubstring = -1;
int posOfNSSep = -1;
boolean isStartOfPat = true;
boolean isAttrName = false;
boolean isNum = false;
int nesting = 0;
for (int i = 0; i < nChars; i++)
{
char c = pat.charAt(i);
switch (c)
{
case '\"' :
{
if (startSubstring != -1)
{
isNum = false;
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
isAttrName = false;
if (-1 != posOfNSSep)
{
posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
}
else
{
addToTokenQueue(pat.substring(startSubstring, i));
}
}
startSubstring = i;
for (i++; (i < nChars) && ((c = pat.charAt(i)) != '\"'); i++);
if (c == '\"' && i < nChars)
{
addToTokenQueue(pat.substring(startSubstring, i + 1));
startSubstring = -1;
}
else
{
m_processor.error(XPATHErrorResources.ER_EXPECTED_DOUBLE_QUOTE,
null);
}
}
break;
case '\'' :
if (startSubstring != -1)
{
isNum = false;
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
isAttrName = false;
if (-1 != posOfNSSep)
{
posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
}
else
{
addToTokenQueue(pat.substring(startSubstring, i));
}
}
startSubstring = i;
for (i++; (i < nChars) && ((c = pat.charAt(i)) != '\''); i++);
if (c == '\'' && i < nChars)
{
addToTokenQueue(pat.substring(startSubstring, i + 1));
startSubstring = -1;
}
else
{
m_processor.error(XPATHErrorResources.ER_EXPECTED_SINGLE_QUOTE,
null);
}
break;
case 0x0A :
case 0x0D :
case ' ' :
case '\t' :
if (startSubstring != -1)
{
isNum = false;
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
isAttrName = false;
if (-1 != posOfNSSep)
{
posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
}
else
{
addToTokenQueue(pat.substring(startSubstring, i));
}
startSubstring = -1;
}
break;
case '@' :
isAttrName = true;
case '-' :
if ('-' == c)
{
if (!(isNum || (startSubstring == -1)))
{
break;
}
isNum = false;
}
case '(' :
case '[' :
case ')' :
case ']' :
case '|' :
case '/' :
case '*' :
case '+' :
case '=' :
case ',' :
case '\\' :
case '^' :
case '!' :
case '$' :
case '<' :
case '>' :
if (startSubstring != -1)
{
isNum = false;
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
isAttrName = false;
if (-1 != posOfNSSep)
{
posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
}
else
{
addToTokenQueue(pat.substring(startSubstring, i));
}
startSubstring = -1;
}
else if (('/' == c) && isStartOfPat)
{
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
}
else if ('*' == c)
{
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
isAttrName = false;
}
if (0 == nesting)
{
if ('|' == c)
{
if (null != targetStrings)
{
recordTokenString(targetStrings);
}
isStartOfPat = true;
}
}
if ((')' == c) || (']' == c))
{
nesting--;
}
else if (('(' == c) || ('[' == c))
{
nesting++;
}
addToTokenQueue(pat.substring(i, i + 1));
break;
case ':' :
if (i>0)
{
if (posOfNSSep == (i - 1))
{
if (startSubstring != -1)
{
if (startSubstring < (i - 1))
addToTokenQueue(pat.substring(startSubstring, i - 1));
}
isNum = false;
isAttrName = false;
startSubstring = -1;
posOfNSSep = -1;
addToTokenQueue(pat.substring(i - 1, i + 1));
break;
}
else
{
posOfNSSep = i;
}
}
default :
if (-1 == startSubstring)
{
startSubstring = i;
isNum = Character.isDigit(c);
}
else if (isNum)
{
isNum = Character.isDigit(c);
}
}
}
if (startSubstring != -1)
{
isNum = false;
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
if ((-1 != posOfNSSep) ||
((m_namespaceContext != null) && (m_namespaceContext.handlesNullPrefixes())))
{
posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, nChars);
}
else
{
addToTokenQueue(pat.substring(startSubstring, nChars));
}
}
if (0 == m_compiler.getTokenQueueSize())
{
m_processor.error(XPATHErrorResources.ER_EMPTY_EXPRESSION, null);
}
else if (null != targetStrings)
{
recordTokenString(targetStrings);
}
m_processor.m_queueMark = 0;
}
| void tokenize(String pat, Vector targetStrings)
throws javax.xml.transform.TransformerException
{
m_compiler.m_currentPattern = pat;
m_patternMapSize = 0;
int initTokQueueSize = ((pat.length() < OpMap.MAXTOKENQUEUESIZE)
? pat.length() : OpMap.MAXTOKENQUEUESIZE) * 5;
m_compiler.m_opMap = new OpMapVector(initTokQueueSize,
OpMap.BLOCKTOKENQUEUESIZE * 5,
OpMap.MAPINDEX_LENGTH);
int nChars = pat.length();
int startSubstring = -1;
int posOfNSSep = -1;
boolean isStartOfPat = true;
boolean isAttrName = false;
boolean isNum = false;
int nesting = 0;
for (int i = 0; i < nChars; i++)
{
char c = pat.charAt(i);
switch (c)
{
case '\"' :
{
if (startSubstring != -1)
{
isNum = false;
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
isAttrName = false;
if (-1 != posOfNSSep)
{
posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
}
else
{
addToTokenQueue(pat.substring(startSubstring, i));
}
}
startSubstring = i;
for (i++; (i < nChars) && ((c = pat.charAt(i)) != '\"'); i++);
if (c == '\"' && i < nChars)
{
addToTokenQueue(pat.substring(startSubstring, i + 1));
startSubstring = -1;
}
else
{
m_processor.error(XPATHErrorResources.ER_EXPECTED_DOUBLE_QUOTE,
null);
}
}
break;
case '\'' :
if (startSubstring != -1)
{
isNum = false;
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
isAttrName = false;
if (-1 != posOfNSSep)
{
posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
}
else
{
addToTokenQueue(pat.substring(startSubstring, i));
}
}
startSubstring = i;
for (i++; (i < nChars) && ((c = pat.charAt(i)) != '\''); i++);
if (c == '\'' && i < nChars)
{
addToTokenQueue(pat.substring(startSubstring, i + 1));
startSubstring = -1;
}
else
{
m_processor.error(XPATHErrorResources.ER_EXPECTED_SINGLE_QUOTE,
null);
}
break;
case 0x0A :
case 0x0D :
case ' ' :
case '\t' :
if (startSubstring != -1)
{
isNum = false;
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
isAttrName = false;
if (-1 != posOfNSSep)
{
posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
}
else
{
addToTokenQueue(pat.substring(startSubstring, i));
}
startSubstring = -1;
}
break;
case '@' :
isAttrName = true;
case '-' :
if ('-' == c)
{
if (!(isNum || (startSubstring == -1)))
{
break;
}
isNum = false;
}
case '(' :
case '[' :
case ')' :
case ']' :
case '|' :
case '/' :
case '*' :
case '+' :
case '=' :
case ',' :
case '\\' :
case '^' :
case '!' :
case '$' :
case '<' :
case '>' :
if (startSubstring != -1)
{
isNum = false;
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
isAttrName = false;
if (-1 != posOfNSSep)
{
posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, i);
}
else
{
addToTokenQueue(pat.substring(startSubstring, i));
}
startSubstring = -1;
}
else if (('/' == c) && isStartOfPat)
{
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
}
else if ('*' == c)
{
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
isAttrName = false;
}
if (0 == nesting)
{
if ('|' == c)
{
if (null != targetStrings)
{
recordTokenString(targetStrings);
}
isStartOfPat = true;
}
}
if ((')' == c) || (']' == c))
{
nesting--;
}
else if (('(' == c) || ('[' == c))
{
nesting++;
}
addToTokenQueue(pat.substring(i, i + 1));
break;
case ':' :
if (i>0)
{
if (posOfNSSep == (i - 1))
{
if (startSubstring != -1)
{
if (startSubstring < (i - 1))
addToTokenQueue(pat.substring(startSubstring, i - 1));
}
isNum = false;
isAttrName = false;
startSubstring = -1;
posOfNSSep = -1;
addToTokenQueue(pat.substring(i - 1, i + 1));
break;
}
else
{
posOfNSSep = i;
}
}
default :
if (-1 == startSubstring)
{
startSubstring = i;
isNum = Character.isDigit(c);
}
else if (isNum)
{
isNum = Character.isDigit(c);
}
}
}
if (startSubstring != -1)
{
isNum = false;
isStartOfPat = mapPatternElemPos(nesting, isStartOfPat, isAttrName);
if ((-1 != posOfNSSep) ||
((m_namespaceContext != null) && (m_namespaceContext.handlesNullPrefixes())))
{
posOfNSSep = mapNSTokens(pat, startSubstring, posOfNSSep, nChars);
}
else
{
addToTokenQueue(pat.substring(startSubstring, nChars));
}
}
if (0 == m_compiler.getTokenQueueSize())
{
m_processor.error(XPATHErrorResources.ER_EMPTY_EXPRESSION, null);
}
else if (null != targetStrings)
{
recordTokenString(targetStrings);
}
m_processor.m_queueMark = 0;
}
|
public void run(IAction action) {
if (this.currentVariablesValues.size() > 0) {
IViewReference interpreterViewReference = null;
IViewReference[] viewReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getViewReferences();
for (IViewReference iViewReference : viewReferences) {
if ("org.eclipse.acceleo.ui.interpreter.view".equals(iViewReference.getId())) {
interpreterViewReference = iViewReference;
}
}
IViewPart interpreterViewPart = null;
if (interpreterViewReference == null) {
try {
interpreterViewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().showView("org.eclipse.acceleo.ui.interpreter.view");
} catch (PartInitException e) {
InterpreterPlugin.getDefault().getLog().log(
new Status(IStatus.ERROR, InterpreterPlugin.PLUGIN_ID, e.getMessage()));
}
} else {
IWorkbenchPart part = interpreterViewReference.getPart(true);
if (part instanceof IViewPart) {
interpreterViewPart = (IViewPart)part;
}
}
if (interpreterViewPart != null) {
interpreterViewPart.setFocus();
} else {
InterpreterPlugin.getDefault().getLog().log(
new Status(IStatus.ERROR, InterpreterPlugin.PLUGIN_ID, InterpreterMessages
.getString("AddVariablesDebug.InterpreterViewNotFound")));
}
if (interpreterViewPart instanceof InterpreterView) {
InterpreterView interpreterView = (InterpreterView)interpreterViewPart;
if (!interpreterView.isVariableVisible()) {
interpreterView.toggleVariableVisibility();
}
for (Object variableEObject : this.currentVariablesValues) {
interpreterView.addVariables(variableEObject);
}
}
}
}
| public void run(IAction action) {
if (this.currentVariablesValues.size() > 0) {
List<Object> variables = new ArrayList<Object>(currentVariablesValues);
IViewReference interpreterViewReference = null;
IViewReference[] viewReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getViewReferences();
for (IViewReference iViewReference : viewReferences) {
if ("org.eclipse.acceleo.ui.interpreter.view".equals(iViewReference.getId())) {
interpreterViewReference = iViewReference;
}
}
IViewPart interpreterViewPart = null;
if (interpreterViewReference == null) {
try {
interpreterViewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().showView("org.eclipse.acceleo.ui.interpreter.view");
} catch (PartInitException e) {
InterpreterPlugin.getDefault().getLog().log(
new Status(IStatus.ERROR, InterpreterPlugin.PLUGIN_ID, e.getMessage()));
}
} else {
IWorkbenchPart part = interpreterViewReference.getPart(true);
if (part instanceof IViewPart) {
interpreterViewPart = (IViewPart)part;
}
}
if (interpreterViewPart != null) {
interpreterViewPart.setFocus();
} else {
InterpreterPlugin.getDefault().getLog().log(
new Status(IStatus.ERROR, InterpreterPlugin.PLUGIN_ID, InterpreterMessages
.getString("AddVariablesDebug.InterpreterViewNotFound")));
}
if (interpreterViewPart instanceof InterpreterView) {
InterpreterView interpreterView = (InterpreterView)interpreterViewPart;
if (!interpreterView.isVariableVisible()) {
interpreterView.toggleVariableVisibility();
}
for (Object variableEObject : variables) {
interpreterView.addVariables(variableEObject);
}
}
}
}
|
public void interact(PlayerInteractEvent pie) {
try {
if (!pie.hasBlock()) return;
Player player = pie.getPlayer();
Block block = pie.getClickedBlock();
AccessDelegate accessDelegate = AccessDelegate.getDelegate(block);
block = accessDelegate.getBlock();
IReinforcement generic_reinforcement = accessDelegate.getReinforcement();
PlayerReinforcement reinforcement = null;
if (generic_reinforcement instanceof PlayerReinforcement) {
reinforcement = (PlayerReinforcement)generic_reinforcement;
}
if (reinforcement != null
&& reinforcement.isSecurable()
&& !reinforcement.isAccessible(player)) {
Action action = pie.getAction();
if(action == Action.LEFT_CLICK_BLOCK
&& reinforcement.getBlock().getState().getData() instanceof Openable){
pie.setUseInteractedBlock(Event.Result.DENY);
} else if(action == Action.RIGHT_CLICK_BLOCK){
Citadel.info("%s failed to access locked reinforcement %s, "
+ player.getDisplayName() + " at "
+ block.getLocation().toString());
sendMessage(pie.getPlayer(), ChatColor.RED, "%s is locked", block.getType().name());
pie.setCancelled(true);
}
}
if (pie.isCancelled()) return;
PlayerState state = PlayerState.get(player);
PlacementMode placementMode = state.getMode();
switch (placementMode) {
case NORMAL:
return;
case FORTIFICATION:
return;
case INFO:
if (reinforcement != null) {
String reinforcementStatus = reinforcement.getStatus();
SecurityLevel securityLevel = reinforcement.getSecurityLevel();
if(reinforcement.isAccessible(player)){
Faction group = reinforcement.getOwner();
String groupName = group.getName();
String message = "";
if(group.isPersonalGroup()){
message = String.format("%s, security: %s, group: %s (Default Group)", reinforcementStatus, securityLevel, groupName);
} else {
message = String.format("%s, security: %s, group: %s", reinforcementStatus, securityLevel, groupName);
}
sendMessage(player, ChatColor.GREEN, message);
} else {
sendMessage(player, ChatColor.RED, "%s, security: %s", reinforcementStatus, securityLevel);
}
}
break;
default:
if (reinforcement == null) {
if (generic_reinforcement != null) {
reinforcementBroken(generic_reinforcement);
}
createPlayerReinforcement(player, block);
} else if (reinforcement.isBypassable(player)) {
boolean update = false;
String message = "";
if (reinforcement.getSecurityLevel() != state.getSecurityLevel()){
reinforcement.setSecurityLevel(state.getSecurityLevel());
update = true;
message = String.format("Changed security level %s", reinforcement.getSecurityLevel().name());
}
if(!reinforcement.getOwner().equals(state.getFaction())) {
reinforcement.setOwner(state.getFaction());
update = true;
if(!message.equals("")){
message = message + ". ";
}
if(reinforcement.getSecurityLevel() != SecurityLevel.PRIVATE){
message = message + String.format("Changed group to %s", state.getFaction().getName());
}
}
if(update){
Citadel.getReinforcementManager().addReinforcement(reinforcement);
sendMessage(player, ChatColor.GREEN, message);
}
} else {
sendMessage(player, ChatColor.RED, "You are not permitted to modify this reinforcement");
}
pie.setCancelled(true);
if (state.getMode() == PlacementMode.REINFORCEMENT_SINGLE_BLOCK) {
state.reset();
} else {
state.checkResetMode();
}
}
}
catch(Exception e)
{
Citadel.printStackTrace(e);
}
}
| public void interact(PlayerInteractEvent pie) {
try {
if (!pie.hasBlock()) return;
Player player = pie.getPlayer();
Block block = pie.getClickedBlock();
AccessDelegate accessDelegate = AccessDelegate.getDelegate(block);
block = accessDelegate.getBlock();
IReinforcement generic_reinforcement = accessDelegate.getReinforcement();
PlayerReinforcement reinforcement = null;
if (generic_reinforcement instanceof PlayerReinforcement) {
reinforcement = (PlayerReinforcement)generic_reinforcement;
}
if (reinforcement != null
&& reinforcement.isSecurable()
&& !reinforcement.isAccessible(player)) {
Action action = pie.getAction();
if(action == Action.RIGHT_CLICK_BLOCK){
Citadel.info("%s failed to access locked reinforcement %s, "
+ player.getDisplayName() + " at "
+ block.getLocation().toString());
sendMessage(pie.getPlayer(), ChatColor.RED, "%s is locked", block.getType().name());
pie.setCancelled(true);
}
}
if (pie.isCancelled()) return;
PlayerState state = PlayerState.get(player);
PlacementMode placementMode = state.getMode();
switch (placementMode) {
case NORMAL:
return;
case FORTIFICATION:
return;
case INFO:
if (reinforcement != null) {
String reinforcementStatus = reinforcement.getStatus();
SecurityLevel securityLevel = reinforcement.getSecurityLevel();
if(reinforcement.isAccessible(player)){
Faction group = reinforcement.getOwner();
String groupName = group.getName();
String message = "";
if(group.isPersonalGroup()){
message = String.format("%s, security: %s, group: %s (Default Group)", reinforcementStatus, securityLevel, groupName);
} else {
message = String.format("%s, security: %s, group: %s", reinforcementStatus, securityLevel, groupName);
}
sendMessage(player, ChatColor.GREEN, message);
} else {
sendMessage(player, ChatColor.RED, "%s, security: %s", reinforcementStatus, securityLevel);
}
}
break;
default:
if (reinforcement == null) {
if (generic_reinforcement != null) {
reinforcementBroken(generic_reinforcement);
}
createPlayerReinforcement(player, block);
} else if (reinforcement.isBypassable(player)) {
boolean update = false;
String message = "";
if (reinforcement.getSecurityLevel() != state.getSecurityLevel()){
reinforcement.setSecurityLevel(state.getSecurityLevel());
update = true;
message = String.format("Changed security level %s", reinforcement.getSecurityLevel().name());
}
if(!reinforcement.getOwner().equals(state.getFaction())) {
reinforcement.setOwner(state.getFaction());
update = true;
if(!message.equals("")){
message = message + ". ";
}
if(reinforcement.getSecurityLevel() != SecurityLevel.PRIVATE){
message = message + String.format("Changed group to %s", state.getFaction().getName());
}
}
if(update){
Citadel.getReinforcementManager().addReinforcement(reinforcement);
sendMessage(player, ChatColor.GREEN, message);
}
} else {
sendMessage(player, ChatColor.RED, "You are not permitted to modify this reinforcement");
}
pie.setCancelled(true);
if (state.getMode() == PlacementMode.REINFORCEMENT_SINGLE_BLOCK) {
state.reset();
} else {
state.checkResetMode();
}
}
}
catch(Exception e)
{
Citadel.printStackTrace(e);
}
}
|
public void run() {
while (run) {
@SuppressWarnings("unchecked")
ArrayList<TickData> temp = (ArrayList<TickData>)getTicks().clone();
synchronized (temp) {
for (TickData t : temp) {
if (t.getTick().inSeperateThread())
continue;
if (t.getTick().getTimeout() <= t.getTime()) {
try {
t.getTick().tick();
} catch (Exception e) {
e.printStackTrace();
}
t.time = 0;
}
else
t.time++;
}
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| public void run() {
while (run) {
TickData[] temp = ticks.toArray(new TickData[ticks.size()]);
synchronized (temp) {
for (TickData t : temp) {
if (t.getTick().inSeperateThread())
continue;
if (t.getTick().getTimeout() <= t.getTime()) {
try {
t.getTick().tick();
} catch (Exception e) {
e.printStackTrace();
}
t.time = 0;
}
else
t.time++;
}
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
public void run(DataSource dataSource, ConnCallback callback) {
Transaction t = Trans.get();
if (null != t) {
Connection conn = null;
Savepoint sp = null;
try {
conn = t.getConnection(dataSource);
sp = conn.setSavepoint();
callback.invoke(conn);
}
catch (Exception e) {
if (e instanceof DaoException)
if (null != conn
&& null != e.getCause()
&& e.getCause() instanceof SQLException) {
try {
if (null == sp)
conn.rollback();
else
conn.rollback(sp);
}
catch (SQLException e1) {
if (log.isErrorEnabled())
log.error(e1);
}
}
throw new DaoException(e);
}
}
else {
Connection conn = null;
boolean old = false;
try {
conn = dataSource.getConnection();
old = conn.getAutoCommit();
conn.setAutoCommit(false);
callback.invoke(conn);
if (!conn.getAutoCommit())
conn.commit();
}
catch (Exception e) {
try {
conn.rollback();
}
catch (SQLException e1) {}
throw new DaoException(e);
}
finally {
if (null != conn) {
try {
if (old != conn.getAutoCommit())
conn.setAutoCommit(old);
}
catch (SQLException autoE) {
if (log.isWarnEnabled())
log.warn("Fail to restore autoCommet to '" + old + "'", autoE);
}
try {
conn.close();
}
catch (SQLException closeE) {
if (log.isWarnEnabled())
log.warn("Fail to close connection!", closeE);
}
}
}
}
}
| public void run(DataSource dataSource, ConnCallback callback) {
Transaction t = Trans.get();
if (null != t) {
Connection conn = null;
Savepoint sp = null;
try {
conn = t.getConnection(dataSource);
sp = conn.setSavepoint();
callback.invoke(conn);
}
catch (Exception e) {
if (e instanceof DaoException)
if (null != conn
&& null != e.getCause()
&& e.getCause() instanceof SQLException) {
try {
if (null == sp)
conn.rollback();
else
conn.rollback(sp);
}
catch (SQLException e1) {
if (log.isErrorEnabled())
log.error(e1);
}
}
throw new DaoException(e);
}
}
else {
Connection conn = null;
boolean old = false;
try {
conn = dataSource.getConnection();
old = conn.getAutoCommit();
conn.setAutoCommit(false);
callback.invoke(conn);
if (!conn.getAutoCommit())
conn.commit();
}
catch (Exception e) {
try {
if (conn != null)
conn.rollback();
}
catch (SQLException e1) {}
throw new DaoException(e);
}
finally {
if (null != conn) {
try {
if (old != conn.getAutoCommit())
conn.setAutoCommit(old);
}
catch (SQLException autoE) {
if (log.isWarnEnabled())
log.warn("Fail to restore autoCommet to '" + old + "'", autoE);
}
try {
conn.close();
}
catch (SQLException closeE) {
if (log.isWarnEnabled())
log.warn("Fail to close connection!", closeE);
}
}
}
}
}
|
private void handlePageElementAction(IStepList steps, UserInteraction userInteraction) {
PageElement element = (PageElement) userInteraction.getElement();
String elementType = WatirUtils.getElementType(element);
String idType = WatirUtils.getIdType(element);
String idText = element.getText();
ActionType actionType = userInteraction.getActionType();
ITestStep step = null;
if (element.getIdentifierType().equals(LABEL) && element instanceof FormElement &&
!(element instanceof Button) && !(element instanceof Option)) {
StringBuffer buff = new StringBuffer();
WatirUtils.appendGetLabelTargetId(buff, element, element.getDescription());
idText = "\" + labelTargetId + \"";
idType = ":id";
steps.add(new TestStep(buff.toString()).setDescription("Getting label with text = '" + element.getText()));
}
if(actionType.equals(CLICK)){
step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").click");
step.setDescription("Clicking on " + elementType + " with " + idType + " = '" + idText + "'");
}
else if (actionType.equals(SELECT)) {
selectOptionInSelectList(steps, (Option) element, idType, idText);
}
else if(actionType.equals(CHECK)){
step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").set");
step.setDescription("Setting " + element.getType() + " with " + idType + " = '" + idText + "' to checked");
}
else if(actionType.equals(UNCHECK)){
step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").clear");
step.setDescription("Setting " + element.getType() + " with " + idType + " = '" + idText + "' to NOT checked");
}
else if(actionType.equals(ENTER_TEXT) || actionType.equals(ENTER_PARAMETER_TEXT)){
String textualInput = userInteraction.getTextualInput();
step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").set(\"" + textualInput +"\")");
step.setDescription("Inserting value '" + textualInput + "' into " + element.getType() + " with " + idType + " = '" + idText + "'");
}
else if(actionType.equals(CLEAR_ALL_TEXT)){
step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").clear");
step.setDescription("Clearing " + element.getType() + " with " + idType + " = '" + idText + "'");
}
else{
String eventType = WatirUtils.getEventType(actionType);
step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").fireEvent(\"" + eventType + "\")");
step.setDescription("FireEvent '" + eventType + "' on " + element.getType() + " with " + idType + " = '" + idText + "'");
}
}
| private void handlePageElementAction(IStepList steps, UserInteraction userInteraction) {
PageElement element = (PageElement) userInteraction.getElement();
String elementType = WatirUtils.getElementType(element);
String idType = WatirUtils.getIdType(element);
String idText = element.getText();
ActionType actionType = userInteraction.getActionType();
ITestStep step = null;
if (element.getIdentifierType().equals(LABEL) && element instanceof FormElement &&
!(element instanceof Button) && !(element instanceof Option)) {
StringBuffer buff = new StringBuffer();
WatirUtils.appendGetLabelTargetId(buff, element, element.getDescription());
idText = "\" + labelTargetId + \"";
idType = ":id";
steps.add(new TestStep(buff.toString()).setDescription("Getting label with text = '" + element.getText()));
}
if(actionType.equals(CLICK)){
step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").click");
step.setDescription("Clicking on " + elementType + " with " + idType + " = '" + idText + "'");
}
else if (actionType.equals(SELECT)) {
selectOptionInSelectList(steps, (Option) element, idType, idText);
}
else if(actionType.equals(CHECK)){
step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").set");
step.setDescription("Setting " + element.getType() + " with " + idType + " = '" + idText + "' to checked");
}
else if(actionType.equals(UNCHECK)){
step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").clear");
step.setDescription("Setting " + element.getType() + " with " + idType + " = '" + idText + "' to NOT checked");
}
else if(actionType.equals(ENTER_TEXT) || actionType.equals(ENTER_PARAMETER_TEXT)){
String textualInput = userInteraction.getTextualInput();
step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").set(\"" + textualInput +"\")");
step.setDescription("Inserting value '" + textualInput + "' into " + element.getType() + " with " + idType + " = '" + idText + "'");
}
else if(actionType.equals(CLEAR_ALL_TEXT)){
step = new TestStep("ie." + elementType + "(" + idType + " , \"" + idText + "\").clear");
step.setDescription("Clearing " + element.getType() + " with " + idType + " = '" + idText + "'");
}
else{
String eventType = WatirUtils.getEventType(actionType);
step = new TestStep("ie." + elementType + "(" + idType + ", \"" + idText + "\").fireEvent(\"" + eventType + "\")");
step.setDescription("FireEvent '" + eventType + "' on " + element.getType() + " with " + idType + " = '" + idText + "'");
}
steps.add(step);
}
|
public void visit(State state, Properties props) throws Exception {
Connector conn = state.getConnector();
Random rand = (Random) state.get("rand");
@SuppressWarnings("unchecked")
List<String> userNames = (List<String>) state.get("users");
String userName = userNames.get(rand.nextInt(userNames.size()));
@SuppressWarnings("unchecked")
List<String> tableNames = (List<String>) state.get("tables");
String tableName = tableNames.get(rand.nextInt(tableNames.size()));
@SuppressWarnings("unchecked")
List<String> namespaces = (List<String>) state.get("namespaces");
String namespace = namespaces.get(rand.nextInt(namespaces.size()));
try {
int dice = rand.nextInt(3);
if (dice == 0)
changeSystemPermission(conn, rand, userName);
else if (dice == 1)
changeTablePermission(conn, rand, userName, tableName);
else if (dice == 2)
changeNamespacePermission(conn, rand, userName, namespace);
} catch (AccumuloSecurityException ex) {
log.debug("Unable to change user permissions: " + ex.getCause());
} catch (AccumuloException ex) {
Throwable cause = ex.getCause();
if (cause != null && cause instanceof ThriftTableOperationException) {
ThriftTableOperationException toe = (ThriftTableOperationException)cause.getCause();
if (toe.type == TableOperationExceptionType.NAMESPACE_NOTFOUND) {
log.debug("Unable to change user permissions: " + toe.getCause());
return;
}
}
}
}
| public void visit(State state, Properties props) throws Exception {
Connector conn = state.getConnector();
Random rand = (Random) state.get("rand");
@SuppressWarnings("unchecked")
List<String> userNames = (List<String>) state.get("users");
String userName = userNames.get(rand.nextInt(userNames.size()));
@SuppressWarnings("unchecked")
List<String> tableNames = (List<String>) state.get("tables");
String tableName = tableNames.get(rand.nextInt(tableNames.size()));
@SuppressWarnings("unchecked")
List<String> namespaces = (List<String>) state.get("namespaces");
String namespace = namespaces.get(rand.nextInt(namespaces.size()));
try {
int dice = rand.nextInt(3);
if (dice == 0)
changeSystemPermission(conn, rand, userName);
else if (dice == 1)
changeTablePermission(conn, rand, userName, tableName);
else if (dice == 2)
changeNamespacePermission(conn, rand, userName, namespace);
} catch (AccumuloSecurityException ex) {
log.debug("Unable to change user permissions: " + ex.getCause());
} catch (AccumuloException ex) {
Throwable cause = ex.getCause();
if (cause != null && cause instanceof ThriftTableOperationException) {
ThriftTableOperationException toe = (ThriftTableOperationException)cause.getCause();
if (toe.type == TableOperationExceptionType.NAMESPACE_NOTFOUND) {
log.debug("Unable to change user permissions: " + toe);
return;
}
}
}
}
|
public synchronized void updated(String pid, Dictionary properties) throws ConfigurationException {
try {
deleted(pid);
Properties props = new Properties();
for (Enumeration ek = properties.keys(); ek.hasMoreElements();) {
Object key = ek.nextElement();
Object val = properties.get(key);
props.put(key.toString(), val != null ? val.toString() : "");
}
String serverId = props.getProperty("server.id");
if (serverId != null) {
props.remove("server.id");
File myId = new File(props.getProperty("dataDir"), "myid");
if (myId.exists()) {
myId.delete();
}
myId.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(myId);
try {
fos.write((serverId + "\n").getBytes());
} finally {
fos.close();
}
}
QuorumPeerConfig config = new QuorumPeerConfig();
config.parseProperties(props);
if (!config.getServers().isEmpty()) {
NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory();
cnxnFactory.configure(config.getClientPortAddress(), config.getMaxClientCnxns());
QuorumPeer quorumPeer = new QuorumPeer();
quorumPeer.setClientPortAddress(config.getClientPortAddress());
quorumPeer.setTxnFactory(new FileTxnSnapLog(
new File(config.getDataLogDir()),
new File(config.getDataDir())));
quorumPeer.setQuorumPeers(config.getServers());
quorumPeer.setElectionType(config.getElectionAlg());
quorumPeer.setMyid(config.getServerId());
quorumPeer.setTickTime(config.getTickTime());
quorumPeer.setMinSessionTimeout(config.getMinSessionTimeout());
quorumPeer.setMaxSessionTimeout(config.getMaxSessionTimeout());
quorumPeer.setInitLimit(config.getInitLimit());
quorumPeer.setSyncLimit(config.getSyncLimit());
quorumPeer.setQuorumVerifier(config.getQuorumVerifier());
quorumPeer.setCnxnFactory(cnxnFactory);
quorumPeer.setZKDatabase(new ZKDatabase(quorumPeer.getTxnFactory()));
quorumPeer.setLearnerType(config.getPeerType());
try {
debug("Starting quorum peer \"%s\" on address %s", quorumPeer.getMyid(), config.getClientPortAddress());
quorumPeer.start();
debug("Started quorum peer \"%s\"", quorumPeer.getMyid());
} catch (Exception e) {
LOG.warn(String.format("Failed to start quorum peer \"%s\", reason : ", quorumPeer.getMyid(), e));
quorumPeer.shutdown();
throw e;
}
servers.put(pid, quorumPeer);
services.put(pid, bundleContext.registerService(QuorumStats.Provider.class.getName(), quorumPeer, properties));
} else {
ServerConfig cfg = new ServerConfig();
cfg.readFrom(config);
ZooKeeperServer zkServer = new ZooKeeperServer();
FileTxnSnapLog ftxn = new FileTxnSnapLog(new
File(cfg.getDataLogDir()), new File(cfg.getDataDir()));
zkServer.setTxnLogFactory(ftxn);
zkServer.setTickTime(cfg.getTickTime());
zkServer.setMinSessionTimeout(cfg.getMinSessionTimeout());
zkServer.setMaxSessionTimeout(cfg.getMaxSessionTimeout());
NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory();
cnxnFactory.configure(cfg.getClientPortAddress(), cfg.getMaxClientCnxns());
try {
debug("Starting ZooKeeper server on address %s", config.getClientPortAddress());
cnxnFactory.startup(zkServer);
LOG.debug("Started ZooKeeper server");
} catch (Exception e) {
LOG.warn(String.format("Failed to start ZooKeeper server, reason : %s", e));
cnxnFactory.shutdown();
throw e;
}
servers.put(pid, cnxnFactory);
services.put(pid, bundleContext.registerService(ServerStats.Provider.class.getName(), zkServer, properties));
}
} catch (Exception e) {
throw (ConfigurationException) new ConfigurationException(null, "Unable to parse ZooKeeper configuration: " + e.getMessage()).initCause(e);
}
}
| public synchronized void updated(String pid, Dictionary properties) throws ConfigurationException {
try {
deleted(pid);
Properties props = new Properties();
for (Enumeration ek = properties.keys(); ek.hasMoreElements();) {
Object key = ek.nextElement();
Object val = properties.get(key);
props.put(key.toString(), val != null ? val.toString() : "");
}
String serverId = props.getProperty("server.id");
if (serverId != null) {
props.remove("server.id");
File myId = new File(props.getProperty("dataDir"), "myid");
if (myId.exists()) {
myId.delete();
}
if (myId.getParentFile() != null) {
myId.getParentFile().mkdirs();
}
FileOutputStream fos = new FileOutputStream(myId);
try {
fos.write((serverId + "\n").getBytes());
} finally {
fos.close();
}
}
QuorumPeerConfig config = new QuorumPeerConfig();
config.parseProperties(props);
if (!config.getServers().isEmpty()) {
NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory();
cnxnFactory.configure(config.getClientPortAddress(), config.getMaxClientCnxns());
QuorumPeer quorumPeer = new QuorumPeer();
quorumPeer.setClientPortAddress(config.getClientPortAddress());
quorumPeer.setTxnFactory(new FileTxnSnapLog(
new File(config.getDataLogDir()),
new File(config.getDataDir())));
quorumPeer.setQuorumPeers(config.getServers());
quorumPeer.setElectionType(config.getElectionAlg());
quorumPeer.setMyid(config.getServerId());
quorumPeer.setTickTime(config.getTickTime());
quorumPeer.setMinSessionTimeout(config.getMinSessionTimeout());
quorumPeer.setMaxSessionTimeout(config.getMaxSessionTimeout());
quorumPeer.setInitLimit(config.getInitLimit());
quorumPeer.setSyncLimit(config.getSyncLimit());
quorumPeer.setQuorumVerifier(config.getQuorumVerifier());
quorumPeer.setCnxnFactory(cnxnFactory);
quorumPeer.setZKDatabase(new ZKDatabase(quorumPeer.getTxnFactory()));
quorumPeer.setLearnerType(config.getPeerType());
try {
debug("Starting quorum peer \"%s\" on address %s", quorumPeer.getMyid(), config.getClientPortAddress());
quorumPeer.start();
debug("Started quorum peer \"%s\"", quorumPeer.getMyid());
} catch (Exception e) {
LOG.warn(String.format("Failed to start quorum peer \"%s\", reason : ", quorumPeer.getMyid(), e));
quorumPeer.shutdown();
throw e;
}
servers.put(pid, quorumPeer);
services.put(pid, bundleContext.registerService(QuorumStats.Provider.class.getName(), quorumPeer, properties));
} else {
ServerConfig cfg = new ServerConfig();
cfg.readFrom(config);
ZooKeeperServer zkServer = new ZooKeeperServer();
FileTxnSnapLog ftxn = new FileTxnSnapLog(new
File(cfg.getDataLogDir()), new File(cfg.getDataDir()));
zkServer.setTxnLogFactory(ftxn);
zkServer.setTickTime(cfg.getTickTime());
zkServer.setMinSessionTimeout(cfg.getMinSessionTimeout());
zkServer.setMaxSessionTimeout(cfg.getMaxSessionTimeout());
NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory();
cnxnFactory.configure(cfg.getClientPortAddress(), cfg.getMaxClientCnxns());
try {
debug("Starting ZooKeeper server on address %s", config.getClientPortAddress());
cnxnFactory.startup(zkServer);
LOG.debug("Started ZooKeeper server");
} catch (Exception e) {
LOG.warn(String.format("Failed to start ZooKeeper server, reason : %s", e));
cnxnFactory.shutdown();
throw e;
}
servers.put(pid, cnxnFactory);
services.put(pid, bundleContext.registerService(ServerStats.Provider.class.getName(), zkServer, properties));
}
} catch (Exception e) {
throw (ConfigurationException) new ConfigurationException(null, "Unable to parse ZooKeeper configuration: " + e.getMessage()).initCause(e);
}
}
|
public void writeHtml() {
for (String asset : ASSETS) {
copyResourceToOutput(asset, output);
}
DefaultMustacheFactory mustacheFactory = new DefaultMustacheFactory();
Mustache summary = mustacheFactory.compile("index.html");
Mustache device = mustacheFactory.compile("index-device.html");
Mustache testClass = mustacheFactory.compile("index-test-class.html");
Mustache test = mustacheFactory.compile("index-test.html");
try {
summary.execute(new FileWriter(new File(output, "index.html")), this).flush();
for (ExecutionResult result : results) {
result.updateDynamicValues();
File deviceOutput = new File(output, result.serial + "/index.html");
device.execute(new FileWriter(deviceOutput), result).flush();
}
for (InstrumentationTestClass instrumentationTestClass : getInstrumentationTestClasses()) {
File testDir = new File(output, instrumentationTestClass.classSimpleName);
testDir.mkdirs();
File testClassOutput = new File(testDir.getPath(), "index.html");
testClass.execute(new FileWriter(testClassOutput), instrumentationTestClass).flush();
for (InstrumentationTest instrumentationTest : instrumentationTestClass.tests()) {
File testOutput = new File(testDir.getPath(), instrumentationTest.testName + ".html");
test.execute(new FileWriter(testOutput), instrumentationTest).flush();
for (ExecutionTestResult result : instrumentationTest.results()) {
makeGif(result);
}
}
}
} catch (IOException e) {
throw new RuntimeException("Unable to write output HTML.", e);
}
}
| public void writeHtml() {
for (String asset : ASSETS) {
copyResourceToOutput(asset, output);
}
DefaultMustacheFactory mustacheFactory = new DefaultMustacheFactory();
Mustache summary = mustacheFactory.compile("index.html");
Mustache device = mustacheFactory.compile("index-device.html");
Mustache test = mustacheFactory.compile("index-test.html");
try {
summary.execute(new FileWriter(new File(output, "index.html")), this).flush();
for (ExecutionResult result : results) {
result.updateDynamicValues();
File deviceOutput = new File(output, result.serial + "/index.html");
device.execute(new FileWriter(deviceOutput), result).flush();
}
for (InstrumentationTestClass instrumentationTestClass : getInstrumentationTestClasses()) {
File testDir = new File(output, instrumentationTestClass.classSimpleName);
testDir.mkdirs();
for (InstrumentationTest instrumentationTest : instrumentationTestClass.tests()) {
File testOutput = new File(testDir.getPath(), instrumentationTest.testName + ".html");
test.execute(new FileWriter(testOutput), instrumentationTest).flush();
for (ExecutionTestResult result : instrumentationTest.results()) {
makeGif(result);
}
}
}
} catch (IOException e) {
throw new RuntimeException("Unable to write output HTML.", e);
}
}
|
public FetchResult updateData(Context context, boolean force) {
DBOpenHelper dbhelper = new DBOpenHelper(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
try {
if (!isOnline(context)) {
Log.d(TAG, "We do not seem to be online. Skipping Update.");
return FetchResult.NOTONLINE;
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if (!force) {
try {
if (sp.getBoolean("loginFailed", false) == true) {
Log.d(TAG, "Previous login failed. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
return FetchResult.LOGINFAILED;
}
if(sp.getBoolean("autoupdates", true) == false) {
Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Background data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Auto sync not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
return FetchResult.NOTALLOWED;
} else if (!isWifi(context)){
Log.d(TAG, "We are not on wifi.");
if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
} else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update.");
}
} else {
Log.d(TAG, "Update Forced");
}
try {
String username = sp.getString("username", null);
String password = sp.getString("password", null);
if(username == null || password == null) {
DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
return FetchResult.USERNAMEPASSWORDNOTSET;
}
Log.d(TAG, "Finding Action. ");
HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
String loginPageString = loginPageGet.execute();
if (loginPageString != null) {
Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login");
Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
String loginAction = loginForm.attr("action");
List<NameValuePair> loginValues = new ArrayList <NameValuePair>();
loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
loginValues.add(new BasicNameValuePair("hdnAction", "login"));
loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
loginValues.add(new BasicNameValuePair("hdnlocale", ""));
loginValues.add(new BasicNameValuePair("userid", username));
loginValues.add(new BasicNameValuePair("password", password));
Log.d(TAG, "Sending Login ");
HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
Document homePage = Jsoup.parse(sendLoginPoster.execute());
boolean postPaid;
if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) {
Log.d(TAG, "Pre-pay account or no account.");
postPaid = false;
} else {
Log.d(TAG, "Post-paid account.");
postPaid = true;
}
Element accountSummary = homePage.getElementById("accountSummary");
if (accountSummary == null) {
Log.d(TAG, "Login failed.");
return FetchResult.LOGINFAILED;
}
db.delete("cache", "", null);
Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
Elements rows = accountSummaryTable.getElementsByTag("tr");
for (Element row : rows) {
Double value;
String units;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
String[] amountParts = amountHTML.split(" ", 2);
if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")) {
value = Values.INCLUDED;
} else {
try {
value = Double.parseDouble(amountParts[0]);
} catch (NumberFormatException e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
value = 0.0;
}
}
units = amountParts[1];
} catch (NullPointerException e) {
value = null;
units = null;
}
Element details = row.getElementsByClass("tableBilldetail").first();
String name = details.getElementsByTag("strong").first().text();
Element expires = details.getElementsByTag("em").first();
String expiresDetails = "";
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
if (postPaid == false) {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
} else {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
}
Matcher matcher = pattern.matcher(expiresDetails);
Double expiresValue = null;
String expiresDate = null;
if (matcher.find()) {
try {
expiresValue = Double.parseDouble(matcher.group(1));
} catch (NumberFormatException e) {
expiresValue = null;
}
String expiresDateString = matcher.group(2);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", units);
values.put("expires_value", expiresValue);
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
}
if(postPaid == false) {
Log.d(TAG, "Getting Value packs...");
HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
String valuePacksPageString = valuePacksPageGet.execute();
if(valuePacksPageString != null) {
Document valuePacksPage = Jsoup.parse(valuePacksPageString);
Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
for (Element enabledPack : enabledPacks) {
Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first();
String offerName = offerNameElemt.val();
DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
ValuePack[] packs = Values.valuePacks.get(offerName);
if (packs == null) {
DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched.");
} else {
for (ValuePack pack: packs) {
ContentValues values = new ContentValues();
values.put("plan_startamount", pack.value);
values.put("plan_name", offerName);
DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value);
db.update("cache", values, "name = '" + pack.type.id + "'", null);
}
}
}
}
}
SharedPreferences.Editor prefedit = sp.edit();
Date now = new Date();
prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
prefedit.putBoolean("loginFailed", false);
prefedit.putBoolean("networkError", false);
prefedit.commit();
DBLog.insertMessage(context, "i", TAG, "Update Successful");
return FetchResult.SUCCESS;
}
} catch (ClientProtocolException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
} catch (IOException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
}
finally {
db.close();
}
return null;
}
| public FetchResult updateData(Context context, boolean force) {
DBOpenHelper dbhelper = new DBOpenHelper(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
try {
if (!isOnline(context)) {
Log.d(TAG, "We do not seem to be online. Skipping Update.");
return FetchResult.NOTONLINE;
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception during isOnline()");
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
if (!force) {
try {
if (sp.getBoolean("loginFailed", false) == true) {
Log.d(TAG, "Previous login failed. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Previous login failed. Skipping Update.");
return FetchResult.LOGINFAILED;
}
if(sp.getBoolean("autoupdates", true) == false) {
Log.d(TAG, "Automatic updates not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isBackgroundDataEnabled(context) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Background data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Background data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (!isAutoSyncEnabled() && sp.getBoolean("obeyAutoSync", true) && sp.getBoolean("obeyBackgroundData", true)) {
Log.d(TAG, "Auto sync not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Auto sync not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
if (isWifi(context) && !sp.getBoolean("wifiUpdates", true)) {
Log.d(TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
DBLog.insertMessage(context, "i", TAG, "On wifi, and wifi auto updates not allowed. Skipping Update");
return FetchResult.NOTALLOWED;
} else if (!isWifi(context)){
Log.d(TAG, "We are not on wifi.");
if (!isRoaming(context) && !sp.getBoolean("2DData", true)) {
Log.d(TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on 2Degrees data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
} else if (isRoaming(context) && !sp.getBoolean("roamingData", false)) {
Log.d(TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
DBLog.insertMessage(context, "i", TAG, "Automatic updates on roaming mobile data not enabled. Skipping Update.");
return FetchResult.NOTALLOWED;
}
}
} catch (Exception e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Exception while finding if to update.");
}
} else {
Log.d(TAG, "Update Forced");
}
try {
String username = sp.getString("username", null);
String password = sp.getString("password", null);
if(username == null || password == null) {
DBLog.insertMessage(context, "i", TAG, "Username or password not set.");
return FetchResult.USERNAMEPASSWORDNOTSET;
}
Log.d(TAG, "Finding Action. ");
HttpGetter loginPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/web/ip/login");
String loginPageString = loginPageGet.execute();
if (loginPageString != null) {
Document loginPage = Jsoup.parse(loginPageString, "https://secure.2degreesmobile.co.nz/web/ip/login");
Element loginForm = loginPage.getElementsByAttributeValue("name", "loginFrm").first();
String loginAction = loginForm.attr("action");
List<NameValuePair> loginValues = new ArrayList <NameValuePair>();
loginValues.add(new BasicNameValuePair("externalURLRedirect", ""));
loginValues.add(new BasicNameValuePair("hdnAction", "login_userlogin"));
loginValues.add(new BasicNameValuePair("hdnAuthenticationType", "M"));
loginValues.add(new BasicNameValuePair("hdnlocale", ""));
loginValues.add(new BasicNameValuePair("userid", username));
loginValues.add(new BasicNameValuePair("password", password));
Log.d(TAG, "Sending Login ");
HttpPoster sendLoginPoster = new HttpPoster(loginAction, loginValues);
Document homePage = Jsoup.parse(sendLoginPoster.execute());
boolean postPaid;
if (homePage.getElementById("p_p_id_PostPaidHomePage_WAR_Homepage_") == null) {
Log.d(TAG, "Pre-pay account or no account.");
postPaid = false;
} else {
Log.d(TAG, "Post-paid account.");
postPaid = true;
}
Element accountSummary = homePage.getElementById("accountSummary");
if (accountSummary == null) {
Log.d(TAG, "Login failed.");
return FetchResult.LOGINFAILED;
}
db.delete("cache", "", null);
Element accountSummaryTable = accountSummary.getElementsByClass("tableAccountSummary").first();
Elements rows = accountSummaryTable.getElementsByTag("tr");
for (Element row : rows) {
Double value;
String units;
try {
Element amount = row.getElementsByClass("tableBillamount").first();
String amountHTML = amount.html();
String[] amountParts = amountHTML.split(" ", 2);
if (amountParts[0].contains("Included") || amountParts[0].equals("All You Need")) {
value = Values.INCLUDED;
} else {
try {
value = Double.parseDouble(amountParts[0]);
} catch (NumberFormatException e) {
exceptionReporter.reportException(Thread.currentThread(), e, "Decoding value.");
value = 0.0;
}
}
units = amountParts[1];
} catch (NullPointerException e) {
value = null;
units = null;
}
Element details = row.getElementsByClass("tableBilldetail").first();
String name = details.getElementsByTag("strong").first().text();
Element expires = details.getElementsByTag("em").first();
String expiresDetails = "";
if (expires != null) {
expiresDetails = expires.text();
}
Log.d(TAG, expiresDetails);
Pattern pattern;
if (postPaid == false) {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?expiring on (.*)\\)");
} else {
pattern = Pattern.compile("\\(([\\d\\.]*) ?\\w*? ?will expire on (.*)\\)");
}
Matcher matcher = pattern.matcher(expiresDetails);
Double expiresValue = null;
String expiresDate = null;
if (matcher.find()) {
try {
expiresValue = Double.parseDouble(matcher.group(1));
} catch (NumberFormatException e) {
expiresValue = null;
}
String expiresDateString = matcher.group(2);
Date expiresDateObj;
if (expiresDateString != null) {
if (expiresDateString.length() > 0) {
try {
expiresDateObj = DateFormatters.EXPIRESDATE.parse(expiresDateString);
expiresDate = DateFormatters.ISO8601DATEONLYFORMAT.format(expiresDateObj);
} catch (java.text.ParseException e) {
Log.d(TAG, "Could not parse date: " + expiresDateString);
}
}
}
}
ContentValues values = new ContentValues();
values.put("name", name);
values.put("value", value);
values.put("units", units);
values.put("expires_value", expiresValue);
values.put("expires_date", expiresDate);
db.insert("cache", "value", values );
}
if(postPaid == false) {
Log.d(TAG, "Getting Value packs...");
HttpGetter valuePacksPageGet = new HttpGetter("https://secure.2degreesmobile.co.nz/group/ip/prevaluepack");
String valuePacksPageString = valuePacksPageGet.execute();
if(valuePacksPageString != null) {
Document valuePacksPage = Jsoup.parse(valuePacksPageString);
Elements enabledPacks = valuePacksPage.getElementsByClass("yellow");
for (Element enabledPack : enabledPacks) {
Element offerNameElemt = enabledPack.getElementsByAttributeValueStarting("name", "offername").first();
String offerName = offerNameElemt.val();
DBLog.insertMessage(context, "d", "", "Got element: " + offerName);
ValuePack[] packs = Values.valuePacks.get(offerName);
if (packs == null) {
DBLog.insertMessage(context, "d", "", "Offer name: " + offerName + " not matched.");
} else {
for (ValuePack pack: packs) {
ContentValues values = new ContentValues();
values.put("plan_startamount", pack.value);
values.put("plan_name", offerName);
DBLog.insertMessage(context, "d", "", "Pack " + pack.type.id + " start value set to " + pack.value);
db.update("cache", values, "name = '" + pack.type.id + "'", null);
}
}
}
}
}
SharedPreferences.Editor prefedit = sp.edit();
Date now = new Date();
prefedit.putString("updateDate", DateFormatters.ISO8601FORMAT.format(now));
prefedit.putBoolean("loginFailed", false);
prefedit.putBoolean("networkError", false);
prefedit.commit();
DBLog.insertMessage(context, "i", TAG, "Update Successful");
return FetchResult.SUCCESS;
}
} catch (ClientProtocolException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
} catch (IOException e) {
DBLog.insertMessage(context, "w", TAG, "Network error: " + e.getMessage());
return FetchResult.NETWORKERROR;
}
finally {
db.close();
}
return null;
}
|
public static void loadModels(String name) {
VirtualFile yamlFile = null;
try {
for (VirtualFile vf : Play.javaPath) {
yamlFile = vf.child(name);
if (yamlFile != null && yamlFile.exists()) {
break;
}
}
if (yamlFile == null) {
throw new RuntimeException("Cannot load fixture " + name + ", the file was not found");
}
String renderedYaml = TemplateLoader.load(yamlFile).render();
Yaml yaml = new Yaml();
Object o = yaml.load(renderedYaml);
if (o instanceof LinkedHashMap<?, ?>) {
LinkedHashMap<Object, Map<?, ?>> objects = (LinkedHashMap<Object, Map<?, ?>>) o;
for (Object key : objects.keySet()) {
Matcher matcher = keyPattern.matcher(key.toString().trim());
if (matcher.matches()) {
String type = matcher.group(1);
String id = matcher.group(2);
if (!type.startsWith("models.")) {
type = "models." + type;
}
if (idCache.containsKey(type + "-" + id)) {
throw new RuntimeException("Cannot load fixture " + name + ", duplicate id '" + id + "' for type " + type);
}
Map<String, String[]> params = new HashMap<String, String[]>();
if (objects.get(key) == null) {
objects.put(key, new HashMap<Object, Object>());
}
serialize(objects.get(key), "object", params);
Class<?> cType = (Class<?>)Play.classloader.loadClass(type);
resolveDependencies(cType, params);
Object model = Binder.bind("object", cType, cType, null, params);
@SuppressWarnings("rawtypes")
List queryObj = new ArrayList();
for(Field f : model.getClass().getFields()) {
if (f.getType().isAssignableFrom(Map.class)) {
f.set(model, objects.get(key).get(f.getName()));
} else if (f.getType().equals(byte[].class)) {
f.set(model, objects.get(key).get(f.getName()));
} else if(Json.class.isAssignableFrom(f.getType())){
Object obj = objects.get(key).get(f.getName());
Json json = new Json(obj);
if(json!=null){
f.set(model, json);
}
} else if(f.isAnnotationPresent(Embedded.class) && List.class.isAssignableFrom(f.getType())){
Object obj = objects.get(key).get(f.getName());
f.set(model, obj);
} else if(siena.Query.class.isAssignableFrom(f.getType())){
final Class<?> fieldType = (Class<?>) ((ParameterizedType) f.getGenericType()).getActualTypeArguments()[0];
final String ownerFieldName = f.getAnnotation(Filter.class).value();
ArrayList<String> linkedKeys = (ArrayList<String>)objects.get(key).get(f.getName());
if(linkedKeys != null){
for(String linkedKey: linkedKeys){
Object linkedId = idCache.get(type + "-" + linkedKey);
Object linkedObj = SienaPlugin.pm().getByKey(fieldType, linkedId);
if(linkedObj != null){
siena.Util.setField(linkedObj, fieldType.getField(ownerFieldName), model);
queryObj.add(linkedObj);
}else {
throw new RuntimeException("AutoQuery: linkedObj of type:"+fieldType.getName()+" and id:"+linkedKey+" was not found");
}
}
}
}
}
SienaPlugin.pm().save(model);
if(!queryObj.isEmpty()){
SienaPlugin.pm().save(queryObj);
}
Class<?> tType = cType;
while (!tType.equals(Object.class)) {
idCache.put(tType.getName() + "-" + id, SienaModelUtils.keyValue(model));
tType = tType.getSuperclass();
}
}
}
}
Play.pluginCollection.afterFixtureLoad();
} catch (ClassNotFoundException e) {
throw new RuntimeException("Class " + e.getMessage() + " was not found", e);
} catch (ScannerException e) {
throw new YAMLException(e, yamlFile);
} catch (Throwable e) {
throw new RuntimeException("Cannot load fixture " + name + ": " + e.getMessage(), e);
}
}
| public static void loadModels(String name) {
VirtualFile yamlFile = null;
try {
for (VirtualFile vf : Play.javaPath) {
yamlFile = vf.child(name);
if (yamlFile != null && yamlFile.exists()) {
break;
}
}
if (yamlFile == null) {
throw new RuntimeException("Cannot load fixture " + name + ", the file was not found");
}
String renderedYaml = TemplateLoader.load(yamlFile).render();
Yaml yaml = new Yaml();
Object o = yaml.load(renderedYaml);
if (o instanceof LinkedHashMap<?, ?>) {
LinkedHashMap<Object, Map<?, ?>> objects = (LinkedHashMap<Object, Map<?, ?>>) o;
for (Object key : objects.keySet()) {
Matcher matcher = keyPattern.matcher(key.toString().trim());
if (matcher.matches()) {
String type = matcher.group(1);
String id = matcher.group(2);
if (!type.startsWith("models.")) {
type = "models." + type;
}
if (idCache.containsKey(type + "-" + id)) {
throw new RuntimeException("Cannot load fixture " + name + ", duplicate id '" + id + "' for type " + type);
}
Map<String, String[]> params = new HashMap<String, String[]>();
if (objects.get(key) == null) {
objects.put(key, new HashMap<Object, Object>());
}
serialize(objects.get(key), "object", params);
Class<?> cType = (Class<?>)Play.classloader.loadClass(type);
resolveDependencies(cType, params);
Object model = Binder.bind("object", cType, cType, null, params);
@SuppressWarnings("rawtypes")
List queryObj = new ArrayList();
for(Field f : model.getClass().getFields()) {
if (f.getType().isAssignableFrom(Map.class)) {
f.set(model, objects.get(key).get(f.getName()));
} else if (f.getType().equals(byte[].class)) {
f.set(model, objects.get(key).get(f.getName()));
} else if(Json.class.isAssignableFrom(f.getType())){
Object obj = objects.get(key).get(f.getName());
Json json = new Json(obj);
if(json!=null){
f.set(model, json);
}
} else if(f.isAnnotationPresent(Embedded.class) && List.class.isAssignableFrom(f.getType())){
Object obj = objects.get(key).get(f.getName());
f.set(model, obj);
} else if(siena.Query.class.isAssignableFrom(f.getType())){
final Class<?> fieldType = (Class<?>) ((ParameterizedType) f.getGenericType()).getActualTypeArguments()[0];
final String ownerFieldName = f.getAnnotation(Filter.class).value();
ArrayList<String> linkedKeys = (ArrayList<String>)objects.get(key).get(f.getName());
if(linkedKeys != null){
for(String linkedKey: linkedKeys){
Object linkedId = idCache.get(fieldType.getName() + "-" + linkedKey);
if(linkedId == null){
throw new RuntimeException("YAML AutoQuery mapping: linkedObj of type:"+fieldType.getName()+" and id:"+linkedKey+" was not found");
}
Object linkedObj = SienaPlugin.pm().getByKey(fieldType, linkedId);
if(linkedObj != null){
siena.Util.setField(linkedObj, fieldType.getField(ownerFieldName), model);
queryObj.add(linkedObj);
}else {
throw new RuntimeException("YAML AutoQuery mapping: linkedObj of type:"+fieldType.getName()+" and id:"+linkedKey+" was not found");
}
}
}
}
}
SienaPlugin.pm().save(model);
if(!queryObj.isEmpty()){
SienaPlugin.pm().save(queryObj);
}
Class<?> tType = cType;
while (!tType.equals(Object.class)) {
idCache.put(tType.getName() + "-" + id, SienaModelUtils.keyValue(model));
tType = tType.getSuperclass();
}
}
}
}
Play.pluginCollection.afterFixtureLoad();
} catch (ClassNotFoundException e) {
throw new RuntimeException("Class " + e.getMessage() + " was not found", e);
} catch (ScannerException e) {
throw new YAMLException(e, yamlFile);
} catch (Throwable e) {
throw new RuntimeException("Cannot load fixture " + name + ": " + e.getMessage(), e);
}
}
|
public final boolean isSameRowAs(SourcePosition other)
{
if (getContext() == null && other.getContext() == null)
return true;
else if (getContext() == null && other.getContext() != null)
return false;
else if (other.getContext() == null && getContext() != null)
return false;
else
return other.getContext().equals(getContext()) &&
(other.getRow() == getRow());
}
| public final boolean isSameRowAs(SourcePosition other)
{
if (getContext() == null && other.getContext() == null)
return other.getRow() == getRow();
else if (getContext() == null && other.getContext() != null)
return false;
else if (other.getContext() == null && getContext() != null)
return false;
else
return other.getContext().equals(getContext()) &&
(other.getRow() == getRow());
}
|
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem addAccountItem = menu.add("Add account");
addAccountItem.setIcon(R.drawable.ic_menu_add);
addAccountItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
addAccountItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
addAccount();
return true;
}
});
MenuItem sendFeedback = menu.add("Send feedback");
sendFeedback.setIcon(R.drawable.ic_menu_start_conversation);
sendFeedback.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
sendFeedback.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
getZubhiumSDK(HomeActivity.this).openFeedbackDialog(HomeActivity.this);
return true;
}
});
return true;
}
| public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem addAccountItem = menu.add("Add account");
addAccountItem.setIcon(R.drawable.ic_menu_add);
addAccountItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
addAccountItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
addAccount();
return true;
}
});
MenuItem sendFeedback = menu.add("Send feedback");
sendFeedback.setIcon(R.drawable.ic_menu_start_conversation);
sendFeedback.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
sendFeedback.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
getZubhiumSDK(HomeActivity.this).openFeedbackDialog(HomeActivity.this);
return true;
}
});
return true;
}
|
public void doCrawl(HttpServletRequest req) throws WebCrawlException {
int i = 0;
int j = 0;
int k = 0;
String msg = null;
String urlStr = null;
try {
for (k=0; k<URL_LIST.length; k++) {
urlStr = URL_LIST[k];
logger.info("Processing URL: " + urlStr);
URL url = new URL(urlStr);
InputStream is = url.openStream();
String res = null;
try {
res = convertStreamToString(is);
}
catch (Exception e) {
}
Tidy tidy = new Tidy();
tidy.setMakeClean(true);
tidy.setQuiet(false);
tidy.setBreakBeforeBR(true);
tidy.setOutputEncoding("latin1");
tidy.setXmlOut(false);
tidy.setNumEntities(true);
tidy.setDropFontTags(true);
tidy.setSpaces(2);
tidy.setIndentAttributes(false);
tidy.setHideComments(true);
tidy.setShowWarnings(false);
OutputStream os = null;
StringReader r = new StringReader(res);
StringWriter w = new StringWriter();
Document doc = tidy.parseDOM(r, w);
Date reportDate = null;
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
NodeList spanList = doc.getElementsByTagName("span");
if (spanList != null && spanList.getLength() > 0) {
logger.info("Found expected span tag(s) on the page");
}
else {
throw new WebCrawlException("Unexpected number of <table> tags", urlStr);
}
ReportDO report = null;
Node tdTag = null;
ReportDao reportDao = new ReportDao();
report.setReportedBy(PROVIDER);
String keyword = null;
String dateStr = null;
String reportStr = null;
List<String> textList = null;
NamedNodeMap attribMap = null;
for (i=0; i<spanList.getLength(); i++) {
Node node = spanList.item(i);
if (node != null) {
attribMap = node.getAttributes();
Node id = attribMap.getNamedItem("id");
if (id != null) {
if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_NameLabel")) {
keyword = getNodeContents(node);
logger.info("Found keyword: " + keyword);
}
else if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_Label1")) {
dateStr = getNodeContents(node);
logger.info("Found dateStr: " + dateStr);
try {
reportDate = formatter.parse(dateStr);
}
catch (Exception e) {
throw new WebCrawlException(e.getMessage(), urlStr);
}
}
else if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_FishingReportLabel")) {
reportStr = getNodeContents(node);
logger.info("Using report text: " + reportStr);
report = new ReportDO();
report.setKeyword(keyword);
report.setReportDate(reportDate);
report.setReportBody(reportStr);
report.setState(STATE);
StringBuilder sb = new StringBuilder();
sb.append(STATE);
sb.append(":");
String uniqueKey = report.getKeyword();
uniqueKey= uniqueKey.toUpperCase();
uniqueKey = EscapeChars.forXML(uniqueKey);
sb.append(uniqueKey);
report.setReportKey(sb.toString());
reportDao.addOrUpdateReport(report);
break;
}
else {
throw new WebCrawlException("Unknown <span id='" + id.getNodeValue() + "'> tag; page might have changed.", urlStr);
}
}
}
}
}
}
catch (MalformedURLException e) {
logger.severe(Util.getStackTrace(e));
throw new WebCrawlException(e.getMessage(), urlStr);
}
catch (IOException e) {
logger.severe(Util.getStackTrace(e));
throw new WebCrawlException(e.getMessage(), urlStr);
}
}
| public void doCrawl(HttpServletRequest req) throws WebCrawlException {
int i = 0;
int j = 0;
int k = 0;
String msg = null;
String urlStr = null;
try {
for (k=0; k<URL_LIST.length; k++) {
urlStr = URL_LIST[k];
logger.info("Processing URL: " + urlStr);
URL url = new URL(urlStr);
InputStream is = url.openStream();
String res = null;
try {
res = convertStreamToString(is);
}
catch (Exception e) {
}
Tidy tidy = new Tidy();
tidy.setMakeClean(true);
tidy.setQuiet(false);
tidy.setBreakBeforeBR(true);
tidy.setOutputEncoding("latin1");
tidy.setXmlOut(false);
tidy.setNumEntities(true);
tidy.setDropFontTags(true);
tidy.setSpaces(2);
tidy.setIndentAttributes(false);
tidy.setHideComments(true);
tidy.setShowWarnings(false);
OutputStream os = null;
StringReader r = new StringReader(res);
StringWriter w = new StringWriter();
Document doc = tidy.parseDOM(r, w);
Date reportDate = null;
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
NodeList spanList = doc.getElementsByTagName("span");
if (spanList != null && spanList.getLength() > 0) {
logger.info("Found expected span tag(s) on the page");
}
else {
throw new WebCrawlException("Unexpected number of <table> tags", urlStr);
}
ReportDO report = null;
Node tdTag = null;
ReportDao reportDao = new ReportDao();
String keyword = null;
String dateStr = null;
String reportStr = null;
List<String> textList = null;
NamedNodeMap attribMap = null;
for (i=0; i<spanList.getLength(); i++) {
Node node = spanList.item(i);
if (node != null) {
attribMap = node.getAttributes();
Node id = attribMap.getNamedItem("id");
if (id != null) {
if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_NameLabel")) {
keyword = getNodeContents(node);
logger.info("Found keyword: " + keyword);
}
else if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_Label1")) {
dateStr = getNodeContents(node);
logger.info("Found dateStr: " + dateStr);
try {
reportDate = formatter.parse(dateStr);
}
catch (Exception e) {
throw new WebCrawlException(e.getMessage(), urlStr);
}
}
else if (id.getNodeValue().equalsIgnoreCase("ctl00_ContentPlaceHolder1_FormView1_FishingReportLabel")) {
reportStr = getNodeContents(node);
logger.info("Using report text: " + reportStr);
report = new ReportDO();
report.setReportedBy(PROVIDER);
report.setKeyword(keyword);
report.setReportDate(reportDate);
report.setReportBody(reportStr);
report.setState(STATE);
StringBuilder sb = new StringBuilder();
sb.append(STATE);
sb.append(":");
String uniqueKey = report.getKeyword();
uniqueKey= uniqueKey.toUpperCase();
uniqueKey = EscapeChars.forXML(uniqueKey);
sb.append(uniqueKey);
report.setReportKey(sb.toString());
reportDao.addOrUpdateReport(report);
break;
}
else {
throw new WebCrawlException("Unknown <span id='" + id.getNodeValue() + "'> tag; page might have changed.", urlStr);
}
}
}
}
}
}
catch (MalformedURLException e) {
logger.severe(Util.getStackTrace(e));
throw new WebCrawlException(e.getMessage(), urlStr);
}
catch (IOException e) {
logger.severe(Util.getStackTrace(e));
throw new WebCrawlException(e.getMessage(), urlStr);
}
}
|
public String[] list(String file) throws IOException {
FileConnection fc = (FileConnection)Connector.open(pathFor(file)+'/', Connector.READ);
try {
Enumeration e = fc.list("*", true);
Vector v = new Vector();
while (e.hasMoreElements()) v.addElement(e.nextElement());
int size = v.size();
String[] files = new String[size];
for (int i=0; i<size; i++) {
files[i] = (String)v.elementAt(i);
}
return files;
} finally {
fc.close();
}
}
| public String[] list(String file) throws IOException {
String path = pathFor(file);
if (!path.endsWith("/")) path += "/";
FileConnection fc = (FileConnection)Connector.open(path, Connector.READ);
try {
Enumeration e = fc.list("*", false);
Vector v = new Vector();
while (e.hasMoreElements()) v.addElement(e.nextElement());
int size = v.size();
String[] files = new String[size];
for (int i=0; i<size; i++) {
files[i] = (String)v.elementAt(i);
}
return files;
} finally {
fc.close();
}
}
|
public AnyKeyboard nextKeyboard(EditorInfo currentEditorInfo, NextKeyboardType type)
{
AnyKeyboard locked = getLockedKeyboard(currentEditorInfo);
if (locked != null)
return locked;
switch(type)
{
case Alphabet:
case AlphabetSupportsPhysical:
return nextAlphabetKeyboard(currentEditorInfo, (type == NextKeyboardType.AlphabetSupportsPhysical));
case Symbols:
return nextSymbolsKeyboard(currentEditorInfo);
case Any:
case PreviousAny:
final int alphabetKeyboardsCount = getAlphabetKeyboards().length;
final int symbolsKeyboardsCount = mSymbolsKeyboardsArray.length;
if (mAlphabetMode)
{
if (mLastSelectedKeyboard >= (alphabetKeyboardsCount-1))
{
mLastSelectedKeyboard = 0;
return nextSymbolsKeyboard(currentEditorInfo);
}
else
return nextAlphabetKeyboard(currentEditorInfo, false);
}
else
{
if (mLastSelectedSymbolsKeyboard >= (symbolsKeyboardsCount-1))
{
mLastSelectedSymbolsKeyboard = 0;
return nextAlphabetKeyboard(currentEditorInfo, false);
}
else
return nextSymbolsKeyboard(currentEditorInfo);
}
case AnyInsideMode:
if (mAlphabetMode)
{
return nextKeyboard(currentEditorInfo, NextKeyboardType.Alphabet);
}
else
{
return nextKeyboard(currentEditorInfo, NextKeyboardType.Symbols);
}
case OtherMode:
if (mAlphabetMode)
{
return nextKeyboard(currentEditorInfo, NextKeyboardType.Symbols);
}
else
{
return nextKeyboard(currentEditorInfo, NextKeyboardType.Alphabet);
}
default:
return nextAlphabetKeyboard(currentEditorInfo, false);
}
}
| public AnyKeyboard nextKeyboard(EditorInfo currentEditorInfo, NextKeyboardType type)
{
AnyKeyboard locked = getLockedKeyboard(currentEditorInfo);
if (locked != null)
return locked;
switch(type)
{
case Alphabet:
case AlphabetSupportsPhysical:
return nextAlphabetKeyboard(currentEditorInfo, (type == NextKeyboardType.AlphabetSupportsPhysical));
case Symbols:
return nextSymbolsKeyboard(currentEditorInfo);
case Any:
case PreviousAny:
final int alphabetKeyboardsCount = getAlphabetKeyboards().length;
if (mAlphabetMode)
{
if (mLastSelectedKeyboard >= (alphabetKeyboardsCount-1))
{
mLastSelectedKeyboard = 0;
return nextSymbolsKeyboard(currentEditorInfo);
}
else
{
return nextAlphabetKeyboard(currentEditorInfo, false);
}
}
else
{
if (mLastSelectedSymbolsKeyboard >= SYMBOLS_KEYBOARD_LAST_CYCLE_INDEX)
{
mLastSelectedSymbolsKeyboard = 0;
return nextAlphabetKeyboard(currentEditorInfo, false);
}
else
{
return nextSymbolsKeyboard(currentEditorInfo);
}
}
case AnyInsideMode:
if (mAlphabetMode)
{
return nextKeyboard(currentEditorInfo, NextKeyboardType.Alphabet);
}
else
{
return nextKeyboard(currentEditorInfo, NextKeyboardType.Symbols);
}
case OtherMode:
if (mAlphabetMode)
{
return nextKeyboard(currentEditorInfo, NextKeyboardType.Symbols);
}
else
{
return nextKeyboard(currentEditorInfo, NextKeyboardType.Alphabet);
}
default:
return nextAlphabetKeyboard(currentEditorInfo, false);
}
}
|
public void run() {
if (source != null) {
running = true;
System.out.println("Clusterer Started: " + source.getVertexCount()
+ " nodes & " + source.getEdgeCount()
+ " edges. on "
+ Thread.currentThread().getName());
HashSet<ChromatinLocation> clustered = new HashSet<ChromatinLocation>();
BlockingQueue<ChromatinGraph> clusterQueue = new LinkedBlockingQueue<ChromatinGraph>();
notifyStart(clusterQueue, source);
Map<ChromatinLocation, Double> clusteringCoefficients = Metrics.clusteringCoefficients(source);
for (ChromatinLocation headLocation : clusteringCoefficients.keySet()) {
if (clusteringCoefficients.get(headLocation) >= threshold
&& !clustered.contains(headLocation)) {
HashSet<ChromatinLocation> cluster = new HashSet<ChromatinLocation>();
cluster.add(headLocation);
cluster.addAll(cluster);
ChromatinGraph induced = FilterUtils.createInducedSubgraph(cluster,
source);
clustered.addAll(clustered);
try {
clusterQueue.put(induced);
notifyNewCluster(induced);
} catch (InterruptedException e) {
System.err.println("Interrupted while adding cluster to out queue");
break;
}
}
}
System.out.println("Clusterer Finished");
notifyFinished();
running = false;
}
}
| public void run() {
if (source != null) {
running = true;
System.out.println("Clusterer Started: " + source.getVertexCount()
+ " nodes & " + source.getEdgeCount()
+ " edges. on "
+ Thread.currentThread().getName());
HashSet<ChromatinLocation> clustered = new HashSet<ChromatinLocation>();
BlockingQueue<ChromatinGraph> clusterQueue = new LinkedBlockingQueue<ChromatinGraph>();
notifyStart(clusterQueue, source);
Map<ChromatinLocation, Double> clusteringCoefficients = Metrics.clusteringCoefficients(source);
for (ChromatinLocation headLocation : clusteringCoefficients.keySet()) {
if (clusteringCoefficients.get(headLocation) >= threshold
&& !clustered.contains(headLocation)) {
HashSet<ChromatinLocation> cluster = new HashSet<ChromatinLocation>();
cluster.add(headLocation);
cluster.addAll(source.getNeighbors(headLocation));
ChromatinGraph induced = FilterUtils.createInducedSubgraph(cluster,
source);
clustered.addAll(clustered);
try {
clusterQueue.put(induced);
notifyNewCluster(induced);
} catch (InterruptedException e) {
System.err.println("Interrupted while adding cluster to out queue");
break;
}
}
}
System.out.println("Clusterer Finished");
notifyFinished();
running = false;
}
}
|
public void testWithPolicy() {
try {
String repo = Constants.TESTING_PATH + "rampart_client_repo";
ConfigurationContext configContext = ConfigurationContextFactory.
createConfigurationContextFromFileSystem(repo, null);
ServiceClient serviceClient = new ServiceClient(configContext, null);
serviceClient.engageModule("addressing");
serviceClient.engageModule("rampart");
boolean basic256Supported = true;
if(basic256Supported) {
System.out.println("\nWARNING: We are using key sizes from JCE " +
"Unlimited Strength Jurisdiction Policy !!!");
}
for (int i = 1; i <= 29; i++) {
if(!basic256Supported && (i == 3 || i == 4 || i == 5)) {
continue;
}
if(i == 25){
continue;
}
Options options = new Options();
if( i == 13 ) {
continue;
}
System.out.println("Testing WS-Sec: custom scenario " + i);
options.setAction("urn:echo");
options.setTo(new EndpointReference("http://127.0.0.1:" +
PORT +
"/axis2/services/SecureService" + i));
ServiceContext context = serviceClient.getServiceContext();
context.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("/rampart/policy/" + i + ".xml"));
serviceClient.setOptions(options);
if (i == 28) {
try {
serviceClient.sendReceive(getOMElement());
fail("Service Should throw an error..");
} catch (AxisFault axisFault) {
assertEquals("Expected encrypted part missing", axisFault.getMessage());
}
}
else{
serviceClient.sendReceive(getEchoElement());
}
}
System.out.println("--------------Testing negative scenarios----------------------------");
for (int i = 1; i <= 22; i++) {
if (!basic256Supported && (i == 3 || i == 4 || i == 5)) {
continue;
}
Options options = new Options();
if (i == 13) {
continue;
}
System.out.println("Testing WS-Sec: negative scenario " + i);
options.setAction("urn:returnError");
options.setTo(new EndpointReference("http://127.0.0.1:" +
PORT +
"/axis2/services/SecureService" + i));
ServiceContext context = serviceClient.getServiceContext();
context.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("/rampart/policy/" + i + ".xml"));
serviceClient.setOptions(options);
try {
serviceClient.sendReceive(getOMElement());
fail("Service Should throw an error..");
} catch (AxisFault axisFault) {
assertEquals("Testing negative scenarios with Apache Rampart. Intentional Exception", axisFault.getMessage());
}
}
for (int i = 1; i <= 3; i++) {
if (i == 2 || i == 3) {
continue;
}
Options options = new Options();
System.out.println("Testing WS-SecConv: custom scenario " + i);
options.setAction("urn:echo");
options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureServiceSC" + i));
serviceClient.getServiceContext().setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/sc-" + i + ".xml"));
serviceClient.setOptions(options);
serviceClient.sendReceive(getEchoElement());
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE);
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_FALSE);
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE);
serviceClient.sendReceive(getEchoElement());
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
| public void testWithPolicy() {
try {
String repo = Constants.TESTING_PATH + "rampart_client_repo";
ConfigurationContext configContext = ConfigurationContextFactory.
createConfigurationContextFromFileSystem(repo, null);
ServiceClient serviceClient = new ServiceClient(configContext, null);
serviceClient.engageModule("addressing");
serviceClient.engageModule("rampart");
boolean basic256Supported = true;
if(basic256Supported) {
System.out.println("\nWARNING: We are using key sizes from JCE " +
"Unlimited Strength Jurisdiction Policy !!!");
}
for (int i = 1; i <= 30; i++) {
if(!basic256Supported && (i == 3 || i == 4 || i == 5)) {
continue;
}
if(i == 25){
continue;
}
Options options = new Options();
if( i == 13 ) {
continue;
}
System.out.println("Testing WS-Sec: custom scenario " + i);
options.setAction("urn:echo");
options.setTo(new EndpointReference("http://127.0.0.1:" +
PORT +
"/axis2/services/SecureService" + i));
ServiceContext context = serviceClient.getServiceContext();
context.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("/rampart/policy/" + i + ".xml"));
serviceClient.setOptions(options);
if (i == 28) {
try {
serviceClient.sendReceive(getOMElement());
fail("Service Should throw an error..");
} catch (AxisFault axisFault) {
assertEquals("Expected encrypted part missing", axisFault.getMessage());
}
}
else{
serviceClient.sendReceive(getEchoElement());
}
}
System.out.println("--------------Testing negative scenarios----------------------------");
for (int i = 1; i <= 22; i++) {
if (!basic256Supported && (i == 3 || i == 4 || i == 5)) {
continue;
}
Options options = new Options();
if (i == 13) {
continue;
}
System.out.println("Testing WS-Sec: negative scenario " + i);
options.setAction("urn:returnError");
options.setTo(new EndpointReference("http://127.0.0.1:" +
PORT +
"/axis2/services/SecureService" + i));
ServiceContext context = serviceClient.getServiceContext();
context.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("/rampart/policy/" + i + ".xml"));
serviceClient.setOptions(options);
try {
serviceClient.sendReceive(getOMElement());
fail("Service Should throw an error..");
} catch (AxisFault axisFault) {
assertEquals("Testing negative scenarios with Apache Rampart. Intentional Exception", axisFault.getMessage());
}
}
for (int i = 1; i <= 3; i++) {
if (i == 2 || i == 3) {
continue;
}
Options options = new Options();
System.out.println("Testing WS-SecConv: custom scenario " + i);
options.setAction("urn:echo");
options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureServiceSC" + i));
serviceClient.getServiceContext().setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/sc-" + i + ".xml"));
serviceClient.setOptions(options);
serviceClient.sendReceive(getEchoElement());
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE);
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_FALSE);
serviceClient.sendReceive(getEchoElement());
options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE);
serviceClient.sendReceive(getEchoElement());
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
|
private void terrainCollision(Entity collidee, int millis) {
Shape sh = getShape(millis);
Shape oth = collidee.getShape(millis);
if (sh.getMaxX() >= oth.getMinX()) {
velocity.x = 0;
position.x -= (sh.getMaxX() - oth.getMinX());
} else if (sh.getMinX() <= oth.getMaxX()) {
velocity.x = 0;
position.x += oth.getMaxX() - sh.getMinX();
}
else if (sh.getMaxY() >= oth.getMinY()) {
velocity.y = 0;
position.y -= sh.getMaxY() - oth.getMinY();
onGround = false;
} else if (sh.getMinY() <= oth.getMaxY()) {
velocity.y = 0;
position.y += oth.getMaxY() - sh.getMinY();
onGround = true;
} else {
throw new RuntimeException("No overlap detected: " + sh.toString() + " with " + oth.toString());
}
updateShape();
}
| private void terrainCollision(Entity collidee, int millis) {
Shape sh = getShape(millis);
Shape oth = collidee.getShape(millis);
if (sh.getMaxX() >= oth.getMinX()) {
velocity.x = 0;
position.x -= sh.getMaxX() - oth.getMinX() + 1;
} else if (sh.getMinX() <= oth.getMaxX()) {
velocity.x = 0;
position.x += oth.getMaxX() - sh.getMinX() + 1;
}
else if (sh.getMaxY() >= oth.getMinY()) {
velocity.y = 0;
position.y -= sh.getMaxY() - oth.getMinY() + 1;
onGround = false;
} else if (sh.getMinY() <= oth.getMaxY()) {
velocity.y = 0;
position.y += oth.getMaxY() - sh.getMinY() + 1;
onGround = true;
} else {
throw new RuntimeException("No overlap detected: " + sh.toString() + " with " + oth.toString());
}
updateShape();
}
|
public SecGroups getGroupById(final Long groupId, final SecUsers secUser){
return (SecGroups) DataAccessUtils.uniqueResult(getHibernateTemplate()
.findByNamedParam("from SecGroups where groupId = :groupId and secUsers = :secUser",
new String[]{"groupId", "secUsers"}, new Object[]{groupId, secUser}));
}
| public SecGroups getGroupById(final Long groupId, final SecUsers secUser){
return (SecGroups) DataAccessUtils.uniqueResult(getHibernateTemplate()
.findByNamedParam("from SecGroups where groupId = :groupId and secUsers = :secUser",
new String[]{"groupId", "secUser"}, new Object[]{groupId, secUser}));
}
|
public void initFile(String id) throws FormatException, IOException {
super.initFile(id);
tiffReader = new MinimalTiffReader();
status("Reading metadata file");
Location file = new Location(currentId).getAbsoluteFile();
metadataFile = file.exists() ? new Location(file.getParentFile(),
METADATA).getAbsolutePath() : METADATA;
in = new RandomAccessInputStream(metadataFile);
String parent = file.exists() ?
file.getParentFile().getAbsolutePath() + File.separator : "";
byte[] meta = new byte[(int) in.length()];
in.read(meta);
String s = new String(meta);
meta = null;
status("Finding image file names");
String baseTiff = null;
tiffs = new Vector();
int pos = 0;
while (true) {
pos = s.indexOf("FileName", pos);
if (pos == -1 || pos >= in.length()) break;
String name = s.substring(s.indexOf(":", pos), s.indexOf(",", pos));
baseTiff = parent + name.substring(3, name.length() - 1);
pos++;
}
status("Populating metadata");
Vector stamps = new Vector();
Vector voltage = new Vector();
StringTokenizer st = new StringTokenizer(s, "\n");
int[] slice = new int[3];
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
boolean open = token.indexOf("[") != -1;
boolean closed = token.indexOf("]") != -1;
if (open || (!open && !closed && !token.equals("{") &&
!token.startsWith("}")))
{
int quote = token.indexOf("\"") + 1;
String key = token.substring(quote, token.indexOf("\"", quote));
String value = null;
if (!open && !closed) {
value = token.substring(token.indexOf(":") + 1);
}
else if (!closed){
StringBuffer valueBuffer = new StringBuffer();
while (!closed) {
token = st.nextToken();
closed = token.indexOf("]") != -1;
valueBuffer.append(token);
}
value = valueBuffer.toString();
value = value.replaceAll("\n", "");
}
int startIndex = value.indexOf("[");
int endIndex = value.indexOf("]");
if (endIndex == -1) endIndex = value.length();
value = value.substring(startIndex + 1, endIndex).trim();
value = value.substring(0, value.length() - 1);
value = value.replaceAll("\"", "");
if (value.endsWith(",")) value = value.substring(0, value.length() - 1);
addGlobalMeta(key, value);
if (key.equals("Channels")) core[0].sizeC = Integer.parseInt(value);
else if (key.equals("ChNames")) {
StringTokenizer t = new StringTokenizer(value, ",");
int nTokens = t.countTokens();
channels = new String[nTokens];
for (int q=0; q<nTokens; q++) {
channels[q] = t.nextToken().replaceAll("\"", "").trim();
}
}
else if (key.equals("Frames")) {
core[0].sizeT = Integer.parseInt(value);
}
else if (key.equals("Slices")) {
core[0].sizeZ = Integer.parseInt(value);
}
else if (key.equals("PixelSize_um")) {
pixelSize = new Float(value);
}
else if (key.equals("z-step_um")) {
sliceThickness = new Float(value);
}
else if (key.equals("Time")) time = value;
else if (key.equals("Comment")) comment = value;
}
if (token.startsWith("\"FrameKey")) {
int dash = token.indexOf("-") + 1;
int nextDash = token.indexOf("-", dash);
slice[2] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
nextDash = token.indexOf("-", dash);
slice[1] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
slice[0] = Integer.parseInt(token.substring(dash,
token.indexOf("\"", dash)));
token = st.nextToken().trim();
String key = "", value = "";
while (!token.startsWith("}")) {
int colon = token.indexOf(":");
key = token.substring(1, colon).trim();
value = token.substring(colon + 1, token.length() - 1).trim();
key = key.replaceAll("\"", "");
value = value.replaceAll("\"", "");
addGlobalMeta(key, value);
if (key.equals("Exposure-ms")) {
float t = Float.parseFloat(value);
exposureTime = new Float(t / 1000);
}
else if (key.equals("ElapsedTime-ms")) {
float t = Float.parseFloat(value);
stamps.add(new Float(t / 1000));
}
else if (key.equals("Core-Camera")) cameraRef = value;
else if (key.equals(cameraRef + "-Binning")) {
if (value.indexOf("x") != -1) binning = value;
else binning = value + "x" + value;
}
else if (key.equals(cameraRef + "-CameraID")) detectorID = value;
else if (key.equals(cameraRef + "-CameraName")) detectorModel = value;
else if (key.equals(cameraRef + "-Gain")) {
gain = Integer.parseInt(value);
}
else if (key.equals(cameraRef + "-Name")) {
detectorManufacturer = value;
}
else if (key.equals(cameraRef + "-Temperature")) {
temperature = Float.parseFloat(value);
}
else if (key.equals(cameraRef + "-CCDMode")) {
cameraMode = value;
}
else if (key.startsWith("DAC-") && key.endsWith("-Volts")) {
voltage.add(new Float(value));
}
token = st.nextToken().trim();
}
}
}
timestamps = (Float[]) stamps.toArray(new Float[0]);
Arrays.sort(timestamps);
String prefix = "";
if (baseTiff.indexOf(File.separator) != -1) {
prefix = baseTiff.substring(0, baseTiff.lastIndexOf(File.separator) + 1);
baseTiff = baseTiff.substring(baseTiff.lastIndexOf(File.separator) + 1);
}
String[] blocks = baseTiff.split("_");
StringBuffer filename = new StringBuffer();
for (int t=0; t<getSizeT(); t++) {
for (int c=0; c<getSizeC(); c++) {
for (int z=0; z<getSizeZ(); z++) {
filename.append(prefix);
filename.append(blocks[0]);
filename.append("_");
int zeros = blocks[1].length() - String.valueOf(t).length();
for (int q=0; q<zeros; q++) {
filename.append("0");
}
filename.append(t);
filename.append("_");
filename.append(channels[c]);
filename.append("_");
zeros = blocks[3].length() - String.valueOf(z).length() - 4;
for (int q=0; q<zeros; q++) {
filename.append("0");
}
filename.append(z);
filename.append(".tif");
tiffs.add(filename.toString());
filename.delete(0, filename.length());
}
}
}
tiffReader.setId((String) tiffs.get(0));
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeT() == 0) core[0].sizeT = tiffs.size() / getSizeC();
core[0].sizeX = tiffReader.getSizeX();
core[0].sizeY = tiffReader.getSizeY();
core[0].dimensionOrder = "XYZCT";
core[0].pixelType = tiffReader.getPixelType();
core[0].rgb = tiffReader.isRGB();
core[0].interleaved = false;
core[0].littleEndian = tiffReader.isLittleEndian();
core[0].imageCount = getSizeZ() * getSizeC() * getSizeT();
core[0].indexed = false;
core[0].falseColor = false;
core[0].metadataComplete = true;
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this, true);
store.setImageName("", 0);
store.setImageDescription(comment, 0);
if (time != null) {
SimpleDateFormat parser =
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
try {
long stamp = parser.parse(time).getTime();
store.setImageCreationDate(
DataTools.convertDate(stamp, DataTools.UNIX), 0);
}
catch (ParseException e) {
MetadataTools.setDefaultCreationDate(store, id, 0);
}
}
else MetadataTools.setDefaultCreationDate(store, id, 0);
store.setInstrumentID("Instrument:0", 0);
store.setImageInstrumentRef("Instrument:0", 0);
for (int i=0; i<channels.length; i++) {
store.setLogicalChannelName(channels[i], 0, i);
}
store.setDimensionsPhysicalSizeX(pixelSize, 0, 0);
store.setDimensionsPhysicalSizeY(pixelSize, 0, 0);
store.setDimensionsPhysicalSizeZ(sliceThickness, 0, 0);
for (int i=0; i<getImageCount(); i++) {
store.setPlaneTimingExposureTime(exposureTime, 0, 0, i);
if (i < timestamps.length) {
store.setPlaneTimingDeltaT(timestamps[i], 0, 0, i);
}
}
if (detectorID == null) detectorID = "Detector:0";
for (int i=0; i<channels.length; i++) {
store.setDetectorSettingsBinning(binning, 0, i);
store.setDetectorSettingsGain(new Float(gain), 0, i);
if (i < voltage.size()) {
store.setDetectorSettingsVoltage((Float) voltage.get(i), 0, i);
}
store.setDetectorSettingsDetector(detectorID, 0, i);
}
store.setDetectorID(detectorID, 0, 0);
store.setDetectorModel(detectorModel, 0, 0);
store.setDetectorManufacturer(detectorManufacturer, 0, 0);
store.setDetectorType(cameraMode, 0, 0);
store.setImagingEnvironmentTemperature(new Float(temperature), 0);
}
| public void initFile(String id) throws FormatException, IOException {
super.initFile(id);
tiffReader = new MinimalTiffReader();
status("Reading metadata file");
Location file = new Location(currentId).getAbsoluteFile();
metadataFile = file.exists() ? new Location(file.getParentFile(),
METADATA).getAbsolutePath() : METADATA;
in = new RandomAccessInputStream(metadataFile);
String parent = file.exists() ?
file.getParentFile().getAbsolutePath() + File.separator : "";
byte[] meta = new byte[(int) in.length()];
in.read(meta);
String s = new String(meta);
meta = null;
status("Finding image file names");
String baseTiff = null;
tiffs = new Vector();
int pos = 0;
while (true) {
pos = s.indexOf("FileName", pos);
if (pos == -1 || pos >= in.length()) break;
String name = s.substring(s.indexOf(":", pos), s.indexOf(",", pos));
baseTiff = parent + name.substring(3, name.length() - 1);
pos++;
}
status("Populating metadata");
Vector stamps = new Vector();
Vector voltage = new Vector();
StringTokenizer st = new StringTokenizer(s, "\n");
int[] slice = new int[3];
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
boolean open = token.indexOf("[") != -1;
boolean closed = token.indexOf("]") != -1;
if (open || (!open && !closed && !token.equals("{") &&
!token.startsWith("}")))
{
int quote = token.indexOf("\"") + 1;
String key = token.substring(quote, token.indexOf("\"", quote));
String value = null;
if (open == closed) {
value = token.substring(token.indexOf(":") + 1);
}
else if (!closed) {
StringBuffer valueBuffer = new StringBuffer();
while (!closed) {
token = st.nextToken();
closed = token.indexOf("]") != -1;
valueBuffer.append(token);
}
value = valueBuffer.toString();
value = value.replaceAll("\n", "");
}
int startIndex = value.indexOf("[");
int endIndex = value.indexOf("]");
if (endIndex == -1) endIndex = value.length();
value = value.substring(startIndex + 1, endIndex).trim();
value = value.substring(0, value.length() - 1);
value = value.replaceAll("\"", "");
if (value.endsWith(",")) value = value.substring(0, value.length() - 1);
addGlobalMeta(key, value);
if (key.equals("Channels")) core[0].sizeC = Integer.parseInt(value);
else if (key.equals("ChNames")) {
StringTokenizer t = new StringTokenizer(value, ",");
int nTokens = t.countTokens();
channels = new String[nTokens];
for (int q=0; q<nTokens; q++) {
channels[q] = t.nextToken().replaceAll("\"", "").trim();
}
}
else if (key.equals("Frames")) {
core[0].sizeT = Integer.parseInt(value);
}
else if (key.equals("Slices")) {
core[0].sizeZ = Integer.parseInt(value);
}
else if (key.equals("PixelSize_um")) {
pixelSize = new Float(value);
}
else if (key.equals("z-step_um")) {
sliceThickness = new Float(value);
}
else if (key.equals("Time")) time = value;
else if (key.equals("Comment")) comment = value;
}
if (token.startsWith("\"FrameKey")) {
int dash = token.indexOf("-") + 1;
int nextDash = token.indexOf("-", dash);
slice[2] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
nextDash = token.indexOf("-", dash);
slice[1] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
slice[0] = Integer.parseInt(token.substring(dash,
token.indexOf("\"", dash)));
token = st.nextToken().trim();
String key = "", value = "";
while (!token.startsWith("}")) {
int colon = token.indexOf(":");
key = token.substring(1, colon).trim();
value = token.substring(colon + 1, token.length() - 1).trim();
key = key.replaceAll("\"", "");
value = value.replaceAll("\"", "");
addGlobalMeta(key, value);
if (key.equals("Exposure-ms")) {
float t = Float.parseFloat(value);
exposureTime = new Float(t / 1000);
}
else if (key.equals("ElapsedTime-ms")) {
float t = Float.parseFloat(value);
stamps.add(new Float(t / 1000));
}
else if (key.equals("Core-Camera")) cameraRef = value;
else if (key.equals(cameraRef + "-Binning")) {
if (value.indexOf("x") != -1) binning = value;
else binning = value + "x" + value;
}
else if (key.equals(cameraRef + "-CameraID")) detectorID = value;
else if (key.equals(cameraRef + "-CameraName")) detectorModel = value;
else if (key.equals(cameraRef + "-Gain")) {
gain = Integer.parseInt(value);
}
else if (key.equals(cameraRef + "-Name")) {
detectorManufacturer = value;
}
else if (key.equals(cameraRef + "-Temperature")) {
temperature = Float.parseFloat(value);
}
else if (key.equals(cameraRef + "-CCDMode")) {
cameraMode = value;
}
else if (key.startsWith("DAC-") && key.endsWith("-Volts")) {
voltage.add(new Float(value));
}
token = st.nextToken().trim();
}
}
}
timestamps = (Float[]) stamps.toArray(new Float[0]);
Arrays.sort(timestamps);
String prefix = "";
if (baseTiff.indexOf(File.separator) != -1) {
prefix = baseTiff.substring(0, baseTiff.lastIndexOf(File.separator) + 1);
baseTiff = baseTiff.substring(baseTiff.lastIndexOf(File.separator) + 1);
}
String[] blocks = baseTiff.split("_");
StringBuffer filename = new StringBuffer();
for (int t=0; t<getSizeT(); t++) {
for (int c=0; c<getSizeC(); c++) {
for (int z=0; z<getSizeZ(); z++) {
filename.append(prefix);
filename.append(blocks[0]);
filename.append("_");
int zeros = blocks[1].length() - String.valueOf(t).length();
for (int q=0; q<zeros; q++) {
filename.append("0");
}
filename.append(t);
filename.append("_");
filename.append(channels[c]);
filename.append("_");
zeros = blocks[3].length() - String.valueOf(z).length() - 4;
for (int q=0; q<zeros; q++) {
filename.append("0");
}
filename.append(z);
filename.append(".tif");
tiffs.add(filename.toString());
filename.delete(0, filename.length());
}
}
}
tiffReader.setId((String) tiffs.get(0));
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeT() == 0) core[0].sizeT = tiffs.size() / getSizeC();
core[0].sizeX = tiffReader.getSizeX();
core[0].sizeY = tiffReader.getSizeY();
core[0].dimensionOrder = "XYZCT";
core[0].pixelType = tiffReader.getPixelType();
core[0].rgb = tiffReader.isRGB();
core[0].interleaved = false;
core[0].littleEndian = tiffReader.isLittleEndian();
core[0].imageCount = getSizeZ() * getSizeC() * getSizeT();
core[0].indexed = false;
core[0].falseColor = false;
core[0].metadataComplete = true;
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
MetadataTools.populatePixels(store, this, true);
store.setImageName("", 0);
store.setImageDescription(comment, 0);
if (time != null) {
SimpleDateFormat parser =
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
try {
long stamp = parser.parse(time).getTime();
store.setImageCreationDate(
DataTools.convertDate(stamp, DataTools.UNIX), 0);
}
catch (ParseException e) {
MetadataTools.setDefaultCreationDate(store, id, 0);
}
}
else MetadataTools.setDefaultCreationDate(store, id, 0);
store.setInstrumentID("Instrument:0", 0);
store.setImageInstrumentRef("Instrument:0", 0);
for (int i=0; i<channels.length; i++) {
store.setLogicalChannelName(channels[i], 0, i);
}
store.setDimensionsPhysicalSizeX(pixelSize, 0, 0);
store.setDimensionsPhysicalSizeY(pixelSize, 0, 0);
store.setDimensionsPhysicalSizeZ(sliceThickness, 0, 0);
for (int i=0; i<getImageCount(); i++) {
store.setPlaneTimingExposureTime(exposureTime, 0, 0, i);
if (i < timestamps.length) {
store.setPlaneTimingDeltaT(timestamps[i], 0, 0, i);
}
}
if (detectorID == null) detectorID = "Detector:0";
for (int i=0; i<channels.length; i++) {
store.setDetectorSettingsBinning(binning, 0, i);
store.setDetectorSettingsGain(new Float(gain), 0, i);
if (i < voltage.size()) {
store.setDetectorSettingsVoltage((Float) voltage.get(i), 0, i);
}
store.setDetectorSettingsDetector(detectorID, 0, i);
}
store.setDetectorID(detectorID, 0, 0);
store.setDetectorModel(detectorModel, 0, 0);
store.setDetectorManufacturer(detectorManufacturer, 0, 0);
store.setDetectorType(cameraMode, 0, 0);
store.setImagingEnvironmentTemperature(new Float(temperature), 0);
}
|
private Command handleLldp(LLDP lldp, long sw, short inPort,
boolean isStandard, FloodlightContext cntx) {
IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
if (!isIncomingDiscoveryAllowed(sw, inPort, isStandard))
return Command.STOP;
if (lldp.getPortId() == null || lldp.getPortId().getLength() != 3) {
return Command.CONTINUE;
}
long myId = ByteBuffer.wrap(controllerTLV.getValue()).getLong();
long otherId = 0;
boolean myLLDP = false;
Boolean isReverse = null;
ByteBuffer portBB = ByteBuffer.wrap(lldp.getPortId().getValue());
portBB.position(1);
Short remotePort = portBB.getShort();
IOFSwitch remoteSwitch = null;
for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) {
if (lldptlv.getType() == 127 && lldptlv.getLength() == 12
&& lldptlv.getValue()[0] == 0x0
&& lldptlv.getValue()[1] == 0x26
&& lldptlv.getValue()[2] == (byte) 0xe1
&& lldptlv.getValue()[3] == 0x0) {
ByteBuffer dpidBB = ByteBuffer.wrap(lldptlv.getValue());
remoteSwitch = floodlightProvider.getSwitches()
.get(dpidBB.getLong(4));
} else if (lldptlv.getType() == 12 && lldptlv.getLength() == 8) {
otherId = ByteBuffer.wrap(lldptlv.getValue()).getLong();
if (myId == otherId) myLLDP = true;
} else if (lldptlv.getType() == TLV_DIRECTION_TYPE
&& lldptlv.getLength() == TLV_DIRECTION_LENGTH) {
if (lldptlv.getValue()[0] == TLV_DIRECTION_VALUE_FORWARD[0])
isReverse = false;
else if (lldptlv.getValue()[0] == TLV_DIRECTION_VALUE_REVERSE[0])
isReverse = true;
}
}
if (myLLDP == false) {
if (isStandard) {
if (log.isTraceEnabled()) {
log.trace("Got a standard LLDP=[{}]. Not fowarding it.", lldp.toString());
}
return Command.STOP;
} else if (myId < otherId) {
if (log.isTraceEnabled()) {
log.trace("Getting BDDP packets from a different controller"
+ "and letting it go through normal processing chain.");
}
return Command.CONTINUE;
}
}
if (remoteSwitch == null) {
if (log.isTraceEnabled()) {
log.trace("Received LLDP from remote switch not connected to the controller");
}
return Command.STOP;
}
if (!remoteSwitch.portEnabled(remotePort)) {
if (log.isTraceEnabled()) {
log.trace("Ignoring link with disabled source port: switch {} port {}",
remoteSwitch.getStringId(), remotePort);
}
return Command.STOP;
}
if (suppressLinkDiscovery.contains(new NodePortTuple(
remoteSwitch.getId(),
remotePort))) {
if (log.isTraceEnabled()) {
log.trace("Ignoring link with suppressed src port: switch {} port {}",
remoteSwitch.getStringId(), remotePort);
}
return Command.STOP;
}
if (!iofSwitch.portEnabled(inPort)) {
if (log.isTraceEnabled()) {
log.trace("Ignoring link with disabled dest port: switch {} port {}",
HexString.toHexString(sw), inPort);
}
return Command.STOP;
}
OFPhysicalPort physicalPort = remoteSwitch.getPort(remotePort);
int srcPortState = (physicalPort != null) ? physicalPort.getState()
: 0;
physicalPort = iofSwitch.getPort(inPort);
int dstPortState = (physicalPort != null) ? physicalPort.getState()
: 0;
Link lt = new Link(remoteSwitch.getId(), remotePort,
iofSwitch.getId(), inPort);
if (!isLinkAllowed(lt.getSrc(), lt.getSrcPort(),
lt.getDst(), lt.getDstPort()))
return Command.STOP;
Long lastLldpTime = null;
Long lastBddpTime = null;
Long firstSeenTime = System.currentTimeMillis();
if (isStandard)
lastLldpTime = System.currentTimeMillis();
else
lastBddpTime = System.currentTimeMillis();
LinkInfo newLinkInfo = new LinkInfo(firstSeenTime, lastLldpTime,
lastBddpTime, srcPortState,
dstPortState);
addOrUpdateLink(lt, newLinkInfo);
newLinkInfo = links.get(lt);
if (newLinkInfo != null && isStandard && isReverse == false) {
Link reverseLink = new Link(lt.getDst(), lt.getDstPort(),
lt.getSrc(), lt.getSrcPort());
LinkInfo reverseInfo = links.get(reverseLink);
if (reverseInfo == null) {
if (newLinkInfo.getFirstSeenTime() > System.currentTimeMillis()
- LINK_TIMEOUT) {
this.sendDiscoveryMessage(lt.getDst(), lt.getDstPort(),
isStandard, true);
}
}
}
if (!isStandard) {
Link reverseLink = new Link(lt.getDst(), lt.getDstPort(),
lt.getSrc(), lt.getSrcPort());
LinkInfo reverseInfo = new LinkInfo(firstSeenTime, lastLldpTime,
lastBddpTime, dstPortState,
srcPortState);
addOrUpdateLink(reverseLink, reverseInfo);
}
NodePortTuple nptSrc = new NodePortTuple(lt.getSrc(),
lt.getSrcPort());
NodePortTuple nptDst = new NodePortTuple(lt.getDst(),
lt.getDstPort());
removeFromQuarantineQueue(nptSrc);
removeFromMaintenanceQueue(nptSrc);
removeFromQuarantineQueue(nptDst);
removeFromMaintenanceQueue(nptDst);
return Command.STOP;
}
| private Command handleLldp(LLDP lldp, long sw, short inPort,
boolean isStandard, FloodlightContext cntx) {
IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
if (!isIncomingDiscoveryAllowed(sw, inPort, isStandard))
return Command.STOP;
if (lldp.getPortId() == null || lldp.getPortId().getLength() != 3) {
return Command.STOP;
}
long myId = ByteBuffer.wrap(controllerTLV.getValue()).getLong();
long otherId = 0;
boolean myLLDP = false;
Boolean isReverse = null;
ByteBuffer portBB = ByteBuffer.wrap(lldp.getPortId().getValue());
portBB.position(1);
Short remotePort = portBB.getShort();
IOFSwitch remoteSwitch = null;
for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) {
if (lldptlv.getType() == 127 && lldptlv.getLength() == 12
&& lldptlv.getValue()[0] == 0x0
&& lldptlv.getValue()[1] == 0x26
&& lldptlv.getValue()[2] == (byte) 0xe1
&& lldptlv.getValue()[3] == 0x0) {
ByteBuffer dpidBB = ByteBuffer.wrap(lldptlv.getValue());
remoteSwitch = floodlightProvider.getSwitches()
.get(dpidBB.getLong(4));
} else if (lldptlv.getType() == 12 && lldptlv.getLength() == 8) {
otherId = ByteBuffer.wrap(lldptlv.getValue()).getLong();
if (myId == otherId) myLLDP = true;
} else if (lldptlv.getType() == TLV_DIRECTION_TYPE
&& lldptlv.getLength() == TLV_DIRECTION_LENGTH) {
if (lldptlv.getValue()[0] == TLV_DIRECTION_VALUE_FORWARD[0])
isReverse = false;
else if (lldptlv.getValue()[0] == TLV_DIRECTION_VALUE_REVERSE[0])
isReverse = true;
}
}
if (myLLDP == false) {
if (isStandard) {
if (log.isTraceEnabled()) {
log.trace("Got a standard LLDP=[{}]. Not fowarding it.", lldp.toString());
}
return Command.STOP;
} else if (myId < otherId) {
if (log.isTraceEnabled()) {
log.trace("Getting BDDP packets from a different controller"
+ "and letting it go through normal processing chain.");
}
return Command.CONTINUE;
}
return Command.STOP;
}
if (remoteSwitch == null) {
if (log.isTraceEnabled()) {
log.trace("Received LLDP from remote switch not connected to the controller");
}
return Command.STOP;
}
if (!remoteSwitch.portEnabled(remotePort)) {
if (log.isTraceEnabled()) {
log.trace("Ignoring link with disabled source port: switch {} port {}",
remoteSwitch.getStringId(), remotePort);
}
return Command.STOP;
}
if (suppressLinkDiscovery.contains(new NodePortTuple(
remoteSwitch.getId(),
remotePort))) {
if (log.isTraceEnabled()) {
log.trace("Ignoring link with suppressed src port: switch {} port {}",
remoteSwitch.getStringId(), remotePort);
}
return Command.STOP;
}
if (!iofSwitch.portEnabled(inPort)) {
if (log.isTraceEnabled()) {
log.trace("Ignoring link with disabled dest port: switch {} port {}",
HexString.toHexString(sw), inPort);
}
return Command.STOP;
}
OFPhysicalPort physicalPort = remoteSwitch.getPort(remotePort);
int srcPortState = (physicalPort != null) ? physicalPort.getState()
: 0;
physicalPort = iofSwitch.getPort(inPort);
int dstPortState = (physicalPort != null) ? physicalPort.getState()
: 0;
Link lt = new Link(remoteSwitch.getId(), remotePort,
iofSwitch.getId(), inPort);
if (!isLinkAllowed(lt.getSrc(), lt.getSrcPort(),
lt.getDst(), lt.getDstPort()))
return Command.STOP;
Long lastLldpTime = null;
Long lastBddpTime = null;
Long firstSeenTime = System.currentTimeMillis();
if (isStandard)
lastLldpTime = System.currentTimeMillis();
else
lastBddpTime = System.currentTimeMillis();
LinkInfo newLinkInfo = new LinkInfo(firstSeenTime, lastLldpTime,
lastBddpTime, srcPortState,
dstPortState);
addOrUpdateLink(lt, newLinkInfo);
newLinkInfo = links.get(lt);
if (newLinkInfo != null && isStandard && isReverse == false) {
Link reverseLink = new Link(lt.getDst(), lt.getDstPort(),
lt.getSrc(), lt.getSrcPort());
LinkInfo reverseInfo = links.get(reverseLink);
if (reverseInfo == null) {
if (newLinkInfo.getFirstSeenTime() > System.currentTimeMillis()
- LINK_TIMEOUT) {
this.sendDiscoveryMessage(lt.getDst(), lt.getDstPort(),
isStandard, true);
}
}
}
if (!isStandard) {
Link reverseLink = new Link(lt.getDst(), lt.getDstPort(),
lt.getSrc(), lt.getSrcPort());
LinkInfo reverseInfo = new LinkInfo(firstSeenTime, lastLldpTime,
lastBddpTime, dstPortState,
srcPortState);
addOrUpdateLink(reverseLink, reverseInfo);
}
NodePortTuple nptSrc = new NodePortTuple(lt.getSrc(),
lt.getSrcPort());
NodePortTuple nptDst = new NodePortTuple(lt.getDst(),
lt.getDstPort());
removeFromQuarantineQueue(nptSrc);
removeFromMaintenanceQueue(nptSrc);
removeFromQuarantineQueue(nptDst);
removeFromMaintenanceQueue(nptDst);
return Command.STOP;
}
|
private void handleCharacter(int primaryCode, int[] keyCodes) {
int keyState = InputTables.KEYSTATE_NONE;
if (isInputViewShown()) {
if (mInputView.isShifted()) {
primaryCode = Character.toUpperCase(primaryCode);
keyState |= InputTables.KEYSTATE_SHIFT;
}
}
if (mHwShift)
keyState |= InputTables.KEYSTATE_SHIFT;
if (isAlphabet(primaryCode)) {
int ret = kauto.DoAutomata((char )primaryCode, keyState);
if (ret < 0)
{
if (kauto.IsKoreanMode())
kauto.ToggleMode();
}
else
{
if ((ret & KoreanAutomata.ACTION_UPDATE_COMPLETESTR) != 0)
{
if (mComposing.length() > 0)
mComposing.replace(mComposing.length()-1, mComposing.length(), kauto.GetCompleteString());
else
mComposing.append(kauto.GetCompleteString());
if (mComposing.length() > 0) {
getCurrentInputConnection().setComposingText(mComposing, 1);
}
}
if ((ret & KoreanAutomata.ACTION_UPDATE_COMPOSITIONSTR) != 0)
{
if ((mComposing.length() > 0) && ((ret & KoreanAutomata.ACTION_UPDATE_COMPLETESTR) == 0))
mComposing.replace(mComposing.length()-1, mComposing.length(), kauto.GetCompositionString());
else
mComposing.append(kauto.GetCompositionString());
getCurrentInputConnection().setComposingText(mComposing, 1);
}
}
if ((ret & KoreanAutomata.ACTION_USE_INPUT_AS_RESULT) != 0)
{
mComposing.append((char) primaryCode);
getCurrentInputConnection().setComposingText(mComposing, 1);
}
updateShiftKeyState(getCurrentInputEditorInfo());
} else {
int ret = kauto.DoAutomata((char )primaryCode, keyState);
if (ret < 0)
{
if (kauto.IsKoreanMode())
kauto.ToggleMode();
}
else
{
if ((ret & KoreanAutomata.ACTION_UPDATE_COMPLETESTR) != 0)
{
if (mComposing.length() > 0)
mComposing.replace(mComposing.length()-1, mComposing.length(), kauto.GetCompleteString());
else
mComposing.append(kauto.GetCompleteString());
if (mComposing.length() > 0) {
getCurrentInputConnection().setComposingText(mComposing, 1);
}
}
if ((ret & KoreanAutomata.ACTION_UPDATE_COMPOSITIONSTR) != 0)
{
if ((mComposing.length() > 0) && ((ret & KoreanAutomata.ACTION_UPDATE_COMPLETESTR) == 0))
mComposing.replace(mComposing.length()-1, mComposing.length(), kauto.GetCompositionString());
else
mComposing.append(kauto.GetCompositionString());
if (mComposing.length() > 0) {
getCurrentInputConnection().setComposingText(mComposing, 1);
}
}
}
if ((ret & KoreanAutomata.ACTION_USE_INPUT_AS_RESULT) != 0)
{
getCurrentInputConnection().commitText(
String.valueOf((char) primaryCode), 1);
}
}
}
| private void handleCharacter(int primaryCode, int[] keyCodes) {
int keyState = InputTables.KEYSTATE_NONE;
if (isInputViewShown()) {
if (mInputView.isShifted()) {
primaryCode = Character.toUpperCase(primaryCode);
keyState |= InputTables.KEYSTATE_SHIFT;
}
}
if (mHwShift)
keyState |= InputTables.KEYSTATE_SHIFT;
if (isAlphabet(primaryCode)) {
int ret = kauto.DoAutomata((char )primaryCode, keyState);
if (ret < 0)
{
if (kauto.IsKoreanMode())
kauto.ToggleMode();
}
else
{
if ((ret & KoreanAutomata.ACTION_UPDATE_COMPLETESTR) != 0)
{
if (mComposing.length() > 0)
mComposing.replace(mComposing.length()-1, mComposing.length(), kauto.GetCompleteString());
else
mComposing.append(kauto.GetCompleteString());
if (mComposing.length() > 0) {
getCurrentInputConnection().setComposingText(mComposing, 1);
}
}
if ((ret & KoreanAutomata.ACTION_UPDATE_COMPOSITIONSTR) != 0)
{
if ((mComposing.length() > 0) && ((ret & KoreanAutomata.ACTION_UPDATE_COMPLETESTR) == 0))
mComposing.replace(mComposing.length()-1, mComposing.length(), kauto.GetCompositionString());
else
mComposing.append(kauto.GetCompositionString());
getCurrentInputConnection().setComposingText(mComposing, 1);
}
}
if ((ret & KoreanAutomata.ACTION_USE_INPUT_AS_RESULT) != 0)
{
mComposing.append((char) primaryCode);
getCurrentInputConnection().setComposingText(mComposing, 1);
}
updateShiftKeyState(getCurrentInputEditorInfo());
} else {
if (mComposing.length() > 0) {
getCurrentInputConnection().commitText(mComposing, 1);
mComposing.setLength(0);
}
kauto.FinishAutomataWithoutInput();
getCurrentInputConnection().commitText(String.valueOf((char) primaryCode), 1);
}
}
|
public void testPetclinicSimple() throws Exception {
for (int i = 0; i < REPETITIONS; i++) {
LogUtils.log("petclinic install number " + (i + 1));
installApplicationAndWait(ScriptUtils.getBuildPath() + "/recipes/apps/petclinic-simple", "petclinic");
ProcessingUnit mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 5, TimeUnit.MINUTES);
ProcessingUnit tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 5, TimeUnit.MINUTES);
AssertUtils.assertNotNull("Failed to discover processing unit petclinic.mongod even though it was installed succesfully ", mongod);
AssertUtils.assertNotNull("Failed to discover processing unit petclinic.tomcat even though it was installed succesfully ", tomcat);
LogUtils.log("petclinic uninstall number " + (i + 1));
uninstallApplicationAndWait("petclinic");
LogUtils.log("Application petclinic uninstalled succesfully");
mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 5, TimeUnit.MINUTES);
tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 5, TimeUnit.MINUTES);
AssertUtils.assertNull("Processing unit petclinic.mongod is still discovered even though it was uninstalled succesfully ", mongod);
AssertUtils.assertNull("Processing unit petclinic.tomcat is still discovered even though it was uninstalled succesfully ", tomcat);
}
}
| public void testPetclinicSimple() throws Exception {
for (int i = 0; i < REPETITIONS; i++) {
LogUtils.log("petclinic install number " + (i + 1));
installApplicationAndWait(ScriptUtils.getBuildPath() + "/recipes/apps/petclinic-simple", "petclinic");
ProcessingUnit mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 1, TimeUnit.MINUTES);
ProcessingUnit tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 1, TimeUnit.MINUTES);
AssertUtils.assertNotNull("Failed to discover processing unit petclinic.mongod even though it was installed succesfully ", mongod);
AssertUtils.assertNotNull("Failed to discover processing unit petclinic.tomcat even though it was installed succesfully ", tomcat);
LogUtils.log("petclinic uninstall number " + (i + 1));
uninstallApplicationAndWait("petclinic");
LogUtils.log("Application petclinic uninstalled succesfully");
mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 1, TimeUnit.MINUTES);
tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 1, TimeUnit.MINUTES);
AssertUtils.assertNull("Processing unit petclinic.mongod is still discovered even though it was uninstalled succesfully ", mongod);
AssertUtils.assertNull("Processing unit petclinic.tomcat is still discovered even though it was uninstalled succesfully ", tomcat);
}
}
|
private String[] readGeoIPFile(Long[] search) {
File GeoFile = new File(_context.getBaseDir(), GEOIP_DIR_DEFAULT);
GeoFile = new File(GeoFile, GEOIP_FILE_DEFAULT);
if (GeoFile == null || (!GeoFile.exists())) {
if (_log.shouldLog(Log.WARN))
_log.warn("GeoIP file not found: " + GeoFile.getAbsolutePath());
return new String[0];
}
String[] rv = new String[search.length];
int idx = 0;
long start = _context.clock().now();
FileInputStream in = null;
try {
in = new FileInputStream(GeoFile);
StringBuilder buf = new StringBuilder(128);
while (DataHelper.readLine(in, buf) && idx < search.length) {
try {
if (buf.charAt(0) == '#') {
buf.setLength(0);
continue;
}
String[] s = buf.toString().split(",");
long ip1 = Long.parseLong(s[0]);
long ip2 = Long.parseLong(s[1]);
while (search[idx].longValue() < ip1 && idx < search.length) {
idx++;
}
while (search[idx].longValue() >= ip1 && search[idx].longValue() <= ip2 && idx < search.length) {
rv[idx++] = s[2].toLowerCase();
}
} catch (IndexOutOfBoundsException ioobe) {
} catch (NumberFormatException nfe) {
}
buf.setLength(0);
}
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR))
_log.error("Error reading the GeoFile", ioe);
} finally {
if (in != null) try { in.close(); } catch (IOException ioe) {}
}
if (_log.shouldLog(Log.WARN)) {
_log.warn("GeoIP processing finished, time: " + (_context.clock().now() - start));
}
return rv;
}
| private String[] readGeoIPFile(Long[] search) {
File GeoFile = new File(_context.getBaseDir(), GEOIP_DIR_DEFAULT);
GeoFile = new File(GeoFile, GEOIP_FILE_DEFAULT);
if (GeoFile == null || (!GeoFile.exists())) {
if (_log.shouldLog(Log.WARN))
_log.warn("GeoIP file not found: " + GeoFile.getAbsolutePath());
return new String[0];
}
String[] rv = new String[search.length];
int idx = 0;
long start = _context.clock().now();
FileInputStream in = null;
try {
in = new FileInputStream(GeoFile);
StringBuilder buf = new StringBuilder(128);
while (DataHelper.readLine(in, buf) && idx < search.length) {
try {
if (buf.charAt(0) == '#') {
buf.setLength(0);
continue;
}
String[] s = buf.toString().split(",");
long ip1 = Long.parseLong(s[0]);
long ip2 = Long.parseLong(s[1]);
while (idx < search.length && search[idx].longValue() < ip1) {
idx++;
}
while (idx < search.length && search[idx].longValue() >= ip1 && search[idx].longValue() <= ip2) {
rv[idx++] = s[2].toLowerCase();
}
} catch (IndexOutOfBoundsException ioobe) {
} catch (NumberFormatException nfe) {
}
buf.setLength(0);
}
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR))
_log.error("Error reading the GeoFile", ioe);
} finally {
if (in != null) try { in.close(); } catch (IOException ioe) {}
}
if (_log.shouldLog(Log.WARN)) {
_log.warn("GeoIP processing finished, time: " + (_context.clock().now() - start));
}
return rv;
}
|
TCFNodeLaunch(final TCFModel model) {
super(model);
children = new TCFChildrenExecContext(this);
children_query = new TCFChildrenContextQuery(this);
filtered_children = new TCFChildren(this) {
@Override
protected boolean startDataRetrieval() {
Set<String> filter = launch.getContextFilter();
if (filter == null) {
if (!children.validate(this)) return false;
set(null, children.getError(), children.getData());
return true;
}
Runnable done = new Runnable() {
@Override
public void run() {
filtered_children.post();
}
};
Map<String,TCFNode> nodes = new HashMap<String,TCFNode>();
for (String id : filter) {
if (!model.createNode(id, done)) return false;
TCFNode node = model.getNode(id);
if (node != null) nodes.put(id, node);
}
set(null, null, nodes);
return true;
}
@Override
public void dispose() {
getNodes().clear();
super.dispose();
}
};
}
| TCFNodeLaunch(final TCFModel model) {
super(model);
children = new TCFChildrenExecContext(this);
children_query = new TCFChildrenContextQuery(this);
filtered_children = new TCFChildren(this) {
@Override
protected boolean startDataRetrieval() {
if (!children.validate(this)) return false;
Set<String> filter = launch.getContextFilter();
if (filter == null) {
set(null, children.getError(), children.getData());
return true;
}
Runnable done = new Runnable() {
@Override
public void run() {
filtered_children.post();
}
};
Map<String,TCFNode> nodes = new HashMap<String,TCFNode>();
for (String id : filter) {
if (!model.createNode(id, done)) return false;
TCFNode node = model.getNode(id);
if (node != null) nodes.put(id, node);
}
set(null, null, nodes);
return true;
}
@Override
public void dispose() {
getNodes().clear();
super.dispose();
}
};
}
|
protected void setDefaultValue() {
if ( useLastInput ) {
String lastUserInput = holder.getExternalSetValue();
if ( lastUserInput != null && !"".equals(lastUserInput))
historyManager.addHistoryEntry(historyManagerKeyForThisNode+"_"+TemplateNode.LAST_USED_PARAMETER, lastUserInput, new Date(), 1);
}
String defaultValue = getDefaultValue();
if (defaultValue != null) {
holder.setComponentField(defaultValue);
}
}
| protected void setDefaultValue() {
if ( useLastInput ) {
String lastUserInput = holder.getExternalSetValue();
if ( lastUserInput != null && !"".equals(lastUserInput))
historyManager.addHistoryEntry(historyManagerKeyForThisNode+"_"+TemplateNode.LAST_USED_PARAMETER, lastUserInput, new Date(), 1);
}
String defaultValue = getDefaultValue();
if (defaultValue != null) {
holder.setComponentField(defaultValue);
} else {
holder.setComponentField(null);
}
}
|
public void prepareForRendering(Range range) throws Exception {
Resolution r = getResolution(range);
List<Object> data = null;
switch (r)
{
case VERY_HIGH:
data = this.retrieveAndSaveData(range);
break;
default:
break;
}
for (TrackRenderer renderer : getTrackRenderers()) {
renderer.getDrawingInstructions().addInstruction(DrawingInstructions.InstructionName.RESOLUTION, r);
renderer.getDrawingInstructions().addInstruction(DrawingInstructions.InstructionName.COLOR_SCHEME, this.getColorScheme());
if (getDrawMode().getName() == "ARC") {
int maxDataValue = getMaxValue(data);
renderer.getDrawingInstructions().addInstruction(DrawingInstructions.InstructionName.AXIS_RANGE, new AxisRange(range, new Range(0,(int)Math.round(Math.log(maxDataValue)))));
}
else renderer.getDrawingInstructions().addInstruction(DrawingInstructions.InstructionName.AXIS_RANGE, new AxisRange(range, getDefaultYRange()));
renderer.getDrawingInstructions().addInstruction(DrawingInstructions.InstructionName.MODE, getDrawMode());
renderer.setData(data);
}
}
| public void prepareForRendering(Range range) throws Throwable {
Resolution r = getResolution(range);
List<Object> data = null;
switch (r)
{
case VERY_HIGH:
data = this.retrieveAndSaveData(range);
break;
default:
break;
}
for (TrackRenderer renderer : getTrackRenderers()) {
renderer.getDrawingInstructions().addInstruction(DrawingInstructions.InstructionName.RESOLUTION, r);
renderer.getDrawingInstructions().addInstruction(DrawingInstructions.InstructionName.COLOR_SCHEME, this.getColorScheme());
if (getDrawMode().getName() == "ARC") {
int maxDataValue = getMaxValue(data);
renderer.getDrawingInstructions().addInstruction(DrawingInstructions.InstructionName.AXIS_RANGE, new AxisRange(range, new Range(0,(int)Math.round(Math.log(maxDataValue)))));
}
else renderer.getDrawingInstructions().addInstruction(DrawingInstructions.InstructionName.AXIS_RANGE, new AxisRange(range, getDefaultYRange()));
renderer.getDrawingInstructions().addInstruction(DrawingInstructions.InstructionName.MODE, getDrawMode());
renderer.setData(data);
}
}
|
public void writeContent(final Map<String, Object> doc) {
if (logger.isDebugEnabled()) {
logger.debug("writing the content of: " + doc);
}
final SystemHelper systemHelper = SingletonS2Container
.getComponent("systemHelper");
final Object configIdObj = doc.get(systemHelper.configIdField);
if (configIdObj == null) {
throw new FessSystemException("Invalid configId: " + configIdObj);
}
final String configId = configIdObj.toString();
if (configId.length() < 2) {
throw new FessSystemException("Invalid configId: " + configIdObj);
}
final ConfigType configType = getConfigType(configId);
CrawlingConfig config = null;
if (logger.isDebugEnabled()) {
logger.debug("configType: " + configType + ", configId: "
+ configId);
}
if (ConfigType.WEB == configType) {
final WebCrawlingConfigService webCrawlingConfigService = SingletonS2Container
.getComponent(WebCrawlingConfigService.class);
config = webCrawlingConfigService
.getWebCrawlingConfig(getId(configId));
} else if (ConfigType.FILE == configType) {
final FileCrawlingConfigService fileCrawlingConfigService = SingletonS2Container
.getComponent(FileCrawlingConfigService.class);
config = fileCrawlingConfigService
.getFileCrawlingConfig(getId(configId));
} else if (ConfigType.DATA == configType) {
final DataCrawlingConfigService dataCrawlingConfigService = SingletonS2Container
.getComponent(DataCrawlingConfigService.class);
config = dataCrawlingConfigService
.getDataCrawlingConfig(getId(configId));
}
if (config == null) {
throw new FessSystemException("No crawlingConfig: " + configIdObj);
}
final String url = (String) doc.get(systemHelper.urlField);
final S2RobotClientFactory robotClientFactory = SingletonS2Container
.getComponent(S2RobotClientFactory.class);
config.initializeClientFactory(robotClientFactory);
final S2RobotClient client = robotClientFactory.getClient(url);
if (client == null) {
throw new FessSystemException("No S2RobotClient: " + configIdObj
+ ", url: " + url);
}
final ResponseData responseData = client.doGet(url);
final HttpServletResponse response = ResponseUtil.getResponse();
writeFileName(response, responseData);
writeContentType(response, responseData);
writeNoCache(response, responseData);
InputStream is = null;
OutputStream os = null;
try {
is = new BufferedInputStream(responseData.getResponseBody());
os = new BufferedOutputStream(response.getOutputStream());
StreamUtil.drain(is, os);
os.flush();
} catch (final IOException e) {
throw new FessSystemException(
"Failed to write a content. configId: " + configIdObj
+ ", url: " + url, e);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
if (logger.isDebugEnabled()) {
logger.debug("Finished to write " + url);
}
}
| public void writeContent(final Map<String, Object> doc) {
if (logger.isDebugEnabled()) {
logger.debug("writing the content of: " + doc);
}
final SystemHelper systemHelper = SingletonS2Container
.getComponent("systemHelper");
final Object configIdObj = doc.get(systemHelper.configIdField);
if (configIdObj == null) {
throw new FessSystemException("Invalid configId: " + configIdObj);
}
final String configId = configIdObj.toString();
if (configId.length() < 2) {
throw new FessSystemException("Invalid configId: " + configIdObj);
}
final ConfigType configType = getConfigType(configId);
CrawlingConfig config = null;
if (logger.isDebugEnabled()) {
logger.debug("configType: " + configType + ", configId: "
+ configId);
}
if (ConfigType.WEB == configType) {
final WebCrawlingConfigService webCrawlingConfigService = SingletonS2Container
.getComponent(WebCrawlingConfigService.class);
config = webCrawlingConfigService
.getWebCrawlingConfig(getId(configId));
} else if (ConfigType.FILE == configType) {
final FileCrawlingConfigService fileCrawlingConfigService = SingletonS2Container
.getComponent(FileCrawlingConfigService.class);
config = fileCrawlingConfigService
.getFileCrawlingConfig(getId(configId));
} else if (ConfigType.DATA == configType) {
final DataCrawlingConfigService dataCrawlingConfigService = SingletonS2Container
.getComponent(DataCrawlingConfigService.class);
config = dataCrawlingConfigService
.getDataCrawlingConfig(getId(configId));
}
if (config == null) {
throw new FessSystemException("No crawlingConfig: " + configIdObj);
}
final String url = (String) doc.get(systemHelper.urlField);
final S2RobotClientFactory robotClientFactory = SingletonS2Container
.getComponent(S2RobotClientFactory.class);
config.initializeClientFactory(robotClientFactory);
final S2RobotClient client = robotClientFactory.getClient(url);
if (client == null) {
throw new FessSystemException("No S2RobotClient: " + configIdObj
+ ", url: " + url);
}
final ResponseData responseData = client.doGet(url);
final HttpServletResponse response = ResponseUtil.getResponse();
writeFileName(response, responseData);
writeContentType(response, responseData);
writeNoCache(response, responseData);
InputStream is = null;
OutputStream os = null;
try {
is = new BufferedInputStream(responseData.getResponseBody());
os = new BufferedOutputStream(response.getOutputStream());
StreamUtil.drain(is, os);
os.flush();
} catch (final IOException e) {
if (!"ClientAbortException".equals(e.getClass().getSimpleName())) {
throw new FessSystemException(
"Failed to write a content. configId: " + configIdObj
+ ", url: " + url, e);
}
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
if (logger.isDebugEnabled()) {
logger.debug("Finished to write " + url);
}
}
|
public void run() {
StringBuilder builder = new StringBuilder();
try {
char[] cbuf = new char[8192];
int n = reader.read(cbuf);
while (n > 0) {
builder.append(cbuf, 0, n);
n = reader.read(cbuf);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
SExpParser parser = new SExpParser(builder.toString());
SExp exp = parser.read();
if (exp == null || !exp.isSymbol()) {
OrccLogger.warnln("Actor " + actor.getName() + ": ");
String error[] = builder.toString().split("\n");
for (int i = 0; i < error.length; i++) {
OrccLogger.warnln(error[i]);
}
return;
}
SExpSymbol symbol = (SExpSymbol) exp;
satisfied = "sat".equals(symbol.getContents());
if (satisfied && action != null && ports != null) {
exp = parser.read();
if (exp != null && exp.isList()) {
SExpList list = (SExpList) exp;
Pattern pattern = action.getPeekPattern();
int index = 0;
for (Port port : ports) {
exp = list.get(index);
index++;
Object value;
int numTokens = pattern.getNumTokens(port);
if (numTokens > 1) {
List<Object> values = new ArrayList<Object>();
SExpList portList = (SExpList) exp;
for (int i = 0; i < numTokens; i++) {
SExp subExpr = portList.get(i);
values.add(getExpression(subExpr));
}
value = values.toArray();
} else {
value = getExpression(exp);
}
assertions.put(port.getName(), value);
}
}
}
}
| public void run() {
StringBuilder builder = new StringBuilder();
try {
char[] cbuf = new char[8192];
int n = reader.read(cbuf);
while (n > 0) {
builder.append(cbuf, 0, n);
n = reader.read(cbuf);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
SExpParser parser = new SExpParser(builder.toString());
SExp exp = parser.read();
if (exp == null || !exp.isSymbol()) {
OrccLogger.warnln("Solving of actor " + actor.getName() + ":");
String error[] = builder.toString().split("\n");
for (int i = 0; i < error.length; i++) {
OrccLogger.traceln(error[i]);
}
return;
}
SExpSymbol symbol = (SExpSymbol) exp;
satisfied = "sat".equals(symbol.getContents());
if (satisfied && action != null && ports != null) {
exp = parser.read();
if (exp != null && exp.isList()) {
SExpList list = (SExpList) exp;
Pattern pattern = action.getPeekPattern();
int index = 0;
for (Port port : ports) {
exp = list.get(index);
index++;
Object value;
int numTokens = pattern.getNumTokens(port);
if (numTokens > 1) {
List<Object> values = new ArrayList<Object>();
SExpList portList = (SExpList) exp;
for (int i = 0; i < numTokens; i++) {
SExp subExpr = portList.get(i);
values.add(getExpression(subExpr));
}
value = values.toArray();
} else {
value = getExpression(exp);
}
assertions.put(port.getName(), value);
}
}
}
}
|
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
IJavaStackFrame frame = getFrame();
if (frame != null) {
ICodeAssist codeAssist = null;
if (fEditor != null) {
IEditorInput input = fEditor.getEditorInput();
Object element = JavaUI.getWorkingCopyManager().getWorkingCopy(input);
if (element == null) {
element = input.getAdapter(IClassFile.class);
}
if (element instanceof ICodeAssist) {
codeAssist = ((ICodeAssist)element);
}
}
if (codeAssist == null) {
return getRemoteHoverInfo(frame, textViewer, hoverRegion);
}
try {
IJavaElement[] resolve = codeAssist.codeSelect(hoverRegion.getOffset(), 0);
for (int i = 0; i < resolve.length; i++) {
IJavaElement javaElement = resolve[i];
if (javaElement instanceof IField) {
IField field = (IField)javaElement;
String typeSignature = Signature.createTypeSignature(field.getDeclaringType().getFullyQualifiedName(), true);
typeSignature = typeSignature.replace('.', '/');
IJavaFieldVariable fieldVariable = null;
if (frame.isStatic()) {
fieldVariable = frame.getDeclaringType().getField(field.getElementName());
} else {
fieldVariable = frame.getThis().getField(field.getElementName(), typeSignature);
}
if (fieldVariable != null) {
return getVariableText(fieldVariable);
}
break;
}
if (javaElement instanceof ILocalVariable) {
ILocalVariable var = (ILocalVariable)javaElement;
IJavaElement parent = var.getParent();
while (!(parent instanceof IMethod) && parent != null) {
parent = parent.getParent();
}
if (parent instanceof IMethod) {
IMethod method = (IMethod) parent;
boolean equal = false;
if (method.isBinary()) {
if (method.getSignature().equals(frame.getSignature())) {
equal = true;
}
} else {
if (((frame.isConstructor() && method.isConstructor()) || frame.getMethodName().equals(method.getElementName()))
&& frame.getDeclaringTypeName().endsWith(method.getDeclaringType().getElementName())
&& frame.getArgumentTypeNames().size() == method.getNumberOfParameters()) {
equal = true;
}
}
if (equal) {
return generateHoverForLocal(frame, var.getElementName());
}
}
break;
}
}
} catch (CoreException e) {
JDIDebugPlugin.log(e);
}
}
return null;
}
| public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
IJavaStackFrame frame = getFrame();
if (frame != null) {
IDocument document= textViewer.getDocument();
if (document != null) {
try {
String variableName= document.get(hoverRegion.getOffset(), hoverRegion.getLength());
if (variableName.equals("this")) {
try {
IJavaVariable variable = frame.findVariable(variableName);
if (variable != null) {
return getVariableText(variable);
}
} catch (DebugException e) {
return null;
}
}
} catch (BadLocationException e) {
return null;
}
}
ICodeAssist codeAssist = null;
if (fEditor != null) {
IEditorInput input = fEditor.getEditorInput();
Object element = JavaUI.getWorkingCopyManager().getWorkingCopy(input);
if (element == null) {
element = input.getAdapter(IClassFile.class);
}
if (element instanceof ICodeAssist) {
codeAssist = ((ICodeAssist)element);
}
}
if (codeAssist == null) {
return getRemoteHoverInfo(frame, textViewer, hoverRegion);
}
try {
IJavaElement[] resolve = codeAssist.codeSelect(hoverRegion.getOffset(), 0);
for (int i = 0; i < resolve.length; i++) {
IJavaElement javaElement = resolve[i];
if (javaElement instanceof IField) {
IField field = (IField)javaElement;
String typeSignature = Signature.createTypeSignature(field.getDeclaringType().getFullyQualifiedName(), true);
typeSignature = typeSignature.replace('.', '/');
IJavaFieldVariable fieldVariable = null;
if (frame.isStatic()) {
fieldVariable = frame.getDeclaringType().getField(field.getElementName());
} else {
fieldVariable = frame.getThis().getField(field.getElementName(), typeSignature);
}
if (fieldVariable != null) {
return getVariableText(fieldVariable);
}
break;
}
if (javaElement instanceof ILocalVariable) {
ILocalVariable var = (ILocalVariable)javaElement;
IJavaElement parent = var.getParent();
while (!(parent instanceof IMethod) && parent != null) {
parent = parent.getParent();
}
if (parent instanceof IMethod) {
IMethod method = (IMethod) parent;
boolean equal = false;
if (method.isBinary()) {
if (method.getSignature().equals(frame.getSignature())) {
equal = true;
}
} else {
if (((frame.isConstructor() && method.isConstructor()) || frame.getMethodName().equals(method.getElementName()))
&& frame.getDeclaringTypeName().endsWith(method.getDeclaringType().getElementName())
&& frame.getArgumentTypeNames().size() == method.getNumberOfParameters()) {
equal = true;
}
}
if (equal) {
return generateHoverForLocal(frame, var.getElementName());
}
}
break;
}
}
} catch (CoreException e) {
JDIDebugPlugin.log(e);
}
}
return null;
}
|
public void preview() {
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(this);
this.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(txtQuestionText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(answerCheckBoxes[5], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(answerCheckBoxes[4], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(answerCheckBoxes[3], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(answerCheckBoxes[2], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(answerCheckBoxes[1], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(answerCheckBoxes[0], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(20, Short.MAX_VALUE)));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtQuestionText, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[0])
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[1])
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[2])
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[3])
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[4])
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[5])
.addContainerGap(20, 20)));
clear();
txtQuestionText.setLineWrap(true);
txtQuestionText.setEditable(false);
txtQuestionText.setOpaque(false);
txtQuestionText.setBackground(new Color(0,0,0,0));
txtQuestionText.setText(this.mcqQuestion.getQuestionText());
txtQuestionText.setFont(new java.awt.Font("MV Boli", 0, 16));
ArrayList<String> questionAnswers = mcqQuestion.getAnswers();
ArrayList<Integer> studentAnswers = mcqQuestion.getStudentAnswers();
ArrayList<Integer> correctAnswers = mcqQuestion.getCorrectAnswers();
int cnt;
for (cnt = 0; cnt < questionAnswers.size(); cnt++) {
answerCheckBoxes[cnt].setText(questionAnswers.get(cnt));
}
for (cnt = cnt; cnt < 6; cnt++) {
answerCheckBoxes[cnt].setVisible(false);
}
if (studentAnswers != null) {
for (int i = 0; i < studentAnswers.size(); i++) {
answerCheckBoxes[studentAnswers.get(i)].setSelected(true);
}
}
}
| public void preview() {
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(this);
this.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(txtQuestionText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(answerCheckBoxes[5], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(answerCheckBoxes[4], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(answerCheckBoxes[3], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(answerCheckBoxes[2], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(answerCheckBoxes[1], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(answerCheckBoxes[0], javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(20, Short.MAX_VALUE)));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtQuestionText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[0])
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[1])
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[2])
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[3])
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[4])
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(answerCheckBoxes[5])
.addContainerGap(20, 20)));
clear();
txtQuestionText.setWrapStyleWord(true);
txtQuestionText.setLineWrap(true);
txtQuestionText.setEditable(false);
txtQuestionText.setBackground(new Color(0,0,0,0));
txtQuestionText.setText(this.mcqQuestion.getQuestionText());
txtQuestionText.setFont(new java.awt.Font("MV Boli", 0, 16));
ArrayList<String> questionAnswers = mcqQuestion.getAnswers();
ArrayList<Integer> studentAnswers = mcqQuestion.getStudentAnswers();
ArrayList<Integer> correctAnswers = mcqQuestion.getCorrectAnswers();
int cnt;
for (cnt = 0; cnt < questionAnswers.size(); cnt++) {
answerCheckBoxes[cnt].setText(questionAnswers.get(cnt));
}
for (cnt = cnt; cnt < 6; cnt++) {
answerCheckBoxes[cnt].setVisible(false);
}
if (studentAnswers != null) {
for (int i = 0; i < studentAnswers.size(); i++) {
answerCheckBoxes[studentAnswers.get(i)].setSelected(true);
}
}
}
|
public void test() throws Exception {
Configuration cfg = new Configuration();
cfg.setClassForTemplateLoading(OpenLayersMapProducer.class, "");
cfg.setObjectWrapper(new BeansWrapper());
Template template = cfg.getTemplate("OpenLayersMapTemplate.ftl");
assertNotNull(template);
GetMapRequest request = createGetMapRequest(MockData.BASIC_POLYGONS);
WMSMapContext mapContext = new WMSMapContext();
mapContext.addLayer(createMapLayer(MockData.BASIC_POLYGONS));
mapContext.setRequest(request);
mapContext.setMapWidth(256);
mapContext.setMapHeight(256);
ByteArrayOutputStream output = new ByteArrayOutputStream();
HashMap map = new HashMap();
map.put("context", mapContext);
map.put("request", mapContext.getRequest());
map.put("maxResolution", new Double(0.0005));
template.process(map, new OutputStreamWriter(output));
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = docBuilder.parse(new ByteArrayInputStream(output.toByteArray()));
assertNotNull(document);
assertEquals("html", document.getDocumentElement().getNodeName());
}
| public void test() throws Exception {
Configuration cfg = new Configuration();
cfg.setClassForTemplateLoading(OpenLayersMapProducer.class, "");
cfg.setObjectWrapper(new BeansWrapper());
Template template = cfg.getTemplate("OpenLayersMapTemplate.ftl");
assertNotNull(template);
GetMapRequest request = createGetMapRequest(MockData.BASIC_POLYGONS);
WMSMapContext mapContext = new WMSMapContext();
mapContext.addLayer(createMapLayer(MockData.BASIC_POLYGONS));
mapContext.setRequest(request);
mapContext.setMapWidth(256);
mapContext.setMapHeight(256);
ByteArrayOutputStream output = new ByteArrayOutputStream();
HashMap map = new HashMap();
map.put("context", mapContext);
map.put("request", mapContext.getRequest());
map.put("maxResolution", new Double(0.0005));
map.put("openLayersLocation", "./openLayers.js");
template.process(map, new OutputStreamWriter(output));
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = docBuilder.parse(new ByteArrayInputStream(output.toByteArray()));
assertNotNull(document);
assertEquals("html", document.getDocumentElement().getNodeName());
}
|
protected CPSDatum<Date> getEffectiveDate( int prop_effective ) {
CPSDatum<Date> p, a;
CPSDatum<Date> e = getDatum( prop_effective );
if ( prop_effective == PROP_DATE_PLANT ) {
p = getDateToPlantDatum( DATE_TYPE_PLANNED );
a = getDateToPlantDatum( DATE_TYPE_ACTUAL );
} else if ( prop_effective == PROP_DATE_TP ) {
p = getDateToTPDatum( DATE_TYPE_PLANNED );
a = getDateToTPDatum( DATE_TYPE_ACTUAL );
} else {
p = getDateToHarvestDatum( DATE_TYPE_PLANNED );
a = getDateToHarvestDatum( DATE_TYPE_ACTUAL );
}
if ( a.isNotNull() && ! a.isBlank() ) {
e.setState( a.getState() );
return a;
}
else if ( p.isNotNull() ) {
e.setState( p.getState() );
return p;
}
return e;
}
private CPSDatum<Date> getDateToPlantDatum ( int date_type ) {
return getDateToPlantDatum ( date_type, new ArrayList() );
}
private CPSDatum<Date> getDateToPlantDatum ( int date_type, List source_path ) {
int prop_plant, prop_tp, prop_harv;
if ( date_type == DATE_TYPE_ACTUAL ) {
prop_plant = PROP_DATE_PLANT_ACTUAL;
prop_tp = PROP_DATE_TP_ACTUAL;
prop_harv = PROP_DATE_HARVEST_ACTUAL;
}
else {
prop_plant = PROP_DATE_PLANT_PLAN;
prop_tp = PROP_DATE_TP_PLAN;
prop_harv = PROP_DATE_HARVEST_PLAN;
}
CPSDatum p = getDatum( prop_plant );
if ( p.isConcrete() ||
source_path.contains( p.propertyNum ) ||
this.doesRepresentMultipleRecords() )
return p;
source_path.add( p.propertyNum );
CPSDatum w = getDatum( PROP_TIME_TO_TP );
if ( ! source_path.contains( prop_tp ) && isTransplanted() ) {
CPSDatum tp = getDateToTPDatum( date_type, source_path );
if ( tp.isNotNull() && w.isNotNull() ) {
set( p, CPSCalculations.calcDatePlantFromDateTP( (Date) tp.getValue(),
w.getValueAsInt() ));
p.setCalculated( true );
}
}
else if ( ! source_path.contains( prop_harv )) {
CPSDatum harv = getDateToHarvestDatum( date_type, source_path );
CPSDatum m = getDatum( PROP_MATURITY );
if ( harv.isNotNull() && m.isNotNull() ) {
try {
set( p, CPSCalculations.calcDatePlantFromDateHarvest( (Date) harv.getValue(),
m.getValueAsInt(),
getMatAdjust(),
w.getValueAsInt() ));
p.setCalculated( true );
} catch ( NullPointerException e ) { }
}
}
return p;
}
public Date getDateToPlant() {
return getEffectiveDate( PROP_DATE_PLANT ).getValue( useRawOutput() );
}
public String getDateToPlantString() { return formatDate( getDateToPlant() ); }
public CPSDatumState getDateToPlantState() { return getStateOf( PROP_DATE_PLANT ); }
public Date getDateToPlantPlanned() {
return getDateToPlantDatum( DATE_TYPE_PLANNED ).getValue( useRawOutput() );
}
public String getDateToPlantPlannedString() { return formatDate( getDateToPlantPlanned() ); }
public CPSDatumState getDateToPlantPlannedState() { return getStateOf( PROP_DATE_PLANT_PLAN ); }
public void setDateToPlantPlanned( Date d ) { set( date_plant_plan, d ); }
public void setDateToPlantPlanned( String d ) { setDateToPlantPlanned( parseDate(d) ); }
public Date getDateToPlantActual() {
return getDateToPlantDatum( DATE_TYPE_ACTUAL ).getValue( useRawOutput() );
}
public String getDateToPlantActualString() { return formatDate( getDateToPlantActual() ); }
public CPSDatumState getDateToPlantActualState() { return getStateOf( PROP_DATE_PLANT_ACTUAL ); }
public void setDateToPlantActual( Date d ) { set( date_plant_actual, d ); }
public void setDateToPlantActual( String d ) { setDateToPlantActual( parseDate(d) ); }
private CPSDatum<Date> getDateToTPDatum( int date_type ) {
return getDateToTPDatum( date_type, new ArrayList() );
}
private CPSDatum<Date> getDateToTPDatum( int date_type, List source_path ) {
int prop_plant, prop_tp, prop_harv;
boolean actual = date_type == DATE_TYPE_ACTUAL;
if ( actual ) {
prop_plant = PROP_DATE_PLANT_ACTUAL;
prop_tp = PROP_DATE_TP_ACTUAL;
prop_harv = PROP_DATE_HARVEST_ACTUAL;
}
else {
prop_plant = PROP_DATE_PLANT_PLAN;
prop_tp = PROP_DATE_TP_PLAN;
prop_harv = PROP_DATE_HARVEST_PLAN;
}
CPSDatum t = getDatum( prop_tp );
if ( this.isDirectSeeded() ) {
t.setValue( t.getNullValue() );
return t;
}
if ( t.isConcrete() ||
source_path.contains( t.propertyNum ) ||
this.doesRepresentMultipleRecords() )
return t;
source_path.add( t.propertyNum );
CPSDatum w = getDatum( PROP_TIME_TO_TP );
if ( ! source_path.contains( prop_plant )) {
CPSDatum p = getDateToPlantDatum( date_type, source_path );
if ( p.isNotNull() && w.isNotNull() ) {
set( t, CPSCalculations.calcDateTPFromDatePlant( (Date) p.getValue(),
w.getValueAsInt() ) );
t.setCalculated( true );
}
}
else if ( ! source_path.contains( prop_harv )) {
CPSDatum h = getDateToHarvestDatum( date_type, source_path );
CPSDatum m = getDatum( PROP_MATURITY );
if ( w.isNotNull() && h.isNotNull() && m.isNotNull() ) {
try {
set( t, CPSCalculations.calcDateTPFromDateHarvest( (Date) h.getValue(),
m.getValueAsInt(),
getMatAdjust() ) );
t.setCalculated( true );
} catch ( NullPointerException e ) { }
}
}
return t;
}
public Date getDateToTP() {
return getEffectiveDate( PROP_DATE_TP ).getValue( useRawOutput() );
}
public String getDateToTPString() { return formatDate( getDateToTP() ); }
public CPSDatumState getDateToTPState() { return getStateOf( PROP_DATE_TP ); }
public Date getDateToTPPlanned () {
return getDateToTPDatum( DATE_TYPE_PLANNED ).getValue( useRawOutput() );
}
public String getDateToTPPlannedString() { return formatDate( getDateToTPPlanned() ); }
public CPSDatumState getDateToTPPlannedState() { return getStateOf( PROP_DATE_TP_PLAN ); }
public void setDateToTPPlanned( Date d ) { set( date_tp_plan, d ); }
public void setDateToTPPlanned( String d ) { setDateToTPPlanned( parseDate( d ) ); }
public Date getDateToTPActual() {
return getDateToTPDatum( DATE_TYPE_ACTUAL ).getValue( useRawOutput() );
}
public String getDateToTPActualString() { return formatDate( getDateToTPActual() ); }
public CPSDatumState getDateToTPActualState() { return getStateOf( PROP_DATE_TP_ACTUAL ); }
public void setDateToTPActual( Date d ) { set( date_tp_actual, d ); }
public void setDateToTPActual( String d ) { setDateToTPActual( parseDate( d ) ); }
private CPSDatum<Date> getDateToHarvestDatum( int date_type ) {
return getDateToHarvestDatum( date_type, new ArrayList() );
}
private CPSDatum<Date> getDateToHarvestDatum( int date_type, List source_path ) {
int prop_plant, prop_tp, prop_harv;
if ( date_type == DATE_TYPE_ACTUAL ) {
prop_plant = PROP_DATE_PLANT_ACTUAL;
prop_tp = PROP_DATE_TP_ACTUAL;
prop_harv = PROP_DATE_HARVEST_ACTUAL;
}
else {
prop_plant = PROP_DATE_PLANT_PLAN;
prop_tp = PROP_DATE_TP_PLAN;
prop_harv = PROP_DATE_HARVEST_PLAN;
}
CPSDatum<Date> h = getDatum( prop_harv );
if ( h.isConcrete() ||
source_path.contains( h.propertyNum ) ||
this.doesRepresentMultipleRecords() )
return h;
source_path.add( h.propertyNum );
CPSDatum m = getDatum( PROP_MATURITY );
if ( ! source_path.contains( prop_tp ) && isTransplanted() ) {
CPSDatum t = getDateToTPDatum( date_type, source_path );
if ( t.isNotNull() && m.isNotNull() ) {
try {
set( h, CPSCalculations.calcDateHarvestFromDateTP( (Date) t.getValue(),
m.getValueAsInt(),
getMatAdjust() ) );
h.setCalculated( true );
} catch ( NullPointerException e ) { }
}
}
else if ( ! source_path.contains( prop_plant )) {
CPSDatum p = getDateToPlantDatum( date_type, source_path );
CPSDatum w = getDatum( PROP_TIME_TO_TP );
if ( p.isNotNull() && m.isNotNull() ) {
try {
set( h, CPSCalculations.calcDateHarvestFromDatePlant( (Date) p.getValue(),
m.getValueAsInt(),
getMatAdjust(),
w.getValueAsInt() ));
h.setCalculated( true );
} catch ( NullPointerException e ) { }
}
}
return h;
}
public Date getDateToHarvest() {
return getEffectiveDate( PROP_DATE_HARVEST ).getValue(useRawOutput());
}
public String getDateToHarvestString() { return formatDate( getDateToHarvest() ); }
public CPSDatumState getDateToHarvestState() { return getStateOf( PROP_DATE_HARVEST ); }
public Date getDateToHarvestPlanned() {
return getDateToHarvestDatum( DATE_TYPE_PLANNED ).getValue(useRawOutput());
}
public String getDateToHarvestPlannedString() { return formatDate( getDateToHarvestPlanned() ); }
public CPSDatumState getDateToHarvestPlannedState() { return getStateOf( PROP_DATE_HARVEST_PLAN ); }
public void setDateToHarvestPlanned( Date d ) { set( date_harvest_plan, d ); }
public void setDateToHarvestPlanned( String d ) { setDateToHarvestPlanned( parseDate( d ) ); }
public Date getDateToHarvestActual() {
return getDateToHarvestDatum( DATE_TYPE_ACTUAL ).getValue(useRawOutput());
}
public String getDateToHarvestActualString() { return formatDate( getDateToHarvestActual() ); }
public CPSDatumState getDateToHarvestActualState() { return getStateOf( PROP_DATE_HARVEST_ACTUAL ); }
public void setDateToHarvestActual( Date d ) { set( date_harvest_actual, d ); }
public void setDateToHarvestActual( String d ) { setDateToHarvestActual( parseDate( d ) ); }
public Boolean getDonePlanting() { return get( PROP_DONE_PLANTING ); }
public CPSDatumState getDonePlantingState() { return getStateOf( PROP_DONE_PLANTING ); }
public void setDonePlanting( String s ) {
if ( s != null && s.equalsIgnoreCase("true") )
setDonePlanting( true );
else
setDonePlanting( false );
}
public void setDonePlanting( Boolean b ) { set( done_plant, b ); }
public void setDonePlanting( boolean b ) { set( done_plant, new Boolean( b ) ); }
public Boolean getDoneTP() { return get( PROP_DONE_TP ); }
public CPSDatumState getDoneTPState() { return getStateOf( PROP_DONE_TP ); }
public void setDoneTP( String s ) {
if ( s != null && s.equalsIgnoreCase("true") )
setDoneTP( true );
else
setDoneTP( false );
}
public void setDoneTP( Boolean b ) { set( done_tp, b ); }
public void setDoneTP( boolean b ) { set( done_tp, new Boolean( b ) ); }
public Boolean getDoneHarvest() { return get( PROP_DONE_HARVEST ); }
public CPSDatumState getDoneHarvestState() { return getStateOf( PROP_DONE_HARVEST ); }
public void setDoneHarvest( String s ) {
if ( s != null && s.equalsIgnoreCase("true") )
setDoneHarvest( true );
else
setDoneHarvest( false );
}
public void setDoneHarvest( Boolean b ) { set( done_harvest, b ); }
public void setDoneHarvest( boolean b ) { set( done_harvest, new Boolean( b ) ); }
public Boolean getIgnore() { return get( PROP_IGNORE ); }
public CPSDatumState getIgnoreState() { return getStateOf( PROP_IGNORE ); }
public void setIgnore( String s ) {
if ( s != null && s.equalsIgnoreCase("true") )
setIgnore( true );
else
setIgnore( false );
}
public void setIgnore( Boolean b ) { set( ignore, b ); }
public void setIgnore( boolean b ) { set( ignore, new Boolean( b ) ); }
@NoColumn
public Integer getMatAdjust() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getInt( PROP_DS_MAT_ADJUST );
else
return getInt( PROP_TP_MAT_ADJUST );
}
public String getMatAdjustString() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getString( PROP_DS_MAT_ADJUST );
else
return getString( PROP_TP_MAT_ADJUST );
}
public CPSDatumState getMatAdjustState() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getStateOf( PROP_DS_MAT_ADJUST );
else
return getStateOf( PROP_TP_MAT_ADJUST );
}
public void setMatAdjust( Integer i ) {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
set( ds_mat_adjust, i );
else
set( tp_mat_adjust, i );
}
public void setMatAdjust( int i ) { setMatAdjust( new Integer( i )); }
public void setMatAdjust( String s ) { setMatAdjust( parseInteger(s) ); }
@Deprecated
public Integer getDSMatAdjust() { return getInt( PROP_DS_MAT_ADJUST ); }
@Deprecated
public void setDSMatAdjust( Integer i ) { set( ds_mat_adjust, i ); }
@Deprecated
public Integer getTPMatAdjust() { return getInt( PROP_TP_MAT_ADJUST ); }
@Deprecated
public void setTPMatAdjust( Integer i ) { set( tp_mat_adjust, i ); }
public Integer getTimeToTP() { return getInt( PROP_TIME_TO_TP ); }
public String getTimeToTPString() { return getString( PROP_TIME_TO_TP ); }
public CPSDatumState getTimeToTPState() { return getStateOf( PROP_TIME_TO_TP ); }
public void setTimeToTP( Integer i ) { set( time_to_tp, i ); }
public void setTimeToTP( int i ) { setTimeToTP( new Integer( i ) ); }
public void setTimeToTP( String s ) { setTimeToTP( parseInteger(s) ); }
@NoColumn
public Integer getRowsPerBed() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getInt( PROP_DS_ROWS_P_BED );
else
return getInt( PROP_TP_ROWS_P_BED );
}
public String getRowsPerBedString() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getString( PROP_DS_ROWS_P_BED );
else
return getString( PROP_TP_ROWS_P_BED );
}
public CPSDatumState getRowsPerBedState() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getStateOf( PROP_DS_ROWS_P_BED );
else
return getStateOf( PROP_TP_ROWS_P_BED );
}
public void setRowsPerBed( Integer i ) {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() ) {
set( ds_rows_p_bed, i );
}
else {
set( tp_rows_p_bed, i );
}
}
public void setRowsPerBed( int i ) { setRowsPerBed( new Integer( i )); }
public void setRowsPerBed( String s ) { setRowsPerBed( parseInteger(s) ); }
@Deprecated
public Integer getDSRowsPerBed() { return getInt( PROP_DS_ROWS_P_BED ); }
@Deprecated
public void setDSRowsPerBed( Integer i ) { set( ds_rows_p_bed, i ); }
@Deprecated
public Integer getTPRowsPerBed() { return getInt( PROP_TP_ROWS_P_BED ); }
@Deprecated
public void setTPRowsPerBed( Integer i ) { set( tp_rows_p_bed, i ); }
public Integer getInRowSpacing() { return getInt( PROP_INROW_SPACE ); }
public String getInRowSpacingString() { return getString( PROP_INROW_SPACE ); }
public CPSDatumState getInRowSpacingState() { return getStateOf( PROP_INROW_SPACE ); }
public void setInRowSpacing( Integer i ) { set( inrow_space, i ); }
public void setInRowSpacing( int i ) { setInRowSpacing( new Integer( i ) ); }
public void setInRowSpacing( String s ) { setInRowSpacing( parseInteger(s) ); }
@NoColumn
public Integer getRowSpacing() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getInt( PROP_DS_ROW_SPACE );
else
return getInt( PROP_TP_ROW_SPACE );
}
public String getRowSpacingString() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getString( PROP_DS_ROW_SPACE );
else
return getString( PROP_TP_ROW_SPACE );
}
public CPSDatumState getRowSpacingState() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getStateOf( PROP_DS_ROW_SPACE );
else
return getStateOf( PROP_TP_ROW_SPACE );
}
public void setRowSpacing( Integer i ) {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
set( ds_row_space, i );
else
set( tp_row_space, i );
}
public void setRowSpacing( int i ) { setRowSpacing( new Integer( i ) ); }
public void setRowSpacing( String s ) { setRowSpacing( parseInteger(s) ); }
@Deprecated
public Integer getDSRowSpacing() { return getInt( PROP_DS_ROW_SPACE ); }
@Deprecated
public void setDSRowSpacing( Integer i ) { set( ds_row_space, i ); }
@Deprecated
public Integer getTPRowSpacing() { return getInt( PROP_TP_ROW_SPACE ); }
@Deprecated
public void setTPRowSpacing( Integer i ) { set( tp_row_space, i ); }
public String getFlatSize() { return get( PROP_FLAT_SIZE ); }
public Integer getFlatSizeCapacity() {
return CPSCalculations.extractFlatCapacity( getFlatSize() );
}
public CPSDatumState getFlatSizeState() { return getStateOf( PROP_FLAT_SIZE ); }
public void setFlatSize( String i ) { set( flat_size, parseInheritableString(i) ); }
@NoColumn
public String getPlantingNotesInherited() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return get( PROP_DS_CROP_NOTES );
else
return get( PROP_TP_CROP_NOTES );
}
public CPSDatumState getPlantingNotesInheritedState() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getStateOf( PROP_DS_CROP_NOTES );
else
return getStateOf( PROP_TP_CROP_NOTES );
}
public void setPlantingNotesInherited( String i ) {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
set( ds_crop_notes, parseInheritableString(i) );
else
set( tp_crop_notes, parseInheritableString(i) );
}
public String getPlantingNotes() { return get( PROP_PLANTING_NOTES ); }
public CPSDatumState getPlantingNotesState() { return getStateOf( PROP_PLANTING_NOTES ); }
public void setPlantingNotes( String i ) { set( planting_notes, i ); }
@Deprecated
public String getDSPlantingNotes() { return get( PROP_DS_CROP_NOTES ); }
@Deprecated
public void setDSPlantingNotes( String i ) { set( ds_crop_notes, parseInheritableString(i) ); }
@Deprecated
public String getTPPlantingNotes() { return get( PROP_TP_CROP_NOTES ); }
@Deprecated
public void setTPPlantingNotes( String i ) { set( tp_crop_notes, parseInheritableString(i) ); }
protected CPSDatum<Float> getBedsToPlantDatum() { return getBedsToPlantDatum( new ArrayList() ); }
protected CPSDatum<Float> getBedsToPlantDatum( List source_path ) {
CPSDatum b = getDatum( PROP_BEDS_PLANT );
if ( b.isConcrete() || source_path.contains( b.propertyNum ) )
return b;
source_path.add( b.propertyNum );
if ( ! source_path.contains( PROP_ROWS_P_BED )) {
CPSDatum rpb = getDatum( PROP_ROWS_P_BED );
CPSDatum r = getRowFtToPlantDatum( source_path );
int bedLength = CPSCalculations.extractBedLength( getLocation() );
if ( r.isNotNull() && rpb.isNotNull() ) {
set( b, CPSCalculations.calcBedsToPlantFromRowFtToPlant( r.getValueAsInt(),
rpb.getValueAsInt(),
bedLength ));
b.setCalculated( true );
}
}
return b;
}
public Float getBedsToPlant() { return getBedsToPlantDatum().getValue( useRawOutput() ); }
public String getBedsToPlantString() { return formatFloat( getBedsToPlantDatum(), 3 ); }
public CPSDatumState getBedsToPlantState() { return getStateOf( PROP_BEDS_PLANT ); }
public void setBedsToPlant( Float i ) { set( beds_to_plant, i ); }
public void setBedsToPlant( float i ) { setBedsToPlant( new Float( i ) ); }
public void setBedsToPlant( String s ) { setBedsToPlant( parseFloatBigF(s) ); }
protected CPSDatum<Integer> getPlantsNeededDatum() { return getPlantsNeededDatum( new ArrayList() ); }
protected CPSDatum<Integer> getPlantsNeededDatum( List source_path ) {
CPSDatum p = getDatum( PROP_PLANTS_NEEDED );
if ( this.isDirectSeeded() ) {
p.setValue( p.getNullValue() );
return p;
}
if ( p.isConcrete() || source_path.contains( p.propertyNum ))
return p;
source_path.add( p.propertyNum );
if ( ! source_path.contains( PROP_ROWFT_PLANT )) {
CPSDatum irs = getDatum( PROP_INROW_SPACE );
CPSDatum r = getRowFtToPlantDatum( source_path );
if ( r.isNotNull() && irs.isNotNull() ) {
set( p, CPSCalculations.calcPlantsNeededFromRowFtToPlant( r.getValueAsInt(),
irs.getValueAsInt() ) );
p.setCalculated( true );
}
}
else if ( ! source_path.contains( PROP_PLANTS_START )) {
CPSDatum ps = getPlantsToStartDatum( source_path );
if ( ps.isNotNull() ) {
set( p, CPSCalculations.calcPlantsNeededFromPlantsToStart( ps.getValueAsInt() ) );
p.setCalculated( true );
}
}
return p;
}
public Integer getPlantsNeeded() { return getPlantsNeededDatum().getValue( useRawOutput() ); }
public String getPlantsNeededString() { return formatInt( getPlantsNeededDatum() ); }
public CPSDatumState getPlantsNeededState() { return getStateOf( PROP_PLANTS_NEEDED ); }
public void setPlantsNeeded( Integer i ) { set( plants_needed, i ); }
public void setPlantsNeeded( int i ) { setPlantsNeeded( new Integer( i ) ); }
public void setPlantsNeeded( String s ) { setPlantsNeeded( parseInteger(s) ); }
protected CPSDatum<Integer> getRowFtToPlantDatum() { return getRowFtToPlantDatum( new ArrayList() ); }
protected CPSDatum<Integer> getRowFtToPlantDatum( List source_path ) {
CPSDatum r = getDatum( PROP_ROWFT_PLANT );
if ( r.isConcrete() || source_path.contains( r.propertyNum ))
return r;
source_path.add( r.propertyNum );
if ( ! source_path.contains( PROP_BEDS_PLANT )) {
CPSDatum rpb = getDatum( PROP_ROWS_P_BED );
CPSDatum b = getBedsToPlantDatum( source_path );
if ( ! r.isConcrete() &&
b.isNotNull() && rpb.isNotNull() ) {
int bedLength = CPSCalculations.extractBedLength( getLocation() );
set( r, CPSCalculations.calcRowFtToPlantFromBedsToPlant( b.getValueAsFloat(),
rpb.getValueAsInt(),
bedLength ));
r.setCalculated( true );
}
}
else if ( ! source_path.contains( PROP_PLANTS_NEEDED )) {
CPSDatum ps = getDatum( PROP_INROW_SPACE );
CPSDatum p = getPlantsNeededDatum( source_path );
if ( ! r.isConcrete() &&
p.isNotNull() && ps.isNotNull() ) {
set( r, CPSCalculations.calcRowFtToPlantFromPlantsNeeded( p.getValueAsInt(),
ps.getValueAsInt() ));
r.setCalculated( true );
}
}
else if ( ! source_path.contains( PROP_TOTAL_YIELD )) {
CPSDatum yf = getDatum( PROP_YIELD_P_FOOT );
CPSDatum ty = getTotalYieldDatum( source_path );
if ( ! r.isConcrete() &&
ty.isNotNull() && yf.isNotNull() ) {
set( r, CPSCalculations.calcRowFtToPlantFromTotalYield( ty.getValueAsFloat(),
yf.getValueAsFloat() ));
r.setCalculated( true );
}
}
return r;
}
public Integer getRowFtToPlant() { return getRowFtToPlantDatum().getValue( useRawOutput() ); }
public String getRowFtToPlantString() { return formatInt( getRowFtToPlantDatum() ); }
public CPSDatumState getRowFtToPlantState() { return getStateOf( PROP_ROWFT_PLANT ); }
public void setRowFtToPlant( Integer i ) { set( rowft_to_plant, i ); }
public void setRowFtToPlant( int i ) { setRowFtToPlant( new Integer( i ) ); }
public void setRowFtToPlant( String s ) { setRowFtToPlant( parseInteger(s) ); }
protected CPSDatum<Integer> getPlantsToStartDatum() { return getPlantsToStartDatum( new ArrayList() ); }
protected CPSDatum<Integer> getPlantsToStartDatum( List source_path ) {
CPSDatum ps = getDatum( PROP_PLANTS_START );
if ( this.isDirectSeeded() ) {
ps.setValue( ps.getNullValue() );
return ps;
}
if ( ps.isConcrete() || source_path.contains( ps.propertyNum ))
return ps;
source_path.add( ps.propertyNum );
if ( ! source_path.contains( PROP_PLANTS_NEEDED )) {
CPSDatum pn = getPlantsNeededDatum( source_path );
if ( pn.isNotNull() ) {
set( ps, CPSCalculations.calcPlantsToStart( pn.getValueAsInt() ) );
ps.setCalculated( true );
}
}
else if ( ! source_path.contains( PROP_FLATS_NEEDED )) {
CPSDatum fz = getDatum( PROP_FLAT_SIZE );
CPSDatum fn = getFlatsNeededDatum( source_path );
if ( fn.isNotNull() && fz.isNotNull() ) {
set( ps, CPSCalculations.calcPlantsToStart( fn.getValueAsFloat(), getFlatSizeCapacity() ));
ps.setCalculated( true );
}
}
return ps;
}
public Integer getPlantsToStart() { return getPlantsToStartDatum().getValue( useRawOutput() ); }
public String getPlantsToStartString() { return formatInt( getPlantsToStartDatum() ); }
public CPSDatumState getPlantsToStartState() { return getStateOf( PROP_PLANTS_START ); }
public void setPlantsToStart( Integer i ) { set( plants_to_start, i ); }
public void setPlantsToStart( int i ) { setPlantsToStart( new Integer( i ) ); }
public void setPlantsToStart( String s ) { setPlantsToStart( parseInteger(s) ); }
protected CPSDatum<Float> getFlatsNeededDatum() { return getFlatsNeededDatum( new ArrayList() ); }
protected CPSDatum<Float> getFlatsNeededDatum( List source_path ) {
CPSDatum n = getDatum( PROP_FLATS_NEEDED );
if ( this.isDirectSeeded() ) {
n.setValue( n.getNullValue() );
return n;
}
if ( n.isConcrete() || source_path.contains( n.propertyNum ))
return n;
source_path.add( n.propertyNum );
if ( ! source_path.contains( PROP_PLANTS_START )) {
CPSDatum s = getDatum( PROP_FLAT_SIZE );
CPSDatum p = getPlantsToStartDatum( source_path );
if ( p.isNotNull() && s.isNotNull() ) {
set( n, CPSCalculations.calcFlatsNeeded( p.getValueAsInt(),
getFlatSizeCapacity() ) );
n.setCalculated( true );
}
}
return n;
}
public Float getFlatsNeeded() { return getFlatsNeededDatum().getValue( useRawOutput() ); }
public String getFlatsNeededString() { return formatFloat( getFlatsNeededDatum(), 3 ); }
public CPSDatumState getFlatsNeededState() { return getStateOf( PROP_FLATS_NEEDED ); }
public void setFlatsNeeded( Float i ) { set( flats_needed, i ); }
public void setFlatsNeeded( float i ) { setFlatsNeeded( new Float( i ) ); }
public void setFlatsNeeded( String s ) { setFlatsNeeded( parseFloatBigF(s) ); }
public Float getYieldPerFoot() { return getFloat( PROP_YIELD_P_FOOT ); }
public String getYieldPerFootString() { return formatFloat( getDatum( PROP_YIELD_P_FOOT ), 2 ); }
public CPSDatumState getYieldPerFootState() { return getStateOf( PROP_YIELD_P_FOOT ); }
public void setYieldPerFoot( Float i ) { set( yield_p_foot, i ); }
public void setYieldPerFoot( float i ) { setYieldPerFoot( new Float( i ) ); }
public void setYieldPerFoot( String s ) { setYieldPerFoot( parseFloatBigF(s) ); }
public Integer getYieldNumWeeks() { return getInt( PROP_YIELD_NUM_WEEKS ); }
public String getYieldNumWeeksString() { return formatInt( (Integer) get( PROP_YIELD_NUM_WEEKS ) ); }
public CPSDatumState getYieldNumWeeksState() { return getStateOf( PROP_YIELD_NUM_WEEKS ); }
public void setYieldNumWeeks( Integer i ) { set( yield_num_weeks, i ); }
public void setYieldNumWeeks( int i ) { setYieldNumWeeks( new Integer( i ) ); }
public void setYieldNumWeeks( String s ) { setYieldNumWeeks( parseInteger(s) ); }
public Float getYieldPerWeek() { return getFloat( PROP_YIELD_P_WEEK ); }
public String getYieldPerWeekString() { return formatFloat( (Float) get( PROP_YIELD_P_WEEK )); }
public CPSDatumState getYieldPerWeekState() { return getStateOf( PROP_YIELD_P_WEEK ); }
public void setYieldPerWeek( Float i ) { set( yield_p_week, i ); }
public void setYieldPerWeek( float i ) { setYieldPerWeek( new Float( i ) ); }
public void setYieldPerWeek( String s ) { setYieldPerWeek( parseFloatBigF(s) ); }
public String getCropYieldUnit() { return get( PROP_CROP_UNIT ); }
public CPSDatumState getCropYieldUnitState() { return getStateOf( PROP_CROP_UNIT ); }
public void setCropYieldUnit( String i ) { set( crop_unit, parseInheritableString(i) ); }
public Float getCropYieldUnitValue() { return getFloat( PROP_CROP_UNIT_VALUE ); }
public String getCropYieldUnitValueString() { return formatFloat( getDatum( PROP_CROP_UNIT_VALUE ), 2 ); }
public CPSDatumState getCropYieldUnitValueState() { return getStateOf( PROP_CROP_UNIT_VALUE ); }
public void setCropYieldUnitValue( Float i ) { set( crop_unit_value, i ); }
public void setCropYieldUnitValue( float i ) { setCropYieldUnitValue( new Float( i ) ); }
public void setCropYieldUnitValue( String s ) { setCropYieldUnitValue( parseFloatBigF(s) ); }
protected CPSDatum<Float> getTotalYieldDatum() { return getTotalYieldDatum( new ArrayList() ); }
protected CPSDatum<Float> getTotalYieldDatum( List source_path ) {
CPSDatum t = getDatum( PROP_TOTAL_YIELD );
if ( t.isConcrete() || source_path.contains( t.propertyNum ))
return t;
source_path.add( t.propertyNum );
if ( ! source_path.contains( PROP_ROWFT_PLANT )) {
CPSDatum y = getDatum( PROP_YIELD_P_FOOT );
CPSDatum r = getRowFtToPlantDatum( source_path );
if ( ! t.isConcrete() &&
y.isNotNull() && r.isNotNull() ) {
set( t, CPSCalculations.calcTotalYieldFromRowFtToPlant( r.getValueAsInt(), y.getValueAsFloat() ));
t.setCalculated( true );
}
}
return t;
}
public Float getTotalYield() { return getTotalYieldDatum().getValue( useRawOutput() ); }
public String getTotalYieldString() { return formatFloat( getTotalYieldDatum(), 3 ); }
public CPSDatumState getTotalYieldState() { return getStateOf( PROP_TOTAL_YIELD ); }
public void setTotalYield( Float i ) { set( total_yield, i ); }
public void setTotalYield( float i ) { setTotalYield( new Float( i ) ); }
public void setTotalYield( String s ) { setTotalYield( parseFloatBigF(s) ); }
public Integer getSeedsPerUnit() { return getInt( seedsPerUnit.getPropertyNum() ); }
public String getSeedsPerUnitString() { return getString( seedsPerUnit.getPropertyNum() ); }
public CPSDatumState getSeedsPerUnitState() { return getStateOf( seedsPerUnit.getPropertyNum() ); }
public void setSeedsPerUnit( Integer i ) { set( seedsPerUnit, i ); }
public void setSeedsPerUnit( int i ) { setSeedsPerUnit( new Integer( i )); }
public void setSeedsPerUnit( String s ) { setSeedsPerUnit( parseInteger(s) ); }
public String getSeedUnit() { return get( seedUnit.getPropertyNum() ); }
public CPSDatumState getSeedUnitState() { return getStateOf( seedUnit.getPropertyNum() ); }
public void setSeedUnit( String s ) { set( seedUnit, parseInheritableString(s) ); }
@NoColumn
public Float getSeedsPer() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getFloat( seedsPerDS.getPropertyNum() );
else
return getFloat( seedsPerTP.getPropertyNum() );
}
public String getSeedsPerString() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getString( seedsPerDS.getPropertyNum() );
else
return getString( seedsPerTP.getPropertyNum() );
}
public CPSDatumState getSeedsPerState() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getStateOf( seedsPerDS.getPropertyNum() );
else
return getStateOf( seedsPerTP.getPropertyNum() );
}
public void setSeedsPer( Float i ) {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
set( seedsPerDS, i );
else
set( seedsPerTP, i );
}
public void setSeedsPer( float i ) { setSeedsPer( new Float( i )); }
public void setSeedsPer( String s ) { setSeedsPer( parseFloatBigF(s) ); }
@Deprecated
public Float getSeedsPerDS() { return getFloat( seedsPerDS.getPropertyNum() ); }
@Deprecated
public void setSeedsPerDS( Float i ) { set( seedsPerDS, i ); }
@Deprecated
public Float getSeedsPerTP() { return getFloat( seedsPerTP.getPropertyNum() ); }
@Deprecated
public void setSeedsPerTP( Float f ) { set( seedsPerTP, f ); }
protected CPSDatum<Float> gettSeedNeededDatum() { return gettSeedNeededDatum( new ArrayList() ); }
protected CPSDatum<Float> gettSeedNeededDatum( List source_path ) {
CPSDatum n = getDatum( PROP_SEED_NEEDED );
if ( n.isConcrete() || source_path.contains( n.propertyNum ))
return n;
source_path.add( n.propertyNum );
CPSDatum d = getDatum( seedsPerDS.getPropertyNum() );
CPSDatum r = getRowFtToPlantDatum( source_path );
CPSDatum t = getDatum( seedsPerTP.getPropertyNum() );
CPSDatum p = getPlantsNeededDatum( source_path );
CPSDatum u = getDatum( seedsPerUnit.getPropertyNum() );
Boolean ds = this.isDirectSeeded();
ds = ds == null || ds.booleanValue();
if ( ! n.isConcrete() && u.isNotNull() ) {
if ( ds &&
d.isNotNull() && r.isNotNull() ) {
set( n,
( d.getValueAsFloat() * r.getValueAsInt()) / u.getValueAsInt() );
n.setCalculated( true );
}
else if ( ! ds &&
t.isNotNull() && p.isNotNull() ) {
set( n,
( t.getValueAsFloat() * p.getValueAsInt()) / u.getValueAsInt() );
n.setCalculated( true );
}
}
return n;
}
public Float getSeedNeeded() { return gettSeedNeededDatum().getValue( useRawOutput() ); }
public String getSeedNeededString() { return formatFloat( gettSeedNeededDatum(), 3 ); }
public CPSDatumState getSeedNeededState() { return getStateOf( seedNeeded.getPropertyNum() ); }
public void setSeedNeeded( Float f ) { set( seedNeeded, f ); }
public void setSeedNeeded( float f ) { setSeedNeeded( new Float( f )); }
public void setSeedNeeded( String s ) { setSeedNeeded( parseFloatBigF(s) ); }
public Boolean isDirectSeeded() { return getBoolean( PROP_DIRECT_SEED ); }
@NoColumn
public Boolean isTransplanted() {
if ( isDirectSeeded() == null )
return Boolean.FALSE;
else
return ! isDirectSeeded().booleanValue();
}
public CPSDatumState getDirectSeededState() { return getStateOf( PROP_DIRECT_SEED ); }
public void setDirectSeeded( String s ) {
if ( s != null && s.equalsIgnoreCase("true") )
setDirectSeeded( Boolean.TRUE );
else
setDirectSeeded( Boolean.FALSE );
}
public void setTransplanted( Boolean b ) {
if ( b == null )
setDirectSeeded( (Boolean) null );
else
setDirectSeeded( (Boolean) ! b.booleanValue() );
}
public void setDirectSeeded( Boolean b ) { set( direct_seed, b ); }
public void setDirectSeeded( boolean b ) { setDirectSeeded( new Boolean( b )); }
public Boolean isFrostHardy() { return getBoolean( PROP_FROST_HARDY ); }
public Boolean isFrostTender() { return ! isFrostHardy().booleanValue(); }
public CPSDatumState getFrostHardyState() { return getStateOf( PROP_FROST_HARDY ); }
public void setFrostHardy( String s ) {
if ( s != null && s.equalsIgnoreCase( "true" ) )
setFrostHardy( Boolean.TRUE );
else
setFrostHardy( Boolean.FALSE );
}
public void setFrostHardy( Boolean b ) { set( frost_hardy, b ); }
public void setFrostHardy( boolean b ) { setFrostHardy( new Boolean( b )); }
public String getGroups() { return get( PROP_GROUPS ); }
public CPSDatumState getGroupsState() { return getStateOf( PROP_GROUPS ); }
public void setGroups( String e ) { set( groups, e ); }
public String getKeywords() { return get( PROP_KEYWORDS ); }
public CPSDatumState getKeywordsState() { return getStateOf( PROP_KEYWORDS ); }
public void setKeywords( String e ) { set( keywords, e ); }
public String getOtherRequirements() { return get( PROP_OTHER_REQ ); }
public CPSDatumState getOtherRequirementsState() { return getStateOf( PROP_OTHER_REQ ); }
public void setOtherRequirements( String e ) { set( other_req, e ); }
public String getNotes() { return get( PROP_NOTES ); }
public CPSDatumState getNotesState() { return getStateOf( PROP_NOTES ); }
public void setNotes( String e ) { set( notes, e ); }
public String getCustomField1() { return get( PROP_CUSTOM1 ); }
public String getCustomField2() { return get( PROP_CUSTOM2 ); }
public String getCustomField3() { return get( PROP_CUSTOM3 ); }
public String getCustomField4() { return get( PROP_CUSTOM4 ); }
public String getCustomField5() { return get( PROP_CUSTOM5 ); }
public CPSDatumState getCustomField1State() { return getStateOf( PROP_CUSTOM1 ); }
public CPSDatumState getCustomField2State() { return getStateOf( PROP_CUSTOM2 ); }
public CPSDatumState getCustomField3State() { return getStateOf( PROP_CUSTOM3 ); }
public CPSDatumState getCustomField4State() { return getStateOf( PROP_CUSTOM4 ); }
public CPSDatumState getCustomField5State() { return getStateOf( PROP_CUSTOM5 ); }
public void setCustomField1( String s ) { set( custom1, s ); }
public void setCustomField2( String s ) { set( custom2, s ); }
public void setCustomField3( String s ) { set( custom3, s ); }
public void setCustomField4( String s ) { set( custom4, s ); }
public void setCustomField5( String s ) { set( custom5, s ); }
protected void updateCalculations() { }
public CPSRecord diff( CPSRecord thatPlanting ) {
return super.diff( thatPlanting, new CPSPlanting() );
}
@Override
public CPSRecord inheritFrom( CPSRecord thatRecord ) {
if ( this.getClass().getName().equalsIgnoreCase( thatRecord.getClass().getName() ))
return super.inheritFrom( thatRecord );
else if ( ! thatRecord.getClass().getName().equalsIgnoreCase( CPSCrop.class.getName() )) {
System.err.println("ERROR: CPSPlanting can only inherit from itself and from CPSCrop, " +
"not from " + thatRecord.getClass().getName() );
return this;
}
return super.inheritFrom( thatRecord );
}
public PlantingIterator iterator() { return new PlantingIterator(); }
public class PlantingIterator extends CPSRecordIterator {
public boolean ignoreThisProperty() {
return this.currentProp == PROP_ID ||
this.currentProp == PROP_DATE_PLANT ||
this.currentProp == PROP_DATE_TP ||
this.currentProp == PROP_DATE_HARVEST ||
this.currentProp == PROP_SEEDS_PER ||
this.currentProp == PROP_MAT_ADJUST ||
this.currentProp == PROP_ROWS_P_BED ||
this.currentProp == PROP_ROW_SPACE ||
this.currentProp == PROP_CROP_NOTES;
}
}
public String toString() {
String s = "";
PlantingIterator i = this.iterator();
CPSDatum c;
while ( i.hasNext() ) {
c = i.next();
if ( c.isNotNull() ) {
s += c.getName() + " = '" + c.getValue() + "'";
if ( c.isInherited() )
s += "(i)";
if ( c.isCalculated() )
s += "(c)";
s += ", ";
}
}
return s;
}
public Date parseDate( String s ) {
if ( s == null || s.equals("") )
return null;
return dateValidator.parse(s);
}
public String formatDate( Date d ) {
if ( d == null || d.getTime() == 0 )
return "";
else
return CPSDateValidator.format( d );
}
}
| protected CPSDatum<Date> getEffectiveDate( int prop_effective ) {
CPSDatum<Date> p, a;
CPSDatum<Date> e = getDatum( prop_effective );
if ( prop_effective == PROP_DATE_PLANT ) {
p = getDateToPlantDatum( DATE_TYPE_PLANNED );
a = getDateToPlantDatum( DATE_TYPE_ACTUAL );
} else if ( prop_effective == PROP_DATE_TP ) {
p = getDateToTPDatum( DATE_TYPE_PLANNED );
a = getDateToTPDatum( DATE_TYPE_ACTUAL );
} else {
p = getDateToHarvestDatum( DATE_TYPE_PLANNED );
a = getDateToHarvestDatum( DATE_TYPE_ACTUAL );
}
if ( a.isNotNull() && ! a.isBlank() ) {
e.setState( a.getState() );
return a;
}
else if ( p.isNotNull() ) {
e.setState( p.getState() );
return p;
}
return e;
}
private CPSDatum<Date> getDateToPlantDatum ( int date_type ) {
return getDateToPlantDatum ( date_type, new ArrayList() );
}
private CPSDatum<Date> getDateToPlantDatum ( int date_type, List source_path ) {
int prop_plant, prop_tp, prop_harv;
if ( date_type == DATE_TYPE_ACTUAL ) {
prop_plant = PROP_DATE_PLANT_ACTUAL;
prop_tp = PROP_DATE_TP_ACTUAL;
prop_harv = PROP_DATE_HARVEST_ACTUAL;
}
else {
prop_plant = PROP_DATE_PLANT_PLAN;
prop_tp = PROP_DATE_TP_PLAN;
prop_harv = PROP_DATE_HARVEST_PLAN;
}
CPSDatum p = getDatum( prop_plant );
if ( p.isConcrete() ||
source_path.contains( p.propertyNum ) ||
this.doesRepresentMultipleRecords() )
return p;
source_path.add( p.propertyNum );
CPSDatum w = getDatum( PROP_TIME_TO_TP );
if ( ! source_path.contains( prop_tp ) && isTransplanted() ) {
CPSDatum tp = getDateToTPDatum( date_type, source_path );
if ( tp.isNotNull() && w.isNotNull() ) {
set( p, CPSCalculations.calcDatePlantFromDateTP( (Date) tp.getValue(),
w.getValueAsInt() ));
p.setCalculated( true );
}
}
else if ( ! source_path.contains( prop_harv )) {
CPSDatum harv = getDateToHarvestDatum( date_type, source_path );
CPSDatum m = getDatum( PROP_MATURITY );
if ( harv.isNotNull() && m.isNotNull() ) {
try {
set( p, CPSCalculations.calcDatePlantFromDateHarvest( (Date) harv.getValue(),
m.getValueAsInt(),
getMatAdjust(),
w.getValueAsInt() ));
p.setCalculated( true );
} catch ( NullPointerException e ) { }
}
}
return p;
}
public Date getDateToPlant() {
return getEffectiveDate( PROP_DATE_PLANT ).getValue( useRawOutput() );
}
public String getDateToPlantString() { return formatDate( getDateToPlant() ); }
public CPSDatumState getDateToPlantState() { return getStateOf( PROP_DATE_PLANT ); }
public Date getDateToPlantPlanned() {
return getDateToPlantDatum( DATE_TYPE_PLANNED ).getValue( useRawOutput() );
}
public String getDateToPlantPlannedString() { return formatDate( getDateToPlantPlanned() ); }
public CPSDatumState getDateToPlantPlannedState() { return getStateOf( PROP_DATE_PLANT_PLAN ); }
public void setDateToPlantPlanned( Date d ) { set( date_plant_plan, d ); }
public void setDateToPlantPlanned( String d ) { setDateToPlantPlanned( parseDate(d) ); }
public Date getDateToPlantActual() {
return getDateToPlantDatum( DATE_TYPE_ACTUAL ).getValue( useRawOutput() );
}
public String getDateToPlantActualString() { return formatDate( getDateToPlantActual() ); }
public CPSDatumState getDateToPlantActualState() { return getStateOf( PROP_DATE_PLANT_ACTUAL ); }
public void setDateToPlantActual( Date d ) { set( date_plant_actual, d ); }
public void setDateToPlantActual( String d ) { setDateToPlantActual( parseDate(d) ); }
private CPSDatum<Date> getDateToTPDatum( int date_type ) {
return getDateToTPDatum( date_type, new ArrayList() );
}
private CPSDatum<Date> getDateToTPDatum( int date_type, List source_path ) {
int prop_plant, prop_tp, prop_harv;
boolean actual = date_type == DATE_TYPE_ACTUAL;
if ( actual ) {
prop_plant = PROP_DATE_PLANT_ACTUAL;
prop_tp = PROP_DATE_TP_ACTUAL;
prop_harv = PROP_DATE_HARVEST_ACTUAL;
}
else {
prop_plant = PROP_DATE_PLANT_PLAN;
prop_tp = PROP_DATE_TP_PLAN;
prop_harv = PROP_DATE_HARVEST_PLAN;
}
CPSDatum t = getDatum( prop_tp );
if ( this.isDirectSeeded() ) {
t.setValue( t.getNullValue() );
return t;
}
if ( t.isConcrete() ||
source_path.contains( t.propertyNum ) ||
this.doesRepresentMultipleRecords() )
return t;
source_path.add( t.propertyNum );
CPSDatum w = getDatum( PROP_TIME_TO_TP );
if ( ! source_path.contains( prop_plant )) {
CPSDatum p = getDateToPlantDatum( date_type, source_path );
if ( p.isNotNull() && w.isNotNull() ) {
set( t, CPSCalculations.calcDateTPFromDatePlant( (Date) p.getValue(),
w.getValueAsInt() ) );
t.setCalculated( true );
}
}
else if ( ! source_path.contains( prop_harv )) {
CPSDatum h = getDateToHarvestDatum( date_type, source_path );
CPSDatum m = getDatum( PROP_MATURITY );
if ( w.isNotNull() && h.isNotNull() && m.isNotNull() ) {
try {
set( t, CPSCalculations.calcDateTPFromDateHarvest( (Date) h.getValue(),
m.getValueAsInt(),
getMatAdjust() ) );
t.setCalculated( true );
} catch ( NullPointerException e ) { }
}
}
return t;
}
public Date getDateToTP() {
return getEffectiveDate( PROP_DATE_TP ).getValue( useRawOutput() );
}
public String getDateToTPString() { return formatDate( getDateToTP() ); }
public CPSDatumState getDateToTPState() { return getStateOf( PROP_DATE_TP ); }
public Date getDateToTPPlanned () {
return getDateToTPDatum( DATE_TYPE_PLANNED ).getValue( useRawOutput() );
}
public String getDateToTPPlannedString() { return formatDate( getDateToTPPlanned() ); }
public CPSDatumState getDateToTPPlannedState() { return getStateOf( PROP_DATE_TP_PLAN ); }
public void setDateToTPPlanned( Date d ) { set( date_tp_plan, d ); }
public void setDateToTPPlanned( String d ) { setDateToTPPlanned( parseDate( d ) ); }
public Date getDateToTPActual() {
return getDateToTPDatum( DATE_TYPE_ACTUAL ).getValue( useRawOutput() );
}
public String getDateToTPActualString() { return formatDate( getDateToTPActual() ); }
public CPSDatumState getDateToTPActualState() { return getStateOf( PROP_DATE_TP_ACTUAL ); }
public void setDateToTPActual( Date d ) { set( date_tp_actual, d ); }
public void setDateToTPActual( String d ) { setDateToTPActual( parseDate( d ) ); }
private CPSDatum<Date> getDateToHarvestDatum( int date_type ) {
return getDateToHarvestDatum( date_type, new ArrayList() );
}
private CPSDatum<Date> getDateToHarvestDatum( int date_type, List source_path ) {
int prop_plant, prop_tp, prop_harv;
if ( date_type == DATE_TYPE_ACTUAL ) {
prop_plant = PROP_DATE_PLANT_ACTUAL;
prop_tp = PROP_DATE_TP_ACTUAL;
prop_harv = PROP_DATE_HARVEST_ACTUAL;
}
else {
prop_plant = PROP_DATE_PLANT_PLAN;
prop_tp = PROP_DATE_TP_PLAN;
prop_harv = PROP_DATE_HARVEST_PLAN;
}
CPSDatum<Date> h = getDatum( prop_harv );
if ( h.isConcrete() ||
source_path.contains( h.propertyNum ) ||
this.doesRepresentMultipleRecords() )
return h;
source_path.add( h.propertyNum );
CPSDatum m = getDatum( PROP_MATURITY );
if ( ! source_path.contains( prop_tp ) && isTransplanted() ) {
CPSDatum t = getDateToTPDatum( date_type, source_path );
if ( t.isNotNull() && m.isNotNull() ) {
try {
set( h, CPSCalculations.calcDateHarvestFromDateTP( (Date) t.getValue(),
m.getValueAsInt(),
getMatAdjust() ) );
h.setCalculated( true );
} catch ( NullPointerException e ) { }
}
}
else if ( ! source_path.contains( prop_plant )) {
CPSDatum p = getDateToPlantDatum( date_type, source_path );
CPSDatum w = getDatum( PROP_TIME_TO_TP );
if ( p.isNotNull() && m.isNotNull() ) {
try {
set( h, CPSCalculations.calcDateHarvestFromDatePlant( (Date) p.getValue(),
m.getValueAsInt(),
getMatAdjust(),
w.getValueAsInt() ));
h.setCalculated( true );
} catch ( NullPointerException e ) { }
}
}
return h;
}
public Date getDateToHarvest() {
return getEffectiveDate( PROP_DATE_HARVEST ).getValue(useRawOutput());
}
public String getDateToHarvestString() { return formatDate( getDateToHarvest() ); }
public CPSDatumState getDateToHarvestState() { return getStateOf( PROP_DATE_HARVEST ); }
public Date getDateToHarvestPlanned() {
return getDateToHarvestDatum( DATE_TYPE_PLANNED ).getValue(useRawOutput());
}
public String getDateToHarvestPlannedString() { return formatDate( getDateToHarvestPlanned() ); }
public CPSDatumState getDateToHarvestPlannedState() { return getStateOf( PROP_DATE_HARVEST_PLAN ); }
public void setDateToHarvestPlanned( Date d ) { set( date_harvest_plan, d ); }
public void setDateToHarvestPlanned( String d ) { setDateToHarvestPlanned( parseDate( d ) ); }
public Date getDateToHarvestActual() {
return getDateToHarvestDatum( DATE_TYPE_ACTUAL ).getValue(useRawOutput());
}
public String getDateToHarvestActualString() { return formatDate( getDateToHarvestActual() ); }
public CPSDatumState getDateToHarvestActualState() { return getStateOf( PROP_DATE_HARVEST_ACTUAL ); }
public void setDateToHarvestActual( Date d ) { set( date_harvest_actual, d ); }
public void setDateToHarvestActual( String d ) { setDateToHarvestActual( parseDate( d ) ); }
public Boolean getDonePlanting() { return get( PROP_DONE_PLANTING ); }
public CPSDatumState getDonePlantingState() { return getStateOf( PROP_DONE_PLANTING ); }
public void setDonePlanting( String s ) {
if ( s != null && s.equalsIgnoreCase("true") )
setDonePlanting( true );
else
setDonePlanting( false );
}
public void setDonePlanting( Boolean b ) { set( done_plant, b ); }
public void setDonePlanting( boolean b ) { set( done_plant, new Boolean( b ) ); }
public Boolean getDoneTP() { return get( PROP_DONE_TP ); }
public CPSDatumState getDoneTPState() { return getStateOf( PROP_DONE_TP ); }
public void setDoneTP( String s ) {
if ( s != null && s.equalsIgnoreCase("true") )
setDoneTP( true );
else
setDoneTP( false );
}
public void setDoneTP( Boolean b ) { set( done_tp, b ); }
public void setDoneTP( boolean b ) { set( done_tp, new Boolean( b ) ); }
public Boolean getDoneHarvest() { return get( PROP_DONE_HARVEST ); }
public CPSDatumState getDoneHarvestState() { return getStateOf( PROP_DONE_HARVEST ); }
public void setDoneHarvest( String s ) {
if ( s != null && s.equalsIgnoreCase("true") )
setDoneHarvest( true );
else
setDoneHarvest( false );
}
public void setDoneHarvest( Boolean b ) { set( done_harvest, b ); }
public void setDoneHarvest( boolean b ) { set( done_harvest, new Boolean( b ) ); }
public Boolean getIgnore() { return get( PROP_IGNORE ); }
public CPSDatumState getIgnoreState() { return getStateOf( PROP_IGNORE ); }
public void setIgnore( String s ) {
if ( s != null && s.equalsIgnoreCase("true") )
setIgnore( true );
else
setIgnore( false );
}
public void setIgnore( Boolean b ) { set( ignore, b ); }
public void setIgnore( boolean b ) { set( ignore, new Boolean( b ) ); }
@NoColumn
public Integer getMatAdjust() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getInt( PROP_DS_MAT_ADJUST );
else
return getInt( PROP_TP_MAT_ADJUST );
}
public String getMatAdjustString() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getString( PROP_DS_MAT_ADJUST );
else
return getString( PROP_TP_MAT_ADJUST );
}
public CPSDatumState getMatAdjustState() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getStateOf( PROP_DS_MAT_ADJUST );
else
return getStateOf( PROP_TP_MAT_ADJUST );
}
public void setMatAdjust( Integer i ) {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
set( ds_mat_adjust, i );
else
set( tp_mat_adjust, i );
}
public void setMatAdjust( int i ) { setMatAdjust( new Integer( i )); }
public void setMatAdjust( String s ) { setMatAdjust( parseInteger(s) ); }
@Deprecated
public Integer getDSMatAdjust() { return getInt( PROP_DS_MAT_ADJUST ); }
@Deprecated
public void setDSMatAdjust( Integer i ) { set( ds_mat_adjust, i ); }
@Deprecated
public Integer getTPMatAdjust() { return getInt( PROP_TP_MAT_ADJUST ); }
@Deprecated
public void setTPMatAdjust( Integer i ) { set( tp_mat_adjust, i ); }
public Integer getTimeToTP() { return getInt( PROP_TIME_TO_TP ); }
public String getTimeToTPString() { return getString( PROP_TIME_TO_TP ); }
public CPSDatumState getTimeToTPState() { return getStateOf( PROP_TIME_TO_TP ); }
public void setTimeToTP( Integer i ) { set( time_to_tp, i ); }
public void setTimeToTP( int i ) { setTimeToTP( new Integer( i ) ); }
public void setTimeToTP( String s ) { setTimeToTP( parseInteger(s) ); }
@NoColumn
public Integer getRowsPerBed() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getInt( PROP_DS_ROWS_P_BED );
else
return getInt( PROP_TP_ROWS_P_BED );
}
public String getRowsPerBedString() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getString( PROP_DS_ROWS_P_BED );
else
return getString( PROP_TP_ROWS_P_BED );
}
public CPSDatumState getRowsPerBedState() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getStateOf( PROP_DS_ROWS_P_BED );
else
return getStateOf( PROP_TP_ROWS_P_BED );
}
public void setRowsPerBed( Integer i ) {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() ) {
set( ds_rows_p_bed, i );
}
else {
set( tp_rows_p_bed, i );
}
}
public void setRowsPerBed( int i ) { setRowsPerBed( new Integer( i )); }
public void setRowsPerBed( String s ) { setRowsPerBed( parseInteger(s) ); }
@Deprecated
public Integer getDSRowsPerBed() { return getInt( PROP_DS_ROWS_P_BED ); }
@Deprecated
public void setDSRowsPerBed( Integer i ) { set( ds_rows_p_bed, i ); }
@Deprecated
public Integer getTPRowsPerBed() { return getInt( PROP_TP_ROWS_P_BED ); }
@Deprecated
public void setTPRowsPerBed( Integer i ) { set( tp_rows_p_bed, i ); }
public Integer getInRowSpacing() { return getInt( PROP_INROW_SPACE ); }
public String getInRowSpacingString() { return getString( PROP_INROW_SPACE ); }
public CPSDatumState getInRowSpacingState() { return getStateOf( PROP_INROW_SPACE ); }
public void setInRowSpacing( Integer i ) { set( inrow_space, i ); }
public void setInRowSpacing( int i ) { setInRowSpacing( new Integer( i ) ); }
public void setInRowSpacing( String s ) { setInRowSpacing( parseInteger(s) ); }
@NoColumn
public Integer getRowSpacing() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getInt( PROP_DS_ROW_SPACE );
else
return getInt( PROP_TP_ROW_SPACE );
}
public String getRowSpacingString() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getString( PROP_DS_ROW_SPACE );
else
return getString( PROP_TP_ROW_SPACE );
}
public CPSDatumState getRowSpacingState() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getStateOf( PROP_DS_ROW_SPACE );
else
return getStateOf( PROP_TP_ROW_SPACE );
}
public void setRowSpacing( Integer i ) {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
set( ds_row_space, i );
else
set( tp_row_space, i );
}
public void setRowSpacing( int i ) { setRowSpacing( new Integer( i ) ); }
public void setRowSpacing( String s ) { setRowSpacing( parseInteger(s) ); }
@Deprecated
public Integer getDSRowSpacing() { return getInt( PROP_DS_ROW_SPACE ); }
@Deprecated
public void setDSRowSpacing( Integer i ) { set( ds_row_space, i ); }
@Deprecated
public Integer getTPRowSpacing() { return getInt( PROP_TP_ROW_SPACE ); }
@Deprecated
public void setTPRowSpacing( Integer i ) { set( tp_row_space, i ); }
public String getFlatSize() { return get( PROP_FLAT_SIZE ); }
public Integer getFlatSizeCapacity() {
return CPSCalculations.extractFlatCapacity( getFlatSize() );
}
public CPSDatumState getFlatSizeState() { return getStateOf( PROP_FLAT_SIZE ); }
public void setFlatSize( String i ) { set( flat_size, parseInheritableString(i) ); }
@NoColumn
public String getPlantingNotesInherited() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return get( PROP_DS_CROP_NOTES );
else
return get( PROP_TP_CROP_NOTES );
}
public CPSDatumState getPlantingNotesInheritedState() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getStateOf( PROP_DS_CROP_NOTES );
else
return getStateOf( PROP_TP_CROP_NOTES );
}
public void setPlantingNotesInherited( String i ) {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
set( ds_crop_notes, parseInheritableString(i) );
else
set( tp_crop_notes, parseInheritableString(i) );
}
public String getPlantingNotes() { return get( PROP_PLANTING_NOTES ); }
public CPSDatumState getPlantingNotesState() { return getStateOf( PROP_PLANTING_NOTES ); }
public void setPlantingNotes( String i ) { set( planting_notes, i ); }
@Deprecated
public String getDSPlantingNotes() { return get( PROP_DS_CROP_NOTES ); }
@Deprecated
public void setDSPlantingNotes( String i ) { set( ds_crop_notes, parseInheritableString(i) ); }
@Deprecated
public String getTPPlantingNotes() { return get( PROP_TP_CROP_NOTES ); }
@Deprecated
public void setTPPlantingNotes( String i ) { set( tp_crop_notes, parseInheritableString(i) ); }
protected CPSDatum<Float> getBedsToPlantDatum() { return getBedsToPlantDatum( new ArrayList() ); }
protected CPSDatum<Float> getBedsToPlantDatum( List source_path ) {
CPSDatum b = getDatum( PROP_BEDS_PLANT );
if ( b.isConcrete() || source_path.contains( b.propertyNum ) )
return b;
source_path.add( b.propertyNum );
if ( ! source_path.contains( PROP_ROWS_P_BED )) {
CPSDatum rpb = getDatum( PROP_ROWS_P_BED );
CPSDatum r = getRowFtToPlantDatum( source_path );
int bedLength = CPSCalculations.extractBedLength( getLocation() );
if ( r.isNotNull() && rpb.isNotNull() ) {
set( b, CPSCalculations.calcBedsToPlantFromRowFtToPlant( r.getValueAsInt(),
rpb.getValueAsInt(),
bedLength ));
b.setCalculated( true );
}
}
return b;
}
public Float getBedsToPlant() { return getBedsToPlantDatum().getValue( useRawOutput() ); }
public String getBedsToPlantString() { return formatFloat( getBedsToPlantDatum(), 3 ); }
public CPSDatumState getBedsToPlantState() { return getStateOf( PROP_BEDS_PLANT ); }
public void setBedsToPlant( Float i ) { set( beds_to_plant, i ); }
public void setBedsToPlant( float i ) { setBedsToPlant( new Float( i ) ); }
public void setBedsToPlant( String s ) { setBedsToPlant( parseFloatBigF(s) ); }
protected CPSDatum<Integer> getPlantsNeededDatum() { return getPlantsNeededDatum( new ArrayList() ); }
protected CPSDatum<Integer> getPlantsNeededDatum( List source_path ) {
CPSDatum p = getDatum( PROP_PLANTS_NEEDED );
if ( this.isDirectSeeded() ) {
p.setValue( p.getNullValue() );
return p;
}
if ( p.isConcrete() || source_path.contains( p.propertyNum ))
return p;
source_path.add( p.propertyNum );
if ( ! source_path.contains( PROP_ROWFT_PLANT )) {
CPSDatum irs = getDatum( PROP_INROW_SPACE );
CPSDatum r = getRowFtToPlantDatum( source_path );
if ( r.isNotNull() && irs.isNotNull() ) {
set( p, CPSCalculations.calcPlantsNeededFromRowFtToPlant( r.getValueAsInt(),
irs.getValueAsInt() ) );
p.setCalculated( true );
}
}
else if ( ! source_path.contains( PROP_PLANTS_START )) {
CPSDatum ps = getPlantsToStartDatum( source_path );
if ( ps.isNotNull() ) {
set( p, CPSCalculations.calcPlantsNeededFromPlantsToStart( ps.getValueAsInt() ) );
p.setCalculated( true );
}
}
return p;
}
public Integer getPlantsNeeded() { return getPlantsNeededDatum().getValue( useRawOutput() ); }
public String getPlantsNeededString() { return formatInt( getPlantsNeededDatum() ); }
public CPSDatumState getPlantsNeededState() { return getStateOf( PROP_PLANTS_NEEDED ); }
public void setPlantsNeeded( Integer i ) { set( plants_needed, i ); }
public void setPlantsNeeded( int i ) { setPlantsNeeded( new Integer( i ) ); }
public void setPlantsNeeded( String s ) { setPlantsNeeded( parseInteger(s) ); }
protected CPSDatum<Integer> getRowFtToPlantDatum() { return getRowFtToPlantDatum( new ArrayList() ); }
protected CPSDatum<Integer> getRowFtToPlantDatum( List source_path ) {
CPSDatum r = getDatum( PROP_ROWFT_PLANT );
if ( r.isConcrete() || source_path.contains( r.propertyNum ))
return r;
source_path.add( r.propertyNum );
if ( ! source_path.contains( PROP_BEDS_PLANT )) {
CPSDatum rpb = getDatum( PROP_ROWS_P_BED );
CPSDatum b = getBedsToPlantDatum( source_path );
if ( ! r.isConcrete() &&
b.isNotNull() && rpb.isNotNull() ) {
int bedLength = CPSCalculations.extractBedLength( getLocation() );
set( r, CPSCalculations.calcRowFtToPlantFromBedsToPlant( b.getValueAsFloat(),
rpb.getValueAsInt(),
bedLength ));
r.setCalculated( true );
}
}
else if ( ! source_path.contains( PROP_PLANTS_NEEDED )) {
CPSDatum ps = getDatum( PROP_INROW_SPACE );
CPSDatum p = getPlantsNeededDatum( source_path );
if ( ! r.isConcrete() &&
p.isNotNull() && ps.isNotNull() ) {
set( r, CPSCalculations.calcRowFtToPlantFromPlantsNeeded( p.getValueAsInt(),
ps.getValueAsInt() ));
r.setCalculated( true );
}
}
else if ( ! source_path.contains( PROP_TOTAL_YIELD )) {
CPSDatum yf = getDatum( PROP_YIELD_P_FOOT );
CPSDatum ty = getTotalYieldDatum( source_path );
if ( ! r.isConcrete() &&
ty.isNotNull() && yf.isNotNull() ) {
set( r, CPSCalculations.calcRowFtToPlantFromTotalYield( ty.getValueAsFloat(),
yf.getValueAsFloat() ));
r.setCalculated( true );
}
}
return r;
}
public Integer getRowFtToPlant() { return getRowFtToPlantDatum().getValue( useRawOutput() ); }
public String getRowFtToPlantString() { return formatInt( getRowFtToPlantDatum() ); }
public CPSDatumState getRowFtToPlantState() { return getStateOf( PROP_ROWFT_PLANT ); }
public void setRowFtToPlant( Integer i ) { set( rowft_to_plant, i ); }
public void setRowFtToPlant( int i ) { setRowFtToPlant( new Integer( i ) ); }
public void setRowFtToPlant( String s ) { setRowFtToPlant( parseInteger(s) ); }
protected CPSDatum<Integer> getPlantsToStartDatum() { return getPlantsToStartDatum( new ArrayList() ); }
protected CPSDatum<Integer> getPlantsToStartDatum( List source_path ) {
CPSDatum ps = getDatum( PROP_PLANTS_START );
if ( this.isDirectSeeded() ) {
ps.setValue( ps.getNullValue() );
return ps;
}
if ( ps.isConcrete() || source_path.contains( ps.propertyNum ))
return ps;
source_path.add( ps.propertyNum );
if ( ! source_path.contains( PROP_PLANTS_NEEDED )) {
CPSDatum pn = getPlantsNeededDatum( source_path );
if ( pn.isNotNull() ) {
set( ps, CPSCalculations.calcPlantsToStart( pn.getValueAsInt() ) );
ps.setCalculated( true );
}
}
else if ( ! source_path.contains( PROP_FLATS_NEEDED )) {
CPSDatum fz = getDatum( PROP_FLAT_SIZE );
CPSDatum fn = getFlatsNeededDatum( source_path );
if ( fn.isNotNull() && fz.isNotNull() ) {
set( ps, CPSCalculations.calcPlantsToStart( fn.getValueAsFloat(), getFlatSizeCapacity() ));
ps.setCalculated( true );
}
}
return ps;
}
public Integer getPlantsToStart() { return getPlantsToStartDatum().getValue( useRawOutput() ); }
public String getPlantsToStartString() { return formatInt( getPlantsToStartDatum() ); }
public CPSDatumState getPlantsToStartState() { return getStateOf( PROP_PLANTS_START ); }
public void setPlantsToStart( Integer i ) { set( plants_to_start, i ); }
public void setPlantsToStart( int i ) { setPlantsToStart( new Integer( i ) ); }
public void setPlantsToStart( String s ) { setPlantsToStart( parseInteger(s) ); }
protected CPSDatum<Float> getFlatsNeededDatum() { return getFlatsNeededDatum( new ArrayList() ); }
protected CPSDatum<Float> getFlatsNeededDatum( List source_path ) {
CPSDatum n = getDatum( PROP_FLATS_NEEDED );
if ( this.isDirectSeeded() ) {
n.setValue( n.getNullValue() );
return n;
}
if ( n.isConcrete() || source_path.contains( n.propertyNum ))
return n;
source_path.add( n.propertyNum );
if ( ! source_path.contains( PROP_PLANTS_START )) {
CPSDatum s = getDatum( PROP_FLAT_SIZE );
CPSDatum p = getPlantsToStartDatum( source_path );
if ( p.isNotNull() && s.isNotNull() ) {
set( n, CPSCalculations.calcFlatsNeeded( p.getValueAsInt(),
getFlatSizeCapacity() ) );
n.setCalculated( true );
}
}
return n;
}
public Float getFlatsNeeded() { return getFlatsNeededDatum().getValue( useRawOutput() ); }
public String getFlatsNeededString() { return formatFloat( getFlatsNeededDatum(), 3 ); }
public CPSDatumState getFlatsNeededState() { return getStateOf( PROP_FLATS_NEEDED ); }
public void setFlatsNeeded( Float i ) { set( flats_needed, i ); }
public void setFlatsNeeded( float i ) { setFlatsNeeded( new Float( i ) ); }
public void setFlatsNeeded( String s ) { setFlatsNeeded( parseFloatBigF(s) ); }
public Float getYieldPerFoot() { return getFloat( PROP_YIELD_P_FOOT ); }
public String getYieldPerFootString() { return formatFloat( getDatum( PROP_YIELD_P_FOOT ), 2 ); }
public CPSDatumState getYieldPerFootState() { return getStateOf( PROP_YIELD_P_FOOT ); }
public void setYieldPerFoot( Float i ) { set( yield_p_foot, i ); }
public void setYieldPerFoot( float i ) { setYieldPerFoot( new Float( i ) ); }
public void setYieldPerFoot( String s ) { setYieldPerFoot( parseFloatBigF(s) ); }
public Integer getYieldNumWeeks() { return getInt( PROP_YIELD_NUM_WEEKS ); }
public String getYieldNumWeeksString() { return formatInt( (Integer) get( PROP_YIELD_NUM_WEEKS ) ); }
public CPSDatumState getYieldNumWeeksState() { return getStateOf( PROP_YIELD_NUM_WEEKS ); }
public void setYieldNumWeeks( Integer i ) { set( yield_num_weeks, i ); }
public void setYieldNumWeeks( int i ) { setYieldNumWeeks( new Integer( i ) ); }
public void setYieldNumWeeks( String s ) { setYieldNumWeeks( parseInteger(s) ); }
public Float getYieldPerWeek() { return getFloat( PROP_YIELD_P_WEEK ); }
public String getYieldPerWeekString() { return formatFloat( (Float) get( PROP_YIELD_P_WEEK )); }
public CPSDatumState getYieldPerWeekState() { return getStateOf( PROP_YIELD_P_WEEK ); }
public void setYieldPerWeek( Float i ) { set( yield_p_week, i ); }
public void setYieldPerWeek( float i ) { setYieldPerWeek( new Float( i ) ); }
public void setYieldPerWeek( String s ) { setYieldPerWeek( parseFloatBigF(s) ); }
public String getCropYieldUnit() { return get( PROP_CROP_UNIT ); }
public CPSDatumState getCropYieldUnitState() { return getStateOf( PROP_CROP_UNIT ); }
public void setCropYieldUnit( String i ) { set( crop_unit, parseInheritableString(i) ); }
public Float getCropYieldUnitValue() { return getFloat( PROP_CROP_UNIT_VALUE ); }
public String getCropYieldUnitValueString() { return formatFloat( getDatum( PROP_CROP_UNIT_VALUE ), 2 ); }
public CPSDatumState getCropYieldUnitValueState() { return getStateOf( PROP_CROP_UNIT_VALUE ); }
public void setCropYieldUnitValue( Float i ) { set( crop_unit_value, i ); }
public void setCropYieldUnitValue( float i ) { setCropYieldUnitValue( new Float( i ) ); }
public void setCropYieldUnitValue( String s ) { setCropYieldUnitValue( parseFloatBigF(s) ); }
protected CPSDatum<Float> getTotalYieldDatum() { return getTotalYieldDatum( new ArrayList() ); }
protected CPSDatum<Float> getTotalYieldDatum( List source_path ) {
CPSDatum t = getDatum( PROP_TOTAL_YIELD );
if ( t.isConcrete() || source_path.contains( t.propertyNum ))
return t;
source_path.add( t.propertyNum );
if ( ! source_path.contains( PROP_ROWFT_PLANT )) {
CPSDatum y = getDatum( PROP_YIELD_P_FOOT );
CPSDatum r = getRowFtToPlantDatum( source_path );
if ( ! t.isConcrete() &&
y.isNotNull() && r.isNotNull() ) {
set( t, CPSCalculations.calcTotalYieldFromRowFtToPlant( r.getValueAsInt(), y.getValueAsFloat() ));
t.setCalculated( true );
}
}
return t;
}
public Float getTotalYield() { return getTotalYieldDatum().getValue( useRawOutput() ); }
public String getTotalYieldString() { return formatFloat( getTotalYieldDatum(), 3 ); }
public CPSDatumState getTotalYieldState() { return getStateOf( PROP_TOTAL_YIELD ); }
public void setTotalYield( Float i ) { set( total_yield, i ); }
public void setTotalYield( float i ) { setTotalYield( new Float( i ) ); }
public void setTotalYield( String s ) { setTotalYield( parseFloatBigF(s) ); }
public Integer getSeedsPerUnit() { return getInt( seedsPerUnit.getPropertyNum() ); }
public String getSeedsPerUnitString() { return getString( seedsPerUnit.getPropertyNum() ); }
public CPSDatumState getSeedsPerUnitState() { return getStateOf( seedsPerUnit.getPropertyNum() ); }
public void setSeedsPerUnit( Integer i ) { set( seedsPerUnit, i ); }
public void setSeedsPerUnit( int i ) { setSeedsPerUnit( new Integer( i )); }
public void setSeedsPerUnit( String s ) { setSeedsPerUnit( parseInteger(s) ); }
public String getSeedUnit() { return get( seedUnit.getPropertyNum() ); }
public CPSDatumState getSeedUnitState() { return getStateOf( seedUnit.getPropertyNum() ); }
public void setSeedUnit( String s ) { set( seedUnit, parseInheritableString(s) ); }
@NoColumn
public Float getSeedsPer() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getFloat( seedsPerDS.getPropertyNum() );
else
return getFloat( seedsPerTP.getPropertyNum() );
}
public String getSeedsPerString() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getString( seedsPerDS.getPropertyNum() );
else
return getString( seedsPerTP.getPropertyNum() );
}
public CPSDatumState getSeedsPerState() {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
return getStateOf( seedsPerDS.getPropertyNum() );
else
return getStateOf( seedsPerTP.getPropertyNum() );
}
public void setSeedsPer( Float i ) {
if ( isDirectSeeded() == null || isDirectSeeded().booleanValue() )
set( seedsPerDS, i );
else
set( seedsPerTP, i );
}
public void setSeedsPer( float i ) { setSeedsPer( new Float( i )); }
public void setSeedsPer( String s ) { setSeedsPer( parseFloatBigF(s) ); }
@Deprecated
public Float getSeedsPerDS() { return getFloat( seedsPerDS.getPropertyNum() ); }
@Deprecated
public void setSeedsPerDS( Float i ) { set( seedsPerDS, i ); }
@Deprecated
public Float getSeedsPerTP() { return getFloat( seedsPerTP.getPropertyNum() ); }
@Deprecated
public void setSeedsPerTP( Float f ) { set( seedsPerTP, f ); }
protected CPSDatum<Float> gettSeedNeededDatum() { return gettSeedNeededDatum( new ArrayList() ); }
protected CPSDatum<Float> gettSeedNeededDatum( List source_path ) {
CPSDatum n = getDatum( PROP_SEED_NEEDED );
if ( n.isConcrete() || source_path.contains( n.propertyNum ))
return n;
source_path.add( n.propertyNum );
CPSDatum d = getDatum( seedsPerDS.getPropertyNum() );
CPSDatum r = getRowFtToPlantDatum( source_path );
CPSDatum t = getDatum( seedsPerTP.getPropertyNum() );
CPSDatum p = getPlantsNeededDatum( source_path );
CPSDatum u = getDatum( seedsPerUnit.getPropertyNum() );
Boolean ds = this.isDirectSeeded();
ds = ds == null || ds.booleanValue();
if ( ! n.isConcrete() && u.isNotNull() ) {
if ( ds &&
d.isNotNull() && r.isNotNull() ) {
set( n,
( d.getValueAsFloat() * r.getValueAsInt()) / u.getValueAsInt() );
n.setCalculated( true );
}
else if ( ! ds &&
t.isNotNull() && p.isNotNull() ) {
set( n,
( t.getValueAsFloat() * p.getValueAsInt()) / u.getValueAsInt() );
n.setCalculated( true );
}
}
return n;
}
public Float getSeedNeeded() { return gettSeedNeededDatum().getValue( useRawOutput() ); }
public String getSeedNeededString() { return formatFloat( gettSeedNeededDatum(), 3 ); }
public CPSDatumState getSeedNeededState() { return getStateOf( seedNeeded.getPropertyNum() ); }
public void setSeedNeeded( Float f ) { set( seedNeeded, f ); }
public void setSeedNeeded( float f ) { setSeedNeeded( new Float( f )); }
public void setSeedNeeded( String s ) { setSeedNeeded( parseFloatBigF(s) ); }
public Boolean isDirectSeeded() {
Boolean b = getBoolean( PROP_DIRECT_SEED );
if ( b == null ) b = Boolean.FALSE;
return b;
}
@NoColumn
public Boolean isTransplanted() {
if ( isDirectSeeded() == null )
return Boolean.FALSE;
else
return ! isDirectSeeded().booleanValue();
}
public CPSDatumState getDirectSeededState() { return getStateOf( PROP_DIRECT_SEED ); }
public void setDirectSeeded( String s ) {
if ( s != null && s.equalsIgnoreCase("true") )
setDirectSeeded( Boolean.TRUE );
else
setDirectSeeded( Boolean.FALSE );
}
public void setTransplanted( Boolean b ) {
if ( b == null )
setDirectSeeded( (Boolean) null );
else
setDirectSeeded( (Boolean) ! b.booleanValue() );
}
public void setDirectSeeded( Boolean b ) { set( direct_seed, b ); }
public void setDirectSeeded( boolean b ) { setDirectSeeded( new Boolean( b )); }
public Boolean isFrostHardy() { return getBoolean( PROP_FROST_HARDY ); }
public Boolean isFrostTender() { return ! isFrostHardy().booleanValue(); }
public CPSDatumState getFrostHardyState() { return getStateOf( PROP_FROST_HARDY ); }
public void setFrostHardy( String s ) {
if ( s != null && s.equalsIgnoreCase( "true" ) )
setFrostHardy( Boolean.TRUE );
else
setFrostHardy( Boolean.FALSE );
}
public void setFrostHardy( Boolean b ) { set( frost_hardy, b ); }
public void setFrostHardy( boolean b ) { setFrostHardy( new Boolean( b )); }
public String getGroups() { return get( PROP_GROUPS ); }
public CPSDatumState getGroupsState() { return getStateOf( PROP_GROUPS ); }
public void setGroups( String e ) { set( groups, e ); }
public String getKeywords() { return get( PROP_KEYWORDS ); }
public CPSDatumState getKeywordsState() { return getStateOf( PROP_KEYWORDS ); }
public void setKeywords( String e ) { set( keywords, e ); }
public String getOtherRequirements() { return get( PROP_OTHER_REQ ); }
public CPSDatumState getOtherRequirementsState() { return getStateOf( PROP_OTHER_REQ ); }
public void setOtherRequirements( String e ) { set( other_req, e ); }
public String getNotes() { return get( PROP_NOTES ); }
public CPSDatumState getNotesState() { return getStateOf( PROP_NOTES ); }
public void setNotes( String e ) { set( notes, e ); }
public String getCustomField1() { return get( PROP_CUSTOM1 ); }
public String getCustomField2() { return get( PROP_CUSTOM2 ); }
public String getCustomField3() { return get( PROP_CUSTOM3 ); }
public String getCustomField4() { return get( PROP_CUSTOM4 ); }
public String getCustomField5() { return get( PROP_CUSTOM5 ); }
public CPSDatumState getCustomField1State() { return getStateOf( PROP_CUSTOM1 ); }
public CPSDatumState getCustomField2State() { return getStateOf( PROP_CUSTOM2 ); }
public CPSDatumState getCustomField3State() { return getStateOf( PROP_CUSTOM3 ); }
public CPSDatumState getCustomField4State() { return getStateOf( PROP_CUSTOM4 ); }
public CPSDatumState getCustomField5State() { return getStateOf( PROP_CUSTOM5 ); }
public void setCustomField1( String s ) { set( custom1, s ); }
public void setCustomField2( String s ) { set( custom2, s ); }
public void setCustomField3( String s ) { set( custom3, s ); }
public void setCustomField4( String s ) { set( custom4, s ); }
public void setCustomField5( String s ) { set( custom5, s ); }
protected void updateCalculations() { }
public CPSRecord diff( CPSRecord thatPlanting ) {
return super.diff( thatPlanting, new CPSPlanting() );
}
@Override
public CPSRecord inheritFrom( CPSRecord thatRecord ) {
if ( this.getClass().getName().equalsIgnoreCase( thatRecord.getClass().getName() ))
return super.inheritFrom( thatRecord );
else if ( ! thatRecord.getClass().getName().equalsIgnoreCase( CPSCrop.class.getName() )) {
System.err.println("ERROR: CPSPlanting can only inherit from itself and from CPSCrop, " +
"not from " + thatRecord.getClass().getName() );
return this;
}
return super.inheritFrom( thatRecord );
}
public PlantingIterator iterator() { return new PlantingIterator(); }
public class PlantingIterator extends CPSRecordIterator {
public boolean ignoreThisProperty() {
return this.currentProp == PROP_ID ||
this.currentProp == PROP_DATE_PLANT ||
this.currentProp == PROP_DATE_TP ||
this.currentProp == PROP_DATE_HARVEST ||
this.currentProp == PROP_SEEDS_PER ||
this.currentProp == PROP_MAT_ADJUST ||
this.currentProp == PROP_ROWS_P_BED ||
this.currentProp == PROP_ROW_SPACE ||
this.currentProp == PROP_CROP_NOTES;
}
}
public String toString() {
String s = "";
PlantingIterator i = this.iterator();
CPSDatum c;
while ( i.hasNext() ) {
c = i.next();
if ( c.isNotNull() ) {
s += c.getName() + " = '" + c.getValue() + "'";
if ( c.isInherited() )
s += "(i)";
if ( c.isCalculated() )
s += "(c)";
s += ", ";
}
}
return s;
}
public Date parseDate( String s ) {
if ( s == null || s.equals("") )
return null;
return dateValidator.parse(s);
}
public String formatDate( Date d ) {
if ( d == null || d.getTime() == 0 )
return "";
else
return CPSDateValidator.format( d );
}
}
|
private Control makeControl(Element e) throws ImportFailedException {
Control model = new Control();
model.setName(DOM.getAttributeNS(e, XMLNS.SIGNATURE, "name"));
String kind = DOM.getAttributeNS(e, XMLNS.SIGNATURE, "kind");
if (kind != null) {
model.setKind(
kind.equals("active") ? Kind.ACTIVE :
kind.equals("passive") ? Kind.PASSIVE : Kind.ATOMIC);
}
boolean generatePolygon = false;
Element el = DOM.removeNamedChildElement(e, XMLNS.BIG_RED, "shape");
if (el != null) {
AppearanceGenerator.setShape(el, model);
} else generatePolygon = true;
el = DOM.removeNamedChildElement(e, XMLNS.BIG_RED, "appearance");
if (el != null)
AppearanceGenerator.setAppearance(el, model, cg);
AppearanceGenerator.attributesToModel(e, model);
for (Element j :
DOM.getNamedChildElements(e, XMLNS.SIGNATURE, "port")) {
PortSpec i = makePortSpec(j, !generatePolygon);
if (i != null)
model.addPort(i);
}
if (generatePolygon) {
model.setShape(Shape.POLYGON);
model.setPoints(
new Ellipse(new Rectangle(0, 0, 30, 30)).
getPolygon(Math.max(3, model.getPorts().size())));
int i = 0;
for (PortSpec p : model.getPorts()) {
p.setSegment(i++);
p.setDistance(0.5);
}
}
return model;
}
| private Control makeControl(Element e) throws ImportFailedException {
Control model = new Control();
model.setName(DOM.getAttributeNS(e, XMLNS.SIGNATURE, "name"));
String kind = DOM.getAttributeNS(e, XMLNS.SIGNATURE, "kind");
if (kind != null) {
model.setKind(
kind.equals("active") ? Kind.ACTIVE :
kind.equals("passive") ? Kind.PASSIVE : Kind.ATOMIC);
}
boolean generatePolygon = false;
Element el = DOM.removeNamedChildElement(e, XMLNS.BIG_RED, "shape");
if (el != null) {
AppearanceGenerator.setShape(el, model);
} else generatePolygon = true;
el = DOM.removeNamedChildElement(e, XMLNS.BIG_RED, "appearance");
if (el != null)
AppearanceGenerator.setAppearance(el, model, cg);
AppearanceGenerator.attributesToModel(e, model);
for (Element j :
DOM.getNamedChildElements(e, XMLNS.SIGNATURE, "port")) {
PortSpec i = makePortSpec(j, generatePolygon);
if (i != null)
model.addPort(i);
}
if (generatePolygon) {
model.setShape(Shape.POLYGON);
model.setPoints(
new Ellipse(new Rectangle(0, 0, 30, 30)).
getPolygon(Math.max(3, model.getPorts().size())));
int i = 0;
for (PortSpec p : model.getPorts()) {
p.setSegment(i++);
p.setDistance(0.5);
}
}
return model;
}
|
private void processChunk(Element element, String outputFile) {
String hrefValue = element.getAttribute(Constants.ATTRIBUTE_NAME_HREF);
String chunkValue = element.getAttribute(Constants.ATTRIBUTE_NAME_CHUNK);
String copytoValue = element.getAttribute(Constants.ATTRIBUTE_NAME_COPY_TO);
String scopeValue = element.getAttribute(Constants.ATTRIBUTE_NAME_SCOPE);
String classValue = element.getAttribute(Constants.ATTRIBUTE_NAME_CLASS);
String processRoleValue = element.getAttribute(Constants.ATTRIBUTE_NAME_PROCESSING_ROLE);
String id = element.getAttribute(Constants.ATTRIBUTE_NAME_ID);
String navtitle = element.getAttribute(Constants.ATTRIBUTE_NAME_NAVTITLE);
String parseFilePath = null;
String outputFileName = outputFile;
Writer tempWriter = null;
Set<String> tempTopicID = null;
targetTopicId = null;
selectMethod = "select-document";
include = false;
boolean needWriteDitaTag = true;
try {
if (!copytoValue.equals(Constants.STRING_EMPTY) && !chunkValue.contains("to-content")){
if (hrefValue.indexOf(Constants.SHARP)!=-1){
parseFilePath = copytoValue + hrefValue.substring(hrefValue.indexOf(Constants.SHARP));
}else{
parseFilePath = copytoValue;
}
}else{
parseFilePath = hrefValue;
}
if(!copytoValue.equals(Constants.STRING_EMPTY) && chunkValue.contains("to-content")
&& ! hrefValue.equals(Constants.STRING_EMPTY)){
copyto.add(copytoValue);
if(hrefValue.indexOf(Constants.SHARP) != -1){
copytoSource.add(hrefValue.substring(0, hrefValue.indexOf(Constants.SHARP)));
copytotarget2source.put(copytoValue, hrefValue.substring(0, hrefValue.indexOf(Constants.SHARP)));
}else{
copytoSource.add(hrefValue);
copytotarget2source.put(copytoValue,hrefValue);
}
}
if ( !StringUtils.isEmptyString(classValue) ) {
if ((!classValue.contains(Constants.ATTR_CLASS_VALUE_TOPIC_GROUP))
&& (!StringUtils.isEmptyString(parseFilePath))
&& (!"external".equalsIgnoreCase(scopeValue))) {
if(chunkValue.indexOf("to-content")!=-1){
tempWriter = output;
tempTopicID = topicID;
output = new StringWriter();
topicID = new HashSet<String>();
if (classValue.contains(Constants.ATTR_CLASS_VALUE_MAP)) {
outputFileName = FileUtils.resolveFile(filePath, parseFilePath);
needWriteDitaTag = false;
} else if (!copytoValue.equals(Constants.STRING_EMPTY)){
outputFileName = FileUtils.resolveFile(filePath,copytoValue);
} else if (!hrefValue.equals(Constants.STRING_EMPTY)) {
if (chunkValue.contains("select-topic") || chunkValue.contains("select-branch")) {
if (hrefValue.contains(Constants.SHARP)
&& hrefValue.indexOf(Constants.SHARP) < hrefValue.length() - 1) {
outputFileName = FileUtils.resolveFile(filePath,hrefValue.substring(hrefValue.indexOf(Constants.SHARP)+1))+ditaext;
} else {
String firstTopic = this.getFirstTopicId(FileUtils.resolveFile(filePath, hrefValue));
if (!StringUtils.isEmptyString(firstTopic)) {
outputFileName = FileUtils.resolveFile(filePath, firstTopic) + ditaext;
} else {
outputFileName = FileUtils.resolveFile(filePath,hrefValue);
}
}
} else {
outputFileName = FileUtils.resolveFile(filePath,hrefValue);
}
} else {
Random random = new Random();
outputFileName = FileUtils.resolveFile(filePath,"Chunk"
+new Integer(Math.abs(random.nextInt())).toString())+ditaext;
}
if(FileUtils.fileExists(outputFileName)
&& !classValue.contains(Constants.ATTR_CLASS_VALUE_MAP)) {
String t = outputFileName;
Random random = new Random();
outputFileName = FileUtils.resolveFile(filePath,"Chunk"
+new Integer(Math.abs(random.nextInt())).toString())+ditaext;
conflictTable.put(outputFileName, t);
}
changeTable.put(outputFileName,outputFileName);
}
this.outputFile = outputFileName;
{
String path = FileUtils.resolveTopic(filePath,parseFilePath);
String newpath = null;
if(path.indexOf(Constants.SHARP)!=-1){
newpath = outputFileName + path.substring(path.indexOf(Constants.SHARP));
}else{
String firstTopicID = this.getFirstTopicId(path);
if(!StringUtils.isEmptyString(firstTopicID)) {
newpath = outputFileName + "#" + firstTopicID;
} else {
newpath = outputFileName;
}
}
changeTable.put(path, newpath);
element.setAttribute(Constants.ATTRIBUTE_NAME_HREF,
FileUtils.getRelativePathFromMap(filePath+Constants.SLASH+"stub.ditamap"
,newpath));
}
if(parseFilePath.indexOf(Constants.SHARP)!=-1){
targetTopicId = parseFilePath.substring(parseFilePath.indexOf(Constants.SHARP)+1);
}
if(chunkValue.indexOf("select")!=-1){
int endIndex = chunkValue.indexOf(Constants.STRING_BLANK,
chunkValue.indexOf("select"));
if (endIndex ==-1){
selectMethod = chunkValue.substring(chunkValue.indexOf("select"));
}else{
selectMethod = chunkValue.substring(chunkValue.indexOf("select"),
endIndex);
}
if ("select-topic".equals(selectMethod) ||
"select-branch".equals(selectMethod)){
if(targetTopicId == null){
selectMethod = "select-document";
}
}
}
String tempPath = currentParsingFile;
currentParsingFile = FileUtils.resolveFile(filePath,parseFilePath);
if ( !Constants.ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equalsIgnoreCase(processRoleValue))
reader.parse(currentParsingFile);
currentParsingFile = tempPath;
}
if(outputFileName == null){
if (!StringUtils.isEmptyString(copytoValue)){
outputFileName = FileUtils.resolveFile(filePath,
copytoValue);
}else if(!StringUtils.isEmptyString(id)){
outputFileName = FileUtils.resolveFile(filePath,
id + ditaext);
}else{
Random random = new Random();
outputFileName = FileUtils.resolveFile(filePath,"Chunk"
+new Integer(Math.abs(random.nextInt())).toString())+ditaext;
if(FileUtils.fileExists(outputFileName)
&& !classValue.contains(Constants.ATTR_CLASS_VALUE_MAP)) {
String t = outputFileName;
outputFileName = FileUtils.resolveFile(filePath,"Chunk"
+new Integer(Math.abs(random.nextInt())).toString())+ditaext;
conflictTable.put(outputFileName, t);
}
}
if(element.hasChildNodes() || !StringUtils.isEmptyString(navtitle)){
DITAAttrUtils utils = DITAAttrUtils.getInstance();
String navtitleValue = null;
String shortDescValue = null;
navtitleValue = utils.getChildElementValueOfTopicmeta(element, Constants.ATTR_CLASS_VALUE_NAVTITLE);
shortDescValue = utils.getChildElementValueOfTopicmeta(element, Constants.ATTR_CLASS_VALUE_MAP_SHORTDESC);
if(navtitleValue == null){
navtitleValue = navtitle;
}
changeTable.put(outputFileName,outputFileName);
if(!StringUtils.isEmptyString(navtitleValue)){
element.setAttribute(Constants.ATTRIBUTE_NAME_HREF,
FileUtils.getRelativePathFromMap(filePath+Constants.SLASH+"stub.ditamap", outputFileName));
StringBuffer buffer = new StringBuffer();
buffer.append("<topic id=\"topic\" class=\"- topic/topic \">")
.append("<title class=\"- topic/title \">")
.append(navtitleValue).append("</title>");
if(shortDescValue != null){
buffer.append("<shortdesc class=\"- topic/shortdesc \">")
.append(shortDescValue).append("</shortdesc>");
}
buffer.append("</topic>");
StringReader rder = new StringReader(buffer.toString());
InputSource source = new InputSource(rder);
String tempPath = currentParsingFile;
currentParsingFile = outputFileName;
parseFilePath = outputFileName;
reader.parse(source);
currentParsingFile = tempPath;
}
}
}
if (element.hasChildNodes()){
StringWriter temp = (StringWriter)output;
output = new StringWriter();
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++){
Node current = children.item(i);
if (current.getNodeType() == Node.ELEMENT_NODE
&& ((Element)current).getAttribute(Constants.ATTRIBUTE_NAME_CLASS)
.indexOf(Constants.ATTR_CLASS_VALUE_TOPICREF)!=-1){
processChunk((Element)current,outputFileName);
}
}
StringBuffer parentResult = temp.getBuffer();
if (parentResult.length() > 0
&& !StringUtils.isEmptyString(parseFilePath)
&& !Constants.ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equalsIgnoreCase(processRoleValue)) {
int insertpoint = parentResult.lastIndexOf("</");
int end = parentResult.indexOf(">",insertpoint);
if(insertpoint==-1 || end==-1){
Properties prop=new Properties();
prop.put("%1", hrefValue);
logger.logError(MessageUtils.getMessage("DOTJ033E",prop).toString());
} else {
if (Constants.ELEMENT_NAME_DITA.equalsIgnoreCase(parentResult.substring(insertpoint,end).trim())){
insertpoint = parentResult.lastIndexOf("</",insertpoint);
}
parentResult.insert(insertpoint,((StringWriter)output).getBuffer());
}
} else {
parentResult.append(((StringWriter)output).getBuffer());
}
output = temp;
}
if(chunkValue.indexOf("to-content")!=-1){
FileOutputStream fileOutput = new FileOutputStream(outputFileName);
OutputStreamWriter ditaFileOutput = new OutputStreamWriter(fileOutput, Constants.UTF8);
if (outputFileName.equals(changeTable.get(outputFileName))){
ditaFileOutput.write(Constants.XML_HEAD);
if(Constants.OS_NAME.toLowerCase().indexOf(OS_NAME_WINDOWS)==-1)
{
ditaFileOutput.write(PI_WORKDIR_HEAD + new File(outputFileName).getParent() + PI_END);
}else{
ditaFileOutput.write(PI_WORKDIR_HEAD + Constants.SLASH + new File(outputFileName).getParent() + PI_END);
}
}
if (needWriteDitaTag) ditaFileOutput.write("<dita>");
ditaFileOutput.write(((StringWriter)output).getBuffer().toString());
if (needWriteDitaTag) ditaFileOutput.write("</dita>");
ditaFileOutput.flush();
ditaFileOutput.close();
output = tempWriter;
topicID = tempTopicID;
}
}
} catch (Exception e) {
logger.logException(e);
}
}
| private void processChunk(Element element, String outputFile) {
String hrefValue = element.getAttribute(Constants.ATTRIBUTE_NAME_HREF);
String chunkValue = element.getAttribute(Constants.ATTRIBUTE_NAME_CHUNK);
String copytoValue = element.getAttribute(Constants.ATTRIBUTE_NAME_COPY_TO);
String scopeValue = element.getAttribute(Constants.ATTRIBUTE_NAME_SCOPE);
String classValue = element.getAttribute(Constants.ATTRIBUTE_NAME_CLASS);
String processRoleValue = element.getAttribute(Constants.ATTRIBUTE_NAME_PROCESSING_ROLE);
String id = element.getAttribute(Constants.ATTRIBUTE_NAME_ID);
String navtitle = element.getAttribute(Constants.ATTRIBUTE_NAME_NAVTITLE);
String parseFilePath = null;
String outputFileName = outputFile;
Writer tempWriter = new StringWriter();
Set<String> tempTopicID = new HashSet<String>();
targetTopicId = null;
selectMethod = "select-document";
include = false;
boolean needWriteDitaTag = true;
try {
if (!copytoValue.equals(Constants.STRING_EMPTY) && !chunkValue.contains("to-content")){
if (hrefValue.indexOf(Constants.SHARP)!=-1){
parseFilePath = copytoValue + hrefValue.substring(hrefValue.indexOf(Constants.SHARP));
}else{
parseFilePath = copytoValue;
}
}else{
parseFilePath = hrefValue;
}
if(!copytoValue.equals(Constants.STRING_EMPTY) && chunkValue.contains("to-content")
&& ! hrefValue.equals(Constants.STRING_EMPTY)){
copyto.add(copytoValue);
if(hrefValue.indexOf(Constants.SHARP) != -1){
copytoSource.add(hrefValue.substring(0, hrefValue.indexOf(Constants.SHARP)));
copytotarget2source.put(copytoValue, hrefValue.substring(0, hrefValue.indexOf(Constants.SHARP)));
}else{
copytoSource.add(hrefValue);
copytotarget2source.put(copytoValue,hrefValue);
}
}
if ( !StringUtils.isEmptyString(classValue) ) {
if ((!classValue.contains(Constants.ATTR_CLASS_VALUE_TOPIC_GROUP))
&& (!StringUtils.isEmptyString(parseFilePath))
&& (!"external".equalsIgnoreCase(scopeValue))) {
if(chunkValue.indexOf("to-content")!=-1){
tempWriter = output;
tempTopicID = topicID;
output = new StringWriter();
topicID = new HashSet<String>();
if (classValue.contains(Constants.ATTR_CLASS_VALUE_MAP)) {
outputFileName = FileUtils.resolveFile(filePath, parseFilePath);
needWriteDitaTag = false;
} else if (!copytoValue.equals(Constants.STRING_EMPTY)){
outputFileName = FileUtils.resolveFile(filePath,copytoValue);
} else if (!hrefValue.equals(Constants.STRING_EMPTY)) {
if (chunkValue.contains("select-topic") || chunkValue.contains("select-branch")) {
if (hrefValue.contains(Constants.SHARP)
&& hrefValue.indexOf(Constants.SHARP) < hrefValue.length() - 1) {
outputFileName = FileUtils.resolveFile(filePath,hrefValue.substring(hrefValue.indexOf(Constants.SHARP)+1))+ditaext;
} else {
String firstTopic = this.getFirstTopicId(FileUtils.resolveFile(filePath, hrefValue));
if (!StringUtils.isEmptyString(firstTopic)) {
outputFileName = FileUtils.resolveFile(filePath, firstTopic) + ditaext;
} else {
outputFileName = FileUtils.resolveFile(filePath,hrefValue);
}
}
} else {
outputFileName = FileUtils.resolveFile(filePath,hrefValue);
}
} else {
Random random = new Random();
outputFileName = FileUtils.resolveFile(filePath,"Chunk"
+new Integer(Math.abs(random.nextInt())).toString())+ditaext;
}
if(FileUtils.fileExists(outputFileName)
&& !classValue.contains(Constants.ATTR_CLASS_VALUE_MAP)) {
String t = outputFileName;
Random random = new Random();
outputFileName = FileUtils.resolveFile(filePath,"Chunk"
+new Integer(Math.abs(random.nextInt())).toString())+ditaext;
conflictTable.put(outputFileName, t);
}
changeTable.put(outputFileName,outputFileName);
}
this.outputFile = outputFileName;
{
String path = FileUtils.resolveTopic(filePath,parseFilePath);
String newpath = null;
if(path.indexOf(Constants.SHARP)!=-1){
newpath = outputFileName + path.substring(path.indexOf(Constants.SHARP));
}else{
String firstTopicID = this.getFirstTopicId(path);
if(!StringUtils.isEmptyString(firstTopicID)) {
newpath = outputFileName + "#" + firstTopicID;
} else {
newpath = outputFileName;
}
}
changeTable.put(path, newpath);
element.setAttribute(Constants.ATTRIBUTE_NAME_HREF,
FileUtils.getRelativePathFromMap(filePath+Constants.SLASH+"stub.ditamap"
,newpath));
}
if(parseFilePath.indexOf(Constants.SHARP)!=-1){
targetTopicId = parseFilePath.substring(parseFilePath.indexOf(Constants.SHARP)+1);
}
if(chunkValue.indexOf("select")!=-1){
int endIndex = chunkValue.indexOf(Constants.STRING_BLANK,
chunkValue.indexOf("select"));
if (endIndex ==-1){
selectMethod = chunkValue.substring(chunkValue.indexOf("select"));
}else{
selectMethod = chunkValue.substring(chunkValue.indexOf("select"),
endIndex);
}
if ("select-topic".equals(selectMethod) ||
"select-branch".equals(selectMethod)){
if(targetTopicId == null){
selectMethod = "select-document";
}
}
}
String tempPath = currentParsingFile;
currentParsingFile = FileUtils.resolveFile(filePath,parseFilePath);
if ( !Constants.ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equalsIgnoreCase(processRoleValue))
reader.parse(currentParsingFile);
currentParsingFile = tempPath;
}
if(outputFileName == null){
if (!StringUtils.isEmptyString(copytoValue)){
outputFileName = FileUtils.resolveFile(filePath,
copytoValue);
}else if(!StringUtils.isEmptyString(id)){
outputFileName = FileUtils.resolveFile(filePath,
id + ditaext);
}else{
Random random = new Random();
outputFileName = FileUtils.resolveFile(filePath,"Chunk"
+new Integer(Math.abs(random.nextInt())).toString())+ditaext;
if(FileUtils.fileExists(outputFileName)
&& !classValue.contains(Constants.ATTR_CLASS_VALUE_MAP)) {
String t = outputFileName;
outputFileName = FileUtils.resolveFile(filePath,"Chunk"
+new Integer(Math.abs(random.nextInt())).toString())+ditaext;
conflictTable.put(outputFileName, t);
}
}
if(element.hasChildNodes() || !StringUtils.isEmptyString(navtitle)){
DITAAttrUtils utils = DITAAttrUtils.getInstance();
String navtitleValue = null;
String shortDescValue = null;
navtitleValue = utils.getChildElementValueOfTopicmeta(element, Constants.ATTR_CLASS_VALUE_NAVTITLE);
shortDescValue = utils.getChildElementValueOfTopicmeta(element, Constants.ATTR_CLASS_VALUE_MAP_SHORTDESC);
if(navtitleValue == null){
navtitleValue = navtitle;
}
changeTable.put(outputFileName,outputFileName);
if(!StringUtils.isEmptyString(navtitleValue)){
element.setAttribute(Constants.ATTRIBUTE_NAME_HREF,
FileUtils.getRelativePathFromMap(filePath+Constants.SLASH+"stub.ditamap", outputFileName));
StringBuffer buffer = new StringBuffer();
buffer.append("<topic id=\"topic\" class=\"- topic/topic \">")
.append("<title class=\"- topic/title \">")
.append(navtitleValue).append("</title>");
if(shortDescValue != null){
buffer.append("<shortdesc class=\"- topic/shortdesc \">")
.append(shortDescValue).append("</shortdesc>");
}
buffer.append("</topic>");
StringReader rder = new StringReader(buffer.toString());
InputSource source = new InputSource(rder);
String tempPath = currentParsingFile;
currentParsingFile = outputFileName;
parseFilePath = outputFileName;
reader.parse(source);
currentParsingFile = tempPath;
}
}
}
if (element.hasChildNodes()){
StringWriter temp = (StringWriter)output;
output = new StringWriter();
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++){
Node current = children.item(i);
if (current.getNodeType() == Node.ELEMENT_NODE
&& ((Element)current).getAttribute(Constants.ATTRIBUTE_NAME_CLASS)
.indexOf(Constants.ATTR_CLASS_VALUE_TOPICREF)!=-1){
processChunk((Element)current,outputFileName);
}
}
StringBuffer parentResult = temp.getBuffer();
if (parentResult.length() > 0
&& !StringUtils.isEmptyString(parseFilePath)
&& !Constants.ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equalsIgnoreCase(processRoleValue)) {
int insertpoint = parentResult.lastIndexOf("</");
int end = parentResult.indexOf(">",insertpoint);
if(insertpoint==-1 || end==-1){
Properties prop=new Properties();
prop.put("%1", hrefValue);
logger.logError(MessageUtils.getMessage("DOTJ033E",prop).toString());
} else {
if (Constants.ELEMENT_NAME_DITA.equalsIgnoreCase(parentResult.substring(insertpoint,end).trim())){
insertpoint = parentResult.lastIndexOf("</",insertpoint);
}
parentResult.insert(insertpoint,((StringWriter)output).getBuffer());
}
} else {
parentResult.append(((StringWriter)output).getBuffer());
}
output = temp;
}
if(chunkValue.indexOf("to-content")!=-1){
FileOutputStream fileOutput = new FileOutputStream(outputFileName);
OutputStreamWriter ditaFileOutput = new OutputStreamWriter(fileOutput, Constants.UTF8);
if (outputFileName.equals(changeTable.get(outputFileName))){
ditaFileOutput.write(Constants.XML_HEAD);
if(Constants.OS_NAME.toLowerCase().indexOf(OS_NAME_WINDOWS)==-1)
{
ditaFileOutput.write(PI_WORKDIR_HEAD + new File(outputFileName).getParent() + PI_END);
}else{
ditaFileOutput.write(PI_WORKDIR_HEAD + Constants.SLASH + new File(outputFileName).getParent() + PI_END);
}
}
if (needWriteDitaTag) ditaFileOutput.write("<dita>");
ditaFileOutput.write(((StringWriter)output).getBuffer().toString());
if (needWriteDitaTag) ditaFileOutput.write("</dita>");
ditaFileOutput.flush();
ditaFileOutput.close();
output = tempWriter;
topicID = tempTopicID;
}
}
} catch (Exception e) {
logger.logException(e);
}
}
|
public static Material getOrCreateMaterial(int id, short data) {
Object o = idLookup[id];
Material[] materials;
Material mat;
if (o == null || o instanceof Material) {
mat = (Material)o;
materials = new Material[Math.max(mat.getRawData(), data) *2 + 1];
materials[mat.getRawData()] = mat;
} else {
materials = (Material[])o;
if (data > materials.length) {
materials = adjust(materials, data * 2 + 1);
}
mat = materials[data];
}
idLookup[id] = materials;
if (mat != null && id != FLINT_ID) {
if (mat.getRawId() == id && mat.getRawData() == data) {
return mat;
}
Material orig = mat;
try {
Class<?>[] params = {String.class, int.class, int.class, boolean.class};
Constructor<? extends Material> constructor = orig.getClass().getConstructor(params);
constructor.setAccessible(true);
mat = constructor.newInstance(orig.getName(), id, data, true);
insertItem(id, data, mat);
} catch (Exception e) {
System.out.println("[Spoutcraft] Available constructors: ");
for (Constructor<?> c : orig.getClass().getConstructors()) {
System.out.println("[Spoutcraft] Constructor Params: " + c.getParameterTypes());
}
e.printStackTrace();
System.out.println("[Spoutcraft] Failed to create a duplicate item in MaterialData.getOrCreateMaterial, for " + id + ", " + data);
}
return mat;
}
return null;
}
| public static Material getOrCreateMaterial(int id, short data) {
Object o = idLookup[id];
Material[] materials;
Material mat;
if (o == null || o instanceof Material) {
mat = (Material)o;
materials = new Material[Math.max(mat.getRawData(), data) *2 + 1];
materials[mat.getRawData()] = mat;
} else {
materials = (Material[])o;
if (data >= materials.length) {
materials = adjust(materials, data * 2 + 1);
}
mat = materials[data];
}
idLookup[id] = materials;
if (mat != null && id != FLINT_ID) {
if (mat.getRawId() == id && mat.getRawData() == data) {
return mat;
}
Material orig = mat;
try {
Class<?>[] params = {String.class, int.class, int.class, boolean.class};
Constructor<? extends Material> constructor = orig.getClass().getConstructor(params);
constructor.setAccessible(true);
mat = constructor.newInstance(orig.getName(), id, data, true);
insertItem(id, data, mat);
} catch (Exception e) {
System.out.println("[Spoutcraft] Available constructors: ");
for (Constructor<?> c : orig.getClass().getConstructors()) {
System.out.println("[Spoutcraft] Constructor Params: " + c.getParameterTypes());
}
e.printStackTrace();
System.out.println("[Spoutcraft] Failed to create a duplicate item in MaterialData.getOrCreateMaterial, for " + id + ", " + data);
}
return mat;
}
return null;
}
|
public void authenticate(final CallbackContext callbackContext) {
Log.i("SalesforceDroidGapActivity.authenticate", "authenticate called");
clientManager.getRestClient(this, new RestClientCallback() {
@Override
public void authenticatedRestClient(RestClient client) {
if (client == null) {
Log.i("SalesforceDroidGapActivity.authenticate", "authenticatedRestClient called with null client");
ForceApp.APP.logout(SalesforceDroidGapActivity.this);
} else {
Log.i("SalesforceDroidGapActivity.authenticate", "authenticatedRestClient called with actual client");
SalesforceDroidGapActivity.this.client = client;
SalesforceDroidGapActivity.this.client.sendAsync(RestRequest.getRequestForResources(API_VERSION), new AsyncRequestCallback() {
@Override
public void onSuccess(RestRequest request, RestResponse response) {
setSidCookies();
loadVFPingPage();
callbackContext.success(getJSONCredentials());
}
@Override
public void onError(Exception exception) {
callbackContext.error(exception.getMessage());
}
});
}
}
});
}
| public void authenticate(final CallbackContext callbackContext) {
Log.i("SalesforceDroidGapActivity.authenticate", "authenticate called");
clientManager.getRestClient(this, new RestClientCallback() {
@Override
public void authenticatedRestClient(RestClient client) {
if (client == null) {
Log.i("SalesforceDroidGapActivity.authenticate", "authenticatedRestClient called with null client");
ForceApp.APP.logout(SalesforceDroidGapActivity.this);
} else {
Log.i("SalesforceDroidGapActivity.authenticate", "authenticatedRestClient called with actual client");
SalesforceDroidGapActivity.this.client = client;
SalesforceDroidGapActivity.this.client.sendAsync(RestRequest.getRequestForResources(API_VERSION), new AsyncRequestCallback() {
@Override
public void onSuccess(RestRequest request, RestResponse response) {
setSidCookies();
loadVFPingPage();
if (callbackContext != null) {
callbackContext.success(getJSONCredentials());
}
}
@Override
public void onError(Exception exception) {
if (callbackContext != null) {
callbackContext.error(exception.getMessage());
}
}
});
}
}
});
}
|
public void testSendMessagesToJmsThenOutofJmsToReceiver() throws Exception {
QName service = new QName("http://servicemix.org/cheese/", "myJmsSender");
assertSendAndReceiveMessages(service);
}
| public void testSendMessagesToJmsThenOutofJmsToReceiver() throws Exception {
QName service = new QName("http://servicemix.org/cheese/", "myJmsSender");
sendMessages(service, messageCount, false);
assertMessagesReceived(messageCount);
}
|
public void parseCommand(String cmd, String[] args) {
PacketHandler ph = new PacketHandler();
DataManager dm = new DataManager();
if(cmd.equalsIgnoreCase("quit")) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " quit. Reason: " + msg) ;
Packet4Kick packet = new Packet4Kick("Quitting. Reason: " + msg);
Packet5Message packet2 = new Packet5Message(client.getUsername() + " quit. (" + msg + ")");
ph.sendPacket(packet, client, this.socket);
client.stopKeepAliveThread();
clients.remove(client);
ph.sendAllPacket(packet2, clients, this.socket);
}
else if(cmd.equalsIgnoreCase("stop")) {
if(dm.isOp(client.getUsername())) {
System.out.println(client.getUsername() + " stopped the server.");
System.exit(0);
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("say")) {
if(dm.isOp(client.getUsername())) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
Packet5Message packet = new Packet5Message("[Server] " + msg);
ph.sendAllPacket(packet, clients, this.socket);
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("ping")) {
Packet5Message packet = new Packet5Message("Pong!");
ph.sendPacket(packet, client, this.socket);
}
else if(cmd.equalsIgnoreCase("list")) {
String msg = "Online Users: ";
for(int i = 0; i < clients.size(); i++) {
ClientData client2 = (ClientData)clients.get(i);
msg += client2.getUsername() + ", ";
}
Packet5Message packet = new Packet5Message(msg.substring(0, msg.length() - 2).trim());
ph.sendPacket(packet, client, this.socket);
}
else if(cmd.equalsIgnoreCase("me")) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " did action: " + msg);
Packet5Message packet = new Packet5Message("*" + client.getUsername() + " " + msg);
ph.sendAllPacket(packet, clients, this.socket);
}
else if(cmd.equalsIgnoreCase("nick")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("Your name is already " + args[0] + ".");
ph.sendPacket(packet, client, this.socket);
}
else if(nameTaken(args[0])) {
Packet5Message packet = new Packet5Message("That name is taken.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isOp(args[0]) && !dm.isOp(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can't /nick to an op's name if you aren't an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
System.out.println(client.getUsername() + " has changed name to " + args[0]);
Packet5Message packet = new Packet5Message(client.getUsername() + " is now known as " + args[0]);
clients.remove(client);
client.setUsername(args[0]);
clients.add(client);
Packet6NameChange packet2 = new Packet6NameChange(args[0]);
ph.sendAllPacket(packet, clients, this.socket);
ph.sendPacket(packet2, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("op")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not op yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isOp(args[0])) {
Packet5Message packet = new Packet5Message("That user is already an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.addOp(args[0]);
System.out.println(client.getUsername() + " opped " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been opped.");
Packet5Message packet2 = new Packet5Message("You are now an op!");
ph.sendPacket(packet, client, this.socket);
ClientData client2 = findClient(args[0]);
if(client2 != null) ph.sendPacket(packet2, client2, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("deop")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not deop yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isOp(args[0])) {
Packet5Message packet = new Packet5Message("That user is not an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeOp(args[0]);
System.out.println(client.getUsername() + " deopped " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been deopped.");
Packet5Message packet2 = new Packet5Message("You are no longer an op!");
ph.sendPacket(packet, client, this.socket);
ClientData client2 = findClient(args[0]);
if(client2 != null) ph.sendPacket(packet2, client2, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("kick")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not kick yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(findClient(args[0]) == null) {
Packet5Message packet = new Packet5Message("That user isn't in the chat.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " kicked " + args[0] + " with reason: " + msg);
Packet5Message packet = new Packet5Message(args[0] + " has been kicked. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("You were kicked: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(args[0]);
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
clients.remove(client2);
ph.sendAllPacket(packet, clients, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("ban")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not ban yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isBanned(args[0])) {
Packet5Message packet = new Packet5Message("That user is already banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
dm.addBan(args[0]);
System.out.println(client.getUsername() + " banned " + args[0] + " with reason: " + msg);
Packet5Message packet = new Packet5Message(args[0] + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("You have been banned: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(args[0]);
if(client2 != null) {
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
clients.remove(client2);
}
ph.sendAllPacket(packet, clients, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("unban")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not unban yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isBanned(args[0])) {
Packet5Message packet = new Packet5Message("That user is not banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeBan(args[0]);
System.out.println(client.getUsername() + " unbanned " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been unbanned.");
ph.sendPacket(packet, client, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("banip")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
InetAddress ip = null;
try {
ip = InetAddress.getByName(args[0]);
}
catch(UnknownHostException e) {
}
if(ip == null) {
Packet5Message packet = new Packet5Message("The IP is invalid.");
ph.sendPacket(packet, client, this.socket);
}
else if(ip == client.getIP()) {
Packet5Message packet = new Packet5Message("You can not ban your own IP.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isIPBanned(ip.getHostAddress())) {
Packet5Message packet = new Packet5Message("That IP is already banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
dm.addIPBan(ip.getHostAddress());
System.out.println(client.getUsername() + " banned the IP " + ip.getHostAddress() + " with reason: " + msg);
Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("Your IP has been banned: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(ip);
if(client2 != null) {
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
clients.remove(client2);
}
ph.sendAllPacket(packet, clients, this.socket);
}
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("unbanip")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
InetAddress ip = null;
try {
ip = InetAddress.getByName(args[0]);
}
catch(UnknownHostException e) {
}
if(ip == null) {
Packet5Message packet = new Packet5Message("The IP is invalid.");
ph.sendPacket(packet, client, this.socket);
}
else if(ip == client.getIP()) {
Packet5Message packet = new Packet5Message("You can not unban your own IP.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isIPBanned(ip.getHostAddress())) {
Packet5Message packet = new Packet5Message("That IP is not banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeIPBan(ip.getHostAddress());
System.out.println(client.getUsername() + " unbanned the IP " + ip.getHostAddress() + ".");
Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been unbanned.");
ph.sendPacket(packet, client, this.socket);
}
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else {
System.out.println("Command \"" + cmd + "\" not found.");
Packet5Message packet = new Packet5Message("Unknown command.");
ph.sendPacket(packet, client, this.socket);
}
}
| public void parseCommand(String cmd, String[] args) {
PacketHandler ph = new PacketHandler();
DataManager dm = new DataManager();
if(cmd.equalsIgnoreCase("quit")) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " quit. Reason: " + msg) ;
Packet4Kick packet = new Packet4Kick("Quitting. Reason: " + msg);
Packet5Message packet2 = new Packet5Message(client.getUsername() + " quit. (" + msg + ")");
ph.sendPacket(packet, client, this.socket);
client.stopKeepAliveThread();
clients.remove(client);
ph.sendAllPacket(packet2, clients, this.socket);
}
else if(cmd.equalsIgnoreCase("stop")) {
if(dm.isOp(client.getUsername())) {
System.out.println(client.getUsername() + " stopped the server.");
System.exit(0);
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("say")) {
if(dm.isOp(client.getUsername())) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
Packet5Message packet = new Packet5Message("[Server] " + msg);
ph.sendAllPacket(packet, clients, this.socket);
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("ping")) {
Packet5Message packet = new Packet5Message("Pong!");
ph.sendPacket(packet, client, this.socket);
}
else if(cmd.equalsIgnoreCase("list")) {
String msg = "Online Users: ";
for(int i = 0; i < clients.size(); i++) {
ClientData client2 = (ClientData)clients.get(i);
msg += client2.getUsername() + ", ";
}
Packet5Message packet = new Packet5Message(msg.substring(0, Math.min(msg.length() - 2, 500)));
ph.sendPacket(packet, client, this.socket);
}
else if(cmd.equalsIgnoreCase("me")) {
String msg = "";
for(int i = 0; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " did action: " + msg);
Packet5Message packet = new Packet5Message("*" + client.getUsername() + " " + msg);
ph.sendAllPacket(packet, clients, this.socket);
}
else if(cmd.equalsIgnoreCase("nick")) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("Your name is already " + args[0] + ".");
ph.sendPacket(packet, client, this.socket);
}
else if(nameTaken(args[0])) {
Packet5Message packet = new Packet5Message("That name is taken.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isOp(args[0]) && !dm.isOp(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can't /nick to an op's name if you aren't an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
System.out.println(client.getUsername() + " has changed name to " + args[0]);
Packet5Message packet = new Packet5Message(client.getUsername() + " is now known as " + args[0]);
clients.remove(client);
client.setUsername(args[0]);
clients.add(client);
Packet6NameChange packet2 = new Packet6NameChange(args[0]);
ph.sendAllPacket(packet, clients, this.socket);
ph.sendPacket(packet2, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("op")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not op yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isOp(args[0])) {
Packet5Message packet = new Packet5Message("That user is already an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.addOp(args[0]);
System.out.println(client.getUsername() + " opped " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been opped.");
Packet5Message packet2 = new Packet5Message("You are now an op!");
ph.sendPacket(packet, client, this.socket);
ClientData client2 = findClient(args[0]);
if(client2 != null) ph.sendPacket(packet2, client2, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("deop")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not deop yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isOp(args[0])) {
Packet5Message packet = new Packet5Message("That user is not an op.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeOp(args[0]);
System.out.println(client.getUsername() + " deopped " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been deopped.");
Packet5Message packet2 = new Packet5Message("You are no longer an op!");
ph.sendPacket(packet, client, this.socket);
ClientData client2 = findClient(args[0]);
if(client2 != null) ph.sendPacket(packet2, client2, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("kick")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not kick yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(findClient(args[0]) == null) {
Packet5Message packet = new Packet5Message("That user isn't in the chat.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
System.out.println(client.getUsername() + " kicked " + args[0] + " with reason: " + msg);
Packet5Message packet = new Packet5Message(args[0] + " has been kicked. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("You were kicked: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(args[0]);
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
clients.remove(client2);
ph.sendAllPacket(packet, clients, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("ban")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not ban yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isBanned(args[0])) {
Packet5Message packet = new Packet5Message("That user is already banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
dm.addBan(args[0]);
System.out.println(client.getUsername() + " banned " + args[0] + " with reason: " + msg);
Packet5Message packet = new Packet5Message(args[0] + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("You have been banned: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(args[0]);
if(client2 != null) {
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
clients.remove(client2);
}
ph.sendAllPacket(packet, clients, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("unban")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else if(args[0].equalsIgnoreCase(client.getUsername())) {
Packet5Message packet = new Packet5Message("You can not unban yourself.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isBanned(args[0])) {
Packet5Message packet = new Packet5Message("That user is not banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeBan(args[0]);
System.out.println(client.getUsername() + " unbanned " + args[0] + ".");
Packet5Message packet = new Packet5Message(args[0] + " has been unbanned.");
ph.sendPacket(packet, client, this.socket);
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("banip")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
InetAddress ip = null;
try {
ip = InetAddress.getByName(args[0]);
}
catch(UnknownHostException e) {
}
if(ip == null) {
Packet5Message packet = new Packet5Message("The IP is invalid.");
ph.sendPacket(packet, client, this.socket);
}
else if(ip == client.getIP()) {
Packet5Message packet = new Packet5Message("You can not ban your own IP.");
ph.sendPacket(packet, client, this.socket);
}
else if(dm.isIPBanned(ip.getHostAddress())) {
Packet5Message packet = new Packet5Message("That IP is already banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
String msg = "";
for(int i = 1; i < args.length; i++) msg += args[i] + " ";
msg = msg.trim();
dm.addIPBan(ip.getHostAddress());
System.out.println(client.getUsername() + " banned the IP " + ip.getHostAddress() + " with reason: " + msg);
Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been banned. (" + (msg.equals("") ? "No reason." : msg) + ")");
Packet4Kick packet2 = new Packet4Kick("Your IP has been banned: " + (msg.equals("") ? "No reason." : msg));
ClientData client2 = findClient(ip);
if(client2 != null) {
ph.sendPacket(packet2, client2, this.socket);
client2.stopKeepAliveThread();
clients.remove(client2);
}
ph.sendAllPacket(packet, clients, this.socket);
}
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else if(cmd.equalsIgnoreCase("unbanip")) {
if(dm.isOp(client.getUsername())) {
if(args.length < 1) {
Packet5Message packet = new Packet5Message("Not enough paramters.");
ph.sendPacket(packet, client, this.socket);
}
else {
InetAddress ip = null;
try {
ip = InetAddress.getByName(args[0]);
}
catch(UnknownHostException e) {
}
if(ip == null) {
Packet5Message packet = new Packet5Message("The IP is invalid.");
ph.sendPacket(packet, client, this.socket);
}
else if(ip == client.getIP()) {
Packet5Message packet = new Packet5Message("You can not unban your own IP.");
ph.sendPacket(packet, client, this.socket);
}
else if(!dm.isIPBanned(ip.getHostAddress())) {
Packet5Message packet = new Packet5Message("That IP is not banned.");
ph.sendPacket(packet, client, this.socket);
}
else {
dm.removeIPBan(ip.getHostAddress());
System.out.println(client.getUsername() + " unbanned the IP " + ip.getHostAddress() + ".");
Packet5Message packet = new Packet5Message("The IP " + ip.getHostAddress() + " has been unbanned.");
ph.sendPacket(packet, client, this.socket);
}
}
}
else {
Packet5Message packet = new Packet5Message("You are not an op.");
ph.sendPacket(packet, client, this.socket);
}
}
else {
System.out.println("Command \"" + cmd + "\" not found.");
Packet5Message packet = new Packet5Message("Unknown command.");
ph.sendPacket(packet, client, this.socket);
}
}
|
public String isValid(final EngineMachineLearning eml) {
if( !(eml instanceof BasicNetwork) )
return "Only a BasicNetwork can be converted to a flat network.";
BasicNetwork network = (BasicNetwork)eml;
final Layer inputLayer = network.getLayer(BasicNetwork.TAG_INPUT);
final Layer outputLayer = network.getLayer(BasicNetwork.TAG_INPUT);
if (inputLayer == null) {
return "To convert to a flat network, there must be an input layer.";
}
if (outputLayer == null) {
return "To convert to a flat network, there must be an output layer.";
}
if( !(network.getLogic() instanceof FeedforwardLogic) ) {
return "To convert to flat, must be using FeedforwardLogic or SimpleRecurrentLogic.";
}
for (final Layer layer : network.getStructure().getLayers()) {
if (layer.getNext().size() > 2) {
return "To convert to flat a network must have at most two outbound synapses.";
}
if (layer.getClass()!=ContextLayer.class && layer.getClass()!=BasicLayer.class && layer.getClass()!=RadialBasisFunctionLayer.class ) {
return "To convert to flat a network must have only BasicLayer and ContextLayer layers.";
}
}
return null;
}
| public String isValid(final EngineMachineLearning eml) {
if( !(eml instanceof BasicNetwork) )
return "Only a BasicNetwork can be converted to a flat network.";
BasicNetwork network = (BasicNetwork)eml;
final Layer inputLayer = network.getLayer(BasicNetwork.TAG_INPUT);
final Layer outputLayer = network.getLayer(BasicNetwork.TAG_OUTPUT);
if (inputLayer == null) {
return "To convert to a flat network, there must be an input layer.";
}
if (outputLayer == null) {
return "To convert to a flat network, there must be an output layer.";
}
if( !(network.getLogic() instanceof FeedforwardLogic) ) {
return "To convert to flat, must be using FeedforwardLogic or SimpleRecurrentLogic.";
}
for (final Layer layer : network.getStructure().getLayers()) {
if (layer.getNext().size() > 2) {
return "To convert to flat a network must have at most two outbound synapses.";
}
if (layer.getClass()!=ContextLayer.class && layer.getClass()!=BasicLayer.class && layer.getClass()!=RadialBasisFunctionLayer.class ) {
return "To convert to flat a network must have only BasicLayer and ContextLayer layers.";
}
}
return null;
}
|
public static QTNode intersection(QTNode rootOne, QTNode rootTwo) {
if (rootOne.color == GREY && rootTwo.color == GREY) {
QTNode newNode = new QTNode(GREY);
for (int i = 0; i < 4; ++i) {
newNode.kids[i] = intersection(rootOne.kids[i], rootTwo.kids[i]);
}
if (newNode.isAllKidsWhite()) {
return new QTNode(WHITE);
} else {
return newNode;
}
} else if (rootOne.color == WHITE && rootTwo.color == WHITE) {
return new QTNode(WHITE);
} else if (rootOne.color == BLACK) {
return cloneQT(rootTwo);
} else {
return cloneQT(rootOne);
}
}
| public static QTNode intersection(QTNode rootOne, QTNode rootTwo) {
if (rootOne.color == GREY && rootTwo.color == GREY) {
QTNode newNode = new QTNode(GREY);
for (int i = 0; i < 4; ++i) {
newNode.kids[i] = intersection(rootOne.kids[i], rootTwo.kids[i]);
}
if (newNode.isAllKidsWhite()) {
return new QTNode(WHITE);
} else {
return newNode;
}
} else if (rootOne.color == WHITE || rootTwo.color == WHITE) {
return new QTNode(WHITE);
} else if (rootOne.color == BLACK) {
return cloneQT(rootTwo);
} else {
return cloneQT(rootOne);
}
}
|
public Type getType() throws InvalidSpecificationException {
if (_parameterType == null || _parameterType.equals("") || _parameterType.equals("_text")) {
return org.xins.common.types.standard.Text.SINGLETON;
} else if (_parameterType.equals("_int8")) {
return org.xins.common.types.standard.Int8.SINGLETON;
} else if (_parameterType.equals("_int16")) {
return org.xins.common.types.standard.Int16.SINGLETON;
} else if (_parameterType.equals("_int32")) {
return org.xins.common.types.standard.Int32.SINGLETON;
} else if (_parameterType.equals("_int64")) {
return org.xins.common.types.standard.Int64.SINGLETON;
} else if (_parameterType.equals("_float32")) {
return org.xins.common.types.standard.Float32.SINGLETON;
} else if (_parameterType.equals("_float64")) {
return org.xins.common.types.standard.Float64.SINGLETON;
} else if (_parameterType.equals("_boolean")) {
return org.xins.common.types.standard.Boolean.SINGLETON;
} else if (_parameterType.equals("_date")) {
return org.xins.common.types.standard.Date.SINGLETON;
} else if (_parameterType.equals("_timestamp")) {
return org.xins.common.types.standard.Timestamp.SINGLETON;
} else if (_parameterType.equals("_base64")) {
return org.xins.common.types.standard.Base64.SINGLETON;
} else if (_parameterType.equals("_descriptor")) {
return org.xins.common.types.standard.Descriptor.SINGLETON;
} else if (_parameterType.equals("_properties")) {
return org.xins.common.types.standard.Properties.SINGLETON;
} else if (_parameterType.equals("_url")) {
return org.xins.common.types.standard.URL.SINGLETON;
} else if (_parameterType.charAt(0) != '_') {
String className = _reference.getName();
int truncatePos = className.lastIndexOf(".capi.CAPI");
if (truncatePos == -1) {
truncatePos = className.lastIndexOf(".api.APIImpl");
}
try {
String typeClassName = className.substring(0, truncatePos) + ".types." + _parameterType + ".class";
Class typeClass = Class.forName(className);
Type type = (Type) typeClass.getField("SINGLETON").get(null);
return type;
} catch (Exception ex) {
throw new InvalidSpecificationException("Invalid type: " + _parameterType + " ; " + ex.getMessage());
}
}
throw new InvalidSpecificationException("Invalid type: " + _parameterType + ".");
}
| public Type getType() throws InvalidSpecificationException {
if (_parameterType == null || _parameterType.equals("") || _parameterType.equals("_text")) {
return org.xins.common.types.standard.Text.SINGLETON;
} else if (_parameterType.equals("_int8")) {
return org.xins.common.types.standard.Int8.SINGLETON;
} else if (_parameterType.equals("_int16")) {
return org.xins.common.types.standard.Int16.SINGLETON;
} else if (_parameterType.equals("_int32")) {
return org.xins.common.types.standard.Int32.SINGLETON;
} else if (_parameterType.equals("_int64")) {
return org.xins.common.types.standard.Int64.SINGLETON;
} else if (_parameterType.equals("_float32")) {
return org.xins.common.types.standard.Float32.SINGLETON;
} else if (_parameterType.equals("_float64")) {
return org.xins.common.types.standard.Float64.SINGLETON;
} else if (_parameterType.equals("_boolean")) {
return org.xins.common.types.standard.Boolean.SINGLETON;
} else if (_parameterType.equals("_date")) {
return org.xins.common.types.standard.Date.SINGLETON;
} else if (_parameterType.equals("_timestamp")) {
return org.xins.common.types.standard.Timestamp.SINGLETON;
} else if (_parameterType.equals("_base64")) {
return org.xins.common.types.standard.Base64.SINGLETON;
} else if (_parameterType.equals("_descriptor")) {
return org.xins.common.types.standard.Descriptor.SINGLETON;
} else if (_parameterType.equals("_properties")) {
return org.xins.common.types.standard.Properties.SINGLETON;
} else if (_parameterType.equals("_url")) {
return org.xins.common.types.standard.URL.SINGLETON;
} else if (_parameterType.charAt(0) != '_') {
String className = _reference.getName();
int truncatePos = className.lastIndexOf(".capi.CAPI");
if (truncatePos == -1) {
truncatePos = className.lastIndexOf(".api.APIImpl");
}
try {
String typeClassName = className.substring(0, truncatePos) + ".types." + _parameterType + ".class";
Class typeClass = Class.forName(typeClassName);
Type type = (Type) typeClass.getField("SINGLETON").get(null);
return type;
} catch (Exception ex) {
throw new InvalidSpecificationException("Invalid type: " + _parameterType + " ; " + ex.getMessage());
}
}
throw new InvalidSpecificationException("Invalid type: " + _parameterType + ".");
}
|
public void run() {
String config = SystemPropertyUtil.get(R66SystemProperties.OPENR66_CONFIGFILE);
if (config == null) {
logger.error("Cannot find "+R66SystemProperties.OPENR66_CONFIGFILE+" parameter for SpooledEngine");
closeFuture.cancel();
shutdown();
return;
}
Configuration.configuration.shutdownConfiguration.serviceFuture = closeFuture;
try {
Properties prop = new Properties();
prop.load(new FileInputStream(config));
ArrayList<String> array = new ArrayList<String>();
for (Object okey : prop.keySet()) {
String key = (String) okey;
String val = prop.getProperty(key);
if (key.equals("xmlfile")) {
if (val != null) {
array.add(0, val);
} else {
throw new Exception("Initialization in error: missing xmlfile");
}
} else {
array.add(key);
if (val != null) {
array.add(val);
}
}
}
if (! SpooledDirectoryTransfer.initialize((String[]) array.toArray(), false)) {
throw new Exception("Initialization in error");
}
} catch (Throwable e) {
logger.error("Cannot start SpooledDirectory", e);
closeFuture.cancel();
shutdown();
return;
}
logger.warn("SpooledDirectory Service started with "+config);
}
| public void run() {
String config = SystemPropertyUtil.get(R66SystemProperties.OPENR66_CONFIGFILE);
if (config == null) {
logger.error("Cannot find "+R66SystemProperties.OPENR66_CONFIGFILE+" parameter for SpooledEngine");
closeFuture.cancel();
shutdown();
return;
}
Configuration.configuration.shutdownConfiguration.serviceFuture = closeFuture;
try {
Properties prop = new Properties();
prop.load(new FileInputStream(config));
ArrayList<String> array = new ArrayList<String>();
for (Object okey : prop.keySet()) {
String key = (String) okey;
String val = prop.getProperty(key);
if (key.equals("xmlfile")) {
if (val != null && ! val.trim().isEmpty()) {
array.add(0, val);
} else {
throw new Exception("Initialization in error: missing xmlfile");
}
} else {
array.add("-"+key);
if (val != null && ! val.trim().isEmpty()) {
array.add(val);
}
}
}
if (! SpooledDirectoryTransfer.initialize((String[]) array.toArray(), false)) {
throw new Exception("Initialization in error");
}
} catch (Throwable e) {
logger.error("Cannot start SpooledDirectory", e);
closeFuture.cancel();
shutdown();
return;
}
logger.warn("SpooledDirectory Service started with "+config);
}
|
private static void showErrorDialog(Component parent, String title, String msg) {
JTextArea area = new JTextArea(msg);
area.setEditable(false);
JLabel dummylbl = new JLabel();
area.setBackground(dummylbl.getBackground());
area.setForeground(dummylbl.getForeground());
area.setFont(dummylbl.getFont());
JScrollPane pane = new JScrollPane(area, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setBorder(null);
final JOptionPane optionPane = new JOptionPane(
new Object[] { pane },
JOptionPane.ERROR_MESSAGE,
JOptionPane.YES_NO_OPTION,
null,
new Object[] {btntxtCopy, btntxtOk}, btntxtOk);
final JDialog dlg = createJDialog(parent);
dlg.setTitle(title);
dlg.setContentPane(optionPane);
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
optionPane.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (dlg.isVisible() && (e.getSource() == optionPane)) {
if (e.getPropertyName().equals(JOptionPane.VALUE_PROPERTY)
&& (e.getNewValue().equals(btntxtCopy)) ) {
LogWindowHandler.getInstance().getWindow().copyToClipboard();
} else if (e.getPropertyName().equals(JOptionPane.VALUE_PROPERTY)
&& (e.getNewValue().equals(btntxtOk)) ) {
dlg.dispose();
}
}
}
});
dlg.pack();
dlg.setVisible(true);
}
| private static void showErrorDialog(Component parent, String title, String msg) {
JTextArea area = new JTextArea(msg);
area.setEditable(false);
JLabel dummylbl = new JLabel();
area.setBackground(dummylbl.getBackground());
area.setForeground(dummylbl.getForeground());
area.setFont(dummylbl.getFont());
JScrollPane pane = new JScrollPane(area, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setBorder(null);
final JOptionPane optionPane = new JOptionPane(
new Object[] { pane },
JOptionPane.ERROR_MESSAGE,
JOptionPane.YES_NO_OPTION,
null,
new Object[] {btntxtCopy, btntxtOk}, btntxtOk);
final JDialog dlg = createJDialog(parent);
dlg.setTitle(title);
dlg.setContentPane(optionPane);
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
optionPane.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (dlg.isVisible() && (e.getSource() == optionPane)) {
if (e.getPropertyName().equals(JOptionPane.VALUE_PROPERTY)
&& (e.getNewValue().equals(btntxtCopy)) ) {
LogWindowHandler.getInstance().getWindow().copyToClipboard();
} else if (e.getPropertyName().equals(JOptionPane.VALUE_PROPERTY)
&& (e.getNewValue().equals(btntxtOk)) ) {
dlg.dispose();
}
}
}
});
dlg.pack();
dlg.setModal(true);
dlg.setVisible(true);
}
|
private void createWordPinyinRelation(JdbcTemplate jdbcTemplate, int wordId, String wordName) {
if (wordName.length() == 1) {
NodeRepository observeBank = WordToPinyinClassfierFactory.apply().getClassifier().model().getObserveBank();
Node o = observeBank.get(wordName);
if (o != null) {
Emission emission = WordToPinyinClassfierFactory.apply().getClassifier().model().getViterbi().getE();
Collection stateProbByObserve = emission.getStateProbByObserve(o.getIndex());
if (null != stateProbByObserve) {
NodeRepository stateBank = WordToPinyinClassfierFactory.apply().getClassifier().model().getStateBank();
for (Object i : stateProbByObserve) {
Node state = stateBank.get(Integer.parseInt(i.toString()));
jdbcTemplate.execute("INSERT INTO Pinyins (WordId, Name) VALUES (" +
+wordId + ",'" + state.getName() + "')");
}
}
}
} else {
List<String> pinyinList = WordToPinyinClassfierFactory.apply().getClassifier().classify(wordName);
String pinyin = join(pinyinList, "'");
jdbcTemplate.update("INSERT INTO Pinyins (WordId, Name) VALUES (" +
+wordId + ", ?)", pinyin);
}
}
| private void createWordPinyinRelation(JdbcTemplate jdbcTemplate, int wordId, String wordName) {
if (wordName.length() == 1) {
NodeRepository observeBank = WordToPinyinClassfierFactory.apply().getClassifier().getModel().getObserveBank();
Node o = observeBank.get(wordName);
if (o != null) {
Emission emission = WordToPinyinClassfierFactory.apply().getClassifier().getModel().getViterbi().getE();
Collection stateProbByObserve = emission.getStateProbByObserve(o.getIndex());
if (null != stateProbByObserve) {
NodeRepository stateBank = WordToPinyinClassfierFactory.apply().getClassifier().getModel().getStateBank();
for (Object i : stateProbByObserve) {
Node state = stateBank.get(Integer.parseInt(i.toString()));
jdbcTemplate.execute("INSERT INTO Pinyins (WordId, Name) VALUES (" +
+wordId + ",'" + state.getName() + "')");
}
}
}
} else {
List<String> pinyinList = WordToPinyinClassfierFactory.apply().getClassifier().classify(wordName);
String pinyin = join(pinyinList, "'");
jdbcTemplate.update("INSERT INTO Pinyins (WordId, Name) VALUES (" +
+wordId + ", ?)", pinyin);
}
}
|
public void process(MessageExchange exchange) throws Exception {
if (exchange.getStatus() == ExchangeStatus.DONE) {
return;
} else if (exchange.getStatus() == ExchangeStatus.ERROR) {
return;
}
XFire xfire = endpoint.getXFire();
Service service = endpoint.getXFireService();
Transport t = xfire.getTransportManager().getTransport(JbiTransport.JBI_BINDING);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Channel c = t.createChannel();
MessageContext ctx = new MessageContext();
ctx.setXFire(xfire);
ctx.setService(service);
ctx.setProperty(Channel.BACKCHANNEL_URI, out);
ctx.setExchange(new org.codehaus.xfire.exchange.MessageExchange(ctx));
InMessage msg = new InMessage();
ctx.getExchange().setInMessage(msg);
if (exchange.getOperation() != null) {
OperationInfo op = service.getServiceInfo().getOperation(exchange.getOperation().getLocalPart());
if (op != null) {
ctx.getExchange().setOperation(op);
}
}
ctx.setCurrentMessage(msg);
NormalizedMessage in = exchange.getMessage("in");
msg.setXMLStreamReader(getXMLStreamReader(in.getContent()));
if (in.getAttachmentNames() != null && in.getAttachmentNames().size() > 0) {
JavaMailAttachments attachments = new JavaMailAttachments();
for (Iterator it = in.getAttachmentNames().iterator(); it.hasNext();) {
String name = (String) it.next();
DataHandler dh = in.getAttachment(name);
attachments.addPart(new SimpleAttachment(name, dh));
}
msg.setAttachments(attachments);
}
JBIContext.setMessageExchange(exchange);
try {
c.receive(ctx, msg);
} finally {
JBIContext.setMessageExchange(null);
}
c.close();
if (isInAndOut(exchange)) {
String charSet = ctx.getOutMessage().getEncoding();
if (ctx.getExchange().hasFaultMessage() && ctx.getExchange().getFaultMessage().getBody() != null) {
Fault fault = exchange.createFault();
fault.setContent(new StringSource(out.toString(charSet)));
XFireFault xFault = (XFireFault) ctx.getExchange().getFaultMessage().getBody();
fault.setProperty(SOAP_FAULT_CODE, xFault.getFaultCode());
fault.setProperty(SOAP_FAULT_REASON, xFault.getReason());
fault.setProperty(SOAP_FAULT_ROLE, xFault.getRole());
fault.setProperty(SOAP_FAULT_SUBCODE, xFault.getSubCode());
exchange.setFault(fault);
} else {
NormalizedMessage outMsg = exchange.createMessage();
Attachments attachments = ctx.getCurrentMessage().getAttachments();
if (attachments != null) {
for (Iterator it = attachments.getParts(); it.hasNext();) {
Attachment att = (Attachment) it.next();
outMsg.addAttachment(att.getId(), att.getDataHandler());
}
}
outMsg.setContent(new StringSource(out.toString(charSet)));
exchange.setMessage(outMsg, "out");
}
if (exchange.isTransacted() && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC))) {
channel.sendSync(exchange);
} else {
channel.send(exchange);
}
} else {
exchange.setStatus(ExchangeStatus.DONE);
channel.send(exchange);
}
}
| public void process(MessageExchange exchange) throws Exception {
if (exchange.getStatus() == ExchangeStatus.DONE) {
return;
} else if (exchange.getStatus() == ExchangeStatus.ERROR) {
return;
}
XFire xfire = endpoint.getXFire();
Service service = endpoint.getXFireService();
Transport t = xfire.getTransportManager().getTransport(JbiTransport.JBI_BINDING);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Channel c = t.createChannel();
MessageContext ctx = new MessageContext();
ctx.setXFire(xfire);
ctx.setService(service);
ctx.setProperty(Channel.BACKCHANNEL_URI, out);
ctx.setExchange(new org.codehaus.xfire.exchange.MessageExchange(ctx));
InMessage msg = new InMessage();
ctx.getExchange().setInMessage(msg);
if (exchange.getOperation() != null) {
OperationInfo op = service.getServiceInfo().getOperation(exchange.getOperation().getLocalPart());
if (op != null) {
ctx.getExchange().setOperation(op);
}
}
ctx.setCurrentMessage(msg);
NormalizedMessage in = exchange.getMessage("in");
msg.setXMLStreamReader(getXMLStreamReader(in.getContent()));
if (in.getAttachmentNames() != null && in.getAttachmentNames().size() > 0) {
JavaMailAttachments attachments = new JavaMailAttachments();
for (Iterator it = in.getAttachmentNames().iterator(); it.hasNext();) {
String name = (String) it.next();
DataHandler dh = in.getAttachment(name);
attachments.addPart(new SimpleAttachment(name, dh));
}
msg.setAttachments(attachments);
}
JBIContext.setMessageExchange(exchange);
try {
c.receive(ctx, msg);
} finally {
JBIContext.setMessageExchange(null);
}
c.close();
if (isInAndOut(exchange)) {
if (ctx.getExchange().hasFaultMessage() && ctx.getExchange().getFaultMessage().getBody() != null) {
String charSet = ctx.getExchange().getFaultMessage().getEncoding();
Fault fault = exchange.createFault();
fault.setContent(new StringSource(out.toString(charSet)));
XFireFault xFault = (XFireFault) ctx.getExchange().getFaultMessage().getBody();
fault.setProperty(SOAP_FAULT_CODE, xFault.getFaultCode());
fault.setProperty(SOAP_FAULT_REASON, xFault.getReason());
fault.setProperty(SOAP_FAULT_ROLE, xFault.getRole());
fault.setProperty(SOAP_FAULT_SUBCODE, xFault.getSubCode());
exchange.setFault(fault);
} else {
String charSet = ctx.getOutMessage().getEncoding();
NormalizedMessage outMsg = exchange.createMessage();
Attachments attachments = ctx.getCurrentMessage().getAttachments();
if (attachments != null) {
for (Iterator it = attachments.getParts(); it.hasNext();) {
Attachment att = (Attachment) it.next();
outMsg.addAttachment(att.getId(), att.getDataHandler());
}
}
outMsg.setContent(new StringSource(out.toString(charSet)));
exchange.setMessage(outMsg, "out");
}
if (exchange.isTransacted() && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC))) {
channel.sendSync(exchange);
} else {
channel.send(exchange);
}
} else {
exchange.setStatus(ExchangeStatus.DONE);
channel.send(exchange);
}
}
|
protected void copyTo(Description destination) {
Preconditions.checkNotNull(destination);
super.copyTo(destination);
destination.setUri(getUri());
destination.setTitle(getTitle());
if (getPublisher() != null) {
destination.setPublisher(getPublisher().copy());
}
destination.setImage(getImage());
destination.setThumbnail(getThumbnail());
destination.setGenres(getGenres());
destination.setTags(getTags());
destination.setContainedIn(getContainedIn());
destination.setClips(Iterables.transform(getClips(), Item.TO_COPY));
destination.setSameAs(getSameAs());
destination.setMediaType(getMediaType());
destination.setSpecialization(getSpecialization());
}
| protected void copyTo(Description destination) {
Preconditions.checkNotNull(destination);
super.copyTo(destination);
destination.setUri(getUri());
destination.setTitle(getTitle());
destination.setDescription(getDescription());
if (getPublisher() != null) {
destination.setPublisher(getPublisher().copy());
}
destination.setImage(getImage());
destination.setThumbnail(getThumbnail());
destination.setGenres(getGenres());
destination.setTags(getTags());
destination.setContainedIn(getContainedIn());
destination.setClips(Iterables.transform(getClips(), Item.TO_COPY));
destination.setSameAs(getSameAs());
destination.setMediaType(getMediaType());
destination.setSpecialization(getSpecialization());
}
|
public SimpleObject getVisitDetails(
@SpringBean("adminService") AdministrationService administrationService,
@RequestParam("visitId") Visit visit,
UiUtils uiUtils,
EmrContext emrContext) throws ParseException {
SimpleObject simpleObject = SimpleObject.fromObject(visit, uiUtils, "id", "location");
User authenticatedUser = emrContext.getUserContext().getAuthenticatedUser();
boolean canDelete = authenticatedUser.hasPrivilege(EmrConstants.PRIVILEGE_DELETE_ENCOUNTER);
Date startDatetime = visit.getStartDatetime();
Date stopDatetime = visit.getStopDatetime();
simpleObject.put("startDatetime", DateFormatUtils.format(startDatetime, "dd MMM yyyy hh:mm a", emrContext.getUserContext().getLocale()));
if (stopDatetime!=null){
simpleObject.put("stopDatetime", DateFormatUtils.format(stopDatetime, "dd MMM yyyy hh:mm a", emrContext.getUserContext().getLocale()));
} else {
simpleObject.put("stopDatetime", null);
}
List<SimpleObject> encounters = new ArrayList<SimpleObject>();
simpleObject.put("encounters", encounters);
String[] datePatterns = { administrationService.getGlobalProperty(UiFrameworkConstants.GP_FORMATTER_DATETIME_FORMAT) };
for (Encounter e : visit.getEncounters()) {
if (!e.getVoided()) {
SimpleObject simpleEncounter = SimpleObject.fromObject(e, uiUtils, "encounterId", "location", "encounterProviders.provider", "voided", "form");
simpleEncounter.put("encounterDate", DateFormatUtils.format(e.getEncounterDatetime(), "dd MMM yyyy", emrContext.getUserContext().getLocale()));
simpleEncounter.put("encounterTime", DateFormatUtils.format(e.getEncounterDatetime(), "hh:mm a", emrContext.getUserContext().getLocale()));
EncounterType encounterType = e.getEncounterType();
simpleEncounter.put("encounterType", SimpleObject.create("uuid", encounterType.getUuid(), "name", uiUtils.format(encounterType)));
if(canDelete){
simpleEncounter.put("canDelete", true);
}
encounters.add(simpleEncounter);
}
}
return simpleObject;
}
| public SimpleObject getVisitDetails(
@SpringBean("adminService") AdministrationService administrationService,
@RequestParam("visitId") Visit visit,
UiUtils uiUtils,
EmrContext emrContext) throws ParseException {
SimpleObject simpleObject = SimpleObject.fromObject(visit, uiUtils, "id", "location");
User authenticatedUser = emrContext.getUserContext().getAuthenticatedUser();
boolean canDelete = authenticatedUser.hasPrivilege(EmrConstants.PRIVILEGE_DELETE_ENCOUNTER);
Date startDatetime = visit.getStartDatetime();
Date stopDatetime = visit.getStopDatetime();
simpleObject.put("startDatetime", DateFormatUtils.format(startDatetime, "dd MMM yyyy hh:mm a", emrContext.getUserContext().getLocale()));
if (stopDatetime!=null){
simpleObject.put("stopDatetime", DateFormatUtils.format(stopDatetime, "dd MMM yyyy hh:mm a", emrContext.getUserContext().getLocale()));
} else {
simpleObject.put("stopDatetime", null);
}
List<SimpleObject> encounters = new ArrayList<SimpleObject>();
simpleObject.put("encounters", encounters);
String[] datePatterns = { administrationService.getGlobalProperty(UiFrameworkConstants.GP_FORMATTER_DATETIME_FORMAT) };
for (Encounter e : visit.getEncounters()) {
if (!e.getVoided()) {
SimpleObject simpleEncounter = SimpleObject.fromObject(e, uiUtils, "encounterId", "location", "encounterDatetime", "encounterProviders.provider", "voided", "form");
simpleEncounter.put("encounterDate", DateFormatUtils.format(e.getEncounterDatetime(), "dd MMM yyyy", emrContext.getUserContext().getLocale()));
simpleEncounter.put("encounterTime", DateFormatUtils.format(e.getEncounterDatetime(), "hh:mm a", emrContext.getUserContext().getLocale()));
EncounterType encounterType = e.getEncounterType();
simpleEncounter.put("encounterType", SimpleObject.create("uuid", encounterType.getUuid(), "name", uiUtils.format(encounterType)));
if(canDelete){
simpleEncounter.put("canDelete", true);
}
encounters.add(simpleEncounter);
}
}
return simpleObject;
}
|
private void doAuthSeq() {
int response = BluetoothConnection.RESPONSE_NONE;
Log.v(CLASS_NAME, "Sending unlock command");
while (!(btConnection.write("dsadsa\r".getBytes())));
boolean miDataOK = false;
byte miData[] = new byte[8];
while (response != BluetoothConnection.RESPONSE_ACK) {
do {
miDataOK = true;
miData = listenForMIChallenge();
for (int i=0; i<8; i++) {
if (miData[i] > 'z' || miData[i] < 'A') {
miDataOK = false;
break;
}
}
if (!miDataOK) {
ByteBuffer buf = ByteBuffer.wrap(miData);
long shifted = ((buf.getLong()) >>> 2) | 0x4000000000000000L;
ByteBuffer bufShifted = ByteBuffer.allocate(8);
bufShifted.putLong(shifted);
miData = bufShifted.array();
for (int i=0; i<8; i++) {
if (miData[i] > 'z' || miData[i] < 'A') {
miDataOK = false;
break;
}
}
}
} while (!miDataOK);
try {
btConnection.write(miData);
btConnection.write("\r".getBytes());
} catch (Exception e) { Log.e("Exception!", e.toString()); }
synchronized (btConnection.mConnectedThread) {
try {
Log.v("before", "before wait");
btConnection.mConnectedThread.wait(1000);
Log.v("after", "after wait");
} catch (Exception e) { Log.e("Exception!", e.toString()); }
}
response = btConnection.getResponse();
Log.v("response", response+"");
}
}
| private void doAuthSeq() {
int response = BluetoothConnection.RESPONSE_NONE;
Log.v(CLASS_NAME, "Sending unlock command");
while (!(btConnection.write("dsadsa\r".getBytes())));
boolean miDataOK = false;
byte miData[] = new byte[8];
while (response != BluetoothConnection.RESPONSE_ACK) {
do {
miDataOK = true;
miData = listenForMIChallenge();
byte miDataCopy[] = miData;
for (int i=0; i<8; i++) {
if (miData[i] > 'z' || miData[i] < 'A') {
miDataOK = false;
break;
}
}
if (!miDataOK) {
ByteBuffer buf = ByteBuffer.wrap(miData);
long shifted = ((buf.getLong()) >>> 2) | 0x4000000000000000L;
ByteBuffer bufShifted = ByteBuffer.allocate(8);
bufShifted.putLong(shifted);
miData = bufShifted.array();
miDataOK = true;
for (int i=0; i<8; i++) {
if (miData[i] > 'z' || miData[i] < 'A') {
miDataOK = false;
}
}
}
if (!miDataOK) {
for (int j=0; j<8; j++) {
byte oldByte = miDataCopy[j];
byte newByte;
byte oldBit = (byte)((oldByte >> 7) & 0x1);
byte newBit;
newByte = (byte) (oldBit << 7);
for(int i=6; i>=0; i--) {
if (((oldByte >> i) & 0x1) == oldBit) {
if (oldBit == 1)
newBit = 0;
else
newBit = 1;
newByte = (byte) (newByte | (newBit << i));
}
else {
newByte = (byte) (newByte | (byte)(((oldByte >> i) & 0x1) << i));
}
oldBit = (byte)((oldByte >> i) & 0x1);
}
miDataCopy[j] = newByte;
}
miDataOK = true;
for (int i=0; i<8; i++) {
if (miData[i] > 'z' || miData[i] < 'A') {
miDataOK = false;
}
}
}
} while (!miDataOK);
try {
btConnection.write(miData);
btConnection.write("\r".getBytes());
} catch (Exception e) { Log.e("Exception!", e.toString()); }
synchronized (btConnection.mConnectedThread) {
try {
Log.v("before", "before wait");
btConnection.mConnectedThread.wait(1000);
Log.v("after", "after wait");
} catch (Exception e) { Log.e("Exception!", e.toString()); }
}
response = btConnection.getResponse();
Log.v("response", response+"");
}
}
|
public void publish(LogMessage logMessage) {
PrintWriter output = null;
try {
File file;
file = new File(fileName);
if (!file.exists())
file.createNewFile();
output = new PrintWriter(new FileWriter(file));
output.println(loggerFormatter.applyFormat(logMessage));
output.close();
} catch (IOException exception) {
Logger.log(exception);
} finally {
output.close();
}
}
| public void publish(LogMessage logMessage) {
try {
File file;
file = new File(fileName);
if (!file.exists())
file.createNewFile();
PrintWriter output = new PrintWriter(new FileWriter(file));
output.println(loggerFormatter.applyFormat(logMessage));
output.close();
} catch (IOException exception) {
Logger.log(exception);
} finally {
}
}
|
private void publish(RemoteServiceDescription rsd) {
synchronized (rsDescs) {
ServiceHooksProxy handler = new ServiceHooksProxy(rsd.getService());
Object service = Proxy.newProxyInstance(rsd.getServiceInterfaceClass().getClassLoader(), new Class[] { rsd
.getServiceInterfaceClass() }, handler);
rsd.setService(service);
handler.setRemoteServiceDescription(rsd);
RemoteServiceDescription rsDescFound = rsDescs.get(rsd.getProtocol() + "::" + rsd.getPath());
if (rsDescFound != null) {
LOGGER.log(LogService.LOG_WARNING, "A service endpoint with path=[" + rsd.getPath()
+ "] and remoteType=[" + rsd.getProtocol() + "] already published... ignored");
return;
}
if (rsd.getPath() == null) {
LOGGER.log(LogService.LOG_WARNING, "no path for service: " + service.toString()
+ " Service not published remote");
return;
}
IServicePublisher servicePublisher = servicePublishers.get(rsd.getProtocol());
if (servicePublisher == null) {
LOGGER.log(LogService.LOG_INFO, "no publisher found for protocol " + rsd.getProtocol());
unpublishedServices.add(rsd);
return;
}
String url = null;
try {
url = servicePublisher.publishService(rsd);
} catch (RuntimeException e) {
LOGGER.log(LogService.LOG_ERROR, e.getMessage());
return;
}
rsd.setURL(url);
handler.setMessageContextAccessor(servicePublisher.getMessageContextAccessor());
rsDescs.put(rsd.getProtocol() + "::" + rsd.getPath(), rsd);
LOGGER.log(LogService.LOG_DEBUG, "service endpoints count: " + rsDescs.size());
}
}
| private void publish(RemoteServiceDescription rsd) {
synchronized (rsDescs) {
ServiceHooksProxy handler = new ServiceHooksProxy(rsd.getService());
Object service = Proxy.newProxyInstance(rsd.getServiceInterfaceClass().getClassLoader(), new Class[] { rsd
.getServiceInterfaceClass() }, handler);
handler.setRemoteServiceDescription(rsd);
RemoteServiceDescription rsDescFound = rsDescs.get(rsd.getProtocol() + "::" + rsd.getPath());
if (rsDescFound != null) {
LOGGER.log(LogService.LOG_WARNING, "A service endpoint with path=[" + rsd.getPath()
+ "] and remoteType=[" + rsd.getProtocol() + "] already published... ignored");
return;
}
if (rsd.getPath() == null) {
LOGGER.log(LogService.LOG_WARNING, "no path for service: " + service.toString()
+ " Service not published remote");
return;
}
IServicePublisher servicePublisher = servicePublishers.get(rsd.getProtocol());
if (servicePublisher == null) {
LOGGER.log(LogService.LOG_INFO, "no publisher found for protocol " + rsd.getProtocol());
unpublishedServices.add(rsd);
return;
}
rsd.setService(service);
String url = null;
try {
url = servicePublisher.publishService(rsd);
} catch (RuntimeException e) {
LOGGER.log(LogService.LOG_ERROR, e.getMessage());
return;
}
rsd.setURL(url);
handler.setMessageContextAccessor(servicePublisher.getMessageContextAccessor());
rsDescs.put(rsd.getProtocol() + "::" + rsd.getPath(), rsd);
LOGGER.log(LogService.LOG_DEBUG, "service endpoints count: " + rsDescs.size());
}
}
|
public void preInit (FMLPreInitializationEvent event)
{
TinkerSmelteryEvents smelteryEvents = new TinkerSmelteryEvents();
MinecraftForge.EVENT_BUS.register(smelteryEvents);
FMLCommonHandler.instance().bus().register(smelteryEvents);
TinkerSmeltery.buckets = new FilledBucket(BlockUtils.getBlockFromItem(TinkerSmeltery.buckets));
GameRegistry.registerItem(TinkerSmeltery.buckets, "buckets");
TinkerSmeltery.searedSlab = new SearedSlab().setBlockName("SearedSlab");
TinkerSmeltery.searedSlab.stepSound = Block.soundTypeStone;
TinkerSmeltery.speedSlab = new SpeedSlab().setBlockName("SpeedSlab");
TinkerSmeltery.speedSlab.stepSound = Block.soundTypeStone;
TinkerSmeltery.glueBlock = new GlueBlock().setBlockName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab);
TinkerSmeltery.smeltery = new SmelteryBlock().setBlockName("Smeltery");
TinkerSmeltery.smelteryNether = new SmelteryBlock("nether").setBlockName("Smeltery");
TinkerSmeltery.lavaTank = new LavaTankBlock().setBlockName("LavaTank");
TinkerSmeltery.lavaTank.setStepSound(Block.soundTypeGlass);
TinkerSmeltery.lavaTankNether = new LavaTankBlock("nether").setStepSound(Block.soundTypeGlass).setBlockName("LavaTank");
TinkerSmeltery.searedBlock = new SearedBlock().setBlockName("SearedBlock");
TinkerSmeltery.searedBlockNether = new SearedBlock("nether").setBlockName("SearedBlock");
TinkerSmeltery.castingChannel = (new CastingChannelBlock()).setBlockName("CastingChannel");
TinkerSmeltery.liquidMetal = new MaterialLiquid(MapColor.tntColor);
TinkerSmeltery.moltenIronFluid = registerFluid("iron");
TinkerSmeltery.moltenIron = TinkerSmeltery.moltenIronFluid.getBlock();
TinkerSmeltery.moltenGoldFluid = registerFluid("gold");
TinkerSmeltery.moltenGold = TinkerSmeltery.moltenGoldFluid.getBlock();
TinkerSmeltery.moltenCopperFluid = registerFluid("copper");
TinkerSmeltery.moltenCopper = TinkerSmeltery.moltenCopperFluid.getBlock();
TinkerSmeltery.moltenTinFluid = registerFluid("tin");
TinkerSmeltery.moltenTin = TinkerSmeltery.moltenTinFluid.getBlock();
TinkerSmeltery.moltenAluminumFluid = registerFluid("aluminum");
TinkerSmeltery.moltenAluminum = TinkerSmeltery.moltenAluminumFluid.getBlock();
TinkerSmeltery.moltenCobaltFluid = registerFluid("cobalt");
TinkerSmeltery.moltenCobalt = TinkerSmeltery.moltenCobaltFluid.getBlock();
TinkerSmeltery.moltenArditeFluid = registerFluid("ardite");
TinkerSmeltery.moltenArdite = TinkerSmeltery.moltenArditeFluid.getBlock();
TinkerSmeltery.moltenBronzeFluid = registerFluid("bronze");
TinkerSmeltery.moltenBronze = TinkerSmeltery.moltenBronzeFluid.getBlock();
TinkerSmeltery.moltenAlubrassFluid = registerFluid("aluminiumbrass", "aluminiumbrass.molten", "fluid.molten.alubrass", "liquid_alubrass", 3000, 6000, 1300, Material.lava);
TinkerSmeltery.moltenAlubrass = TinkerSmeltery.moltenAlubrassFluid.getBlock();
TinkerSmeltery.moltenManyullynFluid = registerFluid("manyullyn");
TinkerSmeltery.moltenManyullyn = TinkerSmeltery.moltenManyullynFluid.getBlock();
TinkerSmeltery.moltenAlumiteFluid = registerFluid("alumite");
TinkerSmeltery.moltenAlumite = TinkerSmeltery.moltenAlumiteFluid.getBlock();
TinkerSmeltery.moltenObsidianFluid = registerFluid("obsidian");
TinkerSmeltery.moltenObsidian = TinkerSmeltery.moltenObsidianFluid.getBlock();
TinkerSmeltery.moltenSteelFluid = registerFluid("steel");
TinkerSmeltery.moltenSteel = TinkerSmeltery.moltenSteelFluid.getBlock();
TinkerSmeltery.moltenGlassFluid = registerFluid("glass");
TinkerSmeltery.moltenGlass = TinkerSmeltery.moltenGlassFluid.getBlock();
TinkerSmeltery.moltenStoneFluid = registerFluid("stone", "stone.seared", "molten.stone", "liquid_stone", 3000, 6000, 1300, Material.lava);
TinkerSmeltery.moltenStone = TinkerSmeltery.moltenStoneFluid.getBlock();
TinkerSmeltery.moltenEmeraldFluid = registerFluid("emerald", "emerald.liquid", "molten.emerald", "liquid_villager", 3000, 6000, 1300, Material.lava);
TinkerSmeltery.moltenEmerald = TinkerSmeltery.moltenEmeraldFluid.getBlock();
TinkerSmeltery.moltenNickelFluid = registerFluid("nickel", "liquid_ferrous");
TinkerSmeltery.moltenNickel = TinkerSmeltery.moltenNickelFluid.getBlock();
TinkerSmeltery.moltenLeadFluid = registerFluid("lead");
TinkerSmeltery.moltenLead = TinkerSmeltery.moltenLeadFluid.getBlock();
TinkerSmeltery.moltenSilverFluid = registerFluid("silver");
TinkerSmeltery.moltenSilver = TinkerSmeltery.moltenSilverFluid.getBlock();
TinkerSmeltery.moltenShinyFluid = registerFluid("platinum", "platinum.molten", "fluid.molten.shiny", "liquid_shiny", 3000, 6000, 1300, Material.lava);
TinkerSmeltery.moltenShiny = TinkerSmeltery.moltenShinyFluid.getBlock();
TinkerSmeltery.moltenInvarFluid = registerFluid("invar");
TinkerSmeltery.moltenInvar = TinkerSmeltery.moltenInvarFluid.getBlock();
TinkerSmeltery.moltenElectrumFluid = registerFluid("electrum");
TinkerSmeltery.moltenElectrum = TinkerSmeltery.moltenElectrumFluid.getBlock();
TinkerSmeltery.moltenEnderFluid = registerFluid("ender", "ender", "fluid.ender", "liquid_ender", 3000, 6000, 295, Material.water);
TinkerSmeltery.moltenEnder = TinkerSmeltery.moltenEnderFluid.getBlock();
TinkerSmeltery.moltenLumiumFluid = registerFluid("lumium");
TinkerSmeltery.moltenLumium = TinkerSmeltery.moltenLumiumFluid.getBlock();
TinkerSmeltery.moltenSignalumFluid = registerFluid("signalum");
TinkerSmeltery.moltenSignalum = TinkerSmeltery.moltenSignalumFluid.getBlock();
TinkerSmeltery.moltenMithrilFluid = registerFluid("mithril");
TinkerSmeltery.moltenMithril = TinkerSmeltery.moltenMithrilFluid.getBlock();
TinkerSmeltery.moltenEnderiumFluid = registerFluid("enderium");
TinkerSmeltery.moltenEnderium = TinkerSmeltery.moltenEnderiumFluid.getBlock();
TinkerSmeltery.bloodFluid = new Fluid("blood").setDensity(3000).setViscosity(6000).setTemperature(1300);
boolean isBloodPreReg = !FluidRegistry.registerFluid(TinkerSmeltery.bloodFluid);
TinkerSmeltery.blood = new BloodBlock(TinkerSmeltery.bloodFluid, Material.water, "liquid_cow").setBlockName("liquid.blood");
GameRegistry.registerBlock(TinkerSmeltery.blood, "liquid.blood");
if (isBloodPreReg)
{
TinkerSmeltery.bloodFluid = FluidRegistry.getFluid("blood");
Block regBloodBlock = TinkerSmeltery.bloodFluid.getBlock();
if (regBloodBlock != null)
{
((TConstructFluid) TinkerSmeltery.blood).suppressOverwritingFluidIcons();
TinkerSmeltery.blood = regBloodBlock;
}
else
TinkerSmeltery.bloodFluid.setBlock(TinkerSmeltery.blood);
}
if (FluidContainerRegistry.fillFluidContainer(new FluidStack(TinkerSmeltery.bloodFluid, 1000), new ItemStack(Items.bucket)) == null)
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.bloodFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 16), new ItemStack(Items.bucket)));
TinkerSmeltery.glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200);
boolean isGluePreReg = !FluidRegistry.registerFluid(TinkerSmeltery.glueFluid);
TinkerSmeltery.glueFluidBlock = new GlueFluid(TinkerSmeltery.glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TinkerWorld.slimeStep).setBlockName("liquid.glue");
GameRegistry.registerBlock(TinkerSmeltery.glueFluidBlock, "liquid.glue");
if (isGluePreReg)
{
TinkerSmeltery.glueFluid = FluidRegistry.getFluid("glue");
Block regGlueFluidBlock = TinkerSmeltery.glueFluid.getBlock();
if (regGlueFluidBlock != null)
{
((GlueFluid) TinkerSmeltery.glueFluidBlock).suppressOverwritingFluidIcons();
TinkerSmeltery.glueFluidBlock = regGlueFluidBlock;
}
else
TinkerSmeltery.glueFluid.setBlock(TinkerSmeltery.glueFluidBlock);
}
if (FluidContainerRegistry.fillFluidContainer(new FluidStack(TinkerSmeltery.glueFluid, 1000), new ItemStack(Items.bucket)) == null)
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.glueFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 25), new ItemStack(Items.bucket)));
TinkerSmeltery.pigIronFluid = new Fluid("pigiron.molten").setDensity(3000).setViscosity(6000).setTemperature(1300);
boolean isPigIronPreReg = !FluidRegistry.registerFluid(TinkerSmeltery.pigIronFluid);
TinkerSmeltery.pigIronFluidBlock = new PigIronMoltenBlock(pigIronFluid, Material.water, "liquid_pigiron").setBlockName("fluid.molten.pigiron");
GameRegistry.registerBlock(TinkerSmeltery.pigIronFluidBlock, "fluid.molten.pigiron");
if (isPigIronPreReg)
{
TinkerSmeltery.pigIronFluid = FluidRegistry.getFluid("pigiron.molten");
Block regPigIronFluid = TinkerSmeltery.pigIronFluid.getBlock();
if (regPigIronFluid != null)
{
((PigIronMoltenBlock) TinkerSmeltery.pigIronFluidBlock).suppressOverwritingFluidIcons();
TinkerSmeltery.pigIronFluidBlock = regPigIronFluid;
}
else
TinkerSmeltery.pigIronFluid.setBlock(TinkerSmeltery.pigIronFluidBlock);
}
if (FluidContainerRegistry.fillFluidContainer(new FluidStack(TinkerSmeltery.pigIronFluid, 1000), new ItemStack(Items.bucket)) == null)
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.pigIronFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 26), new ItemStack(Items.bucket)));
if (FluidContainerRegistry.fillFluidContainer(new FluidStack(TinkerWorld.blueSlimeFluid, 1000), new ItemStack(Items.bucket)) == null)
FluidContainerRegistry.registerFluidContainer(new FluidContainerRegistry.FluidContainerData(new FluidStack(TinkerWorld.blueSlimeFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 24), new ItemStack(Items.bucket)));
TinkerSmeltery.fluids = new Fluid[] { TinkerSmeltery.moltenIronFluid, TinkerSmeltery.moltenGoldFluid, TinkerSmeltery.moltenCopperFluid, TinkerSmeltery.moltenTinFluid, TinkerSmeltery.moltenAluminumFluid, TinkerSmeltery.moltenCobaltFluid, TinkerSmeltery.moltenArditeFluid, TinkerSmeltery.moltenBronzeFluid, TinkerSmeltery.moltenAlubrassFluid, TinkerSmeltery.moltenManyullynFluid, TinkerSmeltery.moltenAlumiteFluid, TinkerSmeltery.moltenObsidianFluid, TinkerSmeltery.moltenSteelFluid, TinkerSmeltery.moltenGlassFluid, TinkerSmeltery.moltenStoneFluid, TinkerSmeltery.moltenEmeraldFluid, TinkerSmeltery.bloodFluid, TinkerSmeltery.moltenNickelFluid, TinkerSmeltery.moltenLeadFluid, TinkerSmeltery.moltenSilverFluid, TinkerSmeltery.moltenShinyFluid, TinkerSmeltery.moltenInvarFluid, TinkerSmeltery.moltenElectrumFluid, TinkerSmeltery.moltenEnderFluid, TinkerWorld.blueSlimeFluid, TinkerSmeltery.glueFluid, TinkerSmeltery.pigIronFluid };
TinkerSmeltery.fluidBlocks = new Block[] { TinkerSmeltery.moltenIron, TinkerSmeltery.moltenGold, TinkerSmeltery.moltenCopper, TinkerSmeltery.moltenTin, TinkerSmeltery.moltenAluminum, TinkerSmeltery.moltenCobalt, TinkerSmeltery.moltenArdite, TinkerSmeltery.moltenBronze, TinkerSmeltery.moltenAlubrass, TinkerSmeltery.moltenManyullyn, TinkerSmeltery.moltenAlumite, TinkerSmeltery.moltenObsidian, TinkerSmeltery.moltenSteel, TinkerSmeltery.moltenGlass, TinkerSmeltery.moltenStone, TinkerSmeltery.moltenEmerald, TinkerSmeltery.blood, TinkerSmeltery.moltenNickel, TinkerSmeltery.moltenLead, TinkerSmeltery.moltenSilver, TinkerSmeltery.moltenShiny, TinkerSmeltery.moltenInvar, TinkerSmeltery.moltenElectrum, TinkerSmeltery.moltenEnder, TinkerWorld.slimePool, TinkerSmeltery.glueFluidBlock, TinkerSmeltery.pigIronFluidBlock };
FluidType.registerFluidType("Water", Blocks.snow, 0, 20, FluidRegistry.getFluid("water"), false);
FluidType.registerFluidType("Iron", Blocks.iron_block, 0, 600, TinkerSmeltery.moltenIronFluid, true);
FluidType.registerFluidType("Gold", Blocks.gold_block, 0, 400, TinkerSmeltery.moltenGoldFluid, false);
FluidType.registerFluidType("Tin", TinkerWorld.metalBlock, 5, 400, TinkerSmeltery.moltenTinFluid, false);
FluidType.registerFluidType("Copper", TinkerWorld.metalBlock, 3, 550, TinkerSmeltery.moltenCopperFluid, true);
FluidType.registerFluidType("Aluminum", TinkerWorld.metalBlock, 6, 350, TinkerSmeltery.moltenAluminumFluid, false);
FluidType.registerFluidType("NaturalAluminum", TinkerWorld.oreSlag, 6, 350, TinkerSmeltery.moltenAluminumFluid, false);
FluidType.registerFluidType("Cobalt", TinkerWorld.metalBlock, 0, 650, TinkerSmeltery.moltenCobaltFluid, true);
FluidType.registerFluidType("Ardite", TinkerWorld.metalBlock, 1, 650, TinkerSmeltery.moltenArditeFluid, true);
FluidType.registerFluidType("AluminumBrass", TinkerWorld.metalBlock, 7, 350, TinkerSmeltery.moltenAlubrassFluid, false);
FluidType.registerFluidType("Alumite", TinkerWorld.metalBlock, 8, 800, TinkerSmeltery.moltenAlumiteFluid, true);
FluidType.registerFluidType("Manyullyn", TinkerWorld.metalBlock, 2, 750, TinkerSmeltery.moltenManyullynFluid, true);
FluidType.registerFluidType("Bronze", TinkerWorld.metalBlock, 4, 500, TinkerSmeltery.moltenBronzeFluid, true);
FluidType.registerFluidType("Steel", TinkerWorld.metalBlock, 9, 700, TinkerSmeltery.moltenSteelFluid, true);
FluidType.registerFluidType("Obsidian", Blocks.obsidian, 0, 750, TinkerSmeltery.moltenObsidianFluid, true);
FluidType.registerFluidType("Ender", TinkerWorld.metalBlock, 10, 500, TinkerSmeltery.moltenEnderFluid, false);
FluidType.registerFluidType("Glass", Blocks.sand, 0, 625, TinkerSmeltery.moltenGlassFluid, false);
FluidType.registerFluidType("Stone", Blocks.stone, 0, 800, TinkerSmeltery.moltenStoneFluid, true);
FluidType.registerFluidType("Emerald", Blocks.emerald_block, 0, 575, TinkerSmeltery.moltenEmeraldFluid, false);
FluidType.registerFluidType("PigIron", TinkerWorld.meatBlock, 0, 610, TinkerSmeltery.pigIronFluid, true);
FluidType.registerFluidType("Glue", TinkerSmeltery.glueBlock, 0, 125, TinkerSmeltery.glueFluid, false);
TinkerSmeltery.speedBlock = new SpeedBlock().setBlockName("SpeedBlock");
TinkerSmeltery.clearGlass = new GlassBlockConnected("clear", false).setBlockName("GlassBlock");
TinkerSmeltery.clearGlass.stepSound = Block.soundTypeGlass;
TinkerSmeltery.glassPane = new GlassPaneConnected("clear", false);
TinkerSmeltery.stainedGlassClear = new GlassBlockConnectedMeta("stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black").setBlockName("GlassBlock.StainedClear");
TinkerSmeltery.stainedGlassClear.stepSound = Block.soundTypeGlass;
TinkerSmeltery.stainedGlassClearPane = new GlassPaneStained();
GameRegistry.registerBlock(TinkerSmeltery.searedSlab, SearedSlabItem.class, "SearedSlab");
GameRegistry.registerBlock(TinkerSmeltery.speedSlab, SpeedSlabItem.class, "SpeedSlab");
GameRegistry.registerBlock(TinkerSmeltery.glueBlock, "GlueBlock");
OreDictionary.registerOre("blockRubber", new ItemStack(TinkerSmeltery.glueBlock));
GameRegistry.registerBlock(TinkerSmeltery.smeltery, SmelteryItemBlock.class, "Smeltery");
GameRegistry.registerBlock(TinkerSmeltery.smelteryNether, SmelteryItemBlock.class, "SmelteryNether");
GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain");
GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants");
GameRegistry.registerBlock(TinkerSmeltery.lavaTank, LavaTankItemBlock.class, "LavaTank");
GameRegistry.registerBlock(TinkerSmeltery.lavaTankNether, LavaTankItemBlock.class, "LavaTankNether");
GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank");
GameRegistry.registerBlock(TinkerSmeltery.searedBlock, SearedTableItemBlock.class, "SearedBlock");
GameRegistry.registerBlock(TinkerSmeltery.searedBlockNether, SearedTableItemBlock.class, "SearedBlockNether");
GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable");
GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet");
GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin");
GameRegistry.registerBlock(TinkerSmeltery.castingChannel, CastingChannelItem.class, "CastingChannel");
GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel");
GameRegistry.registerBlock(TinkerSmeltery.speedBlock, SpeedBlockItem.class, "SpeedBlock");
GameRegistry.registerBlock(TinkerSmeltery.clearGlass, GlassBlockItem.class, "GlassBlock");
GameRegistry.registerBlock(TinkerSmeltery.glassPane, GlassPaneItem.class, "GlassPane");
GameRegistry.registerBlock(TinkerSmeltery.stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear");
GameRegistry.registerBlock(TinkerSmeltery.stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained");
TinkerSmeltery.metalPattern = new MetalPattern("cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
GameRegistry.registerItem(TinkerSmeltery.metalPattern, "metalPattern");
TConstructRegistry.addItemToDirectory("metalPattern", TinkerSmeltery.metalPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead", "knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(TinkerSmeltery.metalPattern, 1, i));
}
oreRegistry();
}
| public void preInit (FMLPreInitializationEvent event)
{
TinkerSmelteryEvents smelteryEvents = new TinkerSmelteryEvents();
MinecraftForge.EVENT_BUS.register(smelteryEvents);
FMLCommonHandler.instance().bus().register(smelteryEvents);
TinkerSmeltery.buckets = new FilledBucket(BlockUtils.getBlockFromItem(TinkerSmeltery.buckets));
GameRegistry.registerItem(TinkerSmeltery.buckets, "buckets");
TinkerSmeltery.searedSlab = new SearedSlab().setBlockName("SearedSlab");
TinkerSmeltery.searedSlab.stepSound = Block.soundTypeStone;
TinkerSmeltery.speedSlab = new SpeedSlab().setBlockName("SpeedSlab");
TinkerSmeltery.speedSlab.stepSound = Block.soundTypeStone;
TinkerSmeltery.glueBlock = new GlueBlock().setBlockName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab);
TinkerSmeltery.smeltery = new SmelteryBlock().setBlockName("Smeltery");
TinkerSmeltery.smelteryNether = new SmelteryBlock("nether").setBlockName("Smeltery");
TinkerSmeltery.lavaTank = new LavaTankBlock().setBlockName("LavaTank");
TinkerSmeltery.lavaTank.setStepSound(Block.soundTypeGlass);
TinkerSmeltery.lavaTankNether = new LavaTankBlock("nether").setStepSound(Block.soundTypeGlass).setBlockName("LavaTank");
TinkerSmeltery.searedBlock = new SearedBlock().setBlockName("SearedBlock");
TinkerSmeltery.searedBlockNether = new SearedBlock("nether").setBlockName("SearedBlock");
TinkerSmeltery.castingChannel = (new CastingChannelBlock()).setBlockName("CastingChannel");
TinkerSmeltery.liquidMetal = new MaterialLiquid(MapColor.tntColor);
TinkerSmeltery.moltenIronFluid = registerFluid("iron");
TinkerSmeltery.moltenIron = TinkerSmeltery.moltenIronFluid.getBlock();
TinkerSmeltery.moltenGoldFluid = registerFluid("gold");
TinkerSmeltery.moltenGold = TinkerSmeltery.moltenGoldFluid.getBlock();
TinkerSmeltery.moltenCopperFluid = registerFluid("copper");
TinkerSmeltery.moltenCopper = TinkerSmeltery.moltenCopperFluid.getBlock();
TinkerSmeltery.moltenTinFluid = registerFluid("tin");
TinkerSmeltery.moltenTin = TinkerSmeltery.moltenTinFluid.getBlock();
TinkerSmeltery.moltenAluminumFluid = registerFluid("aluminum");
TinkerSmeltery.moltenAluminum = TinkerSmeltery.moltenAluminumFluid.getBlock();
TinkerSmeltery.moltenCobaltFluid = registerFluid("cobalt");
TinkerSmeltery.moltenCobalt = TinkerSmeltery.moltenCobaltFluid.getBlock();
TinkerSmeltery.moltenArditeFluid = registerFluid("ardite");
TinkerSmeltery.moltenArdite = TinkerSmeltery.moltenArditeFluid.getBlock();
TinkerSmeltery.moltenBronzeFluid = registerFluid("bronze");
TinkerSmeltery.moltenBronze = TinkerSmeltery.moltenBronzeFluid.getBlock();
TinkerSmeltery.moltenAlubrassFluid = registerFluid("aluminiumbrass", "aluminiumbrass.molten", "fluid.molten.alubrass", "liquid_alubrass", 3000, 6000, 1300, Material.lava);
TinkerSmeltery.moltenAlubrass = TinkerSmeltery.moltenAlubrassFluid.getBlock();
TinkerSmeltery.moltenManyullynFluid = registerFluid("manyullyn");
TinkerSmeltery.moltenManyullyn = TinkerSmeltery.moltenManyullynFluid.getBlock();
TinkerSmeltery.moltenAlumiteFluid = registerFluid("alumite");
TinkerSmeltery.moltenAlumite = TinkerSmeltery.moltenAlumiteFluid.getBlock();
TinkerSmeltery.moltenObsidianFluid = registerFluid("obsidian");
TinkerSmeltery.moltenObsidian = TinkerSmeltery.moltenObsidianFluid.getBlock();
TinkerSmeltery.moltenSteelFluid = registerFluid("steel");
TinkerSmeltery.moltenSteel = TinkerSmeltery.moltenSteelFluid.getBlock();
TinkerSmeltery.moltenGlassFluid = registerFluid("glass");
TinkerSmeltery.moltenGlass = TinkerSmeltery.moltenGlassFluid.getBlock();
TinkerSmeltery.moltenStoneFluid = registerFluid("stone", "stone.seared", "molten.stone", "liquid_stone", 3000, 6000, 1300, Material.lava);
TinkerSmeltery.moltenStone = TinkerSmeltery.moltenStoneFluid.getBlock();
TinkerSmeltery.moltenEmeraldFluid = registerFluid("emerald", "emerald.liquid", "molten.emerald", "liquid_villager", 3000, 6000, 1300, Material.lava);
TinkerSmeltery.moltenEmerald = TinkerSmeltery.moltenEmeraldFluid.getBlock();
TinkerSmeltery.moltenNickelFluid = registerFluid("nickel", "liquid_ferrous");
TinkerSmeltery.moltenNickel = TinkerSmeltery.moltenNickelFluid.getBlock();
TinkerSmeltery.moltenLeadFluid = registerFluid("lead");
TinkerSmeltery.moltenLead = TinkerSmeltery.moltenLeadFluid.getBlock();
TinkerSmeltery.moltenSilverFluid = registerFluid("silver");
TinkerSmeltery.moltenSilver = TinkerSmeltery.moltenSilverFluid.getBlock();
TinkerSmeltery.moltenShinyFluid = registerFluid("platinum", "platinum.molten", "fluid.molten.shiny", "liquid_shiny", 3000, 6000, 1300, Material.lava);
TinkerSmeltery.moltenShiny = TinkerSmeltery.moltenShinyFluid.getBlock();
TinkerSmeltery.moltenInvarFluid = registerFluid("invar");
TinkerSmeltery.moltenInvar = TinkerSmeltery.moltenInvarFluid.getBlock();
TinkerSmeltery.moltenElectrumFluid = registerFluid("electrum");
TinkerSmeltery.moltenElectrum = TinkerSmeltery.moltenElectrumFluid.getBlock();
TinkerSmeltery.moltenEnderFluid = registerFluid("ender", "ender", "fluid.ender", "liquid_ender", 3000, 6000, 295, Material.water);
TinkerSmeltery.moltenEnder = TinkerSmeltery.moltenEnderFluid.getBlock();
TinkerSmeltery.moltenLumiumFluid = registerFluid("lumium");
TinkerSmeltery.moltenLumium = TinkerSmeltery.moltenLumiumFluid.getBlock();
TinkerSmeltery.moltenSignalumFluid = registerFluid("signalum");
TinkerSmeltery.moltenSignalum = TinkerSmeltery.moltenSignalumFluid.getBlock();
TinkerSmeltery.moltenMithrilFluid = registerFluid("mithril");
TinkerSmeltery.moltenMithril = TinkerSmeltery.moltenMithrilFluid.getBlock();
TinkerSmeltery.moltenEnderiumFluid = registerFluid("enderium");
TinkerSmeltery.moltenEnderium = TinkerSmeltery.moltenEnderiumFluid.getBlock();
TinkerSmeltery.bloodFluid = new Fluid("blood").setDensity(3000).setViscosity(6000).setTemperature(1300);
boolean isBloodPreReg = !FluidRegistry.registerFluid(TinkerSmeltery.bloodFluid);
TinkerSmeltery.blood = new BloodBlock(TinkerSmeltery.bloodFluid, Material.water, "liquid_cow").setBlockName("liquid.blood");
GameRegistry.registerBlock(TinkerSmeltery.blood, "liquid.blood");
if (isBloodPreReg)
{
TinkerSmeltery.bloodFluid = FluidRegistry.getFluid("blood");
Block regBloodBlock = TinkerSmeltery.bloodFluid.getBlock();
if (regBloodBlock != null)
{
((TConstructFluid) TinkerSmeltery.blood).suppressOverwritingFluidIcons();
TinkerSmeltery.blood = regBloodBlock;
}
else
TinkerSmeltery.bloodFluid.setBlock(TinkerSmeltery.blood);
}
if (FluidContainerRegistry.fillFluidContainer(new FluidStack(TinkerSmeltery.bloodFluid, 1000), new ItemStack(Items.bucket)) == null)
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.bloodFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 16), new ItemStack(Items.bucket)));
TinkerSmeltery.glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200);
boolean isGluePreReg = !FluidRegistry.registerFluid(TinkerSmeltery.glueFluid);
TinkerSmeltery.glueFluidBlock = new GlueFluid(TinkerSmeltery.glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(TinkerWorld.slimeStep).setBlockName("liquid.glue");
GameRegistry.registerBlock(TinkerSmeltery.glueFluidBlock, "liquid.glue");
if (isGluePreReg)
{
TinkerSmeltery.glueFluid = FluidRegistry.getFluid("glue");
Block regGlueFluidBlock = TinkerSmeltery.glueFluid.getBlock();
if (regGlueFluidBlock != null)
{
((GlueFluid) TinkerSmeltery.glueFluidBlock).suppressOverwritingFluidIcons();
TinkerSmeltery.glueFluidBlock = regGlueFluidBlock;
}
else
TinkerSmeltery.glueFluid.setBlock(TinkerSmeltery.glueFluidBlock);
}
if (FluidContainerRegistry.fillFluidContainer(new FluidStack(TinkerSmeltery.glueFluid, 1000), new ItemStack(Items.bucket)) == null)
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.glueFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 25), new ItemStack(Items.bucket)));
TinkerSmeltery.pigIronFluid = new Fluid("pigiron.molten").setDensity(3000).setViscosity(6000).setTemperature(1300);
boolean isPigIronPreReg = !FluidRegistry.registerFluid(TinkerSmeltery.pigIronFluid);
TinkerSmeltery.pigIronFluidBlock = new PigIronMoltenBlock(pigIronFluid, Material.water, "liquid_pigiron").setBlockName("fluid.molten.pigiron");
GameRegistry.registerBlock(TinkerSmeltery.pigIronFluidBlock, "fluid.molten.pigiron");
if (isPigIronPreReg)
{
TinkerSmeltery.pigIronFluid = FluidRegistry.getFluid("pigiron.molten");
Block regPigIronFluid = TinkerSmeltery.pigIronFluid.getBlock();
if (regPigIronFluid != null)
{
((PigIronMoltenBlock) TinkerSmeltery.pigIronFluidBlock).suppressOverwritingFluidIcons();
TinkerSmeltery.pigIronFluidBlock = regPigIronFluid;
}
else
TinkerSmeltery.pigIronFluid.setBlock(TinkerSmeltery.pigIronFluidBlock);
}
if (FluidContainerRegistry.fillFluidContainer(new FluidStack(TinkerSmeltery.pigIronFluid, 1000), new ItemStack(Items.bucket)) == null)
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(TinkerSmeltery.pigIronFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 26), new ItemStack(Items.bucket)));
if (FluidContainerRegistry.fillFluidContainer(new FluidStack(TinkerWorld.blueSlimeFluid, 1000), new ItemStack(Items.bucket)) == null)
FluidContainerRegistry.registerFluidContainer(new FluidContainerRegistry.FluidContainerData(new FluidStack(TinkerWorld.blueSlimeFluid, 1000), new ItemStack(TinkerSmeltery.buckets, 1, 24), new ItemStack(Items.bucket)));
TinkerSmeltery.fluids = new Fluid[] { TinkerSmeltery.moltenIronFluid, TinkerSmeltery.moltenGoldFluid, TinkerSmeltery.moltenCopperFluid, TinkerSmeltery.moltenTinFluid, TinkerSmeltery.moltenAluminumFluid, TinkerSmeltery.moltenCobaltFluid, TinkerSmeltery.moltenArditeFluid, TinkerSmeltery.moltenBronzeFluid, TinkerSmeltery.moltenAlubrassFluid, TinkerSmeltery.moltenManyullynFluid, TinkerSmeltery.moltenAlumiteFluid, TinkerSmeltery.moltenObsidianFluid, TinkerSmeltery.moltenSteelFluid, TinkerSmeltery.moltenGlassFluid, TinkerSmeltery.moltenStoneFluid, TinkerSmeltery.moltenEmeraldFluid, TinkerSmeltery.bloodFluid, TinkerSmeltery.moltenNickelFluid, TinkerSmeltery.moltenLeadFluid, TinkerSmeltery.moltenSilverFluid, TinkerSmeltery.moltenShinyFluid, TinkerSmeltery.moltenInvarFluid, TinkerSmeltery.moltenElectrumFluid, TinkerSmeltery.moltenEnderFluid, TinkerWorld.blueSlimeFluid, TinkerSmeltery.glueFluid, TinkerSmeltery.pigIronFluid };
TinkerSmeltery.fluidBlocks = new Block[] { TinkerSmeltery.moltenIron, TinkerSmeltery.moltenGold, TinkerSmeltery.moltenCopper, TinkerSmeltery.moltenTin, TinkerSmeltery.moltenAluminum, TinkerSmeltery.moltenCobalt, TinkerSmeltery.moltenArdite, TinkerSmeltery.moltenBronze, TinkerSmeltery.moltenAlubrass, TinkerSmeltery.moltenManyullyn, TinkerSmeltery.moltenAlumite, TinkerSmeltery.moltenObsidian, TinkerSmeltery.moltenSteel, TinkerSmeltery.moltenGlass, TinkerSmeltery.moltenStone, TinkerSmeltery.moltenEmerald, TinkerSmeltery.blood, TinkerSmeltery.moltenNickel, TinkerSmeltery.moltenLead, TinkerSmeltery.moltenSilver, TinkerSmeltery.moltenShiny, TinkerSmeltery.moltenInvar, TinkerSmeltery.moltenElectrum, TinkerSmeltery.moltenEnder, TinkerWorld.slimePool, TinkerSmeltery.glueFluidBlock, TinkerSmeltery.pigIronFluidBlock, TinkerSmeltery.moltenLumium, TinkerSmeltery.moltenSignalum, TinkerSmeltery.moltenMithril, TinkerSmeltery.moltenEnderium};
FluidType.registerFluidType("Water", Blocks.snow, 0, 20, FluidRegistry.getFluid("water"), false);
FluidType.registerFluidType("Iron", Blocks.iron_block, 0, 600, TinkerSmeltery.moltenIronFluid, true);
FluidType.registerFluidType("Gold", Blocks.gold_block, 0, 400, TinkerSmeltery.moltenGoldFluid, false);
FluidType.registerFluidType("Tin", TinkerWorld.metalBlock, 5, 400, TinkerSmeltery.moltenTinFluid, false);
FluidType.registerFluidType("Copper", TinkerWorld.metalBlock, 3, 550, TinkerSmeltery.moltenCopperFluid, true);
FluidType.registerFluidType("Aluminum", TinkerWorld.metalBlock, 6, 350, TinkerSmeltery.moltenAluminumFluid, false);
FluidType.registerFluidType("NaturalAluminum", TinkerWorld.oreSlag, 6, 350, TinkerSmeltery.moltenAluminumFluid, false);
FluidType.registerFluidType("Cobalt", TinkerWorld.metalBlock, 0, 650, TinkerSmeltery.moltenCobaltFluid, true);
FluidType.registerFluidType("Ardite", TinkerWorld.metalBlock, 1, 650, TinkerSmeltery.moltenArditeFluid, true);
FluidType.registerFluidType("AluminumBrass", TinkerWorld.metalBlock, 7, 350, TinkerSmeltery.moltenAlubrassFluid, false);
FluidType.registerFluidType("Alumite", TinkerWorld.metalBlock, 8, 800, TinkerSmeltery.moltenAlumiteFluid, true);
FluidType.registerFluidType("Manyullyn", TinkerWorld.metalBlock, 2, 750, TinkerSmeltery.moltenManyullynFluid, true);
FluidType.registerFluidType("Bronze", TinkerWorld.metalBlock, 4, 500, TinkerSmeltery.moltenBronzeFluid, true);
FluidType.registerFluidType("Steel", TinkerWorld.metalBlock, 9, 700, TinkerSmeltery.moltenSteelFluid, true);
FluidType.registerFluidType("Obsidian", Blocks.obsidian, 0, 750, TinkerSmeltery.moltenObsidianFluid, true);
FluidType.registerFluidType("Ender", TinkerWorld.metalBlock, 10, 500, TinkerSmeltery.moltenEnderFluid, false);
FluidType.registerFluidType("Glass", Blocks.sand, 0, 625, TinkerSmeltery.moltenGlassFluid, false);
FluidType.registerFluidType("Stone", Blocks.stone, 0, 800, TinkerSmeltery.moltenStoneFluid, true);
FluidType.registerFluidType("Emerald", Blocks.emerald_block, 0, 575, TinkerSmeltery.moltenEmeraldFluid, false);
FluidType.registerFluidType("PigIron", TinkerWorld.meatBlock, 0, 610, TinkerSmeltery.pigIronFluid, true);
FluidType.registerFluidType("Glue", TinkerSmeltery.glueBlock, 0, 125, TinkerSmeltery.glueFluid, false);
TinkerSmeltery.speedBlock = new SpeedBlock().setBlockName("SpeedBlock");
TinkerSmeltery.clearGlass = new GlassBlockConnected("clear", false).setBlockName("GlassBlock");
TinkerSmeltery.clearGlass.stepSound = Block.soundTypeGlass;
TinkerSmeltery.glassPane = new GlassPaneConnected("clear", false);
TinkerSmeltery.stainedGlassClear = new GlassBlockConnectedMeta("stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black").setBlockName("GlassBlock.StainedClear");
TinkerSmeltery.stainedGlassClear.stepSound = Block.soundTypeGlass;
TinkerSmeltery.stainedGlassClearPane = new GlassPaneStained();
GameRegistry.registerBlock(TinkerSmeltery.searedSlab, SearedSlabItem.class, "SearedSlab");
GameRegistry.registerBlock(TinkerSmeltery.speedSlab, SpeedSlabItem.class, "SpeedSlab");
GameRegistry.registerBlock(TinkerSmeltery.glueBlock, "GlueBlock");
OreDictionary.registerOre("blockRubber", new ItemStack(TinkerSmeltery.glueBlock));
GameRegistry.registerBlock(TinkerSmeltery.smeltery, SmelteryItemBlock.class, "Smeltery");
GameRegistry.registerBlock(TinkerSmeltery.smelteryNether, SmelteryItemBlock.class, "SmelteryNether");
GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery");
GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain");
GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants");
GameRegistry.registerBlock(TinkerSmeltery.lavaTank, LavaTankItemBlock.class, "LavaTank");
GameRegistry.registerBlock(TinkerSmeltery.lavaTankNether, LavaTankItemBlock.class, "LavaTankNether");
GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank");
GameRegistry.registerBlock(TinkerSmeltery.searedBlock, SearedTableItemBlock.class, "SearedBlock");
GameRegistry.registerBlock(TinkerSmeltery.searedBlockNether, SearedTableItemBlock.class, "SearedBlockNether");
GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable");
GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet");
GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin");
GameRegistry.registerBlock(TinkerSmeltery.castingChannel, CastingChannelItem.class, "CastingChannel");
GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel");
GameRegistry.registerBlock(TinkerSmeltery.speedBlock, SpeedBlockItem.class, "SpeedBlock");
GameRegistry.registerBlock(TinkerSmeltery.clearGlass, GlassBlockItem.class, "GlassBlock");
GameRegistry.registerBlock(TinkerSmeltery.glassPane, GlassPaneItem.class, "GlassPane");
GameRegistry.registerBlock(TinkerSmeltery.stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear");
GameRegistry.registerBlock(TinkerSmeltery.stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained");
TinkerSmeltery.metalPattern = new MetalPattern("cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern");
GameRegistry.registerItem(TinkerSmeltery.metalPattern, "metalPattern");
TConstructRegistry.addItemToDirectory("metalPattern", TinkerSmeltery.metalPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead", "knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 0; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(TinkerSmeltery.metalPattern, 1, i));
}
oreRegistry();
}
|
public void conquer() {
HashSet<BigInteger> seen = new HashSet<BigInteger>();
BigInteger maxHash = game.lastHash();
BigInteger numPositionsInLevel = BigInteger.ZERO;
BigInteger numPositionsSeen = BigInteger.ZERO;
for (T s : game.startingPositions()) {
BigInteger hash = game.stateToHash(s);
seen.add(hash);
database.putRecord(hash, new Record(conf,game.primitiveValue(s)));
numPositionsInLevel = numPositionsInLevel.add(BigInteger.ONE);
}
int remoteness = 0;
Task solveTask = Task.beginTask(String.format("BFS solving \"%s\"", game.describe()));
solveTask.setTotal(maxHash);
solveTask.setProgress(0);
while (!numPositionsInLevel.equals(BigInteger.ZERO) && remoteness < maxRemoteness) {
numPositionsInLevel = BigInteger.ZERO;
for (BigInteger hash : Util.bigIntIterator(maxHash)) {
if (seen.contains(hash)) {
Record rec = database.getRecord(hash);
if (rec.get(RecordFields.Remoteness) == remoteness) {
for (Pair<String,T> child : game.validMoves(game.hashToState(hash))) {
BigInteger childhash = game.stateToHash(child.cdr);
if (!seen.contains(childhash)) {
Record childrec = new Record(conf, PrimitiveValue.Win);
childrec.set(RecordFields.Remoteness, remoteness + 1);
database.putRecord(childhash, childrec);
seen.add(childhash);
numPositionsInLevel = numPositionsInLevel.add(BigInteger.ONE);
numPositionsSeen = numPositionsSeen.add(BigInteger.ONE);
if(numPositionsSeen.remainder(BigInteger.valueOf(100000)).equals(BigInteger.ZERO))
solveTask.setProgress(numPositionsSeen);
}
}
}
}
}
remoteness += 1;
Util.debug(DebugFacility.Solver, "Number of states at remoteness " + remoteness + ": " + numPositionsInLevel);
}
solveTask.complete();
Util.debug(DebugFacility.Solver, "Solving finished!!! Max remoteness is "+(remoteness-1)+". Total positions seen = "+numPositionsSeen);
}
| public void conquer() {
HashSet<BigInteger> seen = new HashSet<BigInteger>();
BigInteger maxHash = game.lastHash();
BigInteger numPositionsInLevel = BigInteger.ZERO;
for (T s : game.startingPositions()) {
BigInteger hash = game.stateToHash(s);
seen.add(hash);
database.putRecord(hash, new Record(conf,game.primitiveValue(s)));
numPositionsInLevel = numPositionsInLevel.add(BigInteger.ONE);
}
BigInteger numPositionsSeen = numPositionsInLevel;
int remoteness = 0;
Task solveTask = Task.beginTask(String.format("BFS solving \"%s\"", game.describe()));
solveTask.setTotal(maxHash);
solveTask.setProgress(0);
while (!numPositionsInLevel.equals(BigInteger.ZERO) && remoteness < maxRemoteness) {
Util.debug(DebugFacility.Solver, "Number of states at remoteness " + remoteness + ": " + numPositionsInLevel);
numPositionsInLevel = BigInteger.ZERO;
for (BigInteger hash : Util.bigIntIterator(maxHash)) {
if (seen.contains(hash)) {
Record rec = database.getRecord(hash);
if (rec.get(RecordFields.Remoteness) == remoteness) {
for (Pair<String,T> child : game.validMoves(game.hashToState(hash))) {
BigInteger childhash = game.stateToHash(child.cdr);
if (!seen.contains(childhash)) {
Record childrec = new Record(conf, PrimitiveValue.Win);
childrec.set(RecordFields.Remoteness, remoteness + 1);
database.putRecord(childhash, childrec);
seen.add(childhash);
numPositionsInLevel = numPositionsInLevel.add(BigInteger.ONE);
numPositionsSeen = numPositionsSeen.add(BigInteger.ONE);
if(numPositionsSeen.remainder(BigInteger.valueOf(100000)).equals(BigInteger.ZERO))
solveTask.setProgress(numPositionsSeen);
}
}
}
}
}
remoteness += 1;
}
solveTask.complete();
Util.debug(DebugFacility.Solver, "Solving finished!!! Max remoteness is "+(remoteness-1)+". Total positions seen = "+numPositionsSeen);
}
|
public Message speak(String body) throws CampfireException {
String type = (body.contains("\n")) ? "PasteMessage" : "TextMessage";
String url = Campfire.speakPath(id);
try {
body = new String(body.getBytes("UTF-8"), "ISO-8859-1");
String request = new JSONObject().put("message", new JSONObject().put("type", type).put("body", body)).toString();
HttpResponse response = new CampfireRequest(campfire).post(url, request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_CREATED) {
String responseBody = CampfireRequest.responseBody(response);
return new Message(new JSONObject(responseBody).getJSONObject("message"));
} else
throw new CampfireException("Campfire error, message was not sent.");
} catch(JSONException e) {
throw new CampfireException(e, "Couldn't create JSON object while speaking.");
} catch (DateParseException e) {
throw new CampfireException(e, "Couldn't parse date from created message while speaking.");
} catch (UnsupportedEncodingException e) {
throw new CampfireException(e, "Cannot convert from UTF-8 to ISO-8859-1");
}
}
| public Message speak(String body) throws CampfireException {
String type = (body.contains("\n")) ? "PasteMessage" : "TextMessage";
String url = Campfire.speakPath(id);
try {
body = new String(body.getBytes("UTF-8"), "ISO-8859-1");
String request = new JSONObject().put("message", new JSONObject().put("type", type).put("body", body)).toString();
HttpResponse response = new CampfireRequest(campfire).post(url, request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_CREATED) {
String responseBody = CampfireRequest.responseBody(response);
return new Message(new JSONObject(responseBody).getJSONObject("message"));
} else
throw new CampfireException("Campfire error, message was not sent.");
} catch(JSONException e) {
throw new CampfireException(e, "Couldn't create JSON object while speaking.");
} catch (DateParseException e) {
throw new CampfireException(e, "Couldn't parse date from created message while speaking.");
} catch (UnsupportedEncodingException e) {
throw new CampfireException(e, "Problem converting special characters for transmission.");
}
}
|
private void initialize () {
addListener(inputListener = new ClickListener() {
public void clicked (InputEvent event, float x, float y) {
if (getTapCount() > 1) setSelection(0, text.length());
}
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (!super.touchDown(event, x, y, pointer, button)) return false;
if (pointer == 0 && button != 0) return false;
if (disabled) return true;
keyboard.show(true);
clearSelection();
setCursorPosition(x);
selectionStart = cursor;
Stage stage = getStage();
if (stage != null) stage.setKeyboardFocus(TextField.this);
return true;
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
super.touchDragged(event, x, y, pointer);
lastBlink = 0;
cursorOn = false;
setCursorPosition(x);
hasSelection = true;
}
private void setCursorPosition (float x) {
lastBlink = 0;
cursorOn = false;
x -= renderOffset + textOffset;
for (int i = 0; i < glyphPositions.size; i++) {
if (glyphPositions.items[i] > x) {
cursor = Math.max(0, i - 1);
return;
}
}
cursor = Math.max(0, glyphPositions.size - 1);
}
public boolean keyDown (InputEvent event, int keycode) {
if (disabled) return false;
final BitmapFont font = style.font;
lastBlink = 0;
cursorOn = false;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
boolean repeat = false;
boolean ctrl = Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT);
if (ctrl) {
if (keycode == Keys.V) {
paste();
return true;
}
if (keycode == Keys.C || keycode == Keys.INSERT) {
copy();
return true;
}
if (keycode == Keys.X || keycode == Keys.DEL) {
cut();
return true;
}
}
if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) {
if (keycode == Keys.INSERT) paste();
if (keycode == Keys.FORWARD_DEL) {
if (hasSelection) {
copy();
delete();
}
}
if (keycode == Keys.LEFT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
while (--cursor > 0 && ctrl) {
char c = text.charAt(cursor);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.RIGHT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.HOME) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = 0;
}
if (keycode == Keys.END) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = text.length();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
} else {
if (keycode == Keys.LEFT) {
while (cursor-- > 1 && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.RIGHT) {
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.HOME) {
cursor = 0;
clearSelection();
}
if (keycode == Keys.END) {
cursor = text.length();
clearSelection();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
}
if (repeat && (!keyRepeatTask.isScheduled() || keyRepeatTask.keycode != keycode)) {
keyRepeatTask.keycode = keycode;
keyRepeatTask.cancel();
Timer.schedule(keyRepeatTask, keyRepeatInitialTime, keyRepeatTime);
}
return true;
}
return false;
}
public boolean keyUp (InputEvent event, int keycode) {
if (disabled) return false;
keyRepeatTask.cancel();
return true;
}
public boolean keyTyped (InputEvent event, char character) {
if (disabled) return false;
final BitmapFont font = style.font;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
if (character == BACKSPACE && (cursor > 0 || hasSelection)) {
if (!hasSelection) {
text = text.substring(0, cursor - 1) + text.substring(cursor);
updateDisplayText();
cursor--;
renderOffset = 0;
} else {
delete();
}
}
if (character == DELETE) {
if (cursor < text.length() || hasSelection) {
if (!hasSelection) {
text = text.substring(0, cursor) + text.substring(cursor + 1);
updateDisplayText();
} else {
delete();
}
}
return true;
}
if (character != ENTER_DESKTOP && character != ENTER_ANDROID) {
if (filter != null && !filter.acceptChar(TextField.this, character)) return true;
}
if ((character == TAB || character == ENTER_ANDROID) && focusTraversal)
next(Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT));
if (font.containsCharacter(character)) {
if (maxLength > 0 && text.length() + 1 > maxLength) {
return true;
}
if (!hasSelection) {
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
} else {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
cursor = minIndex;
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
clearSelection();
}
}
if (listener != null) listener.keyTyped(TextField.this, character);
return true;
} else
return false;
}
});
}
| private void initialize () {
addListener(inputListener = new ClickListener() {
public void clicked (InputEvent event, float x, float y) {
if (getTapCount() > 1) setSelection(0, text.length());
}
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (!super.touchDown(event, x, y, pointer, button)) return false;
if (pointer == 0 && button != 0) return false;
if (disabled) return true;
clearSelection();
setCursorPosition(x);
selectionStart = cursor;
Stage stage = getStage();
if (stage != null) stage.setKeyboardFocus(TextField.this);
keyboard.show(true);
return true;
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
super.touchDragged(event, x, y, pointer);
lastBlink = 0;
cursorOn = false;
setCursorPosition(x);
hasSelection = true;
}
private void setCursorPosition (float x) {
lastBlink = 0;
cursorOn = false;
x -= renderOffset + textOffset;
for (int i = 0; i < glyphPositions.size; i++) {
if (glyphPositions.items[i] > x) {
cursor = Math.max(0, i - 1);
return;
}
}
cursor = Math.max(0, glyphPositions.size - 1);
}
public boolean keyDown (InputEvent event, int keycode) {
if (disabled) return false;
final BitmapFont font = style.font;
lastBlink = 0;
cursorOn = false;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
boolean repeat = false;
boolean ctrl = Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT);
if (ctrl) {
if (keycode == Keys.V) {
paste();
return true;
}
if (keycode == Keys.C || keycode == Keys.INSERT) {
copy();
return true;
}
if (keycode == Keys.X || keycode == Keys.DEL) {
cut();
return true;
}
}
if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) {
if (keycode == Keys.INSERT) paste();
if (keycode == Keys.FORWARD_DEL) {
if (hasSelection) {
copy();
delete();
}
}
if (keycode == Keys.LEFT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
while (--cursor > 0 && ctrl) {
char c = text.charAt(cursor);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.RIGHT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.HOME) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = 0;
}
if (keycode == Keys.END) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = text.length();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
} else {
if (keycode == Keys.LEFT) {
while (cursor-- > 1 && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.RIGHT) {
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.HOME) {
cursor = 0;
clearSelection();
}
if (keycode == Keys.END) {
cursor = text.length();
clearSelection();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
}
if (repeat && (!keyRepeatTask.isScheduled() || keyRepeatTask.keycode != keycode)) {
keyRepeatTask.keycode = keycode;
keyRepeatTask.cancel();
Timer.schedule(keyRepeatTask, keyRepeatInitialTime, keyRepeatTime);
}
return true;
}
return false;
}
public boolean keyUp (InputEvent event, int keycode) {
if (disabled) return false;
keyRepeatTask.cancel();
return true;
}
public boolean keyTyped (InputEvent event, char character) {
if (disabled) return false;
final BitmapFont font = style.font;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
if (character == BACKSPACE && (cursor > 0 || hasSelection)) {
if (!hasSelection) {
text = text.substring(0, cursor - 1) + text.substring(cursor);
updateDisplayText();
cursor--;
renderOffset = 0;
} else {
delete();
}
}
if (character == DELETE) {
if (cursor < text.length() || hasSelection) {
if (!hasSelection) {
text = text.substring(0, cursor) + text.substring(cursor + 1);
updateDisplayText();
} else {
delete();
}
}
return true;
}
if (character != ENTER_DESKTOP && character != ENTER_ANDROID) {
if (filter != null && !filter.acceptChar(TextField.this, character)) return true;
}
if ((character == TAB || character == ENTER_ANDROID) && focusTraversal)
next(Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT));
if (font.containsCharacter(character)) {
if (maxLength > 0 && text.length() + 1 > maxLength) {
return true;
}
if (!hasSelection) {
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
} else {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
cursor = minIndex;
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
clearSelection();
}
}
if (listener != null) listener.keyTyped(TextField.this, character);
return true;
} else
return false;
}
});
}
|
protected void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "OnCreated called");
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
if (sharedPrefs.getBoolean("debug_logging", false))
{
LogSettings.DEBUG=true;
CommonLogSettings.DEBUG=true;
}
else
{
LogSettings.DEBUG=false;
CommonLogSettings.DEBUG=false;
}
BatteryStatsProxy stats = BatteryStatsProxy.getInstance(this);
if (stats.initFailed())
{
Toast.makeText(this, "The 'batteryinfo' service could not be accessed. If this error persists after a reboot please contact the dev and provide your ROM/Kernel versions.", Toast.LENGTH_SHORT).show();
}
String strLastRelease = sharedPrefs.getString("last_release", "0");
String strCurrentRelease = "";
try
{
PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
strCurrentRelease = Integer.toString(pinfo.versionCode);
}
catch (Exception e)
{
}
if (strLastRelease.equals("0"))
{
FirstLaunch.app_launched(this);
}
else if (!strLastRelease.equals(strCurrentRelease))
{
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putString("last_release", strCurrentRelease);
updater.commit();
boolean migrated = false;
if (!sharedPrefs.getString("default_stat_type", "0").startsWith("ref_"))
{
Log.i(TAG, "Migrating default_stat_type, value was " + sharedPrefs.getString("default_stat_type", "0"));
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
editor.commit();
migrated = true;
}
if (!sharedPrefs.getString("small_widget_default_stat_type", "0").startsWith("ref_"))
{
Log.i(TAG, "Migrating small_widget_default_stat_type, value was " + sharedPrefs.getString("small_widget_default_stat_type", "0"));
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("small_widget_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
editor.commit();
migrated = true;
}
if (!sharedPrefs.getString("widget_fallback_stat_type", "0").startsWith("ref_"))
{
Log.i(TAG, "Migrating widget_fallback_stat_type, value was " + sharedPrefs.getString("widget_fallback_stat_type", "0"));
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("widget_fallback_stat_type", Reference.UNPLUGGED_REF_FILENAME);
editor.commit();
migrated = true;
}
if (!sharedPrefs.getString("large_widget_default_stat_type", "0").startsWith("ref_"))
{
Log.i(TAG, "Migrating large_widget_default_stat_type, value was " + sharedPrefs.getString("large_widget_default_stat_type", "0"));
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("large_widget_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
editor.commit();
migrated = true;
}
if (migrated)
{
Log.i(TAG, "Some preferences were migrated");
Toast.makeText(this, "Upgrading data.", Toast.LENGTH_SHORT).show();
}
Intent intentReleaseNotes = new Intent(this, ReadmeActivity.class);
intentReleaseNotes.putExtra("filename", "readme.html");
this.startActivity(intentReleaseNotes);
}
else
{
boolean bWarningShown = sharedPrefs.getBoolean("analytics_opt_out", false);
boolean bAnalyticsEnabled = sharedPrefs.getBoolean("use_analytics", true);
if (bAnalyticsEnabled && !bWarningShown)
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("BetterBatteryStats makes use of Google Analytics to collect usage statitics. If you disagree or do not want to participate you can opt-out by disabling \"Google Analytics\" in the \"Advanced Preferences\"");
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(StatsActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("analytics_opt_out", true);
editor.commit();
}
});
alertbox.show();
}
else
{
AppRater.app_launched(this);
}
}
m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
if (!ReferenceStore.hasReferenceByName(m_refFromName, this))
{
if (sharedPrefs.getBoolean("fallback_to_since_boot", false))
{
m_refFromName = Reference.BOOT_REF_FILENAME;
Toast.makeText(this, "Fallback to 'Since Boot'", Toast.LENGTH_SHORT).show();
}
}
try
{
if ( (savedInstanceState != null) && (!savedInstanceState.isEmpty()))
{
m_iStat = (Integer) savedInstanceState.getSerializable("stat");
m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom");
m_refToName = (String) savedInstanceState.getSerializable("stattypeTo");
}
}
catch (Exception e)
{
m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
Log.e(TAG, "Exception: " + e.getMessage());
DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle");
DataStorage.LogToFile(LOGFILE, e.getMessage());
DataStorage.LogToFile(LOGFILE, e.getStackTrace());
Toast.makeText(this, "An error occured while recovering the previous state", Toast.LENGTH_SHORT).show();
}
Bundle extras = getIntent().getExtras();
if (extras != null)
{
m_iStat = extras.getInt(StatsActivity.STAT);
m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM);
m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO);
boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false);
if (bCalledFromNotification)
{
NotificationManager nM = (NotificationManager)getSystemService(Service.NOTIFICATION_SERVICE);
nM.cancel(EventWatcherService.NOTFICATION_ID);
}
}
TextView tvSince = (TextView) findViewById(R.id.TextViewSince);
if (tvSince != null)
{
Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this);
Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this);
long sinceMs = StatsProvider.getInstance(this).getSince(myReferenceFrom, myReferenceTo);
if (sinceMs != -1)
{
String sinceText = DateUtils.formatDuration(sinceMs);
boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true);
if (bShowBatteryLevels)
{
sinceText += " " + StatsProvider.getInstance(this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo);
}
tvSince.setText(sinceText);
Log.i(TAG, "Since " + sinceText);
}
else
{
tvSince.setText("n/a");
Log.i(TAG, "Since: n/a ");
}
}
Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);
ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(
this, R.array.stats, android.R.layout.simple_spinner_item);
spinnerStatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStat.setAdapter(spinnerStatAdapter);
spinnerStat.setSelection(m_iStat);
spinnerStat.setOnItemSelectedListener(this);
Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType);
m_spinnerFromAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
m_spinnerFromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStatType.setAdapter(m_spinnerFromAdapter);
try
{
this.setListViewAdapter();
}
catch (BatteryInfoUnavailableException e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
Toast.makeText(this,
"BatteryInfo Service could not be contacted.",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
Toast.makeText(this,
"An unhandled error occured. Please check your logcat",
Toast.LENGTH_LONG).show();
}
spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName));
spinnerStatType.setOnItemSelectedListener(this);
Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
m_spinnerToAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
m_spinnerToAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
boolean bShowSpinner = sharedPrefs.getBoolean("show_to_ref", true);
if (bShowSpinner)
{
spinnerStatSampleEnd.setVisibility(View.VISIBLE);
spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
if ((m_refToName != null) && !m_refToName.equals("") )
{
int pos = m_spinnerToAdapter.getPosition(m_refToName);
spinnerStatSampleEnd.setSelection(pos);
}
else
{
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
}
else
{
spinnerStatSampleEnd.setVisibility(View.GONE);
spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
spinnerStatSampleEnd.setOnItemSelectedListener(this);
String strOrderBy = sharedPrefs.getString("default_orderby", "0");
try
{
m_iSorting = Integer.valueOf(strOrderBy);
}
catch(Exception e)
{
m_iSorting = 0;
}
GoogleAnalytics.getInstance(this).trackStats(this, GoogleAnalytics.ACTIVITY_STATS, m_iStat, m_refFromName, m_refToName, m_iSorting);
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
ReferenceStore.logReferences(this);
}
| protected void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "OnCreated called");
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
if (sharedPrefs.getBoolean("debug_logging", false))
{
LogSettings.DEBUG=true;
CommonLogSettings.DEBUG=true;
}
else
{
LogSettings.DEBUG=false;
CommonLogSettings.DEBUG=false;
}
BatteryStatsProxy stats = BatteryStatsProxy.getInstance(this);
if (stats.initFailed())
{
Toast.makeText(this, "The 'batteryinfo' service could not be accessed. If this error persists after a reboot please contact the dev and provide your ROM/Kernel versions.", Toast.LENGTH_SHORT).show();
}
String strLastRelease = sharedPrefs.getString("last_release", "0");
String strCurrentRelease = "";
try
{
PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
strCurrentRelease = Integer.toString(pinfo.versionCode);
}
catch (Exception e)
{
}
if (strLastRelease.equals("0"))
{
FirstLaunch.app_launched(this);
}
else if (!strLastRelease.equals(strCurrentRelease))
{
SharedPreferences.Editor updater = sharedPrefs.edit();
updater.putString("last_release", strCurrentRelease);
updater.commit();
boolean migrated = false;
if (!sharedPrefs.getString("default_stat_type", "0").startsWith("ref_"))
{
Log.i(TAG, "Migrating default_stat_type, value was " + sharedPrefs.getString("default_stat_type", "0"));
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
editor.commit();
migrated = true;
}
if (!sharedPrefs.getString("small_widget_default_stat_type", "0").startsWith("ref_"))
{
Log.i(TAG, "Migrating small_widget_default_stat_type, value was " + sharedPrefs.getString("small_widget_default_stat_type", "0"));
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("small_widget_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
editor.commit();
migrated = true;
}
if (!sharedPrefs.getString("widget_fallback_stat_type", "0").startsWith("ref_"))
{
Log.i(TAG, "Migrating widget_fallback_stat_type, value was " + sharedPrefs.getString("widget_fallback_stat_type", "0"));
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("widget_fallback_stat_type", Reference.BOOT_REF_FILENAME);
editor.commit();
migrated = true;
}
if (!sharedPrefs.getString("large_widget_default_stat_type", "0").startsWith("ref_"))
{
Log.i(TAG, "Migrating large_widget_default_stat_type, value was " + sharedPrefs.getString("large_widget_default_stat_type", "0"));
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("large_widget_default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
editor.commit();
migrated = true;
}
if (migrated)
{
Log.i(TAG, "Some preferences were migrated");
Toast.makeText(this, "Upgrading data.", Toast.LENGTH_SHORT).show();
}
Intent intentReleaseNotes = new Intent(this, ReadmeActivity.class);
intentReleaseNotes.putExtra("filename", "readme.html");
this.startActivity(intentReleaseNotes);
}
else
{
boolean bWarningShown = sharedPrefs.getBoolean("analytics_opt_out", false);
boolean bAnalyticsEnabled = sharedPrefs.getBoolean("use_analytics", true);
if (bAnalyticsEnabled && !bWarningShown)
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("BetterBatteryStats makes use of Google Analytics to collect usage statitics. If you disagree or do not want to participate you can opt-out by disabling \"Google Analytics\" in the \"Advanced Preferences\"");
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(StatsActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("analytics_opt_out", true);
editor.commit();
}
});
alertbox.show();
}
else
{
AppRater.app_launched(this);
}
}
m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
if (!ReferenceStore.hasReferenceByName(m_refFromName, this))
{
if (sharedPrefs.getBoolean("fallback_to_since_boot", false))
{
m_refFromName = Reference.BOOT_REF_FILENAME;
Toast.makeText(this, "Fallback to 'Since Boot'", Toast.LENGTH_SHORT).show();
}
}
try
{
if ( (savedInstanceState != null) && (!savedInstanceState.isEmpty()))
{
m_iStat = (Integer) savedInstanceState.getSerializable("stat");
m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom");
m_refToName = (String) savedInstanceState.getSerializable("stattypeTo");
}
}
catch (Exception e)
{
m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);
Log.e(TAG, "Exception: " + e.getMessage());
DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle");
DataStorage.LogToFile(LOGFILE, e.getMessage());
DataStorage.LogToFile(LOGFILE, e.getStackTrace());
Toast.makeText(this, "An error occured while recovering the previous state", Toast.LENGTH_SHORT).show();
}
Bundle extras = getIntent().getExtras();
if (extras != null)
{
m_iStat = extras.getInt(StatsActivity.STAT);
m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM);
m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO);
boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false);
if (bCalledFromNotification)
{
NotificationManager nM = (NotificationManager)getSystemService(Service.NOTIFICATION_SERVICE);
nM.cancel(EventWatcherService.NOTFICATION_ID);
}
}
TextView tvSince = (TextView) findViewById(R.id.TextViewSince);
if (tvSince != null)
{
Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this);
Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this);
long sinceMs = StatsProvider.getInstance(this).getSince(myReferenceFrom, myReferenceTo);
if (sinceMs != -1)
{
String sinceText = DateUtils.formatDuration(sinceMs);
boolean bShowBatteryLevels = sharedPrefs.getBoolean("show_batt", true);
if (bShowBatteryLevels)
{
sinceText += " " + StatsProvider.getInstance(this).getBatteryLevelFromTo(myReferenceFrom, myReferenceTo);
}
tvSince.setText(sinceText);
Log.i(TAG, "Since " + sinceText);
}
else
{
tvSince.setText("n/a");
Log.i(TAG, "Since: n/a ");
}
}
Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);
ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(
this, R.array.stats, android.R.layout.simple_spinner_item);
spinnerStatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStat.setAdapter(spinnerStatAdapter);
spinnerStat.setSelection(m_iStat);
spinnerStat.setOnItemSelectedListener(this);
Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType);
m_spinnerFromAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
m_spinnerFromAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStatType.setAdapter(m_spinnerFromAdapter);
try
{
this.setListViewAdapter();
}
catch (BatteryInfoUnavailableException e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
Toast.makeText(this,
"BatteryInfo Service could not be contacted.",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
Toast.makeText(this,
"An unhandled error occured. Please check your logcat",
Toast.LENGTH_LONG).show();
}
spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName));
spinnerStatType.setOnItemSelectedListener(this);
Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
m_spinnerToAdapter = new ReferencesAdapter(this, android.R.layout.simple_spinner_item);
m_spinnerToAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
boolean bShowSpinner = sharedPrefs.getBoolean("show_to_ref", true);
if (bShowSpinner)
{
spinnerStatSampleEnd.setVisibility(View.VISIBLE);
spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
if ((m_refToName != null) && !m_refToName.equals("") )
{
int pos = m_spinnerToAdapter.getPosition(m_refToName);
spinnerStatSampleEnd.setSelection(pos);
}
else
{
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
}
else
{
spinnerStatSampleEnd.setVisibility(View.GONE);
spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
}
spinnerStatSampleEnd.setOnItemSelectedListener(this);
String strOrderBy = sharedPrefs.getString("default_orderby", "0");
try
{
m_iSorting = Integer.valueOf(strOrderBy);
}
catch(Exception e)
{
m_iSorting = 0;
}
GoogleAnalytics.getInstance(this).trackStats(this, GoogleAnalytics.ACTIVITY_STATS, m_iStat, m_refFromName, m_refToName, m_iSorting);
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
ReferenceStore.logReferences(this);
}
|
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String udim = request.getParameter("udim");
String vdim = request.getParameter("vdim");
boolean result = generateOneSystem.doesSystemAllReadyExist(udim, vdim);
SystemPlusSomeDetails systemPlusSomeDetails = null;
if(result){
systemPlusSomeDetails.setTheMessage(udim+":"+vdim+" already exists");
}
else{
generateOneSystem.generateSystem(udim, vdim);
SystemRep systemsRep = new MarshallSystems().getOneSystemRep(udim, vdim);
List<SystemRep> systemsRepList = new ArrayList<SystemRep>();
systemsRepList.add(systemsRep);
systemPlusSomeDetails = new MarshalSystemDetails().addClustersAndStars(systemsRepList).get(0);
systemPlusSomeDetails.setTheMessage(udim+":"+vdim+" generated");
}
ModelAndView modelAndView = new ModelAndView(new SystemDetailView());
modelAndView.addObject(SystemDetailView.JSON_ROOT,SystemSimpleArray.genSimpleArray(systemPlusSomeDetails));
return modelAndView;
}
| public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String udim = request.getParameter("udim");
String vdim = request.getParameter("vdim");
boolean result = generateOneSystem.doesSystemAllReadyExist(udim, vdim);
SystemPlusSomeDetails systemPlusSomeDetails = null;
if(result){
systemPlusSomeDetails = new SystemPlusSomeDetails();
systemPlusSomeDetails.setTheMessage(udim+":"+vdim+" already exists");
}
else{
generateOneSystem.generateSystem(udim, vdim);
SystemRep systemsRep = new MarshallSystems().getOneSystemRep(udim, vdim);
List<SystemRep> systemsRepList = new ArrayList<SystemRep>();
systemsRepList.add(systemsRep);
systemPlusSomeDetails = new MarshalSystemDetails().addClustersAndStars(systemsRepList).get(0);
systemPlusSomeDetails.setTheMessage(udim+":"+vdim+" generated");
}
ModelAndView modelAndView = new ModelAndView(new SystemDetailView());
modelAndView.addObject(SystemDetailView.JSON_ROOT,SystemSimpleArray.genSimpleArray(systemPlusSomeDetails));
return modelAndView;
}
|
public void start() {
frame = new JFrame(frameName);
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
JMenu fileMenu = new JMenu("File");
menubar.add(fileMenu);
final JMenuItem saveAs = new JMenuItem("Save As...");
saveAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FileDialog fileDialog = new FileDialog(frame);
fileDialog.setMode(FileDialog.SAVE);
fileDialog.show();
String outfiledir = fileDialog.getDirectory();
String outfilename = fileDialog.getFile();
if (outfilename != null) {
File outfile = new File(outfiledir, outfilename);
try {
save(outfile);
} catch (IOException ex) {
GlobalExceptionHandler.handle("Unable to save to "+outfile, ex);
}
}
}
});
JMenuItem save = new JMenuItem("Save");
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(getConfigFilename().startsWith("jar")){
saveAs.doClick();
}else{
File configFile = new File(getConfigFilename());
try {
save(configFile);
} catch (IOException ex) {
GlobalExceptionHandler.handle("Unable to save "+configFile, ex);
}
}
}
});
fileMenu.add(save);
fileMenu.add(saveAs);
fileMenu.addSeparator();
JMenuItem load = new JMenuItem("Open");
fileMenu.add(load);
load.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
FileDialog fileDialog = new FileDialog(frame, "Load a SOD config file");
fileDialog.setDirectory(".");
fileDialog.show();
String inFile = fileDialog.getFile();
if (inFile != null) {
try {
setConfigFile(inFile);
loadGUI();
} catch (Exception ex) {
GlobalExceptionHandler.handle("Unable to open "+inFile, ex);
}
}
}
});
JMenuItem loadTutorial = new JMenuItem("Open Tutorial");
loadTutorial.addActionListener(tutorialLoader);
fileMenu.add(loadTutorial);
JMenuItem loadWeed = new JMenuItem("Open WEED");
loadWeed.addActionListener(new FileLoader(configFileBase + "weed.xml"));
fileMenu.add(loadWeed);
fileMenu.addSeparator();
JMenuItem quit = new JMenuItem("Quit");
fileMenu.add(quit);
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
frame.getContentPane().setLayout(new BorderLayout());
loadGUI();
}
| public void start() {
frame = new JFrame(frameName);
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
JMenu fileMenu = new JMenu("File");
menubar.add(fileMenu);
final JMenuItem saveAs = new JMenuItem("Save As...");
saveAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FileDialog fileDialog = new FileDialog(frame);
fileDialog.setMode(FileDialog.SAVE);
fileDialog.show();
String outfiledir = fileDialog.getDirectory();
String outfilename = fileDialog.getFile();
if (outfilename != null) {
File outfile = new File(outfiledir, outfilename);
try {
save(outfile);
} catch (IOException ex) {
GlobalExceptionHandler.handle("Unable to save to "+outfile, ex);
}
}
}
});
JMenuItem save = new JMenuItem("Save");
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(getConfigFilename().startsWith("jar")){
saveAs.doClick();
}else{
File configFile = new File(getConfigFilename());
try {
save(configFile);
} catch (IOException ex) {
GlobalExceptionHandler.handle("Unable to save "+configFile, ex);
}
}
}
});
fileMenu.add(save);
fileMenu.add(saveAs);
fileMenu.addSeparator();
JMenuItem load = new JMenuItem("Open");
fileMenu.add(load);
load.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
FileDialog fileDialog = new FileDialog(frame, "Load a SOD config file");
fileDialog.setDirectory(".");
fileDialog.show();
String infileDir = fileDialog.getDirectory();
String inFile = fileDialog.getFile();
if (inFile != null) {
try {
setConfigFile(infileDir + "/" + inFile);
loadGUI();
} catch (Exception ex) {
GlobalExceptionHandler.handle("Unable to open "+inFile, ex);
}
}
}
});
JMenuItem loadTutorial = new JMenuItem("Open Tutorial");
loadTutorial.addActionListener(tutorialLoader);
fileMenu.add(loadTutorial);
JMenuItem loadWeed = new JMenuItem("Open WEED");
loadWeed.addActionListener(new FileLoader(configFileBase + "weed.xml"));
fileMenu.add(loadWeed);
fileMenu.addSeparator();
JMenuItem quit = new JMenuItem("Quit");
fileMenu.add(quit);
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
frame.getContentPane().setLayout(new BorderLayout());
loadGUI();
}
|
public static String makeFileName(Event e) {
String name = e.getName() + e.getStartTime().toString();
return Integer.toString(name.hashCode());
}
| public static String makeFileName(Event e) {
String name = e.getName() + e.getStartTime().toString();
return "/" + Integer.toString(name.hashCode()) + ".html";
}
|
private ArrayBrowser( final CellGetter cg, final OrderedNDShape shape ) {
int ndim = shape.getNumDims();
final long[] dims = shape.getDims();
final long[] origin = shape.getOrigin();
DefaultTableCellRenderer hrend = new DefaultTableCellRenderer();
hrend.setFont( UIManager.getFont( "TableHeader.font" ) );
hrend.setBackground( UIManager.getColor( "TableHeader.background" ) );
hrend.setForeground( UIManager.getColor( "TableHeader.foreground" ) );
hrend.setHorizontalAlignment( SwingConstants.RIGHT );
final NumericCellRenderer crend =
new NumericCellRenderer( cg.getContentClass() );
crend.setBadValue( BAD_CELL );
crend.setCellFont( new Font( "Monospaced", Font.PLAIN,
crend.getFont().getSize() ) );
if ( ndim == 2 ) {
TableModel dataModel;
final int ncol = (int) dims[ 0 ];
final int nrow = (int) dims[ 1 ];
final long o0 = origin[ 0 ];
final long o1 = origin[ 1 ];
dataModel = new AbstractTableModel() {
public int getRowCount() {
return nrow;
}
public int getColumnCount() {
return ncol;
}
public Object getValueAt( int irow, int icol ) {
long p0 = o0 + ( (long) icol );
long p1 = o1 + ( (long) nrow - 1 - irow );
long[] pos = new long[] { p0, p1 };
int index = (int) shape.positionToOffset( pos );
return cg.getValueAt( index );
}
};
TableModel rowModel = new AbstractTableModel() {
public int getRowCount() {
return nrow;
}
public int getColumnCount() {
return 1;
}
public Object getValueAt( int irow, int icol ) {
return new Long( o1 + (long) nrow - 1 - irow ) + " ";
}
};
TableModel colModel = new AbstractTableModel() {
public int getRowCount() {
return 1;
}
public int getColumnCount() {
return ncol;
}
public Object getValueAt( int irow, int icol ) {
return new Long( o0 + (long) icol ) + " ";
}
};
JTable rowHead = new JTable( rowModel );
JTable colHead = new JTable( colModel );
JTable dataTab = new JTable( dataModel ) {
protected void configureEnclosingScrollPane() {
}
public TableCellRenderer getCellRenderer( int irow, int icol ) {
return crend;
}
};
setViewportView( dataTab );
setRowHeaderView( rowHead );
setColumnHeaderView( colHead );
Color bcol = Color.BLACK;
Border cb = BorderFactory.createMatteBorder( 0, 0, 2, 0, bcol );
colHead.setBorder( cb );
Border rb = BorderFactory.createMatteBorder( 0, 0, 0, 2, bcol );
rowHead.setBorder( rb );
JPanel box = new JPanel();
box.setBorder( BorderFactory
.createMatteBorder( 0, 0, 2, 2, bcol ) );
setCorner( UPPER_LEFT_CORNER, box );
rowHead.setDefaultRenderer( Object.class, hrend );
colHead.setDefaultRenderer( Object.class, hrend );
JTable[] tables = new JTable[] { dataTab, rowHead, colHead };
for ( int i = 0; i < tables.length; i++ ) {
JTable table = tables[ i ];
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
table.setTableHeader( null );
table.setPreferredScrollableViewportSize( table
.getPreferredSize() );
table.setColumnSelectionAllowed( false );
table.setRowSelectionAllowed( false );
}
int cwidth = crend.getCellWidth();
TableColumnModel dataTcm = dataTab.getColumnModel();
TableColumnModel colTcm = colHead.getColumnModel();
for ( int i = 0; i < ncol; i++ ) {
dataTcm.getColumn( i ).setPreferredWidth( cwidth );
colTcm.getColumn( i ).setPreferredWidth( cwidth );
}
int rwidth = 8 +
Math.max( StarJTable.getCellWidth( rowHead, 0, 0 ),
StarJTable.getCellWidth( rowHead, nrow - 1, 0 ) );
rowHead.getColumnModel().getColumn( 0 )
.setPreferredWidth( rwidth );
}
else {
final int nrow = (int) shape.getNumPixels();
final boolean alignRight =
( crend.getHorizontalAlignment() == SwingConstants.RIGHT );
TableModel dataModel = new AbstractTableModel() {
public int getRowCount() {
return nrow;
}
public int getColumnCount() {
return 2 + ( alignRight ? 1 : 0 );
}
public Object getValueAt( int irow, int icol ) {
if ( icol == 0 ) {
long[] pos = shape.offsetToPosition( (long) irow );
return NDShape.toString( pos ) + " ";
}
else if ( icol == 1 ) {
return cg.getValueAt( irow );
}
else {
return null;
}
}
};
JTable tab = new JTable( dataModel );
setViewportView( tab );
tab.setTableHeader( null );
tab.setShowVerticalLines( false );
TableColumnModel tcm = tab.getColumnModel();
TableColumn tcol0 = tcm.getColumn( 0 );
TableColumn tcol1 = tcm.getColumn( 1 );
tcol0.setCellRenderer( hrend );
tcol1.setCellRenderer( crend );
int w0 = Math.max( StarJTable.getCellWidth( tab, 0, 0 ),
StarJTable.getCellWidth( tab, nrow - 1, 0 ) )
+ 8;
tcol0.setMinWidth( w0 );
tcol0.setMaxWidth( w0 );
tcol0.setPreferredWidth( w0 );
if ( alignRight ) {
int w1 = crend.getCellWidth() + 20;
tcol1.setMinWidth( w1 );
tcol1.setMaxWidth( w1 );
}
}
}
| private ArrayBrowser( final CellGetter cg, final OrderedNDShape shape ) {
int ndim = shape.getNumDims();
final long[] dims = shape.getDims();
final long[] origin = shape.getOrigin();
DefaultTableCellRenderer hrend = new DefaultTableCellRenderer();
hrend.setFont( UIManager.getFont( "TableHeader.font" ) );
hrend.setBackground( UIManager.getColor( "TableHeader.background" ) );
hrend.setForeground( UIManager.getColor( "TableHeader.foreground" ) );
hrend.setHorizontalAlignment( SwingConstants.RIGHT );
final NumericCellRenderer crend =
new NumericCellRenderer( cg.getContentClass() );
crend.setBadValue( BAD_CELL );
crend.setCellFont( new Font( "Monospaced", Font.PLAIN,
crend.getFont().getSize() ) );
if ( ndim == 2 ) {
TableModel dataModel;
final int ncol = (int) dims[ 0 ];
final int nrow = (int) dims[ 1 ];
final long o0 = origin[ 0 ];
final long o1 = origin[ 1 ];
dataModel = new AbstractTableModel() {
public int getRowCount() {
return nrow;
}
public int getColumnCount() {
return ncol;
}
public Object getValueAt( int irow, int icol ) {
long p0 = o0 + ( (long) icol );
long p1 = o1 + ( (long) nrow - 1 - irow );
long[] pos = new long[] { p0, p1 };
int index = (int) shape.positionToOffset( pos );
return cg.getValueAt( index );
}
};
TableModel rowModel = new AbstractTableModel() {
public int getRowCount() {
return nrow;
}
public int getColumnCount() {
return 1;
}
public Object getValueAt( int irow, int icol ) {
return new Long( o1 + (long) nrow - 1 - irow ) + " ";
}
};
TableModel colModel = new AbstractTableModel() {
public int getRowCount() {
return 1;
}
public int getColumnCount() {
return ncol;
}
public Object getValueAt( int irow, int icol ) {
return new Long( o0 + (long) icol ) + " ";
}
};
JTable rowHead = new JTable( rowModel );
JTable colHead = new JTable( colModel );
JTable dataTab = new JTable( dataModel ) {
protected void configureEnclosingScrollPane() {
}
public TableCellRenderer getCellRenderer( int irow, int icol ) {
return crend;
}
};
setViewportView( dataTab );
setRowHeaderView( rowHead );
setColumnHeaderView( colHead );
Color bcol = Color.BLACK;
Border cb = BorderFactory.createMatteBorder( 0, 0, 2, 0, bcol );
colHead.setBorder( cb );
Border rb = BorderFactory.createMatteBorder( 0, 0, 0, 2, bcol );
rowHead.setBorder( rb );
JPanel box = new JPanel();
box.setBorder( BorderFactory
.createMatteBorder( 0, 0, 2, 2, bcol ) );
setCorner( UPPER_LEFT_CORNER, box );
rowHead.setDefaultRenderer( Object.class, hrend );
colHead.setDefaultRenderer( Object.class, hrend );
JTable[] tables = new JTable[] { dataTab, rowHead, colHead };
for ( int i = 0; i < tables.length; i++ ) {
JTable table = tables[ i ];
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
table.setTableHeader( null );
table.setPreferredScrollableViewportSize( table
.getPreferredSize() );
table.setColumnSelectionAllowed( false );
table.setRowSelectionAllowed( false );
}
int cwidth = crend.getCellWidth();
TableColumnModel dataTcm = dataTab.getColumnModel();
TableColumnModel colTcm = colHead.getColumnModel();
for ( int i = 0; i < ncol; i++ ) {
dataTcm.getColumn( i ).setPreferredWidth( cwidth );
colTcm.getColumn( i ).setPreferredWidth( cwidth );
}
int rwidth = 8 +
Math.max( StarJTable.getCellWidth( rowHead, 0, 0 ),
StarJTable.getCellWidth( rowHead, nrow - 1, 0 ) );
rowHead.getColumnModel().getColumn( 0 ).setPreferredWidth( rwidth );
rowHead.getPreferredScrollableViewportSize().width = rwidth;
}
else {
final int nrow = (int) shape.getNumPixels();
final boolean alignRight =
( crend.getHorizontalAlignment() == SwingConstants.RIGHT );
TableModel dataModel = new AbstractTableModel() {
public int getRowCount() {
return nrow;
}
public int getColumnCount() {
return 2 + ( alignRight ? 1 : 0 );
}
public Object getValueAt( int irow, int icol ) {
if ( icol == 0 ) {
long[] pos = shape.offsetToPosition( (long) irow );
return NDShape.toString( pos ) + " ";
}
else if ( icol == 1 ) {
return cg.getValueAt( irow );
}
else {
return null;
}
}
};
JTable tab = new JTable( dataModel );
setViewportView( tab );
tab.setTableHeader( null );
tab.setShowVerticalLines( false );
TableColumnModel tcm = tab.getColumnModel();
TableColumn tcol0 = tcm.getColumn( 0 );
TableColumn tcol1 = tcm.getColumn( 1 );
tcol0.setCellRenderer( hrend );
tcol1.setCellRenderer( crend );
int w0 = Math.max( StarJTable.getCellWidth( tab, 0, 0 ),
StarJTable.getCellWidth( tab, nrow - 1, 0 ) )
+ 8;
tcol0.setMinWidth( w0 );
tcol0.setMaxWidth( w0 );
tcol0.setPreferredWidth( w0 );
if ( alignRight ) {
int w1 = crend.getCellWidth() + 20;
tcol1.setMinWidth( w1 );
tcol1.setMaxWidth( w1 );
}
}
}
|
private String formatHelpContext(IContext context) {
String locale = Platform.getNL();
StringBuffer sbuf = new StringBuffer();
sbuf.append("<form>");
sbuf.append("<p>");
sbuf.append(decodeContextBoldTags(context));
sbuf.append("</p>");
ICommandLink[] commands = null;
if (context instanceof IContext3) {
commands = ((IContext3)context).getRelatedCommands();
}
String category = new String();
if (commands != null && commands.length > 0) {
for (int i=0;i<commands.length;++i) {
if (!UAContentFilter.isFiltered(commands[i], HelpEvaluationContext.getContext())) {
if (category != null) {
addCategory(sbuf, null);
}
category = null;
sbuf.append("<li style=\"image\" value=\"");
sbuf.append(IHelpUIConstants.IMAGE_COMMAND_F1TOPIC);
sbuf.append("\" indent=\"21\">");
sbuf.append("<a href=\"command://");
sbuf.append(commands[i].getSerialization());
sbuf.append("\">");
sbuf.append(parent.escapeSpecialChars(commands[i].getLabel()));
sbuf.append("</a>");
sbuf.append("</li>");
}
}
}
IHelpResource[] links = context.getRelatedTopics();
if (links != null && context instanceof IContext2) {
ContextHelpSorter sorter = new ContextHelpSorter((IContext2)context);
sorter.sort(null, links);
}
if (links != null && links.length > 0) {
for (int i = 0; i < links.length; i++) {
IHelpResource link = links[i];
if (!UAContentFilter.isFiltered(link, HelpEvaluationContext.getContext())) {
String cat = null;
if (context instanceof IContext2) {
cat = ((IContext2)context).getCategory(link);
}
if (cat == null && category != null || cat != null
&& category == null || cat != null
&& category != null && !cat.equals(category)) {
addCategory(sbuf, cat);
}
category = cat;
sbuf.append("<li style=\"image\" value=\"");
sbuf.append(IHelpUIConstants.IMAGE_FILE_F1TOPIC);
sbuf.append("\" indent=\"21\">");
sbuf.append("<a href=\"");
sbuf.append(link.getHref());
String tcat = getTopicCategory(link.getHref(), locale);
if (tcat != null && !Platform.getWS().equals(Platform.WS_GTK)) {
sbuf.append("\" alt=\"");
sbuf.append(tcat);
}
sbuf.append("\">");
sbuf.append(parent.escapeSpecialChars(link.getLabel()));
sbuf.append("</a>");
sbuf.append("</li>");
}
}
}
sbuf.append("</form>");
return sbuf.toString();
}
| private String formatHelpContext(IContext context) {
String locale = Platform.getNL();
StringBuffer sbuf = new StringBuffer();
sbuf.append("<form>");
sbuf.append("<p>");
sbuf.append(decodeContextBoldTags(context));
sbuf.append("</p>");
ICommandLink[] commands = null;
if (context instanceof IContext3) {
commands = ((IContext3)context).getRelatedCommands();
}
String category = new String();
if (commands != null && commands.length > 0) {
for (int i=0;i<commands.length;++i) {
if (!UAContentFilter.isFiltered(commands[i], HelpEvaluationContext.getContext())) {
if (category != null) {
addCategory(sbuf, null);
}
category = null;
sbuf.append("<li style=\"image\" value=\"");
sbuf.append(IHelpUIConstants.IMAGE_COMMAND_F1TOPIC);
sbuf.append("\" indent=\"21\">");
sbuf.append("<a href=\"command://");
sbuf.append(commands[i].getSerialization());
sbuf.append("\">");
sbuf.append(parent.escapeSpecialChars(commands[i].getLabel()));
sbuf.append("</a>");
sbuf.append("</li>");
}
}
}
IHelpResource[] links = context.getRelatedTopics();
if (links != null && context instanceof IContext2) {
ContextHelpSorter sorter = new ContextHelpSorter((IContext2)context);
sorter.sort(null, links);
}
if (links != null && links.length > 0) {
for (int i = 0; i < links.length; i++) {
IHelpResource link = links[i];
if (!UAContentFilter.isFiltered(link, HelpEvaluationContext.getContext())) {
String cat = null;
if (context instanceof IContext2) {
cat = ((IContext2)context).getCategory(link);
}
if (cat == null && category != null || cat != null
&& category == null || cat != null
&& category != null && !cat.equals(category)) {
addCategory(sbuf, cat);
}
category = cat;
sbuf.append("<li style=\"image\" value=\"");
sbuf.append(IHelpUIConstants.IMAGE_FILE_F1TOPIC);
sbuf.append("\" indent=\"21\">");
sbuf.append("<a href=\"");
sbuf.append(link.getHref());
String tcat = getTopicCategory(link.getHref(), locale);
if (tcat != null && !Platform.getWS().equals(Platform.WS_GTK)) {
sbuf.append("\" alt=\"");
sbuf.append(parent.escapeSpecialChars(tcat));
}
sbuf.append("\">");
sbuf.append(parent.escapeSpecialChars(link.getLabel()));
sbuf.append("</a>");
sbuf.append("</li>");
}
}
}
sbuf.append("</form>");
return sbuf.toString();
}
|
public static <T> String arrayToString(T[] array) {
StringBuffer buffer = new StringBuffer();
int index = 0;
buffer.append("[");
buffer.append(array[index].toString());
index++;
for (; index < array.length; index++) {
buffer.append(", ");
buffer.append(array[index].toString());
}
buffer.append("]");
return buffer.toString();
}
| public static <T> String arrayToString(T[] array) {
StringBuffer buffer = new StringBuffer();
int index = 0;
buffer.append("[");
buffer.append(array[index] == null ? "null" : array[index].toString());
index++;
for (; index < array.length; index++) {
buffer.append(", ");
buffer.append(array[index] == null ? "null" : array[index]
.toString());
}
buffer.append("]");
return buffer.toString();
}
|
public void createProject(IProject project, boolean defaults, boolean onFinish, IProgressMonitor monitor) throws CoreException {
try {
monitor.beginTask("", 100);
ICProjectDescriptionManager mngr = CoreModel.getDefault().getProjectDescriptionManager();
ICProjectDescription des = mngr.createProjectDescription(project, false, !onFinish);
ManagedBuildInfo info = ManagedBuildManager.createBuildInfo(project);
ManagedProject mProj = new ManagedProject(des);
info.setManagedProject(mProj);
cfgs = CfgHolder.unique(fConfigPage.getCfgItems(defaults));
cfgs = CfgHolder.reorder(cfgs);
for (int i=0; i<cfgs.length; i++) {
String s = (cfgs[i].getToolChain() == null) ? "0" : ((ToolChain)(cfgs[i].getToolChain())).getId();
Configuration cfg = new Configuration(mProj, (ToolChain)cfgs[i].getToolChain(), ManagedBuildManager.calculateChildId(s, null), cfgs[i].getName());
IBuilder bld = cfg.getEditableBuilder();
if (bld != null) {
if(bld.isInternalBuilder()){
IConfiguration prefCfg = ManagedBuildManager.getPreferenceConfiguration(false);
IBuilder prefBuilder = prefCfg.getBuilder();
cfg.changeBuilder(prefBuilder, ManagedBuildManager.calculateChildId(cfg.getId(), null), prefBuilder.getName());
bld = cfg.getEditableBuilder();
bld.setBuildPath(null);
}
bld.setManagedBuildOn(false);
} else {
System.out.println(UIMessages.getString("StdProjectTypeHandler.3"));
}
cfg.setArtifactName(removeSpaces(project.getName()));
CConfigurationData data = cfg.getConfigurationData();
des.createConfiguration(ManagedBuildManager.CFG_DATA_PROVIDER_ID, data);
}
mngr.setProjectDescription(project, des);
RemoteMakeNature.updateProjectDescription(project, RemoteMakeBuilder.REMOTE_MAKE_BUILDER_ID, new NullProgressMonitor());
URI projectLocation = project.getLocationURI();
String pathString = EFSExtensionManager.getDefault().getPathFromURI(projectLocation);
IPath buildPath = Path.fromPortableString(pathString);
IManagedBuildInfo mbsInfo = ManagedBuildManager.getBuildInfo(project);
mbsInfo.getDefaultConfiguration().getBuildData().setBuilderCWD(buildPath);
mbsInfo.setDirty(true);
ManagedBuildManager.saveBuildInfo(project, true);
doTemplatesPostProcess(project);
doCustom(project);
StorableEnvironment vars = EnvironmentVariableManager.fUserSupplier.getWorkspaceEnvironmentCopy();
vars.setAppendContributedEnvironment(false);
vars.setAppendEnvironment(false);
} finally {
monitor.done();
}
}
| public void createProject(IProject project, boolean defaults, boolean onFinish, IProgressMonitor monitor) throws CoreException {
try {
monitor.beginTask("", 100);
ICProjectDescriptionManager mngr = CoreModel.getDefault().getProjectDescriptionManager();
ICProjectDescription des = mngr.createProjectDescription(project, false, !onFinish);
ManagedBuildInfo info = ManagedBuildManager.createBuildInfo(project);
ManagedProject mProj = new ManagedProject(des);
info.setManagedProject(mProj);
cfgs = CfgHolder.unique(fConfigPage.getCfgItems(defaults));
cfgs = CfgHolder.reorder(cfgs);
for (int i=0; i<cfgs.length; i++) {
String s = (cfgs[i].getToolChain() == null) ? "0" : ((ToolChain)(cfgs[i].getToolChain())).getId();
Configuration cfg = new Configuration(mProj, (ToolChain)cfgs[i].getToolChain(), ManagedBuildManager.calculateChildId(s, null), cfgs[i].getName());
IBuilder bld = cfg.getEditableBuilder();
if (bld != null) {
if(bld.isInternalBuilder()){
IConfiguration prefCfg = ManagedBuildManager.getPreferenceConfiguration(false);
IBuilder prefBuilder = prefCfg.getBuilder();
cfg.changeBuilder(prefBuilder, ManagedBuildManager.calculateChildId(cfg.getId(), null), prefBuilder.getName());
bld = cfg.getEditableBuilder();
bld.setBuildPath(null);
}
bld.setManagedBuildOn(false);
} else {
System.out.println(UIMessages.getString("StdProjectTypeHandler.3"));
}
cfg.setArtifactName(removeSpaces(project.getName()));
CConfigurationData data = cfg.getConfigurationData();
des.createConfiguration(ManagedBuildManager.CFG_DATA_PROVIDER_ID, data);
}
mngr.setProjectDescription(project, des);
RemoteMakeNature.updateProjectDescription(project, RemoteMakeBuilder.REMOTE_MAKE_BUILDER_ID, new NullProgressMonitor());
URI projectLocation = project.getLocationURI();
String pathString = EFSExtensionManager.getDefault().getPathFromURI(projectLocation);
IPath buildPath = Path.fromPortableString(pathString);
IManagedBuildInfo mbsInfo = ManagedBuildManager.getBuildInfo(project);
mbsInfo.getDefaultConfiguration().getBuildData().setBuilderCWD(buildPath);
mbsInfo.setDirty(true);
ManagedBuildManager.saveBuildInfo(project, true);
doTemplatesPostProcess(project);
doCustom(project);
StorableEnvironment vars = EnvironmentVariableManager.fUserSupplier.getWorkspaceEnvironmentCopy();
vars.setAppendContributedEnvironment(false);
vars.setAppendEnvironment(false);
EnvironmentVariableManager.fUserSupplier.setWorkspaceEnvironment(vars);
} finally {
monitor.done();
}
}
|
public void conn(
@CliOption(key = { "host" }, mandatory = true, help = "The serengeti host with optional port number, e.g. hostname:port") final String hostName,
@CliOption(key = { "username" }, mandatory = false, help = "The serengeti user name") final String username,
@CliOption(key = { "password" }, mandatory = false, help = "The serengeti password") final String password) {
Map<String,String> loginInfo = new HashMap<String,String>();
loginInfo.put("username", username);
loginInfo.put("password", password);
try {
if (CommandsUtils.isBlank(username)) {
if(!prompt(Constants.CONNECT_ENTER_USER_NAME, PromptType.USER_NAME, loginInfo)){
return ;
}
}
if (CommandsUtils.isBlank(password)) {
if(!prompt(Constants.CONNECT_ENTER_PASSWORD, PromptType.PASSWORD, loginInfo)){
return ;
}
}
connect(hostName, loginInfo, 3);
} catch (Exception e) {
System.out.println();
printConnectionFailure(e.getMessage());
}
}
private static void printConnectionFailure(String message) {
System.out.println(Constants.OUTPUT_OBJECT_CONNECT + " "
+ Constants.OUTPUT_OP_RESULT_FAIL + " " + message);
}
private boolean connect(final String hostName, final Map<String,String> loginInfo, int count) throws Exception {
if (count <= 0) {
return false;
} else {
ConnectType connectType = conn.connect(hostName, loginInfo.get("username"), loginInfo.get("password"));
if (connectType == ConnectType.UNAUTHORIZATION) {
if (!prompt(Constants.CONNECT_ENTER_PASSWORD, PromptType.PASSWORD,
loginInfo)) {
return false;
} else {
count--;
connect(hostName, loginInfo, count);
}
}
}
return true;
}
private boolean prompt(String msg, PromptType promptType, Map<String,String> loginInfo) throws Exception {
int k = 0;
String enter = "";
while (k < 3) {
enter = readEnter(msg, promptType);
if (!CommandsUtils.isBlank(enter)) {
if (promptType == PromptType.USER_NAME) {
loginInfo.put("username", enter);
} else {
loginInfo.put("password", enter);
}
break;
} else {
StringBuilder warningMsg = new StringBuilder();
if (promptType == PromptType.USER_NAME) {
warningMsg.append(Constants.CONNECT_USER_NAME);
} else {
warningMsg.append(Constants.CONNECT_PASSWORD);
}
warningMsg.append(Constants.CONNECT_CAN_NOT_BE_NULL);
System.out.println(warningMsg.toString());
}
k++;
}
return k < 3;
}
private String readEnter(String msg,PromptType promptType) throws Exception {
String enter = "";
ConsoleReader reader = new ConsoleReader();
reader.setDefaultPrompt(msg);
if (promptType == PromptType.USER_NAME) {
enter = reader.readLine();
} else if (promptType == PromptType.PASSWORD) {
enter = reader.readLine(Character.valueOf('*'));
}
return enter;
}
}
| public void conn(
@CliOption(key = { "host" }, mandatory = true, help = "The serengeti host with optional port number, e.g. hostname:port") final String hostName,
@CliOption(key = { "username" }, mandatory = false, help = "The serengeti user name") final String username,
@CliOption(key = { "password" }, mandatory = false, help = "The serengeti password") final String password) {
Map<String,String> loginInfo = new HashMap<String,String>();
loginInfo.put("username", username);
loginInfo.put("password", password);
try {
if (CommandsUtils.isBlank(username)) {
if(!prompt(Constants.CONNECT_ENTER_USER_NAME, PromptType.USER_NAME, loginInfo)){
return ;
}
}
if (CommandsUtils.isBlank(password)) {
if(!prompt(Constants.CONNECT_ENTER_PASSWORD, PromptType.PASSWORD, loginInfo)){
return ;
}
}
connect(hostName, loginInfo, 3);
} catch (Exception e) {
System.out.println();
printConnectionFailure(e.getMessage());
}
}
private static void printConnectionFailure(String message) {
System.out.println(Constants.OUTPUT_OBJECT_CONNECT + " "
+ Constants.OUTPUT_OP_RESULT_FAIL + " " + message);
}
private boolean connect(final String hostName, final Map<String, String> loginInfo, int count) throws Exception {
if (count < 0) {
return false;
}
ConnectType connectType = conn.connect(hostName, loginInfo.get("username"), loginInfo.get("password"));
if (connectType == ConnectType.UNAUTHORIZATION) {
if (count == 0) {
return false;
}
if (!prompt(Constants.CONNECT_ENTER_PASSWORD, PromptType.PASSWORD, loginInfo)) {
return false;
} else {
count--;
connect(hostName, loginInfo, count);
}
}
return true;
}
private boolean prompt(String msg, PromptType promptType, Map<String,String> loginInfo) throws Exception {
int k = 0;
String enter = "";
while (k < 3) {
enter = readEnter(msg, promptType);
if (!CommandsUtils.isBlank(enter)) {
if (promptType == PromptType.USER_NAME) {
loginInfo.put("username", enter);
} else {
loginInfo.put("password", enter);
}
break;
} else {
StringBuilder warningMsg = new StringBuilder();
if (promptType == PromptType.USER_NAME) {
warningMsg.append(Constants.CONNECT_USER_NAME);
} else {
warningMsg.append(Constants.CONNECT_PASSWORD);
}
warningMsg.append(Constants.CONNECT_CAN_NOT_BE_NULL);
System.out.println(warningMsg.toString());
}
k++;
}
return k < 3;
}
private String readEnter(String msg,PromptType promptType) throws Exception {
String enter = "";
ConsoleReader reader = new ConsoleReader();
reader.setDefaultPrompt(msg);
if (promptType == PromptType.USER_NAME) {
enter = reader.readLine();
} else if (promptType == PromptType.PASSWORD) {
enter = reader.readLine(Character.valueOf('*'));
}
return enter;
}
}
|
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
if (request.getParameter("submit") != null) {
String user = request.getParameter("userName");
String pass = request.getParameter("password");
User u = new User();
try {
String connectionURL = "jdbc:derby://localhost:1527/sun-appserv-samples;create=true";
Connection conn = null;
ResultSet rs;
conn = DriverManager.getConnection(connectionURL);
Statement statement = conn.createStatement();
String sql = "SELECT * FROM Users WHERE userName='" + user
+ "' AND password='" + pass + "'";
rs = statement.executeQuery(sql);
rs.next();
if (rs.getString("userName").equals(user)
&& rs.getString("password").equals(pass)) {
if (!singletonBean.loggedUsers.isEmpty()) {
boolean logged = false;
for (User logU : singletonBean.loggedUsers) {
if (logU.getUsername().equals(user)
&& logU.getPassword().equals(pass))
logged = true;
}
if (logged) {
session.setAttribute("error",
"User is already logged in!");
response.sendRedirect("http://localhost:8080/Capstone/Login.jsp");
} else {
u.setUserid(rs.getInt("userID"));
u.setFirstname(rs.getString("firstName"));
u.setLastname(rs.getString("lastName"));
u.setAddress(rs.getString("address"));
u.setCity(rs.getString("city"));
u.setProvince(rs.getString("province"));
u.setPostal(rs.getString("postal"));
u.setPhone(rs.getString("phone"));
u.setFax(rs.getString("fax"));
u.setEmail(rs.getString("email"));
u.setUsername(rs.getString("userName"));
u.setPassword(rs.getString("password"));
u.setUsertype(rs.getString("userType"));
singletonBean.loggedUsers.add(u);
}
} else {
u.setUserid(rs.getInt("userID"));
u.setFirstname(rs.getString("firstName"));
u.setLastname(rs.getString("lastName"));
u.setAddress(rs.getString("address"));
u.setCity(rs.getString("city"));
u.setProvince(rs.getString("province"));
u.setPostal(rs.getString("postal"));
u.setPhone(rs.getString("phone"));
u.setFax(rs.getString("fax"));
u.setEmail(rs.getString("email"));
u.setUsername(rs.getString("userName"));
u.setPassword(rs.getString("password"));
u.setUsertype(rs.getString("userType"));
singletonBean.loggedUsers.add(u);
}
sql = "SELECT * FROM Vehicle";
rs = statement.executeQuery(sql);
ArrayList<Vehicle> vechList = new ArrayList<Vehicle>();
while (rs.next()) {
Vehicle v = new Vehicle();
v.setVechid(rs.getInt("vechID"));
v.setUserid(rs.getInt("userID"));
v.setCarClass(rs.getString("class"));
v.setCarYear(rs.getString("carYear"));
v.setMake(rs.getString("make"));
v.setModel(rs.getString("model"));
v.setColor(rs.getString("color"));
v.setVin(rs.getString("vin"));
v.setPlate(rs.getString("plate"));
v.setEngine(rs.getString("engine"));
v.setTranny(rs.getString("Tranny"));
v.setOdometer(rs.getString("odometer"));
v.setOilType(rs.getString("oilType"));
v.setDateolc(rs.getString("DateOLC"));
v.setStatus(rs.getString("status"));
vechList.add(v);
}
statement.close();
conn.close();
session.setAttribute("vehicles", vechList);
int userIndex = singletonBean.loggedUsers.indexOf(u);
session.setAttribute("user",
singletonBean.loggedUsers.get(userIndex));
response.sendRedirect("http://localhost:8080/Capstone/user_view.jsp");
} else
out.println("nopass");
} catch (IllegalStateException e) {
out.print(e.getMessage());
} catch (SQLException e) {
session.setAttribute("error",
"Username or password is incorrect!");
response.sendRedirect("http://localhost:8080/Capstone/Login.jsp");
}
} else if (request.getParameter("changeVehicle") != null) {
Map<String, String> errors = new HashMap<String, String>(10);
Vehicle newVech = new Vehicle();
try {
User u = (User) session.getAttribute("user");
String action = (String) session.getAttribute("action");
newVech.setUserid(u.getUserid());
newVech.setStatus("Y");
if (request.getParameter("vehicleMake").equals(""))
errors.put("makeError",
"Please fill in the make field.<br/>");
else if (Pattern.matches("[a-zA-Z]+",
request.getParameter("vehicleMake")) == false)
errors.put("makeError", "Please enter a valid make.<br/>");
else
newVech.setMake(request.getParameter("vehicleMake"));
if (request.getParameter("vehicleModel").equals(""))
errors.put("modelError",
"Please fill in the model field.<br/>");
else if (Pattern.matches("[a-zA-Z]+",
request.getParameter("vehicleModel")) == false)
errors.put("modelError", "Please enter a valid model.<br/>");
else
newVech.setModel(request.getParameter("vehicleModel"));
if (request.getParameter("vehicleColor").equals(""))
errors.put("colorError",
"Please fill in the color field.<br/>");
else if (Pattern.matches("[a-zA-Z]+",
request.getParameter("vehicleColor")) == false)
errors.put("colorError", "Please enter a valid color.<br/>");
else
newVech.setColor(request.getParameter("vehicleColor"));
if (request.getParameter("vehicleYear").equals(""))
errors.put("carYearError",
"Please fill in the vehicle year field.<br/>");
else if (Pattern.matches("[0-9]+",
request.getParameter("vehicleYear")) == false
&& request.getParameter("vehicleYear").length() != 4)
errors.put("carYearError",
"Please enter a valid vehicle year.<br/>");
else
newVech.setCarYear(request.getParameter("vehicleYear"));
if (request.getParameter("engineType").equals("Select engine"))
errors.put("engineError",
"Please select a value from the engine dropbox.<br/>");
else
newVech.setEngine(request.getParameter("engineType"));
if (request.getParameter("vehicleVIN").equals(""))
errors.put("vinError", "Please fill in the VIN field.<br/>");
else
newVech.setVin(request.getParameter("vehicleVIN"));
if (request.getParameter("vehiclePlate").equals(""))
errors.put("plateError",
"Please fill in the plate field.<br/>");
else
newVech.setPlate(request.getParameter("vehiclePlate"));
if (request.getParameter("vehicleClass").equals(""))
errors.put("carClassError",
"Please fill in the car class field.<br/>");
else if (Pattern.matches("[a-zA-Z]+",
request.getParameter("vehicleClass")) == false)
errors.put("carClassError",
"Please enter a valid car class.<br/>");
else
newVech.setCarClass(request.getParameter("vehicleClass"));
if (request.getParameter("vehicleOdometer").equals(""))
errors.put("odoError",
"Please fill in the odometer field.<br/>");
else if (Integer.parseInt(request
.getParameter("vehicleOdometer")) < 0)
errors.put("odoError",
"Please enter a positive number.<br/>");
else if (Pattern.matches("[0-9]+",
request.getParameter("vehicleOdometer")) == false)
errors.put("odoError",
"Please enter a positive number.<br/>");
else
newVech.setOdometer(request.getParameter("vehicleOdometer"));
if (request.getParameter("DateOfChange").equals(""))
errors.put("docError",
"Please fill in the date of the vehicle's last oil change.<br/>");
else {
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date doc = new Date();
doc = df.parse(request.getParameter("DateOfChange"));
if (df.format(doc).equals(
request.getParameter("DateOfChange"))) {
newVech.setDateolc(request.getParameter("DateOfChange"));
} else {
errors.put("docError",
"Please enter the date in the following format: MM/dd/yyyy<br/>");
}
}
if (request.getParameter("transmissionType").equals(
"Select transmission"))
errors.put("trannyError",
"Please select a transmission.<br/>");
else
newVech.setTranny(request.getParameter("transmissionType"));
if (request.getParameter("oilType").equals(""))
errors.put("oilTypeError", "Please enter an oil type.<br/>");
else
newVech.setOilType(request.getParameter("oilType"));
if (!errors.isEmpty()) {
session.setAttribute("errors", errors);
session.setAttribute("vehicle", newVech);
response.sendRedirect("http://localhost:8080/Capstone/add_edit.jsp");
} else {
session.setAttribute("errors", null);
session.setAttribute("vehicle", null);
if (action.equals("addVehicle")) {
String connectionURL = "jdbc:derby://localhost:1527/sun-appserv-samples;create=true";
Connection conn = null;
conn = DriverManager.getConnection(connectionURL);
Statement statement = conn.createStatement();
String sql = "insert into vehicle (userID, class, carYear, make, model, color, vin, plate, engine, tranny, odometer, oilType, DateOLC, status) values("
+ u.getUserid()
+ ", '"
+ newVech.getCarClass()
+ "', '"
+ newVech.getCarYear()
+ "', '"
+ newVech.getMake()
+ "', '"
+ newVech.getModel()
+ "', '"
+ newVech.getColor()
+ "', '"
+ newVech.getVin()
+ "', '"
+ newVech.getPlate()
+ "', '"
+ newVech.getEngine()
+ "', '"
+ newVech.getTranny()
+ "', '"
+ newVech.getOdometer()
+ "', '"
+ newVech.getOilType()
+ "', '"
+ newVech.getDateolc()
+ "', '"
+ newVech.getStatus() + "')";
statement.executeUpdate(sql);
sql = "SELECT * FROM Vehicle";
ResultSet rs = statement.executeQuery(sql);
ArrayList<Vehicle> vechList = new ArrayList<Vehicle>();
while (rs.next()) {
Vehicle v = new Vehicle();
v.setVechid(rs.getInt("vechID"));
v.setUserid(rs.getInt("userID"));
v.setCarClass(rs.getString("class"));
v.setCarYear(rs.getString("carYear"));
v.setMake(rs.getString("make"));
v.setModel(rs.getString("model"));
v.setColor(rs.getString("color"));
v.setVin(rs.getString("vin"));
v.setPlate(rs.getString("plate"));
v.setEngine(rs.getString("engine"));
v.setTranny(rs.getString("Tranny"));
v.setOdometer(rs.getString("odometer"));
v.setOilType(rs.getString("oilType"));
v.setDateolc(rs.getString("DateOLC"));
v.setStatus(rs.getString("status"));
vechList.add(v);
}
statement.close();
conn.close();
session.setAttribute("vehicles", vechList);
response.sendRedirect("http://localhost:8080/Capstone/user_view.jsp");
} else if (action.equals("editVehicle")) {
out.print("EDITEN");
} else
System.out.println("Mashugana");
}
} catch (NullPointerException e) {
session.setAttribute("action", "addVehicle");
session.setAttribute("errors", errors);
session.setAttribute("vehicle", newVech);
response.sendRedirect("http://localhost:8080/Capstone/add_edit.jsp");
} catch (NumberFormatException e) {
errors.put("odoError", "Please enter a positive number.<br/>");
session.setAttribute("errors", errors);
session.setAttribute("vehicle", newVech);
response.sendRedirect("http://localhost:8080/Capstone/add_edit.jsp");
} catch (SQLException e) {
e.getMessage();
System.out.println(e.getMessage());
} catch (ParseException e) {
errors.put("docError",
"Please enter the date in the following format: MM/dd/yyyy<br/>");
session.setAttribute("errors", errors);
session.setAttribute("vehicle", newVech);
response.sendRedirect("http://localhost:8080/Capstone/add_edit.jsp");
}
} else if (request.getParameter("addVehicle") != null) {
session.setAttribute("action", "addVehicle");
session.setAttribute("errors", null);
response.sendRedirect("http://localhost:8080/Capstone/add_edit.jsp");
} else if (request.getParameter("Logout") != null) {
}
else if (request.getParameter("checkSubmit") != null)
response.sendRedirect("http://localhost:8080/Capstone/Vehicle_Invoice.jsp");
else if (request.getParameter("createUser") != null) {
}
}
| protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
session.setAttribute("error", null);
if (request.getParameter("submit") != null) {
String user = request.getParameter("userName");
String pass = request.getParameter("password");
User u = new User();
try {
String connectionURL = "jdbc:derby://localhost:1527/sun-appserv-samples;create=true";
Connection conn = null;
ResultSet rs;
conn = DriverManager.getConnection(connectionURL);
Statement statement = conn.createStatement();
String sql = "SELECT * FROM Users WHERE userName='" + user
+ "' AND password='" + pass + "'";
rs = statement.executeQuery(sql);
rs.next();
if (rs.getString("userName").equals(user)
&& rs.getString("password").equals(pass)) {
if (!singletonBean.loggedUsers.isEmpty()) {
boolean logged = false;
for (User logU : singletonBean.loggedUsers) {
if (logU.getUsername().equals(user)
&& logU.getPassword().equals(pass))
logged = true;
}
if (logged) {
session.setAttribute("error",
"User is already logged in!");
} else {
u.setUserid(rs.getInt("userID"));
u.setFirstname(rs.getString("firstName"));
u.setLastname(rs.getString("lastName"));
u.setAddress(rs.getString("address"));
u.setCity(rs.getString("city"));
u.setProvince(rs.getString("province"));
u.setPostal(rs.getString("postal"));
u.setPhone(rs.getString("phone"));
u.setFax(rs.getString("fax"));
u.setEmail(rs.getString("email"));
u.setUsername(rs.getString("userName"));
u.setPassword(rs.getString("password"));
u.setUsertype(rs.getString("userType"));
singletonBean.loggedUsers.add(u);
}
} else {
u.setUserid(rs.getInt("userID"));
u.setFirstname(rs.getString("firstName"));
u.setLastname(rs.getString("lastName"));
u.setAddress(rs.getString("address"));
u.setCity(rs.getString("city"));
u.setProvince(rs.getString("province"));
u.setPostal(rs.getString("postal"));
u.setPhone(rs.getString("phone"));
u.setFax(rs.getString("fax"));
u.setEmail(rs.getString("email"));
u.setUsername(rs.getString("userName"));
u.setPassword(rs.getString("password"));
u.setUsertype(rs.getString("userType"));
singletonBean.loggedUsers.add(u);
}
sql = "SELECT * FROM Vehicle";
rs = statement.executeQuery(sql);
ArrayList<Vehicle> vechList = new ArrayList<Vehicle>();
while (rs.next()) {
Vehicle v = new Vehicle();
v.setVechid(rs.getInt("vechID"));
v.setUserid(rs.getInt("userID"));
v.setCarClass(rs.getString("class"));
v.setCarYear(rs.getString("carYear"));
v.setMake(rs.getString("make"));
v.setModel(rs.getString("model"));
v.setColor(rs.getString("color"));
v.setVin(rs.getString("vin"));
v.setPlate(rs.getString("plate"));
v.setEngine(rs.getString("engine"));
v.setTranny(rs.getString("Tranny"));
v.setOdometer(rs.getString("odometer"));
v.setOilType(rs.getString("oilType"));
v.setDateolc(rs.getString("DateOLC"));
v.setStatus(rs.getString("status"));
vechList.add(v);
}
statement.close();
conn.close();
session.setAttribute("vehicles", vechList);
int userIndex = singletonBean.loggedUsers.indexOf(u);
session.setAttribute("user",
singletonBean.loggedUsers.get(userIndex));
response.sendRedirect("http://localhost:8080/Capstone/user_view.jsp");
} else
out.println("nopass");
} catch (ArrayIndexOutOfBoundsException e) {
response.sendRedirect("http://localhost:8080/Capstone/Login.jsp");
} catch (IllegalStateException e) {
out.print(e.getMessage());
} catch (SQLException e) {
session.setAttribute("error",
"Username or password is incorrect!");
response.sendRedirect("http://localhost:8080/Capstone/Login.jsp");
}
} else if (request.getParameter("changeVehicle") != null) {
Map<String, String> errors = new HashMap<String, String>(10);
Vehicle newVech = new Vehicle();
try {
User u = (User) session.getAttribute("user");
String action = (String) session.getAttribute("action");
newVech.setUserid(u.getUserid());
newVech.setStatus("Y");
if (request.getParameter("vehicleMake").equals(""))
errors.put("makeError",
"Please fill in the make field.<br/>");
else if (Pattern.matches("[a-zA-Z]+",
request.getParameter("vehicleMake")) == false)
errors.put("makeError", "Please enter a valid make.<br/>");
else
newVech.setMake(request.getParameter("vehicleMake"));
if (request.getParameter("vehicleModel").equals(""))
errors.put("modelError",
"Please fill in the model field.<br/>");
else if (Pattern.matches("[a-zA-Z]+",
request.getParameter("vehicleModel")) == false)
errors.put("modelError", "Please enter a valid model.<br/>");
else
newVech.setModel(request.getParameter("vehicleModel"));
if (request.getParameter("vehicleColor").equals(""))
errors.put("colorError",
"Please fill in the color field.<br/>");
else if (Pattern.matches("[a-zA-Z]+",
request.getParameter("vehicleColor")) == false)
errors.put("colorError", "Please enter a valid color.<br/>");
else
newVech.setColor(request.getParameter("vehicleColor"));
if (request.getParameter("vehicleYear").equals(""))
errors.put("carYearError",
"Please fill in the vehicle year field.<br/>");
else if (Pattern.matches("[0-9]+",
request.getParameter("vehicleYear")) == false
&& request.getParameter("vehicleYear").length() != 4)
errors.put("carYearError",
"Please enter a valid vehicle year.<br/>");
else
newVech.setCarYear(request.getParameter("vehicleYear"));
if (request.getParameter("engineType").equals("Select engine"))
errors.put("engineError",
"Please select a value from the engine dropbox.<br/>");
else
newVech.setEngine(request.getParameter("engineType"));
if (request.getParameter("vehicleVIN").equals(""))
errors.put("vinError", "Please fill in the VIN field.<br/>");
else
newVech.setVin(request.getParameter("vehicleVIN"));
if (request.getParameter("vehiclePlate").equals(""))
errors.put("plateError",
"Please fill in the plate field.<br/>");
else
newVech.setPlate(request.getParameter("vehiclePlate"));
if (request.getParameter("vehicleClass").equals(""))
errors.put("carClassError",
"Please fill in the car class field.<br/>");
else if (Pattern.matches("[a-zA-Z]+",
request.getParameter("vehicleClass")) == false)
errors.put("carClassError",
"Please enter a valid car class.<br/>");
else
newVech.setCarClass(request.getParameter("vehicleClass"));
if (request.getParameter("vehicleOdometer").equals(""))
errors.put("odoError",
"Please fill in the odometer field.<br/>");
else if (Integer.parseInt(request
.getParameter("vehicleOdometer")) < 0)
errors.put("odoError",
"Please enter a positive number.<br/>");
else if (Pattern.matches("[0-9]+",
request.getParameter("vehicleOdometer")) == false)
errors.put("odoError",
"Please enter a positive number.<br/>");
else
newVech.setOdometer(request.getParameter("vehicleOdometer"));
if (request.getParameter("DateOfChange").equals(""))
errors.put("docError",
"Please fill in the date of the vehicle's last oil change.<br/>");
else {
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date doc = new Date();
doc = df.parse(request.getParameter("DateOfChange"));
if (df.format(doc).equals(
request.getParameter("DateOfChange"))) {
newVech.setDateolc(request.getParameter("DateOfChange"));
} else {
errors.put("docError",
"Please enter the date in the following format: MM/dd/yyyy<br/>");
}
}
if (request.getParameter("transmissionType").equals(
"Select transmission"))
errors.put("trannyError",
"Please select a transmission.<br/>");
else
newVech.setTranny(request.getParameter("transmissionType"));
if (request.getParameter("oilType").equals(""))
errors.put("oilTypeError", "Please enter an oil type.<br/>");
else
newVech.setOilType(request.getParameter("oilType"));
if (!errors.isEmpty()) {
session.setAttribute("errors", errors);
session.setAttribute("vehicle", newVech);
response.sendRedirect("http://localhost:8080/Capstone/add_edit.jsp");
} else {
session.setAttribute("errors", null);
session.setAttribute("vehicle", null);
if (action.equals("addVehicle")) {
String connectionURL = "jdbc:derby://localhost:1527/sun-appserv-samples;create=true";
Connection conn = null;
conn = DriverManager.getConnection(connectionURL);
Statement statement = conn.createStatement();
String sql = "insert into vehicle (userID, class, carYear, make, model, color, vin, plate, engine, tranny, odometer, oilType, DateOLC, status) values("
+ u.getUserid()
+ ", '"
+ newVech.getCarClass()
+ "', '"
+ newVech.getCarYear()
+ "', '"
+ newVech.getMake()
+ "', '"
+ newVech.getModel()
+ "', '"
+ newVech.getColor()
+ "', '"
+ newVech.getVin()
+ "', '"
+ newVech.getPlate()
+ "', '"
+ newVech.getEngine()
+ "', '"
+ newVech.getTranny()
+ "', '"
+ newVech.getOdometer()
+ "', '"
+ newVech.getOilType()
+ "', '"
+ newVech.getDateolc()
+ "', '"
+ newVech.getStatus() + "')";
statement.executeUpdate(sql);
sql = "SELECT * FROM Vehicle";
ResultSet rs = statement.executeQuery(sql);
ArrayList<Vehicle> vechList = new ArrayList<Vehicle>();
while (rs.next()) {
Vehicle v = new Vehicle();
v.setVechid(rs.getInt("vechID"));
v.setUserid(rs.getInt("userID"));
v.setCarClass(rs.getString("class"));
v.setCarYear(rs.getString("carYear"));
v.setMake(rs.getString("make"));
v.setModel(rs.getString("model"));
v.setColor(rs.getString("color"));
v.setVin(rs.getString("vin"));
v.setPlate(rs.getString("plate"));
v.setEngine(rs.getString("engine"));
v.setTranny(rs.getString("Tranny"));
v.setOdometer(rs.getString("odometer"));
v.setOilType(rs.getString("oilType"));
v.setDateolc(rs.getString("DateOLC"));
v.setStatus(rs.getString("status"));
vechList.add(v);
}
statement.close();
conn.close();
session.setAttribute("vehicles", vechList);
response.sendRedirect("http://localhost:8080/Capstone/user_view.jsp");
} else if (action.equals("editVehicle")) {
out.print("EDITEN");
} else
System.out.println("Mashugana");
}
} catch (NullPointerException e) {
session.setAttribute("action", "addVehicle");
session.setAttribute("errors", errors);
session.setAttribute("vehicle", newVech);
response.sendRedirect("http://localhost:8080/Capstone/add_edit.jsp");
} catch (NumberFormatException e) {
errors.put("odoError", "Please enter a positive number.<br/>");
session.setAttribute("errors", errors);
session.setAttribute("vehicle", newVech);
response.sendRedirect("http://localhost:8080/Capstone/add_edit.jsp");
} catch (SQLException e) {
e.getMessage();
System.out.println(e.getMessage());
} catch (ParseException e) {
errors.put("docError",
"Please enter the date in the following format: MM/dd/yyyy<br/>");
session.setAttribute("errors", errors);
session.setAttribute("vehicle", newVech);
response.sendRedirect("http://localhost:8080/Capstone/add_edit.jsp");
}
} else if (request.getParameter("addVehicle") != null) {
session.setAttribute("action", "addVehicle");
session.setAttribute("errors", null);
response.sendRedirect("http://localhost:8080/Capstone/add_edit.jsp");
} else if (request.getParameter("Logout") != null) {
}
else if (request.getParameter("checkSubmit") != null)
response.sendRedirect("http://localhost:8080/Capstone/Vehicle_Invoice.jsp");
else if (request.getParameter("createUser") != null) {
}
}
|
public void removeUser(String cwid) {
DBCursor cursor = users.find(new BasicDBObject("CWID", cwid));
User u = new User("", "", "", "", "");
ArrayList<String> tools = new ArrayList<String>();
if (!(cursor == null)) {
DBObject obj = cursor.next();
u = new User((String) obj.get("firstName"), (String) obj.get("lastName"), (String) obj.get("CWID"), (String) obj.get("email"), (String) obj.get("department"));
tools = (ArrayList<String>) obj.get("toolsCheckedOut");
users.remove(obj);
tracker.removeUser(u);
}
if (tools != null) {
ArrayList<Tool> ts = new ArrayList<Tool>();
for (String t : tools) {
ts.add(Driver.getAccessTracker().getToolByUPC(t));
}
u.returnTools(ts);
}
}
| public void removeUser(String cwid) {
DBCursor cursor = users.find(new BasicDBObject("CWID", cwid));
User u = new User("", "", "", "", "");
ArrayList<String> tools = new ArrayList<String>();
if (!(cursor == null)) {
DBObject obj = cursor.next();
u = new User((String) obj.get("firstName"), (String) obj.get("lastName"), (String) obj.get("CWID"), (String) obj.get("email"), (String) obj.get("department"));
tools = (ArrayList<String>) obj.get("toolsCheckedOut");
users.remove(obj);
tracker.removeUser(u);
}
if (tools != null && !tools.isEmpty()) {
ArrayList<Tool> ts = new ArrayList<Tool>();
for (String t : tools) {
ts.add(Driver.getAccessTracker().getToolByUPC(t));
}
u.returnTools(ts);
}
}
|
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) throws IOException {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
if (post == null) {
post = new serverObjects();
post.put("page", "start");
}
String pagename = post.get("page", "start");
String ip = post.get("CLIENTIP", "127.0.0.1");
String author = post.get("author", "anonymous");
if (author.equals("anonymous")) {
author = switchboard.wikiDB.guessAuthor(ip);
if (author == null) {
if (de.anomic.yacy.yacyCore.seedDB.mySeed == null) author = "anonymous";
else author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous");
}
}
if (post.containsKey("submit")) {
byte[] content;
try {
content = post.get("content", "").getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
switchboard.wikiDB.write(switchboard.wikiDB.newEntry(pagename, author, ip, post.get("reason", "edit"), content));
HashMap map = new HashMap();
map.put("page", pagename);
map.put("author", author);
map.put("ip", ip);
try {
yacyCore.newsPool.publishMyNews(new yacyNewsRecord("wiki_upd", map));
} catch (IOException e) {}
}
wikiBoard.entry page = switchboard.wikiDB.read(pagename);
if (post.containsKey("edit")) {
try {
prop.put("mode", 1);
prop.put("mode_author", author);
prop.put("mode_page-code", new String(page.page(), "UTF-8"));
prop.put("mode_pagename", pagename);
} catch (UnsupportedEncodingException e) {}
}
else if (post.containsKey("preview")) {
wikiCode wikiTransformer=new wikiCode(switchboard);
prop.put("mode", 2);
prop.put("mode_pagename", pagename);
prop.put("mode_author", author);
prop.put("mode_date", dateString(new Date()));
prop.put("mode_page", wikiTransformer.transform(post.get("content", "")));
prop.put("mode_page-code", post.get("content", ""));
}
else if (post.containsKey("index")) {
prop.put("mode", 3);
String subject;
try {
Iterator i = switchboard.wikiDB.keys(true);
wikiBoard.entry entry;
int count=0;
while (i.hasNext()) {
subject = (String) i.next();
entry = switchboard.wikiDB.read(subject);
prop.put("mode_pages_"+count+"_name",wikiBoard.webalize(subject));
prop.put("mode_pages_"+count+"_subject", subject);
prop.put("mode_pages_"+count+"_date", dateString(entry.date()));
prop.put("mode_pages_"+count+"_author", entry.author());
count++;
}
prop.put("mode_pages", count);
} catch (IOException e) {
prop.put("mode_error", 1);
prop.put("mode_error_message", e.getMessage());
}
prop.put("mode_pagename", pagename);
}
else {
wikiCode wikiTransformer=new wikiCode(switchboard);
prop.put("mode", 0);
prop.put("mode_pagename", pagename);
prop.put("mode_author", page.author());
prop.put("mode_date", dateString(page.date()));
prop.put("mode_page", wikiTransformer.transform(page.page()));
prop.put("controls", 0);
prop.put("controls_pagename", pagename);
}
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) throws IOException {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
if (post == null) {
post = new serverObjects();
post.put("page", "start");
}
String pagename = post.get("page", "start");
String ip = post.get("CLIENTIP", "127.0.0.1");
String author = post.get("author", "anonymous");
if (author.equals("anonymous")) {
author = switchboard.wikiDB.guessAuthor(ip);
if (author == null) {
if (de.anomic.yacy.yacyCore.seedDB.mySeed == null) author = "anonymous";
else author = de.anomic.yacy.yacyCore.seedDB.mySeed.get("Name", "anonymous");
}
}
if (post.containsKey("submit")) {
byte[] content;
try {
content = post.get("content", "").getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
content = post.get("content", "").getBytes();
}
switchboard.wikiDB.write(switchboard.wikiDB.newEntry(pagename, author, ip, post.get("reason", "edit"), content));
HashMap map = new HashMap();
map.put("page", pagename);
map.put("author", author);
map.put("ip", ip);
try {
yacyCore.newsPool.publishMyNews(new yacyNewsRecord("wiki_upd", map));
} catch (IOException e) {}
}
wikiBoard.entry page = switchboard.wikiDB.read(pagename);
if (post.containsKey("edit")) {
try {
prop.put("mode", 1);
prop.put("mode_author", author);
prop.put("mode_page-code", new String(page.page(), "UTF-8").replaceAll("</textarea>","</textarea>"));
prop.put("mode_pagename", pagename);
} catch (UnsupportedEncodingException e) {}
}
else if (post.containsKey("preview")) {
wikiCode wikiTransformer=new wikiCode(switchboard);
prop.put("mode", 2);
prop.put("mode_pagename", pagename);
prop.put("mode_author", author);
prop.put("mode_date", dateString(new Date()));
prop.put("mode_page", wikiTransformer.transform(post.get("content", "")));
prop.put("mode_page-code", post.get("content", "").replaceAll("</textarea>","</textarea>"));
}
else if (post.containsKey("index")) {
prop.put("mode", 3);
String subject;
try {
Iterator i = switchboard.wikiDB.keys(true);
wikiBoard.entry entry;
int count=0;
while (i.hasNext()) {
subject = (String) i.next();
entry = switchboard.wikiDB.read(subject);
prop.put("mode_pages_"+count+"_name",wikiBoard.webalize(subject));
prop.put("mode_pages_"+count+"_subject", subject);
prop.put("mode_pages_"+count+"_date", dateString(entry.date()));
prop.put("mode_pages_"+count+"_author", entry.author());
count++;
}
prop.put("mode_pages", count);
} catch (IOException e) {
prop.put("mode_error", 1);
prop.put("mode_error_message", e.getMessage());
}
prop.put("mode_pagename", pagename);
}
else {
wikiCode wikiTransformer=new wikiCode(switchboard);
prop.put("mode", 0);
prop.put("mode_pagename", pagename);
prop.put("mode_author", page.author());
prop.put("mode_date", dateString(page.date()));
prop.put("mode_page", wikiTransformer.transform(page.page()));
prop.put("controls", 0);
prop.put("controls_pagename", pagename);
}
return prop;
}
|
public void onCreate() {
super.onCreate();
queue = new QueueImpl(new PlayerAndroid());
database = new DatabaseImpl(Constants.DATABASE_PATH);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Messaging.subscribe(AndroidMessages.ServiceRequestMessage.class,
new Messaging.Event() {
@Override
public void messageReceived(Message message) {
ServiceRequestMessage mes = (ServiceRequestMessage) message;
if (mes.type == TypeOfResult.Compositions)
;
switch (mes.type) {
case Compositions:
break;
case Queue:
break;
case Albums:
break;
case Genres:
break;
case Artists:
break;
case Playlists:
break;
case Playlist:
break;
case PlaylistsInDialog:
break;
}
respondMessage.typeOfContent = mes.type;
Messaging.fire(respondMessage);
}
});
Messaging.subscribe(AndroidMessages.ServiceTaskMessage.class,
new Messaging.Event() {
@Override
public void messageReceived(Message message) {
ServiceTaskMessage mes = (ServiceTaskMessage) message;
switch (mes.action) {
case Play:
notification = makeNotification();
startForeground(Constants.PLAYER_NOTIFICATION_ID,
notification);
queue.play();
break;
case Pause:
queue.pause();
stopForeground(false);
break;
case Next:
queue.next();
break;
case Previous:
queue.prev();
break;
case addToQueue:
queue.enqueue(mes.list, EnqueueMode.AfterAll);
break;
case setToQueue:
queue.enqueue(mes.list, EnqueueMode.ReplaceAll);
break;
default:
break;
}
updateNotification();
}
});
Log.d(Constants.LOG_TAG, "Service.onCreate()");
}
| public void onCreate() {
super.onCreate();
queue = new QueueImpl(new PlayerAndroid());
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Messaging.subscribe(AndroidMessages.ServiceRequestMessage.class,
new Messaging.Event() {
@Override
public void messageReceived(Message message) {
ServiceRequestMessage mes = (ServiceRequestMessage) message;
if (mes.type == TypeOfResult.Compositions)
;
switch (mes.type) {
case Compositions:
break;
case Queue:
break;
case Albums:
break;
case Genres:
break;
case Artists:
break;
case Playlists:
break;
case Playlist:
break;
case PlaylistsInDialog:
break;
}
respondMessage.typeOfContent = mes.type;
Messaging.fire(respondMessage);
}
});
Messaging.subscribe(AndroidMessages.ServiceTaskMessage.class,
new Messaging.Event() {
@Override
public void messageReceived(Message message) {
ServiceTaskMessage mes = (ServiceTaskMessage) message;
switch (mes.action) {
case Play:
notification = makeNotification();
startForeground(Constants.PLAYER_NOTIFICATION_ID,
notification);
queue.play();
break;
case Pause:
queue.pause();
stopForeground(false);
break;
case Next:
queue.next();
break;
case Previous:
queue.prev();
break;
case addToQueue:
queue.enqueue(mes.list, EnqueueMode.AfterAll);
break;
case setToQueue:
queue.enqueue(mes.list, EnqueueMode.ReplaceAll);
break;
default:
break;
}
updateNotification();
}
});
Log.d(Constants.LOG_TAG, "Service.onCreate()");
}
|
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cards);
final String deviceId = ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
System.out.println("Oncreate activity!");
ParseQuery<ParseObject> query = ParseQuery.getQuery("cardInfo");
query.whereEqualTo("device_id", deviceId);
Date now = new Date();
Date before = new Date(now.getTime()-(1000*60*2));
query.whereGreaterThan("createdAt", before);
mCardView = (CardUI) findViewById(R.id.cardsview2);
mCardView.setSwipeable(true);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> results, ParseException e) {
if (e == null && results.size()>0) {
for (int i=0; i<results.size(); i++){
ParseObject res = results.get(i);
String cardTitle = res.getString("english");
String cardContent = res.getString("translation");
String cardPlace = res.getString("place");
String cardService = res.getString("service");
System.out.println("CARD INFO:" + cardTitle + " + " + cardContent);
if (i==0){
mCardView.addCard(new MyCard(cardTitle, cardContent + " \n Sent because you checked in at " + cardPlace + " with " + cardService));
}
else{
mCardView.addCardToLastStack(new MyCard(cardTitle, cardContent));
}
}
mCardView.refresh();
} else {
System.out.println("no data");
}
mCardView.refresh();
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cards);
final String deviceId = ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
System.out.println("Oncreate activity!");
ParseQuery<ParseObject> query = ParseQuery.getQuery("cardInfo");
query.whereEqualTo("device_id", deviceId);
Date now = new Date();
Date before = new Date(now.getTime()-(1000*60*10));
query.whereGreaterThan("createdAt", before);
mCardView = (CardUI) findViewById(R.id.cardsview2);
mCardView.setSwipeable(true);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> results, ParseException e) {
if (e == null && results.size()>0) {
for (int i=0; i<results.size(); i++){
ParseObject res = results.get(i);
String cardTitle = res.getString("english");
String cardContent = res.getString("translation");
String cardPlace = res.getString("place");
String cardService = res.getString("service");
System.out.println("CARD INFO:" + cardTitle + " + " + cardContent);
if (i==0){
mCardView.addCard(new MyCard(cardTitle, cardContent + " \n Sent because you checked in at " + cardPlace + " with " + cardService));
}
else{
mCardView.addCardToLastStack(new MyCard(cardTitle, cardContent));
}
}
mCardView.refresh();
} else {
System.out.println("no data");
}
mCardView.refresh();
}
});
}
|
private void checkConnectionErrorTypes(Connection conn){
ComponentImplementation cimpl = conn.getContainingComponentImpl();
ConnectionEnd src = conn.getAllSource();
Context srcCxt = conn.getAllSourceContext();
ErrorPropagation srcprop = null;
ErrorPropagation srccontain = null;
ErrorModelSubclause srcems = null;
ErrorPropagations srceps = null;
if (srcCxt instanceof Subcomponent){
ComponentClassifier cl = ((Subcomponent)srcCxt).getClassifier();
srcems = EM2Util.getContainingClassifierEMV2Subclause(cl);
if (srcems != null) srceps = srcems.getPropagation();
} else {
srcems = EM2Util.getContainingClassifierEMV2Subclause(cimpl);
if (srcems != null) srceps = srcems.getPropagation();
}
if (srceps != null) {
srcprop = EM2Util.findOutgoingErrorPropagation(srceps, src.getName());
srccontain = EM2Util.findOutgoingErrorContainment(srceps, src.getName());
}
ConnectionEnd dst = conn.getAllDestination();
Context dstCxt = conn.getAllDestinationContext();
ErrorPropagations dsteps = null;
ErrorModelSubclause dstems = null;
ErrorPropagation dstprop = null;
ErrorPropagation dstcontain = null;
if (dstCxt instanceof Subcomponent){
ComponentClassifier cl = ((Subcomponent)dstCxt).getClassifier();
dstems = EM2Util.getContainingClassifierEMV2Subclause(cl);
if (dstems != null) dsteps = dstems.getPropagation();
} else {
dstems = EM2Util.getContainingClassifierEMV2Subclause(cimpl);
if (dstems != null) dsteps = dstems.getPropagation();
}
if (dsteps != null) {
dstprop = EM2Util.findIncomingErrorPropagation(dsteps, dst.getName());
dstcontain = EM2Util.findIncomingErrorContainment(dsteps, dst.getName());
}
if (srcprop != null && dstprop != null){
if(! EM2TypeSetUtil.contains(dstprop.getTypeSet(),srcprop.getTypeSet())){
error(conn,"Outgoing propagation "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" has error types not handled by incoming propagation "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srccontain != null && dstcontain != null){
if(! EM2TypeSetUtil.contains(srccontain.getTypeSet(),dstcontain.getTypeSet())){
error(conn,"Outgoing containment "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" does not contain error types listed by incoming containment "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srcCxt instanceof Subcomponent && srcprop == null&&srccontain == null &&dstCxt instanceof Subcomponent&& (dstprop != null||dstcontain != null)){
if (srcems != null){
error(conn,"Connection source has no error propagation/containment but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain)));
} else {
info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please validate propagations in instance model");
}
}
if (dstCxt instanceof Subcomponent && dstprop == null &&dstCxt instanceof Subcomponent&& dstcontain == null && (srcprop != null||srccontain != null)){
if (dstems != null){
error(conn,"Connection target has no error propagation/containment but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain)));
} else {
error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please validate propagations in instance model");
}
}
if (conn.isBidirectional()){
if (srceps != null) {
dstprop = EM2Util.findIncomingErrorPropagation(srceps, src.getName());
dstcontain = EM2Util.findIncomingErrorContainment(srceps, src.getName());
}
if (dsteps != null) {
srcprop = EM2Util.findOutgoingErrorPropagation(dsteps, dst.getName());
srccontain = EM2Util.findOutgoingErrorContainment(dsteps, dst.getName());
}
if (srcprop != null && dstprop != null){
if(! EM2TypeSetUtil.contains(dstprop.getTypeSet(),srcprop.getTypeSet())){
error(conn,"Outgoing propagation "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" has error types not handled by incoming propagation "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srccontain != null && dstcontain != null){
if(! EM2TypeSetUtil.contains(srccontain.getTypeSet(),dstcontain.getTypeSet())){
error(conn,"Outgoing containment "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" does not contain error types listed by incoming containment "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srcCxt instanceof Subcomponent &&dstCxt instanceof Subcomponent&& srcprop == null&&srccontain == null && (dstprop != null||dstcontain != null)){
if (dstems != null){
error(conn,"Connection source has no error propagation/containment but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain)));
} else {
info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please validate propagations in instance model");
}
}
if (dstCxt instanceof Subcomponent &&dstCxt instanceof Subcomponent&& dstprop == null && dstcontain == null && (srcprop != null||srccontain != null)){
if (dstems != null){
error(conn,"Connection target has no error propagation/containment but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain)));
} else {
error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please validate propagations in instance model");
}
}
}
}
| private void checkConnectionErrorTypes(Connection conn){
ComponentImplementation cimpl = conn.getContainingComponentImpl();
ConnectionEnd src = conn.getAllSource();
Context srcCxt = conn.getAllSourceContext();
ErrorPropagation srcprop = null;
ErrorPropagation srccontain = null;
ErrorModelSubclause srcems = null;
ErrorPropagations srceps = null;
if (srcCxt instanceof Subcomponent){
ComponentClassifier cl = ((Subcomponent)srcCxt).getClassifier();
srcems = EM2Util.getContainingClassifierEMV2Subclause(cl);
if (srcems != null) srceps = srcems.getPropagation();
} else {
srcems = EM2Util.getContainingClassifierEMV2Subclause(cimpl);
if (srcems != null) srceps = srcems.getPropagation();
}
if (srceps != null) {
srcprop = EM2Util.findOutgoingErrorPropagation(srceps, src.getName());
srccontain = EM2Util.findOutgoingErrorContainment(srceps, src.getName());
}
ConnectionEnd dst = conn.getAllDestination();
Context dstCxt = conn.getAllDestinationContext();
ErrorPropagations dsteps = null;
ErrorModelSubclause dstems = null;
ErrorPropagation dstprop = null;
ErrorPropagation dstcontain = null;
if (dstCxt instanceof Subcomponent){
ComponentClassifier cl = ((Subcomponent)dstCxt).getClassifier();
dstems = EM2Util.getContainingClassifierEMV2Subclause(cl);
if (dstems != null) dsteps = dstems.getPropagation();
} else {
dstems = EM2Util.getContainingClassifierEMV2Subclause(cimpl);
if (dstems != null) dsteps = dstems.getPropagation();
}
if (dsteps != null) {
dstprop = EM2Util.findIncomingErrorPropagation(dsteps, dst.getName());
dstcontain = EM2Util.findIncomingErrorContainment(dsteps, dst.getName());
}
if (srcprop != null && dstprop != null){
if(! EM2TypeSetUtil.contains(dstprop.getTypeSet(),srcprop.getTypeSet())){
error(conn,"Outgoing propagation "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" has error types not handled by incoming propagation "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srccontain != null && dstcontain != null){
if(! EM2TypeSetUtil.contains(srccontain.getTypeSet(),dstcontain.getTypeSet())){
error(conn,"Outgoing containment "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" does not contain error types listed by incoming containment "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srcCxt instanceof Subcomponent && srcprop == null&&srccontain == null &&dstCxt instanceof Subcomponent&& (dstprop != null||dstcontain != null)){
if (srcems != null){
error(conn,"Connection source has no error propagation/containment but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain)));
} else {
info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please add error model to source or validate against error model of source subcomponents in instance model");
}
}
if (dstCxt instanceof Subcomponent && dstprop == null &&dstCxt instanceof Subcomponent&& dstcontain == null && (srcprop != null||srccontain != null)){
if (dstems != null){
error(conn,"Connection target has no error propagation/containment but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain)));
} else {
error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please add error model to target or validate against error model of target subcomponents in instance model");
}
}
if (conn.isBidirectional()){
if (srceps != null) {
dstprop = EM2Util.findIncomingErrorPropagation(srceps, src.getName());
dstcontain = EM2Util.findIncomingErrorContainment(srceps, src.getName());
}
if (dsteps != null) {
srcprop = EM2Util.findOutgoingErrorPropagation(dsteps, dst.getName());
srccontain = EM2Util.findOutgoingErrorContainment(dsteps, dst.getName());
}
if (srcprop != null && dstprop != null){
if(! EM2TypeSetUtil.contains(dstprop.getTypeSet(),srcprop.getTypeSet())){
error(conn,"Outgoing propagation "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" has error types not handled by incoming propagation "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srccontain != null && dstcontain != null){
if(! EM2TypeSetUtil.contains(srccontain.getTypeSet(),dstcontain.getTypeSet())){
error(conn,"Outgoing containment "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" does not contain error types listed by incoming containment "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srcCxt instanceof Subcomponent &&dstCxt instanceof Subcomponent&& srcprop == null&&srccontain == null && (dstprop != null||dstcontain != null)){
if (dstems != null){
error(conn,"Connection source has no error propagation/containment but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain)));
} else {
info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please validate propagations in instance model");
}
}
if (dstCxt instanceof Subcomponent &&dstCxt instanceof Subcomponent&& dstprop == null && dstcontain == null && (srcprop != null||srccontain != null)){
if (dstems != null){
error(conn,"Connection target has no error propagation/containment but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain)));
} else {
error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please validate propagations in instance model");
}
}
}
}
|
public void onDestroyView() {
super.onDestroyView();
if (mChildFragmentManager != null && mDestoryChildFragments) {
synchronized (mChildFragmentManager) {
for (Fragment fragment : mChildFragmentManager.mActive) {
mChildFragmentManager.removeFragment(fragment, 0, 0);
}
}
mChildFragmentManager = null;
}
}
| public void onDestroyView() {
super.onDestroyView();
if (mChildFragmentManager != null && mDestoryChildFragments) {
synchronized (mChildFragmentManager) {
for (Fragment fragment : mChildFragmentManager.mActive) {
if (fragment == null) {
continue;
}
mChildFragmentManager.removeFragment(fragment, 0, 0);
}
mChildFragmentManager.mActive.clear();
}
mChildFragmentManager = null;
}
}
|
public void execute(CommandSender sender, String[] args) {
int numOfParams = args.length;
boolean hasSeed = numOfParams == 3;
String worldName = args[0];
String env = args[1];
String seed = "";
if(hasSeed) {
seed = args[2];
}
sender.sendMessage("Stuff I found:");
sender.sendMessage(ChatColor.GREEN + "worldName" + ChatColor.WHITE + worldName);
sender.sendMessage(ChatColor.GREEN + "env " + ChatColor.WHITE + env);
sender.sendMessage(ChatColor.GREEN + "seed " + ChatColor.WHITE + seed);
if (args.length < 2) {
sender.sendMessage("Not enough parameters to create a new world");
sender.sendMessage(ChatColor.RED + "/mvcreate {WORLDNAME} {ENVIRONMENT} - Create a new World.");
sender.sendMessage(ChatColor.RED + "Example - /mvcreate world NORMAL");
sender.sendMessage(ChatColor.RED + "Example - /mvcreate airworld SKYLANDS");
sender.sendMessage(ChatColor.RED + "Example - /mvcreate hellworld NETHER");
return;
}
if (new File(worldName).exists() || this.plugin.worlds.containsKey(worldName)) {
sender.sendMessage(ChatColor.RED + "A Folder/World already exists with this name!");
sender.sendMessage(ChatColor.RED + "If you are confident it is a world you can import with /mvimport");
return;
}
Environment environment = null;
if (env.equalsIgnoreCase("HELL"))
env = "NETHER";
if (env.equalsIgnoreCase("SKYLAND") || env.equalsIgnoreCase("STARWARS"))
env = "SKYLAND";
try {
environment = Environment.valueOf(env);
} catch (IllegalArgumentException e) {
sender.sendMessage(ChatColor.RED + "Environment type " + env + " does not exist!");
return;
}
if (hasSeed) {
try {
plugin.addWorld(worldName, environment, Long.parseLong(seed));
} catch (NumberFormatException e) {
plugin.addWorld(worldName, environment, (long) seed.hashCode());
}
} else {
plugin.addWorld(worldName, environment);
}
return;
}
| public void execute(CommandSender sender, String[] args) {
int numOfParams = args.length;
boolean hasSeed = numOfParams == 3;
String worldName = args[0];
String env = args[1];
String seed = "";
if(hasSeed) {
seed = args[2];
}
sender.sendMessage("Stuff I found:");
sender.sendMessage(ChatColor.GREEN + "worldName" + ChatColor.WHITE + worldName);
sender.sendMessage(ChatColor.GREEN + "env " + ChatColor.WHITE + env);
sender.sendMessage(ChatColor.GREEN + "seed " + ChatColor.WHITE + seed);
if (args.length < 2) {
sender.sendMessage("Not enough parameters to create a new world");
sender.sendMessage(ChatColor.RED + "/mvcreate {WORLDNAME} {ENVIRONMENT} - Create a new World.");
sender.sendMessage(ChatColor.RED + "Example - /mvcreate world NORMAL");
sender.sendMessage(ChatColor.RED + "Example - /mvcreate airworld SKYLANDS");
sender.sendMessage(ChatColor.RED + "Example - /mvcreate hellworld NETHER");
return;
}
if (new File(worldName).exists() || this.plugin.worlds.containsKey(worldName)) {
sender.sendMessage(ChatColor.RED + "A Folder/World already exists with this name!");
sender.sendMessage(ChatColor.RED + "If you are confident it is a world you can import with /mvimport");
return;
}
Environment environment = null;
if (env.equalsIgnoreCase("HELL"))
env = "NETHER";
if (env.equalsIgnoreCase("SKYLAND") || env.equalsIgnoreCase("STARWARS"))
env = "SKYLANDS";
try {
environment = Environment.valueOf(env);
} catch (IllegalArgumentException e) {
sender.sendMessage(ChatColor.RED + "Environment type " + env + " does not exist!");
return;
}
if (hasSeed) {
try {
plugin.addWorld(worldName, environment, Long.parseLong(seed));
} catch (NumberFormatException e) {
plugin.addWorld(worldName, environment, (long) seed.hashCode());
}
} else {
plugin.addWorld(worldName, environment);
}
return;
}
|
protected void configure(Configuration config) throws Exception {
Yanel yanel = Yanel.getInstance();
File repoConfig = null;
Configuration repoConfigElement = config.getChild("ac-policies", false);
if (repoConfigElement != null) {
PolicyManagerFactory pmFactory = null;
PolicyManager policyManager = null;
try {
String customPolicyManagerFactoryImplClassName = repoConfigElement.getAttribute("class");
pmFactory = (PolicyManagerFactory) Class.forName(customPolicyManagerFactoryImplClassName).newInstance();
policyManager = pmFactory.newPolicyManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "policy-manager-config", "http://www.wyona.org/security/1.0"), new RealmConfigPathResolver(this));
} catch (ConfigurationException e) {
pmFactory = (PolicyManagerFactory) yanel.getBeanFactory().getBean("PolicyManagerFactory");
log.info("Default PolicyManager will be used for realm: " + getName());
repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigElement.getValue()));
RepositoryFactory policiesRepoFactory = yanel.getRepositoryFactory("ACPoliciesRepositoryFactory");
Repository policiesRepo = policiesRepoFactory.newRepository(getID(), repoConfig);
policyManager = pmFactory.newPolicyManager(policiesRepo);
}
setPolicyManager(policyManager);
}
repoConfigElement = config.getChild("ac-identities", false);
if (repoConfigElement != null) {
IdentityManagerFactory imFactory = null;
IdentityManager identityManager = null;
try {
String customIdentityManagerFactoryImplClassName = repoConfigElement.getAttribute("class");
imFactory = (IdentityManagerFactory) Class.forName(customIdentityManagerFactoryImplClassName).newInstance();
identityManager = imFactory.newIdentityManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "identity-manager-config", "http://www.wyona.org/security/1.0"), null);
} catch (ConfigurationException e) {
imFactory = (IdentityManagerFactory) yanel.getBeanFactory().getBean("IdentityManagerFactory");
log.info("Default IdentityManager will be used for realm: " + getName());
repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigElement.getValue()));
RepositoryFactory identitiesRepoFactory = yanel.getRepositoryFactory("ACIdentitiesRepositoryFactory");
Repository identitiesRepo = identitiesRepoFactory.newRepository(getID(), repoConfig);
identityManager = imFactory.newIdentityManager(identitiesRepo);
}
setIdentityManager(identityManager);
}
RepositoryFactory repoFactory = yanel.getRepositoryFactory("DefaultRepositoryFactory");
RepositoryFactory rtiRepoFactory = yanel.getRepositoryFactory("RTIRepositoryFactory");
RepositoryFactory extraRepoFactory = yanel.getRepositoryFactory("ExtraRepositoryFactory");
String repoConfigSrc = config.getChild("data", false).getValue();
repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigSrc));
setRepository(repoFactory.newRepository(getID(), repoConfig));
repoConfigSrc = config.getChild("rti", false).getValue();
repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigSrc));
setRTIRepository(rtiRepoFactory.newRepository(getID(), repoConfig));
Configuration configElement = config.getChild("default-language", false);
if (configElement != null) {
setDefaultLanguage(configElement.getValue());
} else {
setDefaultLanguage("en");
}
Configuration languagesElement = config.getChild("languages", false);
ArrayList languages = new ArrayList();
if (languagesElement != null) {
Configuration[] langElements = languagesElement.getChildren("language");
for (int i = 0; i < langElements.length; i++) {
String language = langElements[i].getValue();
languages.add(language);
}
}
setLanguages((String[])languages.toArray(new String[languages.size()]));
configElement = config.getChild("translation-manager", false);
TranslationManager translationManager = null;
if (configElement != null) {
String className = configElement.getAttribute("class");
translationManager = (TranslationManager)Class.forName(className).newInstance();
} else {
translationManager = new DefaultTranslationManager();
}
translationManager.init(this);
setTranslationManager(translationManager);
configElement = config.getChild("language-handler", false);
LanguageHandler languageHandler = null;
if (configElement != null) {
String className = configElement.getAttribute("class");
languageHandler = (LanguageHandler)Class.forName(className).newInstance();
} else {
languageHandler = (LanguageHandler)Class.forName("org.wyona.yanel.impl.DefaultLanguageHandler").newInstance();
}
setLanguageHandler(languageHandler);
Configuration rootDirConfig = config.getChild("root-dir", false);
if (rootDirConfig != null) {
setRootDir(FileUtil.resolve(getConfigFile(), new File(rootDirConfig.getValue())));
}
Configuration reposElement = config.getChild("yarep-repositories", false);
ArrayList repos = new ArrayList();
if (reposElement != null) {
Configuration[] repoElements = reposElement.getChildren("repository");
for (int i = 0; i < repoElements.length; i++) {
String id = repoElements[i].getAttribute("id");
String repoConfigPath = repoElements[i].getAttribute("config");
repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigPath));
Repository repo = extraRepoFactory.newRepository(id, repoConfig);
}
}
}
| protected void configure(Configuration config) throws Exception {
Yanel yanel = Yanel.getInstance();
File repoConfig = null;
Configuration repoConfigElement = config.getChild("ac-policies", false);
if (repoConfigElement != null) {
PolicyManagerFactory pmFactory = null;
PolicyManager policyManager = null;
try {
String customPolicyManagerFactoryImplClassName = repoConfigElement.getAttribute("class");
pmFactory = (PolicyManagerFactory) Class.forName(customPolicyManagerFactoryImplClassName).newInstance();
policyManager = pmFactory.newPolicyManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "policy-manager-config", "http://www.wyona.org/security/1.0"), new RealmConfigPathResolver(this));
} catch (ConfigurationException e) {
pmFactory = (PolicyManagerFactory) yanel.getBeanFactory().getBean("PolicyManagerFactory");
log.info("Default PolicyManager will be used for realm: " + getName());
repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigElement.getValue()));
RepositoryFactory policiesRepoFactory = yanel.getRepositoryFactory("ACPoliciesRepositoryFactory");
Repository policiesRepo = policiesRepoFactory.newRepository(getID(), repoConfig);
policyManager = pmFactory.newPolicyManager(policiesRepo);
}
setPolicyManager(policyManager);
}
repoConfigElement = config.getChild("ac-identities", false);
if (repoConfigElement != null) {
IdentityManagerFactory imFactory = null;
IdentityManager identityManager = null;
try {
String customIdentityManagerFactoryImplClassName = repoConfigElement.getAttribute("class");
imFactory = (IdentityManagerFactory) Class.forName(customIdentityManagerFactoryImplClassName).newInstance();
identityManager = imFactory.newIdentityManager(ConfigurationUtil.getCustomConfiguration(repoConfigElement, "identity-manager-config", "http://www.wyona.org/security/1.0"), new RealmConfigPathResolver(this));
} catch (ConfigurationException e) {
imFactory = (IdentityManagerFactory) yanel.getBeanFactory().getBean("IdentityManagerFactory");
log.info("Default IdentityManager will be used for realm: " + getName());
repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigElement.getValue()));
RepositoryFactory identitiesRepoFactory = yanel.getRepositoryFactory("ACIdentitiesRepositoryFactory");
Repository identitiesRepo = identitiesRepoFactory.newRepository(getID(), repoConfig);
identityManager = imFactory.newIdentityManager(identitiesRepo);
}
setIdentityManager(identityManager);
}
RepositoryFactory repoFactory = yanel.getRepositoryFactory("DefaultRepositoryFactory");
RepositoryFactory rtiRepoFactory = yanel.getRepositoryFactory("RTIRepositoryFactory");
RepositoryFactory extraRepoFactory = yanel.getRepositoryFactory("ExtraRepositoryFactory");
String repoConfigSrc = config.getChild("data", false).getValue();
repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigSrc));
setRepository(repoFactory.newRepository(getID(), repoConfig));
repoConfigSrc = config.getChild("rti", false).getValue();
repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigSrc));
setRTIRepository(rtiRepoFactory.newRepository(getID(), repoConfig));
Configuration configElement = config.getChild("default-language", false);
if (configElement != null) {
setDefaultLanguage(configElement.getValue());
} else {
setDefaultLanguage("en");
}
Configuration languagesElement = config.getChild("languages", false);
ArrayList languages = new ArrayList();
if (languagesElement != null) {
Configuration[] langElements = languagesElement.getChildren("language");
for (int i = 0; i < langElements.length; i++) {
String language = langElements[i].getValue();
languages.add(language);
}
}
setLanguages((String[])languages.toArray(new String[languages.size()]));
configElement = config.getChild("translation-manager", false);
TranslationManager translationManager = null;
if (configElement != null) {
String className = configElement.getAttribute("class");
translationManager = (TranslationManager)Class.forName(className).newInstance();
} else {
translationManager = new DefaultTranslationManager();
}
translationManager.init(this);
setTranslationManager(translationManager);
configElement = config.getChild("language-handler", false);
LanguageHandler languageHandler = null;
if (configElement != null) {
String className = configElement.getAttribute("class");
languageHandler = (LanguageHandler)Class.forName(className).newInstance();
} else {
languageHandler = (LanguageHandler)Class.forName("org.wyona.yanel.impl.DefaultLanguageHandler").newInstance();
}
setLanguageHandler(languageHandler);
Configuration rootDirConfig = config.getChild("root-dir", false);
if (rootDirConfig != null) {
setRootDir(FileUtil.resolve(getConfigFile(), new File(rootDirConfig.getValue())));
}
Configuration reposElement = config.getChild("yarep-repositories", false);
ArrayList repos = new ArrayList();
if (reposElement != null) {
Configuration[] repoElements = reposElement.getChildren("repository");
for (int i = 0; i < repoElements.length; i++) {
String id = repoElements[i].getAttribute("id");
String repoConfigPath = repoElements[i].getAttribute("config");
repoConfig = FileUtil.resolve(getConfigFile(), new File(repoConfigPath));
Repository repo = extraRepoFactory.newRepository(id, repoConfig);
}
}
}
|
public void execute() throws MojoExecutionException, MojoFailureException
{
boolean failed = false;
List<String> command = new ArrayList<String>();
try {
command.add(baseDir.getCanonicalPath() + "/libraries/lithium/console/li3");
}
catch (IOException e) {
throw new MojoExecutionException("Couldn't get the canonical path of the basedir");
}
command.add("test");
command.add("app/tests");
ProcessBuilder builder = new ProcessBuilder(command);
try {
Process process = builder.start();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line;
while ((line = input.readLine()) != null) {
log.info(line);
if(isFailure(line)){
failed = true;
}
}
input.close();
while ((line = error.readLine()) != null) {
log.error(line);
if(isFailure(line)){
failed = true;
}
}
error.close();
process.waitFor();
}
catch (IOException e) {
throw new MojoExecutionException("Couldn't get process to start.");
}
catch (InterruptedException e) {
throw new MojoExecutionException("Problem while waiting for process.");
}
if(failed){
throw new MojoFailureException("Lithium Tests Failed");
}
}
| public void execute() throws MojoExecutionException, MojoFailureException
{
boolean failed = false;
List<String> command = new ArrayList<String>();
try {
command.add(baseDir.getCanonicalPath() + "/libraries/lithium/console/li3");
}
catch (IOException e) {
throw new MojoExecutionException("Couldn't get the canonical path of the basedir");
}
command.add("test");
command.add("app/tests");
ProcessBuilder builder = new ProcessBuilder(command);
try {
Process process = builder.start();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line;
while ((line = input.readLine()) != null) {
log.info(line);
if(isFailure(line)){
failed = true;
}
}
input.close();
while ((line = error.readLine()) != null) {
log.error(line);
failed = true;
}
error.close();
process.waitFor();
}
catch (IOException e) {
throw new MojoExecutionException("Couldn't get process to start.");
}
catch (InterruptedException e) {
throw new MojoExecutionException("Problem while waiting for process.");
}
if(failed){
throw new MojoFailureException("Lithium Tests Failed");
}
}
|
public void doView(WidgetRequest request) {
Map<RefundProcessStateType, MultiCounter<RefundProcessStateType>> refundMap = ProcessMapGenerator
.generateRefundMap(Person.getLoggedPerson());
List<Counter<RefundProcessStateType>> refundCounters = new ArrayList<Counter<RefundProcessStateType>>();
for (MultiCounter<RefundProcessStateType> multiCounter : refundMap.values()) {
Counter<RefundProcessStateType> defaultCounter = ProcessMapGenerator.getDefaultCounter(multiCounter);
if (defaultCounter != null) {
refundCounters.add(defaultCounter);
}
}
Collections.sort(refundCounters, new BeanComparator("countableObject"));
request.setAttribute("refundCounters", refundCounters);
}
| public void doView(WidgetRequest request) {
Person loggedPerson = Person.getLoggedPerson();
Map<RefundProcessStateType, MultiCounter<RefundProcessStateType>> refundMap = ProcessMapGenerator
.generateRefundMap(loggedPerson);
List<Counter<RefundProcessStateType>> refundCounters = new ArrayList<Counter<RefundProcessStateType>>();
for (MultiCounter<RefundProcessStateType> multiCounter : refundMap.values()) {
Counter<RefundProcessStateType> defaultCounter = ProcessMapGenerator.getDefaultCounter(multiCounter);
if (defaultCounter != null) {
refundCounters.add(defaultCounter);
}
}
Collections.sort(refundCounters, new BeanComparator("countableObject"));
request.setAttribute("refundCounters", refundCounters);
request.setAttribute("person", loggedPerson);
}
|
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DatabaseInstance == null || LibraryInstance == null) {
finish();
return;
}
FileListAdapter adapter = new FileListAdapter();
setListAdapter(adapter);
myPath = getIntent().getStringExtra(FILE_MANAGER_PATH);
if (myPath == null) {
setTitle(myResource.getResource("fileTree").getValue());
addItem(Paths.BooksDirectoryOption().getValue(), "fileTreeLibrary");
addItem("/", "fileTreeRoot");
addItem(Environment.getExternalStorageDirectory().getPath(), "fileTreeCard");
} else {
setTitle(myPath);
startUpdate();
}
getListView().setOnCreateContextMenuListener(adapter);
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
runItem(((FileListAdapter)getListAdapter()).getItem(position));
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DatabaseInstance == null || LibraryInstance == null) {
finish();
return;
}
FileListAdapter adapter = new FileListAdapter();
setListAdapter(adapter);
myPath = getIntent().getStringExtra(FILE_MANAGER_PATH);
if (myPath == null) {
setTitle(myResource.getResource("fileTree").getValue());
addItem(Paths.BooksDirectoryOption().getValue(), "fileTreeLibrary");
addItem("/", "fileTreeRoot");
addItem(Environment.getExternalStorageDirectory().getPath(), "fileTreeCard");
adapter.notifyDataSetChanged();
} else {
setTitle(myPath);
startUpdate();
}
getListView().setOnCreateContextMenuListener(adapter);
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
runItem(((FileListAdapter)getListAdapter()).getItem(position));
}
});
}
|
@Override protected Response serve() {
if( str == null ) return RequestServer._http404.serve();
Exception e;
try {
Env env = water.exec.Exec2.exec(str);
StringBuilder sb = env._sb;
if( sb.length()!=0 ) sb.append("\n");
if( env == null ) throw new IllegalArgumentException("Null return from Exec2?");
if( env.sp() == 0 ) {
} else if( env.isAry() ) {
Frame fr = env.peekAry();
String skey = env.key();
num_rows = fr.numRows();
num_cols = fr.numCols();
cols = new Inspect2.ColSummary[num_cols];
for( int i=0; i<num_cols; i++ )
cols[i] = new Inspect2.ColSummary(fr._names[i],fr.vecs()[i]);
String[] fs = fr.toStringHdr(sb);
for( int i=0; i<Math.min(6,fr.numRows()); i++ )
fr.toString(sb,fs,i);
env.pop();
} else if( env.isFcn() ) {
ASTOp op = env.peekFcn();
funstr = op.toString();
sb.append(op.toString(true));
env.pop();
} else {
scalar = env.popDbl();
sb.append(Double.toString(scalar));
}
env.remove();
result=sb.toString();
return Response.done(this);
}
catch( IllegalArgumentException pe ) { e=pe;}
catch( Exception e2 ) { Log.err(e=e2); }
return Response.error(e.getMessage());
}
| @Override protected Response serve() {
if( str == null ) return RequestServer._http404.serve();
Exception e;
try {
Env env = water.exec.Exec2.exec(str);
StringBuilder sb = env._sb;
if( sb.length()!=0 ) sb.append("\n");
if( env == null ) throw new IllegalArgumentException("Null return from Exec2?");
if( env.sp() == 0 ) {
} else if( env.isAry() ) {
Frame fr = env.peekAry();
String skey = env.peekKey();
num_rows = fr.numRows();
num_cols = fr.numCols();
cols = new Inspect2.ColSummary[num_cols];
for( int i=0; i<num_cols; i++ )
cols[i] = new Inspect2.ColSummary(fr._names[i],fr.vecs()[i]);
String[] fs = fr.toStringHdr(sb);
for( int i=0; i<Math.min(6,fr.numRows()); i++ )
fr.toString(sb,fs,i);
env.pop();
} else if( env.isFcn() ) {
ASTOp op = env.peekFcn();
funstr = op.toString();
sb.append(op.toString(true));
env.pop();
} else {
scalar = env.popDbl();
sb.append(Double.toString(scalar));
}
env.remove();
result=sb.toString();
return Response.done(this);
}
catch( IllegalArgumentException pe ) { e=pe;}
catch( Exception e2 ) { Log.err(e=e2); }
return Response.error(e.getMessage());
}
|
public static Test suite() {
TestSuite suite = new TestSuite("lang");
suite.addTest(org.apache.derbyTesting.functionTests.tests.memory.TriggerTests.suite());
suite.addTest(CheckConstraintTest.suite());
suite.addTest(AnsiTrimTest.suite());
suite.addTest(AlterTableTest.suite());
suite.addTest(CreateTableFromQueryTest.suite());
suite.addTest(ColumnDefaultsTest.suite());
suite.addTest(CompressTableTest.suite());
suite.addTest(DatabaseClassLoadingTest.suite());
suite.addTest(DropTableTest.suite());
suite.addTest(DynamicLikeOptimizationTest.suite());
suite.addTest(ExistsWithSubqueriesTest.suite());
suite.addTest(FloatTypesTest.suite());
suite.addTest(GrantRevokeTest.suite());
suite.addTest(GroupByExpressionTest.suite());
suite.addTest(InbetweenTest.suite());
suite.addTest(InsertTest.suite());
suite.addTest(JoinTest.suite());
suite.addTest(LangScripts.suite());
suite.addTest(LikeTest.suite());
suite.addTest(LojReorderTest.suite());
suite.addTest(MathTrigFunctionsTest.suite());
suite.addTest(OuterJoinTest.suite());
suite.addTest(PredicateTest.suite());
suite.addTest(PrepareExecuteDDL.suite());
suite.addTest(ReferentialActionsTest.suite());
suite.addTest(RolesTest.suite());
suite.addTest(RolesConferredPrivilegesTest.suite());
suite.addTest(SQLSessionContextTest.suite());
suite.addTest(RoutineSecurityTest.suite());
suite.addTest(RoutineTest.suite());
suite.addTest(RoutinesDefinersRightsTest.suite());
suite.addTest(SQLAuthorizationPropTest.suite());
suite.addTest(StatementPlanCacheTest.suite());
suite.addTest(StreamsTest.suite());
suite.addTest(SubqueryFlatteningTest.suite());
suite.addTest(TimeHandlingTest.suite());
suite.addTest(TriggerTest.suite());
suite.addTest(TruncateTableTest.suite());
suite.addTest(VTITest.suite());
suite.addTest(SysDiagVTIMappingTest.suite());
suite.addTest(UpdatableResultSetTest.suite());
suite.addTest(CurrentOfTest.suite());
suite.addTest(CursorTest.suite());
suite.addTest(CastingTest.suite());
suite.addTest(ScrollCursors2Test.suite());
suite.addTest(NullIfTest.suite());
suite.addTest(InListMultiProbeTest.suite());
suite.addTest(SecurityPolicyReloadingTest.suite());
suite.addTest(CurrentOfTest.suite());
suite.addTest(UnaryArithmeticParameterTest.suite());
suite.addTest(HoldCursorTest.suite());
suite.addTest(ShutdownDatabaseTest.suite());
suite.addTest(StalePlansTest.suite());
suite.addTest(SystemCatalogTest.suite());
suite.addTest(ForBitDataTest.suite());
suite.addTest(DistinctTest.suite());
suite.addTest(GroupByTest.suite());
suite.addTest(UpdateCursorTest.suite());
suite.addTest(CoalesceTest.suite());
suite.addTest(ProcedureInTriggerTest.suite());
suite.addTest(ForUpdateTest.suite());
suite.addTest(CollationTest.suite());
suite.addTest(CollationTest2.suite());
suite.addTest(ScrollCursors1Test.suite());
suite.addTest(SimpleTest.suite());
suite.addTest(GrantRevokeDDLTest.suite());
suite.addTest(ReleaseCompileLocksTest.suite());
suite.addTest(LazyDefaultSchemaCreationTest.suite());
suite.addTest(ErrorCodeTest.suite());
suite.addTest(TimestampArithTest.suite());
suite.addTest(SpillHashTest.suite());
suite.addTest(CaseExpressionTest.suite());
suite.addTest(CharUTF8Test.suite());
suite.addTest(AggregateClassLoadingTest.suite());
suite.addTest(TableFunctionTest.suite());
suite.addTest(DeclareGlobalTempTableJavaTest.suite());
suite.addTest(PrimaryKeyTest.suite());
suite.addTest(RenameTableTest.suite());
suite.addTest(RenameIndexTest.suite());
suite.addTest(Bug5052rtsTest.suite());
suite.addTest(Bug5054Test.suite());
suite.addTest(Bug4356Test.suite());
suite.addTest(SynonymTest.suite());
suite.addTest(CommentTest.suite());
suite.addTest(NestedWhereSubqueryTest.suite());
suite.addTest(ConglomerateSharingTest.suite());
suite.addTest(NullableUniqueConstraintTest.suite());
suite.addTest(UniqueConstraintSetNullTest.suite());
suite.addTest(UniqueConstraintMultiThreadedTest.suite());
suite.addTest(ViewsTest.suite());
suite.addTest(DeadlockDetectionTest.suite());
suite.addTest(DeadlockModeTest.suite());
suite.addTest(AnsiSignaturesTest.suite());
suite.addTest(PredicatePushdownTest.suite());
suite.addTest(UngroupedAggregatesNegativeTest.suite());
suite.addTest(XplainStatisticsTest.suite());
suite.addTest(SelectivityTest.suite());
suite.addTest(XMLSuite.suite());
suite.addTest(NistScripts.suite());
suite.addTest(LangHarnessJavaTest.suite());
suite.addTest(ResultSetsFromPreparedStatementTest.suite());
if (!isPhoneME())
{
suite.addTest(OrderByAndSortAvoidance.suite());
}
if (JDBC.vmSupportsJDBC3())
{
suite.addTest(GrantRevokeDDLTest.suite());
suite.addTest(ErrorMessageTest.suite());
suite.addTest(DBInJarTest.suite());
suite.addTest(ConnectTest.suite());
suite.addTest(DeclareGlobalTempTableJavaJDBC30Test.suite());
}
suite.addTest(BigDataTest.suite());
suite.addTest(MixedCaseExpressionTest.suite());
suite.addTest(UpdateStatisticsTest.suite());
suite.addTest(MiscErrorsTest.suite());
suite.addTest(NullsTest.suite());
suite.addTest(ArithmeticTest.suite());
suite.addTest(ConstantExpressionTest.suite());
suite.addTest(OptimizerOverridesTest.suite());
suite.addTest(PrecedenceTest.suite());
suite.addTest(GeneratedColumnsTest.suite());
suite.addTest(GeneratedColumnsPermsTest.suite());
suite.addTest(RestrictedVTITest.suite());
suite.addTest(UDTTest.suite());
suite.addTest(UDTPermsTest.suite());
suite.addTest(BooleanValuesTest.suite());
suite.addTest(AlterColumnTest.suite());
suite.addTest(UserLobTest.suite());
suite.addTest(OffsetFetchNextTest.suite());
suite.addTest(SequenceTest.suite());
suite.addTest(SequencePermsTest.suite());
suite.addTest(SequenceGeneratorTest.suite());
suite.addTest(DBOAccessTest.suite());
suite.addTest(OLAPTest.suite());
suite.addTest(OrderByAndOffsetFetchInSubqueries.suite());
suite.addTest(Derby5005Test.suite());
suite.addTest(AutoIncrementTest.suite());
suite.addTest(HalfCreatedDatabaseTest.suite());
if ( !getSystemProperty("os.name").startsWith("Windows") ) { suite.addTest(NativeAuthenticationServiceTest.suite()); }
suite.addTest(NativeAuthProcs.suite());
return suite;
}
| public static Test suite() {
TestSuite suite = new TestSuite("lang");
suite.addTest(org.apache.derbyTesting.functionTests.tests.memory.TriggerTests.suite());
suite.addTest(CheckConstraintTest.suite());
suite.addTest(AnsiTrimTest.suite());
suite.addTest(AlterTableTest.suite());
suite.addTest(CreateTableFromQueryTest.suite());
suite.addTest(ColumnDefaultsTest.suite());
suite.addTest(CompressTableTest.suite());
suite.addTest(DatabaseClassLoadingTest.suite());
suite.addTest(DropTableTest.suite());
suite.addTest(DynamicLikeOptimizationTest.suite());
suite.addTest(ExistsWithSubqueriesTest.suite());
suite.addTest(FloatTypesTest.suite());
suite.addTest(GrantRevokeTest.suite());
suite.addTest(GroupByExpressionTest.suite());
suite.addTest(InbetweenTest.suite());
suite.addTest(InsertTest.suite());
suite.addTest(JoinTest.suite());
suite.addTest(LangScripts.suite());
suite.addTest(LikeTest.suite());
suite.addTest(LojReorderTest.suite());
suite.addTest(MathTrigFunctionsTest.suite());
suite.addTest(OuterJoinTest.suite());
suite.addTest(PredicateTest.suite());
suite.addTest(PrepareExecuteDDL.suite());
suite.addTest(ReferentialActionsTest.suite());
suite.addTest(RolesTest.suite());
suite.addTest(RolesConferredPrivilegesTest.suite());
suite.addTest(SQLSessionContextTest.suite());
suite.addTest(RoutineSecurityTest.suite());
suite.addTest(RoutineTest.suite());
suite.addTest(RoutinesDefinersRightsTest.suite());
suite.addTest(SQLAuthorizationPropTest.suite());
suite.addTest(StatementPlanCacheTest.suite());
suite.addTest(StreamsTest.suite());
suite.addTest(SubqueryFlatteningTest.suite());
suite.addTest(TimeHandlingTest.suite());
suite.addTest(TriggerTest.suite());
suite.addTest(TruncateTableTest.suite());
suite.addTest(VTITest.suite());
suite.addTest(SysDiagVTIMappingTest.suite());
suite.addTest(UpdatableResultSetTest.suite());
suite.addTest(CurrentOfTest.suite());
suite.addTest(CursorTest.suite());
suite.addTest(CastingTest.suite());
suite.addTest(ScrollCursors2Test.suite());
suite.addTest(NullIfTest.suite());
suite.addTest(InListMultiProbeTest.suite());
suite.addTest(SecurityPolicyReloadingTest.suite());
suite.addTest(CurrentOfTest.suite());
suite.addTest(UnaryArithmeticParameterTest.suite());
suite.addTest(HoldCursorTest.suite());
suite.addTest(ShutdownDatabaseTest.suite());
suite.addTest(StalePlansTest.suite());
suite.addTest(SystemCatalogTest.suite());
suite.addTest(ForBitDataTest.suite());
suite.addTest(DistinctTest.suite());
suite.addTest(GroupByTest.suite());
suite.addTest(UpdateCursorTest.suite());
suite.addTest(CoalesceTest.suite());
suite.addTest(ProcedureInTriggerTest.suite());
suite.addTest(ForUpdateTest.suite());
suite.addTest(CollationTest.suite());
suite.addTest(CollationTest2.suite());
suite.addTest(ScrollCursors1Test.suite());
suite.addTest(SimpleTest.suite());
suite.addTest(GrantRevokeDDLTest.suite());
suite.addTest(ReleaseCompileLocksTest.suite());
suite.addTest(LazyDefaultSchemaCreationTest.suite());
suite.addTest(ErrorCodeTest.suite());
suite.addTest(TimestampArithTest.suite());
suite.addTest(SpillHashTest.suite());
suite.addTest(CaseExpressionTest.suite());
suite.addTest(CharUTF8Test.suite());
suite.addTest(AggregateClassLoadingTest.suite());
suite.addTest(TableFunctionTest.suite());
suite.addTest(DeclareGlobalTempTableJavaTest.suite());
suite.addTest(PrimaryKeyTest.suite());
suite.addTest(RenameTableTest.suite());
suite.addTest(RenameIndexTest.suite());
suite.addTest(Bug5052rtsTest.suite());
suite.addTest(Bug5054Test.suite());
suite.addTest(Bug4356Test.suite());
suite.addTest(SynonymTest.suite());
suite.addTest(CommentTest.suite());
suite.addTest(NestedWhereSubqueryTest.suite());
suite.addTest(ConglomerateSharingTest.suite());
suite.addTest(NullableUniqueConstraintTest.suite());
suite.addTest(UniqueConstraintSetNullTest.suite());
suite.addTest(UniqueConstraintMultiThreadedTest.suite());
suite.addTest(ViewsTest.suite());
suite.addTest(DeadlockDetectionTest.suite());
suite.addTest(DeadlockModeTest.suite());
suite.addTest(AnsiSignaturesTest.suite());
suite.addTest(PredicatePushdownTest.suite());
suite.addTest(UngroupedAggregatesNegativeTest.suite());
suite.addTest(XplainStatisticsTest.suite());
suite.addTest(SelectivityTest.suite());
suite.addTest(XMLSuite.suite());
suite.addTest(NistScripts.suite());
suite.addTest(LangHarnessJavaTest.suite());
suite.addTest(ResultSetsFromPreparedStatementTest.suite());
if (!isPhoneME())
{
suite.addTest(OrderByAndSortAvoidance.suite());
}
if (JDBC.vmSupportsJDBC3())
{
suite.addTest(GrantRevokeDDLTest.suite());
suite.addTest(ErrorMessageTest.suite());
suite.addTest(DBInJarTest.suite());
suite.addTest(ConnectTest.suite());
suite.addTest(DeclareGlobalTempTableJavaJDBC30Test.suite());
}
suite.addTest(BigDataTest.suite());
suite.addTest(MixedCaseExpressionTest.suite());
suite.addTest(UpdateStatisticsTest.suite());
suite.addTest(MiscErrorsTest.suite());
suite.addTest(NullsTest.suite());
suite.addTest(ArithmeticTest.suite());
suite.addTest(ConstantExpressionTest.suite());
suite.addTest(OptimizerOverridesTest.suite());
suite.addTest(PrecedenceTest.suite());
suite.addTest(GeneratedColumnsTest.suite());
suite.addTest(GeneratedColumnsPermsTest.suite());
suite.addTest(RestrictedVTITest.suite());
suite.addTest(UDTTest.suite());
suite.addTest(UDTPermsTest.suite());
suite.addTest(BooleanValuesTest.suite());
suite.addTest(AlterColumnTest.suite());
suite.addTest(UserLobTest.suite());
suite.addTest(OffsetFetchNextTest.suite());
suite.addTest(SequenceTest.suite());
suite.addTest(SequencePermsTest.suite());
suite.addTest(SequenceGeneratorTest.suite());
suite.addTest(DBOAccessTest.suite());
suite.addTest(OLAPTest.suite());
suite.addTest(OrderByAndOffsetFetchInSubqueries.suite());
suite.addTest(Derby5005Test.suite());
suite.addTest(AutoIncrementTest.suite());
suite.addTest(HalfCreatedDatabaseTest.suite());
suite.addTest(NativeAuthenticationServiceTest.suite());
suite.addTest(NativeAuthProcs.suite());
return suite;
}
|
public void run() {
try {
if(waitfor != null)
waitfor.join();
res.loadwaitint();
try {
seq = MidiSystem.getSequencer(false);
synth = MidiSystem.getSynthesizer();
seq.open();
seq.setSequence(res.layer(Resource.Music.class).seq);
synth.open();
seq.getTransmitter().setReceiver(synth.getReceiver());
} catch(MidiUnavailableException e) {
return;
} catch(InvalidMidiDataException e) {
return;
} catch(IllegalArgumentException e) {
if(e.getMessage().startsWith("No line matching"))
return;
throw(e);
}
seq.addMetaEventListener(new MetaEventListener() {
public void meta(MetaMessage msg) {
debug("Meta " + msg.getType());
if(msg.getType() == 47) {
synchronized(Player.this) {
done = true;
Player.this.notifyAll();
}
}
}
});
do {
debug("Start loop");
done = false;
seq.start();
synchronized(this) {
while(!done)
this.wait();
}
seq.setTickPosition(0);
} while(loop);
} catch(InterruptedException e) {
} finally {
debug("Exit player");
if(seq != null)
seq.close();
if(synth != null)
synth.close();
synchronized(Music.class) {
if(player == this)
player = null;
}
}
}
| public void run() {
try {
if(waitfor != null)
waitfor.join();
res.loadwaitint();
try {
seq = MidiSystem.getSequencer(false);
synth = MidiSystem.getSynthesizer();
seq.open();
seq.setSequence(res.layer(Resource.Music.class).seq);
synth.open();
seq.getTransmitter().setReceiver(synth.getReceiver());
} catch(MidiUnavailableException e) {
return;
} catch(InvalidMidiDataException e) {
return;
} catch(IllegalArgumentException e) {
if(e.getMessage().startsWith("No line matching"))
return;
throw(e);
}
seq.addMetaEventListener(new MetaEventListener() {
public void meta(MetaMessage msg) {
debug("Meta " + msg.getType());
if(msg.getType() == 47) {
synchronized(Player.this) {
done = true;
Player.this.notifyAll();
}
}
}
});
do {
debug("Start loop");
done = false;
seq.start();
synchronized(this) {
while(!done)
this.wait();
}
seq.setTickPosition(0);
} while(loop);
} catch(InterruptedException e) {
} finally {
debug("Exit player");
if(seq != null)
seq.close();
try {
if(synth != null)
synth.close();
} catch(InterruptedException e2) {
}
synchronized(Music.class) {
if(player == this)
player = null;
}
}
}
|
public static DriverProvider getInstance() {
PageObjectLogging listener = new PageObjectLogging();
Global.JS_ERROR_ENABLED = false;
if (Global.BROWSER.equals("IE")) {
setIEProperties();
driver = new EventFiringWebDriver(
new InternetExplorerDriver(caps)
).register(listener);
} else if (Global.BROWSER.contains("FF")) {
if (System.getProperty("os.name").toLowerCase().equals("windows 8")){
System.setProperty("webdriver.firefox.bin", "c:\\Program Files (x86)\\Mozilla Firefox\\");
}
if (Global.BROWSER.contains("CONSOLE")){
try{
File jsErr = new File("./src/test/resources/Firebug/JSErrorCollector.xpi");
profile.addExtension(jsErr);
Global.JS_ERROR_ENABLED = true;
}
catch(FileNotFoundException e){
System.out.println("JS extension file doesn't exist in provided location");
} catch (IOException e) {
System.out.println("Error with adding firefox extension");
}
}
driver = new EventFiringWebDriver(
new FirefoxDriver(profile)
).register(listener);
} else if (Global.BROWSER.equals("CHROME")) {
setChromeProperties();
driver = new EventFiringWebDriver(
new ChromeDriver(caps)
).register(listener);
} else if (Global.BROWSER.equals("SAFARI")) {
System.setProperty("webdriver.safari.driver", "");
driver = new EventFiringWebDriver(new SafariDriver()).register(listener);
}
else if (Global.BROWSER.equals("CHROMEMOBILE")) {
setChromeProperties();
ChromeOptions o = new ChromeOptions();
o.addArguments(
"--user-agent="
+ "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3"
);
driver = new EventFiringWebDriver(new ChromeDriver(o)).register(listener);
} else if (Global.BROWSER.equals("HTMLUNIT")) {
driver = new EventFiringWebDriver(new HtmlUnitDriver()).register(listener);
} else {
System.out.println("This browser is not supported. Check -Dbrowser property value");
}
if (!(Global.BROWSER.equals("CHROME")||Global.BROWSER.equals("CHROMEMOBILE")||Global.BROWSER.equals("SAFARI"))) {
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
} else {
System.out.print(Global.BROWSER+" browser detected. Unable to set pageLoadTimeout()");
}
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
return instance;
}
| public static DriverProvider getInstance() {
PageObjectLogging listener = new PageObjectLogging();
Global.JS_ERROR_ENABLED = false;
if (Global.BROWSER.equals("IE")) {
setIEProperties();
driver = new EventFiringWebDriver(
new InternetExplorerDriver(caps)
).register(listener);
} else if (Global.BROWSER.contains("FF")) {
if (System.getProperty("os.name").toLowerCase().equals("windows 8")){
System.setProperty("webdriver.firefox.bin", "c:\\Program Files (x86)\\Mozilla Firefox\\Firefox.exe");
}
if (Global.BROWSER.contains("CONSOLE")){
try{
File jsErr = new File("./src/test/resources/Firebug/JSErrorCollector.xpi");
profile.addExtension(jsErr);
Global.JS_ERROR_ENABLED = true;
}
catch(FileNotFoundException e){
System.out.println("JS extension file doesn't exist in provided location");
} catch (IOException e) {
System.out.println("Error with adding firefox extension");
}
}
driver = new EventFiringWebDriver(
new FirefoxDriver(profile)
).register(listener);
} else if (Global.BROWSER.equals("CHROME")) {
setChromeProperties();
driver = new EventFiringWebDriver(
new ChromeDriver(caps)
).register(listener);
} else if (Global.BROWSER.equals("SAFARI")) {
System.setProperty("webdriver.safari.driver", "");
driver = new EventFiringWebDriver(new SafariDriver()).register(listener);
}
else if (Global.BROWSER.equals("CHROMEMOBILE")) {
setChromeProperties();
ChromeOptions o = new ChromeOptions();
o.addArguments(
"--user-agent="
+ "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3"
);
driver = new EventFiringWebDriver(new ChromeDriver(o)).register(listener);
} else if (Global.BROWSER.equals("HTMLUNIT")) {
driver = new EventFiringWebDriver(new HtmlUnitDriver()).register(listener);
} else {
System.out.println("This browser is not supported. Check -Dbrowser property value");
}
if (!(Global.BROWSER.equals("CHROME")||Global.BROWSER.equals("CHROMEMOBILE")||Global.BROWSER.equals("SAFARI"))) {
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
} else {
System.out.print(Global.BROWSER+" browser detected. Unable to set pageLoadTimeout()");
}
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
return instance;
}
|
public byte[] transform(String name, String transformedName, byte[] bytes)
{
ClassReader cr = new ClassReader(bytes);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
workingPath.add(transformedName);
if (this.implement(cn))
{
System.out.println("Adding runtime interfaces to " + transformedName);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cn.accept(cw);
bytes = cw.toByteArray();
cr = new ClassReader(bytes);
}
workingPath.remove(workingPath.size() - 1);
if ("net.minecraft.world.WorldServer".equals(transformedName))
{
cn = new ClassNode(Opcodes.ASM4);
cr.accept(cn, ClassReader.EXPAND_FRAMES);
MethodNode m = new MethodNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC, "<init>", "(Lnet/minecraft/server/MinecraftServer;Lakf;Ljava/lang/String;Lacn;Laai;Lla;Lku;)V", null, null);
InsnList code = m.instructions;
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new InsnNode(Opcodes.DUP));
code.add(new InsnNode(Opcodes.DUP));
code.add(new InsnNode(Opcodes.DUP));
code.add(new InsnNode(Opcodes.DUP));
code.add(new VarInsnNode(Opcodes.ALOAD, 2));
code.add(new VarInsnNode(Opcodes.ALOAD, 3));
code.add(new VarInsnNode(Opcodes.ALOAD, 4));
code.add(new VarInsnNode(Opcodes.ALOAD, 5));
code.add(new VarInsnNode(Opcodes.ALOAD, 6));
code.add(new VarInsnNode(Opcodes.ALOAD, 7));
code.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, "aab", "<init>", "(Lakf;Ljava/lang/String;Lacn;Laai;Lla;Lku;)V"));
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
code.add(new FieldInsnNode(Opcodes.PUTFIELD, name, "a", "Lnet/minecraft/server/MinecraftServer;"));
code.add(new InsnNode(Opcodes.ACONST_NULL));
code.add(new FieldInsnNode(Opcodes.PUTFIELD, name, "J", "Lit;"));
code.add(new InsnNode(Opcodes.ACONST_NULL));
code.add(new FieldInsnNode(Opcodes.PUTFIELD, name, "J", "Liw;"));
code.add(new InsnNode(Opcodes.ACONST_NULL));
code.add(new FieldInsnNode(Opcodes.PUTFIELD, name, "J", "Laao;"));
code.add(new InsnNode(Opcodes.RETURN));
cn.methods.add(m);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
cn.accept(cw);
bytes = cw.toByteArray();
}
return bytes;
}
| public byte[] transform(String name, String transformedName, byte[] bytes)
{
ClassReader cr = new ClassReader(bytes);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
workingPath.add(transformedName);
if (this.implement(cn))
{
System.out.println("Adding runtime interfaces to " + transformedName);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cn.accept(cw);
bytes = cw.toByteArray();
cr = new ClassReader(bytes);
}
workingPath.remove(workingPath.size() - 1);
if ("net.minecraft.world.WorldServer".equals(transformedName))
{
cn = new ClassNode(Opcodes.ASM4);
cr.accept(cn, ClassReader.EXPAND_FRAMES);
MethodNode m = new MethodNode(Opcodes.ASM4, Opcodes.ACC_PUBLIC, "<init>", "(Lnet/minecraft/server/MinecraftServer;Lakf;Ljava/lang/String;Lacn;Laai;Lla;Lku;)V", null, null);
InsnList code = m.instructions;
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new InsnNode(Opcodes.DUP));
code.add(new InsnNode(Opcodes.DUP));
code.add(new InsnNode(Opcodes.DUP));
code.add(new InsnNode(Opcodes.DUP));
code.add(new VarInsnNode(Opcodes.ALOAD, 2));
code.add(new VarInsnNode(Opcodes.ALOAD, 3));
code.add(new VarInsnNode(Opcodes.ALOAD, 4));
code.add(new VarInsnNode(Opcodes.ALOAD, 5));
code.add(new VarInsnNode(Opcodes.ALOAD, 6));
code.add(new VarInsnNode(Opcodes.ALOAD, 7));
code.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, "aab", "<init>", "(Lakf;Ljava/lang/String;Lacn;Laai;Lla;Lku;)V"));
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
code.add(new FieldInsnNode(Opcodes.PUTFIELD, name, "a", "Lnet/minecraft/server/MinecraftServer;"));
code.add(new InsnNode(Opcodes.ACONST_NULL));
code.add(new FieldInsnNode(Opcodes.PUTFIELD, name, "J", "Lit;"));
code.add(new InsnNode(Opcodes.ACONST_NULL));
code.add(new FieldInsnNode(Opcodes.PUTFIELD, name, "K", "Liw;"));
code.add(new InsnNode(Opcodes.ACONST_NULL));
code.add(new FieldInsnNode(Opcodes.PUTFIELD, name, "P", "Laao;"));
code.add(new InsnNode(Opcodes.RETURN));
cn.methods.add(m);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
cn.accept(cw);
bytes = cw.toByteArray();
}
return bytes;
}
|
private void displayPublications(List<KmeliaPublication> allPubs,
boolean sortAllowed, boolean linksAllowed, boolean seeAlso, boolean toSearch,
KmeliaSessionController kmeliaScc, String profile,
GraphicElementFactory gef, String context, ResourcesWrapper resources,
List<String> selectedIds, String pubIdToHighlight, Writer out, boolean linkAttachment)
throws IOException {
String publicationSrc = resources.getIcon("kmelia.publication");
ResourceLocator publicationSettings = new ResourceLocator(
"org.silverpeas.util.publication.publicationSettings", kmeliaScc.getLanguage());
boolean showNoPublisMessage = resources.getSetting("showNoPublisMessage", true);
String language = kmeliaScc.getCurrentLanguage();
String currentUserId = kmeliaScc.getUserDetail().getId();
String currentTopicId = kmeliaScc.getCurrentFolderId();
boolean specificTemplateUsed = kmeliaScc.isCustomPublicationTemplateUsed();
PublicationFragmentSettings fragmentSettings = new PublicationFragmentSettings();
fragmentSettings.displayLinks = URLManager.displayUniversalLinks();
fragmentSettings.showImportance = kmeliaScc.isFieldImportanceVisible();
fragmentSettings.fileStorageShowExtraInfoPub = resources.getSetting(
"fileStorageShowExtraInfoPub", false);
fragmentSettings.showTopicPathNameinSearchResult = resources.getSetting(
"showTopicPathNameinSearchResult", true);
fragmentSettings.showDelegatedNewsInfo = kmeliaScc.isNewsManage() && !user.isInRole(profile);
fragmentSettings.toSearch = toSearch;
int nbPubsPerPage = kmeliaScc.getNbPublicationsPerPage();
int firstDisplayedItemIndex = kmeliaScc.getIndexOfFirstPubToDisplay();
int nbPubs = allPubs.size();
Board board = gef.getBoard();
Pagination pagination = gef.getPagination(nbPubs, nbPubsPerPage, firstDisplayedItemIndex);
List<KmeliaPublication> pubs = allPubs.subList(pagination.getFirstItemIndex(), pagination.
getLastItemIndex());
out.write("<form name=\"publicationsForm\" onsubmit=\"return false;\">");
if (!pubs.isEmpty()) {
out.write(board.printBefore());
displayPublicationsListHeader(nbPubs, sortAllowed, pagination, resources, kmeliaScc, out);
out.write("<ul>");
for (KmeliaPublication aPub : pubs) {
PublicationDetail pub = aPub.getDetail();
UserDetail currentUser = aPub.getCreator();
String pubColor = "";
String pubState = null;
String highlightClass = "";
if (StringUtil.isDefined(pubIdToHighlight) && pubIdToHighlight.equals(pub.getPK().getId())) {
highlightClass = "highlight";
}
out.write("<!-- Publication Body -->");
if (pub.getStatus() != null && pub.isValid()) {
if (pub.haveGotClone() && CLONE.equals(pub.getCloneStatus()) && !user.isInRole(profile)) {
pubColor = "blue";
pubState = resources.getString("kmelia.UpdateInProgress");
} else if (DRAFT.equals(pub.getCloneStatus())) {
if (currentUserId.equals(currentUser.getId())) {
pubColor = "gray";
pubState = resources.getString("PubStateDraft");
}
} else if (TO_VALIDATE.equals(pub.getCloneStatus())) {
if (admin.isInRole(profile) || publisher.isInRole(profile)
|| currentUserId.equals(currentUser.getId())) {
pubColor = "red";
pubState = resources.getString("kmelia.PubStateToValidate");
}
} else {
if (pub.isNotYetVisible()) {
pubState = resources.getString("kmelia.VisibleFrom") + " "
+ resources.getOutputDateAndHour(pub.getBeginDateAndHour());
} else if (pub.isNoMoreVisible()) {
pubState = resources.getString("kmelia.VisibleTo") + " "
+ resources.getOutputDateAndHour(pub.getEndDateAndHour());
}
if (!pub.isVisible()) {
pubColor = "gray";
}
}
} else {
if (pub.getStatus() != null && pub.isDraft()) {
if (currentUserId.equals(pub.getUpdaterId())
|| ((kmeliaScc.isCoWritingEnable() && kmeliaScc.isDraftVisibleWithCoWriting())
&& !user.isInRole(profile))) {
pubColor = "gray";
pubState = resources.getString("PubStateDraft");
}
} else {
if (admin.isInRole(profile) || publisher.isInRole(profile)
|| currentUserId.equals(pub.getUpdaterId())
|| (!user.isInRole(profile) && kmeliaScc.isCoWritingEnable())) {
pubColor = "red";
if (pub.isRefused()) {
pubState = resources.getString("kmelia.PubStateUnvalidate");
} else {
pubState = resources.getString("kmelia.PubStateToValidate");
}
}
}
}
if (!pub.getPK().getInstanceId().equals(kmeliaScc.getComponentId())) {
pubState = resources.getString("kmelia.Shortcut");
}
String cssClass = "";
if (toSearch) {
if (aPub.read) {
cssClass = " class=\"read\"";
} else {
cssClass = " class=\"unread\"";
}
}
out.write("<li");
out.write(cssClass);
out.write(" onmouseover=\"showPublicationOperations(this);\"");
out.write(" onmouseout=\"hidePublicationOperations(this);\">");
out.write("<div class=\"firstColumn\">");
if (!kmeliaScc.getUserDetail().isAnonymous() && !kmeliaScc.isKmaxMode) {
String checked = "";
if (selectedIds != null && selectedIds.contains(pub.getPK().getId())) {
checked = "checked=\"checked\"";
}
out.write("<span class=\"selection\">");
out.write("<input type=\"checkbox\" name=\"C1\" value=\""
+ pub.getPK().getId() + "/" + pub.getPK().getInstanceId() + "\" " + checked
+ " onclick=\"sendPubId(this.value, this.checked);\"/>");
out.write("</span>");
}
if (!seeAlso) {
ThumbnailDetail thumbnail = pub.getThumbnail();
if (thumbnail != null && Boolean.valueOf(resources.getSetting("isVignetteVisible"))) {
out.write("<span class=\"thumbnail\">");
try {
displayThumbnail(pub, kmeliaScc, publicationSettings, out);
} catch (ThumbnailException e) {
SilverTrace.info("kmelia", "AjaxPublicationsListServlet.displayPublications()",
"root.MSG_GEN_ENTER_METHOD", "exception = " + e);
}
out.write("</span>");
} else {
out.write("<span class=\"thumbnail\">");
out.write("<img src=\"" + resources.getIcon("kmelia.1px") + "\" alt=\"\"/>");
out.write("</span>");
}
}
out.write("</div>");
fragmentSettings.pubColor = pubColor;
fragmentSettings.highlightClass = highlightClass;
fragmentSettings.pubState = pubState;
fragmentSettings.linksAllowed = linksAllowed;
fragmentSettings.seeAlso = seeAlso;
fragmentSettings.linkAttachment = linkAttachment;
out.write("<div class=\"publication\"><a name=\"" + pub.getPK().getId() + "\"></a>");
displayFragmentOfPublication(specificTemplateUsed, aPub, fragmentSettings, language,
currentUserId, currentTopicId, kmeliaScc, resources, out);
out.write("</div>");
}
out.write("</ul>");
if (nbPubs > nbPubsPerPage) {
out.write("<div id=\"pagination\">");
out.write(pagination.printIndex("doPagination"));
out.write("</div>");
}
displayFilePreviewJavascript(kmeliaScc.getComponentId(), out);
displayFileViewJavascript(kmeliaScc.getComponentId(), out);
out.write(board.printAfter());
} else if (showNoPublisMessage
&& (toSearch || kmeliaScc.getNbPublicationsOnRoot() != 0 || !currentTopicId.equals("0"))) {
String noPublications = kmeliaScc.getString("PubAucune");
if (toSearch) {
noPublications = kmeliaScc.getString("NoPubFound");
}
out.write("<div id=\"noPublicationMessage\">");
out.write(board.printBefore());
out.write("<table width=\"100%\" border=\"0\" cellspacing=\"0\" align=\"center\">");
out.write("<tr valign=\"middle\">");
out.write("<td width=\"80\"><img src=\"" + publicationSrc + "\" border=\"0\"/></td>");
out.write("<td align=\"left\"><b>" + resources.getString("GML.publications")
+ "</b></td></tr>");
out.write("<tr><td colspan=\"2\"> </td></tr>");
out.write("<tr>");
out.write("<td> </td>");
out.write("<td>" + noPublications + "</td>");
out.write("</tr>");
out.write("</table>");
out.write(board.printAfter());
out.write("</div>");
}
out.write("</form>");
}
| private void displayPublications(List<KmeliaPublication> allPubs,
boolean sortAllowed, boolean linksAllowed, boolean seeAlso, boolean toSearch,
KmeliaSessionController kmeliaScc, String profile,
GraphicElementFactory gef, String context, ResourcesWrapper resources,
List<String> selectedIds, String pubIdToHighlight, Writer out, boolean linkAttachment)
throws IOException {
String publicationSrc = resources.getIcon("kmelia.publication");
ResourceLocator publicationSettings = new ResourceLocator(
"org.silverpeas.util.publication.publicationSettings", kmeliaScc.getLanguage());
boolean showNoPublisMessage = resources.getSetting("showNoPublisMessage", true);
String language = kmeliaScc.getCurrentLanguage();
String currentUserId = kmeliaScc.getUserDetail().getId();
String currentTopicId = kmeliaScc.getCurrentFolderId();
boolean specificTemplateUsed = kmeliaScc.isCustomPublicationTemplateUsed();
PublicationFragmentSettings fragmentSettings = new PublicationFragmentSettings();
fragmentSettings.displayLinks = URLManager.displayUniversalLinks();
fragmentSettings.showImportance = kmeliaScc.isFieldImportanceVisible();
fragmentSettings.fileStorageShowExtraInfoPub = resources.getSetting(
"fileStorageShowExtraInfoPub", false);
fragmentSettings.showTopicPathNameinSearchResult = resources.getSetting(
"showTopicPathNameinSearchResult", true);
fragmentSettings.showDelegatedNewsInfo = kmeliaScc.isNewsManage() && !user.isInRole(profile);
fragmentSettings.toSearch = toSearch;
int nbPubsPerPage = kmeliaScc.getNbPublicationsPerPage();
int firstDisplayedItemIndex = kmeliaScc.getIndexOfFirstPubToDisplay();
int nbPubs = allPubs.size();
Board board = gef.getBoard();
Pagination pagination = gef.getPagination(nbPubs, nbPubsPerPage, firstDisplayedItemIndex);
List<KmeliaPublication> pubs = allPubs.subList(pagination.getFirstItemIndex(), pagination.
getLastItemIndex());
out.write("<form name=\"publicationsForm\" onsubmit=\"return false;\">");
if (!pubs.isEmpty()) {
out.write(board.printBefore());
displayPublicationsListHeader(nbPubs, sortAllowed, pagination, resources, kmeliaScc, out);
out.write("<ul>");
for (KmeliaPublication aPub : pubs) {
PublicationDetail pub = aPub.getDetail();
UserDetail currentUser = aPub.getCreator();
String pubColor = "";
String pubState = null;
String highlightClass = "";
if (StringUtil.isDefined(pubIdToHighlight) && pubIdToHighlight.equals(pub.getPK().getId())) {
highlightClass = "highlight";
}
out.write("<!-- Publication Body -->");
if (pub.getStatus() != null && pub.isValid()) {
if (pub.haveGotClone() && CLONE.equals(pub.getCloneStatus()) && !user.isInRole(profile)) {
pubColor = "blue";
pubState = resources.getString("kmelia.UpdateInProgress");
} else if (DRAFT.equals(pub.getCloneStatus())) {
if (currentUserId.equals(currentUser.getId())) {
pubColor = "gray";
pubState = resources.getString("PubStateDraft");
}
} else if (TO_VALIDATE.equals(pub.getCloneStatus())) {
if (admin.isInRole(profile) || publisher.isInRole(profile)
|| currentUserId.equals(currentUser.getId())) {
pubColor = "red";
pubState = resources.getString("kmelia.PubStateToValidate");
}
} else {
if (pub.isNotYetVisible()) {
pubState = resources.getString("kmelia.VisibleFrom") + " "
+ resources.getOutputDateAndHour(pub.getBeginDateAndHour());
} else if (pub.isNoMoreVisible()) {
pubState = resources.getString("kmelia.VisibleTo") + " "
+ resources.getOutputDateAndHour(pub.getEndDateAndHour());
}
if (!pub.isVisible()) {
pubColor = "gray";
}
}
} else {
if (pub.getStatus() != null && pub.isDraft()) {
if (currentUserId.equals(pub.getUpdaterId())
|| ((kmeliaScc.isCoWritingEnable() && kmeliaScc.isDraftVisibleWithCoWriting())
&& !user.isInRole(profile))) {
pubColor = "gray";
pubState = resources.getString("PubStateDraft");
}
} else if (pub.getStatus() != null && pub.isRefused()) {
if (admin.isInRole(profile) || publisher.isInRole(profile)
|| currentUserId.equals(currentUser.getId())) {
pubColor = "red";
pubState = resources.getString("PublicationRefused");
}
} else {
if (admin.isInRole(profile) || publisher.isInRole(profile)
|| currentUserId.equals(pub.getUpdaterId())
|| (!user.isInRole(profile) && kmeliaScc.isCoWritingEnable())) {
pubColor = "red";
if (pub.isRefused()) {
pubState = resources.getString("kmelia.PubStateUnvalidate");
} else {
pubState = resources.getString("kmelia.PubStateToValidate");
}
}
}
}
if (!pub.getPK().getInstanceId().equals(kmeliaScc.getComponentId())) {
pubState = resources.getString("kmelia.Shortcut");
}
String cssClass = "";
if (toSearch) {
if (aPub.read) {
cssClass = " class=\"read\"";
} else {
cssClass = " class=\"unread\"";
}
}
out.write("<li");
out.write(cssClass);
out.write(" onmouseover=\"showPublicationOperations(this);\"");
out.write(" onmouseout=\"hidePublicationOperations(this);\">");
out.write("<div class=\"firstColumn\">");
if (!kmeliaScc.getUserDetail().isAnonymous() && !kmeliaScc.isKmaxMode) {
String checked = "";
if (selectedIds != null && selectedIds.contains(pub.getPK().getId())) {
checked = "checked=\"checked\"";
}
out.write("<span class=\"selection\">");
out.write("<input type=\"checkbox\" name=\"C1\" value=\""
+ pub.getPK().getId() + "/" + pub.getPK().getInstanceId() + "\" " + checked
+ " onclick=\"sendPubId(this.value, this.checked);\"/>");
out.write("</span>");
}
if (!seeAlso) {
ThumbnailDetail thumbnail = pub.getThumbnail();
if (thumbnail != null && Boolean.valueOf(resources.getSetting("isVignetteVisible"))) {
out.write("<span class=\"thumbnail\">");
try {
displayThumbnail(pub, kmeliaScc, publicationSettings, out);
} catch (ThumbnailException e) {
SilverTrace.info("kmelia", "AjaxPublicationsListServlet.displayPublications()",
"root.MSG_GEN_ENTER_METHOD", "exception = " + e);
}
out.write("</span>");
} else {
out.write("<span class=\"thumbnail\">");
out.write("<img src=\"" + resources.getIcon("kmelia.1px") + "\" alt=\"\"/>");
out.write("</span>");
}
}
out.write("</div>");
fragmentSettings.pubColor = pubColor;
fragmentSettings.highlightClass = highlightClass;
fragmentSettings.pubState = pubState;
fragmentSettings.linksAllowed = linksAllowed;
fragmentSettings.seeAlso = seeAlso;
fragmentSettings.linkAttachment = linkAttachment;
out.write("<div class=\"publication\"><a name=\"" + pub.getPK().getId() + "\"></a>");
displayFragmentOfPublication(specificTemplateUsed, aPub, fragmentSettings, language,
currentUserId, currentTopicId, kmeliaScc, resources, out);
out.write("</div>");
}
out.write("</ul>");
if (nbPubs > nbPubsPerPage) {
out.write("<div id=\"pagination\">");
out.write(pagination.printIndex("doPagination"));
out.write("</div>");
}
displayFilePreviewJavascript(kmeliaScc.getComponentId(), out);
displayFileViewJavascript(kmeliaScc.getComponentId(), out);
out.write(board.printAfter());
} else if (showNoPublisMessage
&& (toSearch || kmeliaScc.getNbPublicationsOnRoot() != 0 || !currentTopicId.equals("0"))) {
String noPublications = kmeliaScc.getString("PubAucune");
if (toSearch) {
noPublications = kmeliaScc.getString("NoPubFound");
}
out.write("<div id=\"noPublicationMessage\">");
out.write(board.printBefore());
out.write("<table width=\"100%\" border=\"0\" cellspacing=\"0\" align=\"center\">");
out.write("<tr valign=\"middle\">");
out.write("<td width=\"80\"><img src=\"" + publicationSrc + "\" border=\"0\"/></td>");
out.write("<td align=\"left\"><b>" + resources.getString("GML.publications")
+ "</b></td></tr>");
out.write("<tr><td colspan=\"2\"> </td></tr>");
out.write("<tr>");
out.write("<td> </td>");
out.write("<td>" + noPublications + "</td>");
out.write("</tr>");
out.write("</table>");
out.write(board.printAfter());
out.write("</div>");
}
out.write("</form>");
}
|
public static Object clone(Object o) {
if (o instanceof Cloneable) {
try {
Method clone = o.getClass().getMethod("clone", (Class[])null);
return clone.invoke(o, (Object[])null);
} catch (NoSuchMethodException e) {
new ObjectAccessException("Cloneable type has no clone method", e);
} catch (IllegalAccessException e) {
new ObjectAccessException("Cannot clone Cloneable type", e);
} catch (InvocationTargetException e) {
new ObjectAccessException("Exception cloning Cloneable type", e.getCause());
}
}
return null;
}
| public static Object clone(Object o) {
if (o instanceof Cloneable) {
try {
Method clone = o.getClass().getMethod("clone", (Class[])null);
return clone.invoke(o, (Object[])null);
} catch (NoSuchMethodException e) {
throw new ObjectAccessException("Cloneable type has no clone method", e);
} catch (IllegalAccessException e) {
throw new ObjectAccessException("Cannot clone Cloneable type", e);
} catch (InvocationTargetException e) {
throw new ObjectAccessException("Exception cloning Cloneable type", e.getCause());
}
}
return null;
}
|
private String buildContextForTemplate(String preIndex, int index, VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters();
context.put("tlang", rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
if (preIndex != null)
context.put("backIndex", preIndex);
context.put("templateIndex", String.valueOf(index));
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
List roles = new Vector();
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) {
context.put("totalSteps", state
.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) {
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString(
"withDissertation", Boolean.FALSE.toString());
context.put("cms", cms);
context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE));
context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite());
Site site = getStateSite(state);
switch (index) {
case 0:
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser()) {
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
views.put(rb.getString("java.my") + " "
+ rb.getString("java.sites"), rb.getString("java.my"));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true")) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true")) {
try {
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
if (!isGradToolsCandidate(userId)) {
remove = true;
}
} catch (Exception e) {
remove = true;
M_log.warn(this + "buildContextForTemplate chef_site-list.vm list GradToolsStudent sites", e);
}
} else {
remove = true;
}
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) {
views
.put(type + " " + rb.getString("java.sites"),
type);
}
}
if (!remove) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
}
context.put("views", views);
if (state.getAttribute(STATE_VIEW_SELECTED) != null) {
context.put("viewSelected", (String) state
.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute(SORTED_BY);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state
.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state
.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
Menu bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add(new MenuEntry(rb.getString("java.revise"), null, true,
MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add(new MenuEntry(rb.getString("java.delete"), null, true,
MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String) getContext(data).get("template") + TEMPLATE[0];
case 1:
if (hasGradSites.equalsIgnoreCase("true")) {
context.put("withDissertation", Boolean.TRUE);
try {
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
Boolean isGradStudent = new Boolean(
isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
boolean noGradToolsSite = true;
if (hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context
.put("noGradToolsSite",
new Boolean(noGradToolsSite));
} catch (Exception e) {
M_log.warn(this + "buildContextForTemplate chef_site-type.vm ", e);
}
} else {
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
String typeSelected = (String) state.getAttribute(STATE_TYPE_SELECTED);
context.put("typeSelected", state.getAttribute(STATE_TYPE_SELECTED) != null?state.getAttribute(STATE_TYPE_SELECTED):types.get(0));
setTermListForContext(context, state, true);
setSelectedTermForContext(context, state, STATE_TERM_SELECTED);
setTemplateListForContext(context, state);
return (String) getContext(data).get("template") + TEMPLATE[1];
case 2:
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("type", siteType);
if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
List<SectionObject> cmRequestedList = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (cmRequestedList != null) {
context.put("cmRequestedSections", cmRequestedList);
}
List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (cmAuthorizerSectionList != null) {
context
.put("cmAuthorizerSections",
cmAuthorizerSectionList);
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
} else {
if (courseManagementIsImplemented()) {
} else {
context.put("templateIndex", "37");
}
}
courseSkinSelection(context, state, null, siteInfo);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
}
if (state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE) != null) {
context.put("titleEditableSiteType", Boolean.FALSE);
siteInfo.title = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE);
} else {
context.put("titleEditableSiteType", state
.getAttribute(TITLE_EDITABLE_SITE_TYPE));
}
context.put(FORM_TITLE, siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put(FORM_DESCRIPTION, siteInfo.description);
if (siteInfo.site_contact_name.equals(NULL_STRING)
&& siteInfo.site_contact_email.equals(NULL_STRING)) {
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[2];
case 3:
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
List defaultSelectedTools = ServerConfigurationService
.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList);
context.put(STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
Boolean checkHome = (Boolean) state
.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null)
&& defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[3];
case 4:
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(type));
boolean myworkspace_site = false;
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type)) {
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId())
|| (type != null && type.equalsIgnoreCase("myworkspace"))) {
myworkspace_site = true;
type = "myworkspace";
}
context.put("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases
.get(0)).getId());
} else {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[4];
case 5:
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("isCourseSite", siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))?Boolean.TRUE:Boolean.FALSE);
context.put("officialAccountSectionTitle", ServerConfigurationService
.getString("officialAccountSectionTitle"));
context.put("officialAccountName", ServerConfigurationService
.getString("officialAccountName"));
context.put("officialAccountLabel", ServerConfigurationService
.getString("officialAccountLabel"));
if (state.getAttribute("officialAccountValue") != null) {
context.put("officialAccountValue", (String) state
.getAttribute("officialAccountValue"));
}
String addNonOfficialParticipant = (String) state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT);
if (addNonOfficialParticipant != null)
{
if (addNonOfficialParticipant.equalsIgnoreCase("true"))
{
context.put("nonOfficialAccount", Boolean.TRUE);
context.put("nonOfficialAccountSectionTitle", ServerConfigurationService
.getString("nonOfficialAccountSectionTitle"));
context.put("nonOfficialAccountName", ServerConfigurationService
.getString("nonOfficialAccountName"));
context.put("nonOfficialAccountLabel", ServerConfigurationService
.getString("nonOfficialAccountLabel"));
if (state.getAttribute("nonOfficialAccountValue") != null) {
context.put("nonOfficialAccountValue", (String) state
.getAttribute("nonOfficialAccountValue"));
}
}
else
{
context.put("nonOfficialAccount", Boolean.FALSE);
}
}
if (state.getAttribute("form_same_role") != null) {
context.put("form_same_role", ((Boolean) state
.getAttribute("form_same_role")).toString());
} else {
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[5];
case 8:
String site_title = NULL_STRING;
String[] removals = (String[]) state
.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if (removals != null && removals.length != 0) {
for (int i = 0; i < removals.length; i++) {
String id = (String) removals[i];
if (!(id.equals(workspace))) {
try {
site_title = SiteService.getSite(id).getTitle();
} catch (IdUnusedException e) {
M_log.warn(this + "buildContextForTemplate chef_site-siteDeleteConfirm.vm - IdUnusedException " + id, e);
addAlert(state, rb.getString("java.sitewith") + " "
+ id + " " + rb.getString("java.couldnt")
+ " ");
}
if (SiteService.allowRemoveSite(id)) {
try {
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
} catch (IdUnusedException e) {
M_log.warn(this + ".buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException", e);
}
} else {
addAlert(state, site_title + " "
+ rb.getString("java.couldntdel") + " ");
}
} else {
addAlert(state, rb.getString("java.yourwork"));
}
}
if (remove.size() == 0) {
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String) getContext(data).get("template") + TEMPLATE[8];
case 10:
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
context.put("selectedAuthorizerCourse", state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("selectedRequestedCourse", state
.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType != null && siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList);
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("importSiteTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[10];
case 12:
context.put("userDirectoryService", UserDirectoryService
.getInstance());
try {
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null) {
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
isMyWorkspace = true;
context.put("siteUserId", SiteService
.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS) != null) {
List skins = (List) state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++) {
MyIcon s = (MyIcon) skins.get(i);
if (!StringUtil
.different(s.getUrl(), site.getIconUrl())) {
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if (site.isPublished()) {
context.put("published", Boolean.TRUE);
} else {
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null) {
context.put("siteCreationDate", creationTime
.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService
.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean
.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService
.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean
.valueOf(allowUpdateSiteMembership));
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (allowUpdateSite)
{
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.editsite"),
"doMenu_edit_site_info"));
}
b.add(new MenuEntry(rb.getString("java.edittools"),
"doMenu_edit_site_tools"));
if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) {
b.add(new MenuEntry(rb.getString("java.orderpages"),
"doPageOrderHelper"));
}
}
if (allowUpdateSiteMembership)
{
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.addp"),
"doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
b.add(new MenuEntry(rb.getString("java.editc"),
"doMenu_siteInfo_editClass"));
}
}
}
if (allowUpdateGroupMembership) {
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
b.add(new MenuEntry(rb.getString("java.group"),
"doMenu_group"));
}
}
if (allowUpdateSite)
{
if (!isMyWorkspace) {
List gradToolsSiteTypes = (List) state
.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null
&& gradToolsSiteTypes.contains(siteType)) {
isGradToolSite = true;
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
b.add(new MenuEntry(
rb.getString("java.siteaccess"),
"doMenu_edit_site_access"));
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
if (SiteService.allowAddSite(null))
{
b.add(new MenuEntry(rb.getString("java.duplicate"),
"doMenu_siteInfo_duplicate"));
}
List updatableSites = SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null,
SortType.TITLE_ASC, null);
if (updatableSites.size() > 0) {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_import"));
String importFromFile = ServerConfigurationService
.getString("site.setup.import.file",
Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true")) {
b.add(new MenuEntry(rb
.getString("java.importFile"),
"doAttachmentsMtrlFrmFile"));
}
}
}
}
}
if (b.size() > 0)
{
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null) {
context.put("prevSite", state
.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null) {
context.put("nextSite", state
.getAttribute(STATE_NEXT_SITE));
}
} else {
context.put("fromWSetup", Boolean.FALSE);
}
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster) {
context.put("viewRoster", Boolean.TRUE);
} else {
context.put("viewRoster", Boolean.FALSE);
}
if (allowUpdateSite || allowViewRoster
|| allowUpdateSiteMembership) {
Collection participantsCollection = getParticipantList(state);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy == null) {
state.setAttribute(SORTED_BY,
SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
context.put("participantListSize", new Integer(participantsCollection.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
String contactName = siteProperties
.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null) {
context.put("contactName", contactName);
}
if (contactEmail != null) {
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
coursesIntoContext(state, context, site);
context.put("term", siteProperties
.getProperty(PROP_SITE_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
} catch (Exception e) {
M_log.warn(this + " buildContextForTemplate chef_site-siteInfo-list.vm ", e);
}
roles = getRoles(state);
context.put("roles", roles);
String activeInactiveUser = ServerConfigurationService.getString(
"activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true")) {
context.put("activeInactiveUser", Boolean.TRUE);
} else {
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site
.getGroupsWithMember(UserDirectoryService.getCurrentUser()
.getId()));
return (String) getContext(data).get("template") + TEMPLATE[12];
case 13:
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, site.getType())));
context.put("type", site.getType());
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
courseSkinSelection(context, state, site, null);
setTermListForContext(context, state, true);
if (state.getAttribute(FORM_SITEINFO_TERM) == null) {
String currentTerm = site.getProperties().getProperty(
PROP_SITE_TERM);
if (currentTerm != null) {
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
setSelectedTermForContext(context, state, FORM_SITEINFO_TERM);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null
&& StringUtil.trimToNull(site.getIconUrl()) != null) {
state.setAttribute(FORM_SITEINFO_ICON_URL, site
.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) {
context.put("iconUrl", state
.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state
.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
return (String) getContext(data).get("template") + TEMPLATE[13];
case 14:
siteProperties = site.getProperties();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties
.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String) getContext(data).get("template") + TEMPLATE[14];
case 15:
context.put("title", site.getTitle());
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state
.getAttribute(STATE_SITE_TYPE), (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
return (String) getContext(data).get("template") + TEMPLATE[15];
case 18:
List publicChangeableSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state
.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null) {
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state
.getAttribute(STATE_SITE_TYPE)
: null;
if (siteType != null
&& publicChangeableSiteTypes.contains(siteType)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if (siteType != null && !unJoinableSiteTypes.contains(siteType)) {
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null) {
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site
.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null
&& ((Boolean) state.getAttribute(STATE_JOINABLE))
.booleanValue()) {
state.setAttribute(STATE_JOINERROLE, site
.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null) {
context.put("joinable", state
.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null) {
context.put("joinerRole", state
.getAttribute(STATE_JOINERROLE));
}
} else {
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
} else {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo.site_type != null
&& publicChangeableSiteTypes
.contains(siteInfo.site_type)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo
.getPublished()));
if (siteInfo.site_type != null
&& !unJoinableSiteTypes.contains(siteInfo.site_type)) {
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
} else {
context.put("disableJoinable", Boolean.TRUE);
}
String realmTemplate = "!site.template";
if (siteInfo.site_type != null) {
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try {
AuthzGroup r = AuthzGroupService
.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
} catch (GroupNotDefinedException e) {
try {
AuthzGroup rr = AuthzGroupService
.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
} catch (GroupNotDefinedException ee) {
}
}
context.put("continue", "10");
Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String) getContext(data).get("template") + TEMPLATE[18];
case 19:
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[19];
case 20:
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
return (String) getContext(data).get("template") + TEMPLATE[20];
case 21:
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null) {
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role") == null ? true
: ((Boolean) state.getAttribute("form_same_role"))
.booleanValue();
if (same_role) {
context.put("backIndex", "19");
} else {
context.put("backIndex", "20");
}
return (String) getContext(data).get("template") + TEMPLATE[21];
case 22:
context.put("title", site.getTitle());
context.put("participants", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context
.put("selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[22];
case 26:
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null ? true : false;
if (existingSite) {
context.put("existingSite", Boolean.TRUE);
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
} else {
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
context.put("continue", "18");
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList);
context.put(STATE_MULTIPLE_TOOL_ID_SET, state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP));
context.put("toolManager", ToolManager.getInstance());
String emailId = (String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null) {
context.put("emailId", emailId);
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String) getContext(data).get("template") + TEMPLATE[26];
case 27:
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite) {
context.put("continue", "12");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
} else {
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
context.put("existingSite", Boolean.valueOf(existingSite));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("selectedTools", orderToolIds(state, site_type,
(List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String) getContext(data).get("template") + TEMPLATE[27];
case 28:
context.put("currentSite", site);
context.put("importSiteList", state
.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
return (String) getContext(data).get("template") + TEMPLATE[28];
case 29:
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(
PROP_SITE_TERM));
setTermListForContext(context, state, true);
} else {
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null) {
context.put("siteDuplicated", Boolean.FALSE);
} else {
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state
.getAttribute(SITE_DUPLICATED_NAME));
}
return (String) getContext(data).get("template") + TEMPLATE[29];
case 36:
Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE);
context.put("enableCourseCreationForUser", enableCourseCreationForUser);
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
setTermListForContext(context, state, true);
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
coursesIntoContext(state, context, site);
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
context.put("term", t);
if (t != null) {
String userId = UserDirectoryService.getCurrentUser().getEid();
List courses = prepareCourseAndSectionListing(userId, t
.getEid(), state);
if (courses != null && courses.size() > 0) {
Vector notIncludedCourse = new Vector();
for (Iterator i = courses.iterator(); i.hasNext();) {
CourseObject c = (CourseObject) i.next();
if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) {
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST,
notIncludedCourse);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
} else {
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
|| state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
List<String> providerSectionList = (List<String>) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerSectionList != null) {
context.put("selectedProviderCourse", providerSectionList);
}
List<SectionObject> authorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSectionList != null) {
List authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
ArrayList list2 = new ArrayList();
for (int i=0; i<authorizerSectionList.size();i++){
SectionObject so = (SectionObject)authorizerSectionList.get(i);
list2.add(so.getEid());
}
context.put("selectedAuthorizerCourse", list2);
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("currentUserId", (String) state
.getAttribute(STATE_CM_CURRENT_USERID));
context.put("form_additional", (String) state
.getAttribute(FORM_ADDITIONAL));
context.put("authorizers", getAuthorizers(state));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "1");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
context.put("backIndex", "");
}
List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST);
context.put("termCourseList", state
.getAttribute(STATE_TERM_COURSE_LIST));
context.put("campusDirectory", getCampusDirectory());
context.put("userId", (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED));
return (String) getContext(data).get("template") + TEMPLATE[36];
case 37:
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("officialAccountName", ServerConfigurationService
.getString("officialAccountName", ""));
context.put("value_uniqname", state
.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", number>0?new Integer(number - 1):0);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0)
{
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
List l = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put("selectedProviderCourse", l);
context.put("size", new Integer(l.size() - 1));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
List l = (List) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
context.put("cmRequestedSections", l);
}
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (site == null) {
if (state.getAttribute(STATE_AUTO_ADD) != null) {
context.put("autoAdd", Boolean.TRUE);
}
}
isFutureTermSelected(state);
context.put("isFutureTerm", state
.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString(
"roster.available.weeks.before.term.start", "0"));
return (String) getContext(data).get("template") + TEMPLATE[37];
case 42:
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state
.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList);
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList);
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String) getContext(data).get("template") + TEMPLATE[42];
case 43:
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.addclasses"),
"doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String) getContext(data).get("template") + TEMPLATE[43];
case 44:
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null)
{
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int addNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue() - 1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
} else {
context.put("backIndex", "36");
}
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[44];
case 45:
return (String) getContext(data).get("template") + TEMPLATE[45];
case 46:
context
.put("allZipSites", state
.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[46];
case 47:
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[47];
case 48:
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[48];
case 49:
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId())
|| SiteService.allowUpdateGroupMembership(site.getId())) {
bar.add(new MenuEntry(rb.getString("java.newgroup"), "doGroup_new"));
}
context.put("menu", bar);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for (Iterator gIterator = groups.iterator(); gIterator.hasNext();) {
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(
GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString())) {
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null) {
context.put("groups", new SortedIterator(groupsByWSetup
.iterator(), new SiteComparator(sortedBy, sortedAsc)));
}
return (String) getContext(data).get("template") + TEMPLATE[49];
case 50:
Group g = getStateGroup(state);
if (g != null) {
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
} else {
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null) {
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null) {
context.put("description", state
.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator(getParticipantList(state)
.iterator(), new SiteComparator(SORTED_BY_PARTICIPANT_NAME,
Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext()) {
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null) {
context.put("groupMembers", new SortedIterator(groupMembersSet
.iterator(), new SiteComparator(SORTED_BY_MEMBER_NAME,
Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService
.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[50];
case 51:
context.put("site", site);
context
.put("removeGroupIds", new ArrayList(Arrays
.asList((String[]) state
.getAttribute(STATE_GROUP_REMOVE))));
return (String) getContext(data).get("template") + TEMPLATE[51];
case 53: {
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
if (cmLevels == null)
{
cmLevels = getCMLevelLabels();
}
SectionObject selectedSect = (SectionObject) state
.getAttribute(STATE_CM_SELECTED_SECTION);
List<SectionObject> requestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (courseManagementIsImplemented() && cms != null) {
context.put("cmsAvailable", new Boolean(true));
}
int cmLevelSize = 0;
if (cms == null || !courseManagementIsImplemented()
|| cmLevels == null || cmLevels.size() < 1) {
} else {
cmLevelSize = cmLevels.size();
Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS);
int numSelections = 0;
if (selections != null)
numSelections = selections.size();
if (numSelections == cmLevelSize - 1)
{
levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1));
}
else if (numSelections == cmLevelSize - 2)
{
levelOpts[numSelections] = getCMCourseOfferings((String) selections.get(numSelections-1), t.getEid());
}
else if (numSelections < cmLevelSize)
{
levelOpts[numSelections] = sortCmObject(cms.findCourseSets((String) cmLevels.get(numSelections==0?0:numSelections-1)));
}
levelOpts[0] = sortCmObject(cms.findCourseSets((String) cmLevels.get(0)));
for (int i = numSelections + 1; i<cmLevelSize; i++)
{
levelOpts[i] = null;
}
context.put("cmLevelOptions", Arrays.asList(levelOpts));
state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts);
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int courseInd = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(courseInd - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("cmLevels", cmLevels);
context.put("cmLevelSelections", selections);
context.put("selectedCourse", selectedSect);
context.put("cmRequestedSections", requestedSections);
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_TERM_COURSE_LIST) != null)
{
context.put("backIndex", "36");
}
else
{
context.put("backIndex", "1");
}
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "36");
}
context.put("authzGroupService", AuthzGroupService.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[53];
}
case 54:
SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE));
if (siteTypeQuestions != null)
{
context.put("questionSet", siteTypeQuestions);
context.put("userAnswers", state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER));
}
context.put("continueIndex", state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE));
return (String) getContext(data).get("template") + TEMPLATE[54];
}
return (String) getContext(data).get("template") + TEMPLATE[0];
}
| private String buildContextForTemplate(String preIndex, int index, VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters();
context.put("tlang", rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
if (preIndex != null)
context.put("backIndex", preIndex);
context.put("templateIndex", String.valueOf(index));
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
List roles = new Vector();
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) {
context.put("totalSteps", state
.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) {
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString(
"withDissertation", Boolean.FALSE.toString());
context.put("cms", cms);
context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE));
context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite());
Site site = getStateSite(state);
switch (index) {
case 0:
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser()) {
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
views.put(rb.getString("java.my") + " "
+ rb.getString("java.sites"), rb.getString("java.my"));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true")) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true")) {
try {
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
if (!isGradToolsCandidate(userId)) {
remove = true;
}
} catch (Exception e) {
remove = true;
M_log.warn(this + "buildContextForTemplate chef_site-list.vm list GradToolsStudent sites", e);
}
} else {
remove = true;
}
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) {
views
.put(type + " " + rb.getString("java.sites"),
type);
}
}
if (!remove) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
}
context.put("views", views);
if (state.getAttribute(STATE_VIEW_SELECTED) != null) {
context.put("viewSelected", (String) state
.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute(SORTED_BY);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state
.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state
.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
Menu bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add(new MenuEntry(rb.getString("java.revise"), null, true,
MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add(new MenuEntry(rb.getString("java.delete"), null, true,
MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String) getContext(data).get("template") + TEMPLATE[0];
case 1:
if (hasGradSites.equalsIgnoreCase("true")) {
context.put("withDissertation", Boolean.TRUE);
try {
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
Boolean isGradStudent = new Boolean(
isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
boolean noGradToolsSite = true;
if (hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context
.put("noGradToolsSite",
new Boolean(noGradToolsSite));
} catch (Exception e) {
M_log.warn(this + "buildContextForTemplate chef_site-type.vm ", e);
}
} else {
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
String typeSelected = (String) state.getAttribute(STATE_TYPE_SELECTED);
context.put("typeSelected", state.getAttribute(STATE_TYPE_SELECTED) != null?state.getAttribute(STATE_TYPE_SELECTED):types.get(0));
setTermListForContext(context, state, true);
setSelectedTermForContext(context, state, STATE_TERM_SELECTED);
setTemplateListForContext(context, state);
return (String) getContext(data).get("template") + TEMPLATE[1];
case 2:
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("type", siteType);
if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
List<SectionObject> cmRequestedList = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (cmRequestedList != null) {
context.put("cmRequestedSections", cmRequestedList);
}
List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (cmAuthorizerSectionList != null) {
context
.put("cmAuthorizerSections",
cmAuthorizerSectionList);
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
} else {
if (courseManagementIsImplemented()) {
} else {
context.put("templateIndex", "37");
}
}
courseSkinSelection(context, state, null, siteInfo);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
}
if (state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE) != null) {
context.put("titleEditableSiteType", Boolean.FALSE);
siteInfo.title = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE);
} else {
context.put("titleEditableSiteType", state
.getAttribute(TITLE_EDITABLE_SITE_TYPE));
}
context.put(FORM_TITLE, siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put(FORM_DESCRIPTION, siteInfo.description);
if (siteInfo.site_contact_name.equals(NULL_STRING)
&& siteInfo.site_contact_email.equals(NULL_STRING)) {
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[2];
case 3:
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
List defaultSelectedTools = ServerConfigurationService
.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList);
context.put(STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
Boolean checkHome = (Boolean) state
.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null)
&& defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[3];
case 4:
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(type));
boolean myworkspace_site = false;
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type)) {
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId())
|| (type != null && type.equalsIgnoreCase("myworkspace"))) {
myworkspace_site = true;
type = "myworkspace";
}
context.put("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases
.get(0)).getId());
} else {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[4];
case 5:
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("isCourseSite", siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))?Boolean.TRUE:Boolean.FALSE);
context.put("officialAccountSectionTitle", ServerConfigurationService
.getString("officialAccountSectionTitle"));
context.put("officialAccountName", ServerConfigurationService
.getString("officialAccountName"));
context.put("officialAccountLabel", ServerConfigurationService
.getString("officialAccountLabel"));
String pickerAction = ServerConfigurationService.getString("officialAccountPickerAction");
if (pickerAction != null && !"".equals(pickerAction))
{
context.put("hasPickerDefined", Boolean.TRUE);
context.put("officialAccountPickerLabel", ServerConfigurationService
.getString("officialAccountPickerLabel"));
context.put("officialAccountPickerAction", pickerAction);
}
if (state.getAttribute("officialAccountValue") != null) {
context.put("officialAccountValue", (String) state
.getAttribute("officialAccountValue"));
}
String addNonOfficialParticipant = (String) state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT);
if (addNonOfficialParticipant != null)
{
if (addNonOfficialParticipant.equalsIgnoreCase("true"))
{
context.put("nonOfficialAccount", Boolean.TRUE);
context.put("nonOfficialAccountSectionTitle", ServerConfigurationService
.getString("nonOfficialAccountSectionTitle"));
context.put("nonOfficialAccountName", ServerConfigurationService
.getString("nonOfficialAccountName"));
context.put("nonOfficialAccountLabel", ServerConfigurationService
.getString("nonOfficialAccountLabel"));
if (state.getAttribute("nonOfficialAccountValue") != null) {
context.put("nonOfficialAccountValue", (String) state
.getAttribute("nonOfficialAccountValue"));
}
}
else
{
context.put("nonOfficialAccount", Boolean.FALSE);
}
}
if (state.getAttribute("form_same_role") != null) {
context.put("form_same_role", ((Boolean) state
.getAttribute("form_same_role")).toString());
} else {
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[5];
case 8:
String site_title = NULL_STRING;
String[] removals = (String[]) state
.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if (removals != null && removals.length != 0) {
for (int i = 0; i < removals.length; i++) {
String id = (String) removals[i];
if (!(id.equals(workspace))) {
try {
site_title = SiteService.getSite(id).getTitle();
} catch (IdUnusedException e) {
M_log.warn(this + "buildContextForTemplate chef_site-siteDeleteConfirm.vm - IdUnusedException " + id, e);
addAlert(state, rb.getString("java.sitewith") + " "
+ id + " " + rb.getString("java.couldnt")
+ " ");
}
if (SiteService.allowRemoveSite(id)) {
try {
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
} catch (IdUnusedException e) {
M_log.warn(this + ".buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException", e);
}
} else {
addAlert(state, site_title + " "
+ rb.getString("java.couldntdel") + " ");
}
} else {
addAlert(state, rb.getString("java.yourwork"));
}
}
if (remove.size() == 0) {
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String) getContext(data).get("template") + TEMPLATE[8];
case 10:
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
context.put("selectedAuthorizerCourse", state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("selectedRequestedCourse", state
.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType != null && siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList);
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
context.put("importSiteTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[10];
case 12:
context.put("userDirectoryService", UserDirectoryService
.getInstance());
try {
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null) {
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
isMyWorkspace = true;
context.put("siteUserId", SiteService
.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS) != null) {
List skins = (List) state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++) {
MyIcon s = (MyIcon) skins.get(i);
if (!StringUtil
.different(s.getUrl(), site.getIconUrl())) {
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if (site.isPublished()) {
context.put("published", Boolean.TRUE);
} else {
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null) {
context.put("siteCreationDate", creationTime
.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService
.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean
.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService
.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean
.valueOf(allowUpdateSiteMembership));
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (allowUpdateSite)
{
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.editsite"),
"doMenu_edit_site_info"));
}
b.add(new MenuEntry(rb.getString("java.edittools"),
"doMenu_edit_site_tools"));
if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) {
b.add(new MenuEntry(rb.getString("java.orderpages"),
"doPageOrderHelper"));
}
}
if (allowUpdateSiteMembership)
{
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.addp"),
"doMenu_siteInfo_addParticipant"));
if (siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
b.add(new MenuEntry(rb.getString("java.editc"),
"doMenu_siteInfo_editClass"));
}
}
}
if (allowUpdateGroupMembership) {
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
b.add(new MenuEntry(rb.getString("java.group"),
"doMenu_group"));
}
}
if (allowUpdateSite)
{
if (!isMyWorkspace) {
List gradToolsSiteTypes = (List) state
.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null
&& gradToolsSiteTypes.contains(siteType)) {
isGradToolSite = true;
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
b.add(new MenuEntry(
rb.getString("java.siteaccess"),
"doMenu_edit_site_access"));
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
if (SiteService.allowAddSite(null))
{
b.add(new MenuEntry(rb.getString("java.duplicate"),
"doMenu_siteInfo_duplicate"));
}
List updatableSites = SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null,
SortType.TITLE_ASC, null);
if (updatableSites.size() > 0) {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_import"));
String importFromFile = ServerConfigurationService
.getString("site.setup.import.file",
Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true")) {
b.add(new MenuEntry(rb
.getString("java.importFile"),
"doAttachmentsMtrlFrmFile"));
}
}
}
}
}
if (b.size() > 0)
{
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null) {
context.put("prevSite", state
.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null) {
context.put("nextSite", state
.getAttribute(STATE_NEXT_SITE));
}
} else {
context.put("fromWSetup", Boolean.FALSE);
}
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster) {
context.put("viewRoster", Boolean.TRUE);
} else {
context.put("viewRoster", Boolean.FALSE);
}
if (allowUpdateSite || allowViewRoster
|| allowUpdateSiteMembership) {
Collection participantsCollection = getParticipantList(state);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy == null) {
state.setAttribute(SORTED_BY,
SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
context.put("participantListSize", new Integer(participantsCollection.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
String contactName = siteProperties
.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null) {
context.put("contactName", contactName);
}
if (contactEmail != null) {
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
coursesIntoContext(state, context, site);
context.put("term", siteProperties
.getProperty(PROP_SITE_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
} catch (Exception e) {
M_log.warn(this + " buildContextForTemplate chef_site-siteInfo-list.vm ", e);
}
roles = getRoles(state);
context.put("roles", roles);
String activeInactiveUser = ServerConfigurationService.getString(
"activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true")) {
context.put("activeInactiveUser", Boolean.TRUE);
} else {
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site
.getGroupsWithMember(UserDirectoryService.getCurrentUser()
.getId()));
return (String) getContext(data).get("template") + TEMPLATE[12];
case 13:
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, site.getType())));
context.put("type", site.getType());
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
courseSkinSelection(context, state, site, null);
setTermListForContext(context, state, true);
if (state.getAttribute(FORM_SITEINFO_TERM) == null) {
String currentTerm = site.getProperties().getProperty(
PROP_SITE_TERM);
if (currentTerm != null) {
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
setSelectedTermForContext(context, state, FORM_SITEINFO_TERM);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null
&& StringUtil.trimToNull(site.getIconUrl()) != null) {
state.setAttribute(FORM_SITEINFO_ICON_URL, site
.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) {
context.put("iconUrl", state
.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state
.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
return (String) getContext(data).get("template") + TEMPLATE[13];
case 14:
siteProperties = site.getProperties();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties
.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String) getContext(data).get("template") + TEMPLATE[14];
case 15:
context.put("title", site.getTitle());
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state
.getAttribute(STATE_SITE_TYPE), (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
return (String) getContext(data).get("template") + TEMPLATE[15];
case 18:
List publicChangeableSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state
.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null) {
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state
.getAttribute(STATE_SITE_TYPE)
: null;
if (siteType != null
&& publicChangeableSiteTypes.contains(siteType)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if (siteType != null && !unJoinableSiteTypes.contains(siteType)) {
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null) {
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site
.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null
&& ((Boolean) state.getAttribute(STATE_JOINABLE))
.booleanValue()) {
state.setAttribute(STATE_JOINERROLE, site
.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null) {
context.put("joinable", state
.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null) {
context.put("joinerRole", state
.getAttribute(STATE_JOINERROLE));
}
} else {
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
} else {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo.site_type != null
&& publicChangeableSiteTypes
.contains(siteInfo.site_type)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo
.getPublished()));
if (siteInfo.site_type != null
&& !unJoinableSiteTypes.contains(siteInfo.site_type)) {
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
} else {
context.put("disableJoinable", Boolean.TRUE);
}
String realmTemplate = "!site.template";
if (siteInfo.site_type != null) {
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try {
AuthzGroup r = AuthzGroupService
.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
} catch (GroupNotDefinedException e) {
try {
AuthzGroup rr = AuthzGroupService
.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
} catch (GroupNotDefinedException ee) {
}
}
context.put("continue", "10");
Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String) getContext(data).get("template") + TEMPLATE[18];
case 19:
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[19];
case 20:
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
return (String) getContext(data).get("template") + TEMPLATE[20];
case 21:
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null) {
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role") == null ? true
: ((Boolean) state.getAttribute("form_same_role"))
.booleanValue();
if (same_role) {
context.put("backIndex", "19");
} else {
context.put("backIndex", "20");
}
return (String) getContext(data).get("template") + TEMPLATE[21];
case 22:
context.put("title", site.getTitle());
context.put("participants", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context
.put("selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[22];
case 26:
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null ? true : false;
if (existingSite) {
context.put("existingSite", Boolean.TRUE);
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
} else {
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
context.put("continue", "18");
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList);
context.put(STATE_MULTIPLE_TOOL_ID_SET, state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP));
context.put("toolManager", ToolManager.getInstance());
String emailId = (String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null) {
context.put("emailId", emailId);
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String) getContext(data).get("template") + TEMPLATE[26];
case 27:
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite) {
context.put("continue", "12");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
} else {
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
context.put("existingSite", Boolean.valueOf(existingSite));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("selectedTools", orderToolIds(state, site_type,
(List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String) getContext(data).get("template") + TEMPLATE[27];
case 28:
context.put("currentSite", site);
context.put("importSiteList", state
.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
return (String) getContext(data).get("template") + TEMPLATE[28];
case 29:
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(
PROP_SITE_TERM));
setTermListForContext(context, state, true);
} else {
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null) {
context.put("siteDuplicated", Boolean.FALSE);
} else {
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state
.getAttribute(SITE_DUPLICATED_NAME));
}
return (String) getContext(data).get("template") + TEMPLATE[29];
case 36:
Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE);
context.put("enableCourseCreationForUser", enableCourseCreationForUser);
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
setTermListForContext(context, state, true);
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
coursesIntoContext(state, context, site);
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
context.put("term", t);
if (t != null) {
String userId = UserDirectoryService.getCurrentUser().getEid();
List courses = prepareCourseAndSectionListing(userId, t
.getEid(), state);
if (courses != null && courses.size() > 0) {
Vector notIncludedCourse = new Vector();
for (Iterator i = courses.iterator(); i.hasNext();) {
CourseObject c = (CourseObject) i.next();
if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) {
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST,
notIncludedCourse);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
} else {
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
|| state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
List<String> providerSectionList = (List<String>) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerSectionList != null) {
context.put("selectedProviderCourse", providerSectionList);
}
List<SectionObject> authorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSectionList != null) {
List authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
ArrayList list2 = new ArrayList();
for (int i=0; i<authorizerSectionList.size();i++){
SectionObject so = (SectionObject)authorizerSectionList.get(i);
list2.add(so.getEid());
}
context.put("selectedAuthorizerCourse", list2);
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("currentUserId", (String) state
.getAttribute(STATE_CM_CURRENT_USERID));
context.put("form_additional", (String) state
.getAttribute(FORM_ADDITIONAL));
context.put("authorizers", getAuthorizers(state));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "1");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
context.put("backIndex", "");
}
List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST);
context.put("termCourseList", state
.getAttribute(STATE_TERM_COURSE_LIST));
context.put("campusDirectory", getCampusDirectory());
context.put("userId", (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED));
return (String) getContext(data).get("template") + TEMPLATE[36];
case 37:
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("officialAccountName", ServerConfigurationService
.getString("officialAccountName", ""));
context.put("value_uniqname", state
.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", number>0?new Integer(number - 1):0);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0)
{
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
List l = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put("selectedProviderCourse", l);
context.put("size", new Integer(l.size() - 1));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
List l = (List) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
context.put("cmRequestedSections", l);
}
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (site == null) {
if (state.getAttribute(STATE_AUTO_ADD) != null) {
context.put("autoAdd", Boolean.TRUE);
}
}
isFutureTermSelected(state);
context.put("isFutureTerm", state
.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString(
"roster.available.weeks.before.term.start", "0"));
return (String) getContext(data).get("template") + TEMPLATE[37];
case 42:
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state
.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList);
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList);
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String) getContext(data).get("template") + TEMPLATE[42];
case 43:
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.addclasses"),
"doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String) getContext(data).get("template") + TEMPLATE[43];
case 44:
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null)
{
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int addNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue() - 1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
} else {
context.put("backIndex", "36");
}
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[44];
case 45:
return (String) getContext(data).get("template") + TEMPLATE[45];
case 46:
context
.put("allZipSites", state
.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[46];
case 47:
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[47];
case 48:
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[48];
case 49:
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId())
|| SiteService.allowUpdateGroupMembership(site.getId())) {
bar.add(new MenuEntry(rb.getString("java.newgroup"), "doGroup_new"));
}
context.put("menu", bar);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for (Iterator gIterator = groups.iterator(); gIterator.hasNext();) {
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(
GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString())) {
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null) {
context.put("groups", new SortedIterator(groupsByWSetup
.iterator(), new SiteComparator(sortedBy, sortedAsc)));
}
return (String) getContext(data).get("template") + TEMPLATE[49];
case 50:
Group g = getStateGroup(state);
if (g != null) {
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
} else {
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null) {
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null) {
context.put("description", state
.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator(getParticipantList(state)
.iterator(), new SiteComparator(SORTED_BY_PARTICIPANT_NAME,
Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext()) {
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null) {
context.put("groupMembers", new SortedIterator(groupMembersSet
.iterator(), new SiteComparator(SORTED_BY_MEMBER_NAME,
Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService
.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[50];
case 51:
context.put("site", site);
context
.put("removeGroupIds", new ArrayList(Arrays
.asList((String[]) state
.getAttribute(STATE_GROUP_REMOVE))));
return (String) getContext(data).get("template") + TEMPLATE[51];
case 53: {
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
if (cmLevels == null)
{
cmLevels = getCMLevelLabels();
}
SectionObject selectedSect = (SectionObject) state
.getAttribute(STATE_CM_SELECTED_SECTION);
List<SectionObject> requestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (courseManagementIsImplemented() && cms != null) {
context.put("cmsAvailable", new Boolean(true));
}
int cmLevelSize = 0;
if (cms == null || !courseManagementIsImplemented()
|| cmLevels == null || cmLevels.size() < 1) {
} else {
cmLevelSize = cmLevels.size();
Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS);
int numSelections = 0;
if (selections != null)
numSelections = selections.size();
if (numSelections == cmLevelSize - 1)
{
levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1));
}
else if (numSelections == cmLevelSize - 2)
{
levelOpts[numSelections] = getCMCourseOfferings((String) selections.get(numSelections-1), t.getEid());
}
else if (numSelections < cmLevelSize)
{
levelOpts[numSelections] = sortCmObject(cms.findCourseSets((String) cmLevels.get(numSelections==0?0:numSelections-1)));
}
levelOpts[0] = sortCmObject(cms.findCourseSets((String) cmLevels.get(0)));
for (int i = numSelections + 1; i<cmLevelSize; i++)
{
levelOpts[i] = null;
}
context.put("cmLevelOptions", Arrays.asList(levelOpts));
state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts);
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int courseInd = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(courseInd - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("cmLevels", cmLevels);
context.put("cmLevelSelections", selections);
context.put("selectedCourse", selectedSect);
context.put("cmRequestedSections", requestedSections);
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_TERM_COURSE_LIST) != null)
{
context.put("backIndex", "36");
}
else
{
context.put("backIndex", "1");
}
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "36");
}
context.put("authzGroupService", AuthzGroupService.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[53];
}
case 54:
SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE));
if (siteTypeQuestions != null)
{
context.put("questionSet", siteTypeQuestions);
context.put("userAnswers", state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER));
}
context.put("continueIndex", state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE));
return (String) getContext(data).get("template") + TEMPLATE[54];
}
return (String) getContext(data).get("template") + TEMPLATE[0];
}
|
private boolean manipulateInterestForElementHelper(IInteractionElement element, boolean increment,
boolean forceLandmark, boolean preserveUninteresting, String sourceId, IInteractionContext context,
Set<IInteractionElement> changedElements, AbstractContextStructureBridge forcedBridge) {
if (element == null || context == null) {
return false;
}
float originalValue = element.getInterest().getValue();
float changeValue = 0;
AbstractContextStructureBridge bridge = ContextCore.getStructureBridge(element.getContentType());
Object objectForHandle = bridge.getObjectForHandle(element.getHandleIdentifier());
String parentContentType = bridge.getParentContentType();
if (parentContentType != null && objectForHandle != null) {
AbstractContextStructureBridge parentBridge = ContextCorePlugin.getDefault().getStructureBridge(
parentContentType);
if (parentBridge != null && parentBridge != forcedBridge) {
String parentBridgeHandle = parentBridge.getHandleIdentifier(objectForHandle);
if (parentBridgeHandle != null) {
IInteractionElement parentBridgeElement = context.get(parentBridgeHandle);
manipulateInterestForElementHelper(parentBridgeElement, increment, forceLandmark,
preserveUninteresting, sourceId, context, changedElements, parentBridge);
}
}
}
if (forcedBridge != null) {
bridge = forcedBridge;
}
if (!increment) {
if (element.getInterest().isLandmark() && bridge.canBeLandmark(element.getHandleIdentifier())) {
changeValue = (-1 * originalValue) + 1;
} else {
if (originalValue >= 0) {
changeValue = ((-1) * originalValue) - 1;
}
for (String childHandle : bridge.getChildHandles(element.getHandleIdentifier())) {
IInteractionElement childElement = context.get(childHandle);
if (childElement != null
&& !childElement.equals(element)) {
manipulateInterestForElementHelper(childElement, increment, forceLandmark,
preserveUninteresting, sourceId, context, changedElements, forcedBridge);
}
}
}
} else {
if (!forceLandmark && (originalValue > context.getScaling().getLandmark())) {
changeValue = 0;
} else {
if (bridge.canBeLandmark(element.getHandleIdentifier())) {
changeValue = (context.getScaling().getForcedLandmark()) - originalValue + 1;
} else {
return false;
}
}
}
if (increment || preserveUninteresting) {
InteractionEvent interactionEvent = new InteractionEvent(InteractionEvent.Kind.MANIPULATION,
element.getContentType(), element.getHandleIdentifier(), sourceId, changeValue);
List<IInteractionElement> interestDelta = internalProcessInteractionEvent(interactionEvent, context, true);
changedElements.addAll(interestDelta);
} else {
changedElements.add(element);
delete(element, context);
}
return true;
}
public InteractionContext migrateLegacyActivity(InteractionContext context) {
LegacyActivityAdaptor adaptor = new LegacyActivityAdaptor();
InteractionContext newMetaContext = new InteractionContext(context.getHandleIdentifier(),
ContextCore.getCommonContextScaling());
for (InteractionEvent event : context.getInteractionHistory()) {
InteractionEvent temp = adaptor.parseInteractionEvent(event);
if (temp != null) {
newMetaContext.parseEvent(temp);
}
}
return newMetaContext;
}
private void notifyElementsDeleted(final IInteractionContext context, final List<IInteractionElement> interestDelta) {
if (!interestDelta.isEmpty()) {
for (final AbstractContextListener listener : contextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
ContextChangeEvent event = new ContextChangeEvent(ContextChangeKind.ELEMENTS_DELETED,
context.getHandleIdentifier(), context, interestDelta);
listener.contextChanged(event);
}
});
}
}
}
@Deprecated
public void notifyInterestDelta(final List<IInteractionElement> interestDelta) {
notifyInterestDelta(getActiveContext(), interestDelta);
}
public void notifyInterestDelta(final IInteractionContext context, final List<IInteractionElement> interestDelta) {
if (!interestDelta.isEmpty()) {
for (final AbstractContextListener listener : contextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
ContextChangeEvent event = new ContextChangeEvent(ContextChangeKind.INTEREST_CHANGED,
context.getHandleIdentifier(), context, interestDelta);
listener.contextChanged(event);
}
});
}
}
}
public void notifyRelationshipsChanged(final IInteractionElement element) {
if (suppressListenerNotification) {
return;
}
for (final AbstractContextListener listener : contextListeners) {
if (listener instanceof IRelationsListener) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
((IRelationsListener) listener).relationsChanged(element);
}
});
}
}
}
public void processActivityMetaContextEvent(InteractionEvent event) {
IInteractionElement element = getActivityMetaContext().parseEvent(event);
final List<IInteractionElement> changed = Collections.singletonList(element);
for (final AbstractContextListener listener : activityMetaContextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
ContextChangeEvent event = new ContextChangeEvent(ContextChangeKind.INTEREST_CHANGED,
getActivityMetaContext().getHandleIdentifier(), getActivityMetaContext(), changed);
listener.contextChanged(event);
}
});
}
}
public IInteractionElement processInteractionEvent(InteractionEvent event) {
return processInteractionEvent(event, true);
}
public IInteractionElement processInteractionEvent(InteractionEvent event, boolean propagateToParents) {
return processInteractionEvent(event, propagateToParents, true);
}
public IInteractionElement processInteractionEvent(InteractionEvent event, boolean propagateToParents,
boolean notifyListeners) {
boolean alreadyNotified = false;
if (isContextActive()) {
List<IInteractionElement> interestDelta = internalProcessInteractionEvent(event, activeContext,
propagateToParents);
if (notifyListeners) {
notifyInterestDelta(interestDelta);
}
}
for (IInteractionContext globalContext : globalContexts) {
if (globalContext.getContentLimitedTo().equals(event.getStructureKind())) {
List<IInteractionElement> interestDelta = internalProcessInteractionEvent(event, globalContext,
propagateToParents);
if (notifyListeners && !alreadyNotified) {
notifyInterestDelta(interestDelta);
}
}
}
return activeContext.get(event.getStructureHandle());
}
public IInteractionElement processInteractionEvent(Object object, Kind eventKind, String origin,
IInteractionContext context) {
AbstractContextStructureBridge structureBridge = ContextCore.getStructureBridge(object);
if (structureBridge != null) {
String structureKind = structureBridge.getContentType();
String handle = structureBridge.getHandleIdentifier(object);
if (structureKind != null && handle != null) {
InteractionEvent event = new InteractionEvent(eventKind, structureKind, handle, origin);
List<IInteractionElement> interestDelta = internalProcessInteractionEvent(event, context, true);
notifyInterestDelta(interestDelta);
return context.get(event.getStructureHandle());
}
}
return null;
}
public void processInteractionEvents(List<InteractionEvent> events, boolean propagateToParents) {
Set<IInteractionElement> compositeDelta = new HashSet<IInteractionElement>();
for (InteractionEvent event : events) {
if (isContextActive()) {
compositeDelta.addAll(internalProcessInteractionEvent(event, activeContext, propagateToParents));
}
for (IInteractionContext globalContext : globalContexts) {
if (globalContext.getContentLimitedTo().equals(event.getStructureKind())) {
internalProcessInteractionEvent(event, globalContext, propagateToParents);
}
}
}
notifyInterestDelta(new ArrayList<IInteractionElement>(compositeDelta));
}
private void propegateInterestToParents(IInteractionContext interactionContext, InteractionEvent.Kind kind,
IInteractionElement node, float previousInterest, float decayOffset, int level,
List<IInteractionElement> interestDelta, String origin, AbstractContextStructureBridge forcedBridge,
Set<String> handles) {
if (level > MAX_PROPAGATION || node == null || node.getHandleIdentifier() == null
|| node.getInterest().getValue() <= 0) {
return;
}
checkForLandmarkDeltaAndNotify(previousInterest, node, interactionContext);
level++;
AbstractContextStructureBridge bridge = ContextCorePlugin.getDefault()
.getStructureBridge(node.getContentType());
Object objectForHandle = bridge.getObjectForHandle(node.getHandleIdentifier());
String parentBridgeContentType = bridge.getParentContentType();
if (parentBridgeContentType != null && objectForHandle != null) {
AbstractContextStructureBridge parentBridge = ContextCorePlugin.getDefault().getStructureBridge(
parentBridgeContentType);
if (parentBridge != null && parentBridge != forcedBridge) {
String parentHandle = parentBridge.getHandleIdentifier(objectForHandle);
if (parentHandle != null) {
IInteractionElement parentBridgeElement = interactionContext.get(parentHandle);
float parentPreviousInterest = 0;
float parentDecayOffset = 0;
if (parentBridgeElement != null) {
parentPreviousInterest = parentBridgeElement.getInterest().getValue();
}
if (kind.isUserEvent()) {
parentDecayOffset = ensureIsInteresting(interactionContext, parentBridge.getContentType(),
parentHandle, parentBridgeElement, parentPreviousInterest);
}
if (!handles.contains(parentHandle)) {
handles.add(parentHandle);
parentBridgeElement = addInteractionEvent(interactionContext, new InteractionEvent(
InteractionEvent.Kind.PROPAGATION, parentBridge.getContentType(), parentHandle, origin));
} else {
parentBridgeElement = interactionContext.get(parentHandle);
}
propegateInterestToParents(interactionContext, kind, parentBridgeElement, previousInterest,
parentDecayOffset, level, interestDelta, origin, parentBridge, handles);
}
}
}
if (forcedBridge != null) {
bridge = forcedBridge;
}
String parentHandle = bridge.getParentHandle(node.getHandleIdentifier(), forcedBridge == null);
if (forcedBridge == null) {
for (String contentType : ContextCore.getChildContentTypes(bridge.getContentType())) {
AbstractContextStructureBridge childBridge = ContextCore.getStructureBridge(contentType);
Object resolved = childBridge.getObjectForHandle(parentHandle);
if (resolved != null) {
AbstractContextStructureBridge canonicalBridge = ContextCore.getStructureBridge(resolved);
if (!canonicalBridge.getContentType().equals(ContextCore.CONTENT_TYPE_RESOURCE)) {
bridge = canonicalBridge;
}
}
}
}
if (parentHandle != null) {
String parentContentType = bridge.getContentType(parentHandle);
IInteractionElement parentElement = interactionContext.get(parentHandle);
float parentPreviousInterest = 0;
if (parentElement != null && parentElement.getInterest() != null) {
parentPreviousInterest = parentElement.getInterest().getValue();
}
float increment = interactionContext.getScaling().getInteresting();
if (parentPreviousInterest < node.getInterest().getValue()) {
increment = node.getInterest().getValue() - parentPreviousInterest;
InteractionEvent propagationEvent = new InteractionEvent(InteractionEvent.Kind.PROPAGATION,
parentContentType, parentHandle, SOURCE_ID_MODEL_PROPAGATION,
InteractionContextManager.CONTAINMENT_PROPAGATION_ID, increment);
if (!handles.contains(parentHandle)) {
handles.add(parentHandle);
parentElement = addInteractionEvent(interactionContext, propagationEvent);
} else {
parentElement = interactionContext.get(parentHandle);
}
}
if (parentElement != null && kind.isUserEvent()
&& parentElement.getInterest().getValue() < ContextCore.getCommonContextScaling().getInteresting()) {
float parentOffset = ContextCore.getCommonContextScaling().getInteresting()
- parentElement.getInterest().getValue() + increment;
if (!handles.contains(parentHandle)) {
handles.add(parentHandle);
addInteractionEvent(interactionContext, new InteractionEvent(InteractionEvent.Kind.MANIPULATION,
parentElement.getContentType(), parentElement.getHandleIdentifier(),
SOURCE_ID_DECAY_CORRECTION, parentOffset));
} else {
parentElement = interactionContext.get(parentElement.getHandleIdentifier());
}
}
if (parentElement != null
&& isInterestDelta(parentPreviousInterest, parentElement.getInterest().isPredicted(),
parentElement.getInterest().isPropagated(), parentElement)) {
interestDelta.add(0, parentElement);
}
propegateInterestToParents(interactionContext, kind, parentElement, parentPreviousInterest, decayOffset,
level, interestDelta, origin, forcedBridge, handles);
}
}
public void removeActivityMetaContextListener(AbstractContextListener listener) {
activityMetaContextListeners.remove(listener);
}
public void removeAllListeners() {
waitingContextListeners.clear();
contextListeners.clear();
}
@SuppressWarnings("deprecation")
public void removeErrorPredictedInterest(String handle, String kind, boolean notify) {
if (activeContext.getContextMap().isEmpty()) {
return;
}
if (handle == null) {
return;
}
final IInteractionElement element = activeContext.get(handle);
if (element != null && element.getInterest().isInteresting() && errorElementHandles.contains(handle)) {
InteractionEvent errorEvent = new InteractionEvent(InteractionEvent.Kind.MANIPULATION, kind, handle,
SOURCE_ID_MODEL_ERROR,
((InteractionContextScaling) ContextCore.getCommonContextScaling()).getErrorInterest());
processInteractionEvent(errorEvent, true);
numInterestingErrors--;
errorElementHandles.remove(handle);
if (notify) {
for (final AbstractContextListener listener : contextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN,
"Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
List<IInteractionElement> changed = new ArrayList<IInteractionElement>();
changed.add(element);
listener.interestChanged(changed);
}
});
}
}
}
}
public void removeGlobalContext(IInteractionContext context) {
globalContexts.remove(context);
}
public void removeListener(AbstractContextListener listener) {
waitingContextListeners.remove(listener);
contextListeners.remove(listener);
}
public void resetActivityMetaContext() {
try {
metaContextLock.acquire();
activityMetaContext = new InteractionContext(InteractionContextManager.CONTEXT_HISTORY_FILE_NAME,
ContextCore.getCommonContextScaling());
saveActivityMetaContext();
} finally {
metaContextLock.release();
}
}
public void resetLandmarkRelationshipsOfKind(String reltationKind) {
for (IInteractionElement landmark : activeContext.getLandmarks()) {
for (IInteractionRelation edge : landmark.getRelations()) {
if (edge.getRelationshipHandle().equals(reltationKind)) {
landmark.clearRelations();
}
}
}
for (final AbstractContextListener listener : contextListeners) {
if (listener instanceof IRelationsListener) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
((IRelationsListener) listener).relationsChanged(null);
}
});
}
}
}
public void setActivationHistorySuppressed(boolean activationHistorySuppressed) {
this.activationHistorySuppressed = activationHistorySuppressed;
}
public void setActiveSearchEnabled(boolean enabled) {
for (AbstractRelationProvider provider : ContextCorePlugin.getDefault().getRelationProviders()) {
provider.setEnabled(enabled);
}
}
public void setContextCapturePaused(boolean paused) {
synchronized (InteractionContextManager.this) {
this.contextCapturePaused = paused;
}
}
public void updateHandle(final IInteractionElement element, String newHandle) {
if (element == null) {
return;
}
final IInteractionContext context = getActiveContext();
context.updateElementHandle(element, newHandle);
final List<IInteractionElement> changed = Collections.singletonList(element);
for (final AbstractContextListener listener : contextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
ContextChangeEvent event = new ContextChangeEvent(ContextChangeKind.INTEREST_CHANGED,
context.getHandleIdentifier(), context, changed);
listener.contextChanged(event);
}
});
}
if (element.getInterest().isLandmark()) {
for (final AbstractContextListener listener : contextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
List<IInteractionElement> changed = new ArrayList<IInteractionElement>();
changed.add(element);
ContextChangeEvent event = new ContextChangeEvent(ContextChangeKind.LANDMARKS_ADDED,
context.getHandleIdentifier(), context, changed);
listener.contextChanged(event);
}
});
}
}
}
}
| private boolean manipulateInterestForElementHelper(IInteractionElement element, boolean increment,
boolean forceLandmark, boolean preserveUninteresting, String sourceId, IInteractionContext context,
Set<IInteractionElement> changedElements, AbstractContextStructureBridge forcedBridge) {
if (element == null || context == null) {
return false;
}
float originalValue = element.getInterest().getValue();
float changeValue = 0;
AbstractContextStructureBridge bridge = ContextCore.getStructureBridge(element.getContentType());
Object objectForHandle = bridge.getObjectForHandle(element.getHandleIdentifier());
String parentContentType = bridge.getParentContentType();
if (parentContentType != null && objectForHandle != null) {
AbstractContextStructureBridge parentBridge = ContextCorePlugin.getDefault().getStructureBridge(
parentContentType);
if (parentBridge != null && parentBridge != forcedBridge) {
String parentBridgeHandle = parentBridge.getHandleIdentifier(objectForHandle);
if (parentBridgeHandle != null) {
IInteractionElement parentBridgeElement = context.get(parentBridgeHandle);
manipulateInterestForElementHelper(parentBridgeElement, increment, forceLandmark,
preserveUninteresting, sourceId, context, changedElements, parentBridge);
}
}
}
if (forcedBridge != null) {
bridge = forcedBridge;
}
if (!increment) {
if (element.getInterest().isLandmark() && bridge.canBeLandmark(element.getHandleIdentifier())) {
changeValue = (-1 * originalValue) + 1;
} else {
if (originalValue >= 0) {
changeValue = ((-1) * originalValue) - 1;
}
for (String childHandle : bridge.getChildHandles(element.getHandleIdentifier())) {
IInteractionElement childElement = context.get(childHandle);
if (childElement != null
&& !childElement.equals(element)) {
manipulateInterestForElementHelper(childElement, increment, forceLandmark,
preserveUninteresting, sourceId, context, changedElements, forcedBridge);
}
}
}
} else {
if (!forceLandmark && (originalValue > context.getScaling().getLandmark())) {
changeValue = 0;
} else {
if (bridge.canBeLandmark(element.getHandleIdentifier())) {
changeValue = (context.getScaling().getForcedLandmark()) - originalValue + 1;
} else {
return false;
}
}
}
if (increment || preserveUninteresting) {
InteractionEvent interactionEvent = new InteractionEvent(InteractionEvent.Kind.MANIPULATION,
element.getContentType(), element.getHandleIdentifier(), sourceId, changeValue);
List<IInteractionElement> interestDelta = internalProcessInteractionEvent(interactionEvent, context, true);
changedElements.addAll(interestDelta);
} else {
changedElements.add(element);
delete(element, context);
}
return true;
}
public InteractionContext migrateLegacyActivity(InteractionContext context) {
LegacyActivityAdaptor adaptor = new LegacyActivityAdaptor();
InteractionContext newMetaContext = new InteractionContext(context.getHandleIdentifier(),
ContextCore.getCommonContextScaling());
for (InteractionEvent event : context.getInteractionHistory()) {
InteractionEvent temp = adaptor.parseInteractionEvent(event);
if (temp != null) {
newMetaContext.parseEvent(temp);
}
}
return newMetaContext;
}
private void notifyElementsDeleted(final IInteractionContext context, final List<IInteractionElement> interestDelta) {
if (!interestDelta.isEmpty()) {
for (final AbstractContextListener listener : contextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
ContextChangeEvent event = new ContextChangeEvent(ContextChangeKind.ELEMENTS_DELETED,
context.getHandleIdentifier(), context, interestDelta);
listener.contextChanged(event);
}
});
}
}
}
@Deprecated
public void notifyInterestDelta(final List<IInteractionElement> interestDelta) {
notifyInterestDelta(getActiveContext(), interestDelta);
}
public void notifyInterestDelta(final IInteractionContext context, final List<IInteractionElement> interestDelta) {
if (!interestDelta.isEmpty()) {
for (final AbstractContextListener listener : contextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
ContextChangeEvent event = new ContextChangeEvent(ContextChangeKind.INTEREST_CHANGED,
context.getHandleIdentifier(), context, interestDelta);
listener.contextChanged(event);
}
});
}
}
}
public void notifyRelationshipsChanged(final IInteractionElement element) {
if (suppressListenerNotification) {
return;
}
for (final AbstractContextListener listener : contextListeners) {
if (listener instanceof IRelationsListener) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
((IRelationsListener) listener).relationsChanged(element);
}
});
}
}
}
public void processActivityMetaContextEvent(InteractionEvent event) {
IInteractionElement element = getActivityMetaContext().parseEvent(event);
final List<IInteractionElement> changed = Collections.singletonList(element);
for (final AbstractContextListener listener : activityMetaContextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
ContextChangeEvent event = new ContextChangeEvent(ContextChangeKind.INTEREST_CHANGED,
getActivityMetaContext().getHandleIdentifier(), getActivityMetaContext(), changed);
listener.contextChanged(event);
}
});
}
}
public IInteractionElement processInteractionEvent(InteractionEvent event) {
return processInteractionEvent(event, true);
}
public IInteractionElement processInteractionEvent(InteractionEvent event, boolean propagateToParents) {
return processInteractionEvent(event, propagateToParents, true);
}
public IInteractionElement processInteractionEvent(InteractionEvent event, boolean propagateToParents,
boolean notifyListeners) {
boolean alreadyNotified = false;
if (isContextActive()) {
List<IInteractionElement> interestDelta = internalProcessInteractionEvent(event, activeContext,
propagateToParents);
if (notifyListeners) {
notifyInterestDelta(interestDelta);
}
}
for (IInteractionContext globalContext : globalContexts) {
if (globalContext.getContentLimitedTo().equals(event.getStructureKind())) {
List<IInteractionElement> interestDelta = internalProcessInteractionEvent(event, globalContext,
propagateToParents);
if (notifyListeners && !alreadyNotified) {
notifyInterestDelta(interestDelta);
}
}
}
return activeContext.get(event.getStructureHandle());
}
public IInteractionElement processInteractionEvent(Object object, Kind eventKind, String origin,
IInteractionContext context) {
AbstractContextStructureBridge structureBridge = ContextCore.getStructureBridge(object);
if (structureBridge != null) {
String structureKind = structureBridge.getContentType();
String handle = structureBridge.getHandleIdentifier(object);
if (structureKind != null && handle != null) {
InteractionEvent event = new InteractionEvent(eventKind, structureKind, handle, origin);
List<IInteractionElement> interestDelta = internalProcessInteractionEvent(event, context, true);
notifyInterestDelta(interestDelta);
return context.get(event.getStructureHandle());
}
}
return null;
}
public void processInteractionEvents(List<InteractionEvent> events, boolean propagateToParents) {
Set<IInteractionElement> compositeDelta = new HashSet<IInteractionElement>();
for (InteractionEvent event : events) {
if (isContextActive()) {
compositeDelta.addAll(internalProcessInteractionEvent(event, activeContext, propagateToParents));
}
for (IInteractionContext globalContext : globalContexts) {
if (globalContext.getContentLimitedTo().equals(event.getStructureKind())) {
internalProcessInteractionEvent(event, globalContext, propagateToParents);
}
}
}
notifyInterestDelta(new ArrayList<IInteractionElement>(compositeDelta));
}
private void propegateInterestToParents(IInteractionContext interactionContext, InteractionEvent.Kind kind,
IInteractionElement node, float previousInterest, float decayOffset, int level,
List<IInteractionElement> interestDelta, String origin, AbstractContextStructureBridge forcedBridge,
Set<String> handles) {
if (level > MAX_PROPAGATION || node == null || node.getHandleIdentifier() == null
|| node.getInterest().getValue() <= 0) {
return;
}
checkForLandmarkDeltaAndNotify(previousInterest, node, interactionContext);
level++;
AbstractContextStructureBridge bridge = ContextCorePlugin.getDefault()
.getStructureBridge(node.getContentType());
Object objectForHandle = bridge.getObjectForHandle(node.getHandleIdentifier());
String parentBridgeContentType = bridge.getParentContentType();
if (parentBridgeContentType != null && objectForHandle != null) {
AbstractContextStructureBridge parentBridge = ContextCorePlugin.getDefault().getStructureBridge(
parentBridgeContentType);
if (parentBridge != null && parentBridge != forcedBridge) {
String parentHandle = parentBridge.getHandleIdentifier(objectForHandle);
if (parentHandle != null) {
IInteractionElement parentBridgeElement = interactionContext.get(parentHandle);
float parentPreviousInterest = 0;
float parentDecayOffset = 0;
if (parentBridgeElement != null) {
parentPreviousInterest = parentBridgeElement.getInterest().getValue();
}
if (kind.isUserEvent()) {
parentDecayOffset = ensureIsInteresting(interactionContext, parentBridge.getContentType(),
parentHandle, parentBridgeElement, parentPreviousInterest);
}
if (!handles.contains(parentHandle)) {
handles.add(parentHandle);
parentBridgeElement = addInteractionEvent(interactionContext, new InteractionEvent(
InteractionEvent.Kind.PROPAGATION, parentBridge.getContentType(), parentHandle, origin));
} else {
parentBridgeElement = interactionContext.get(parentHandle);
}
propegateInterestToParents(interactionContext, kind, parentBridgeElement, parentPreviousInterest,
parentDecayOffset, level, interestDelta, origin, parentBridge, handles);
}
}
}
if (forcedBridge != null) {
bridge = forcedBridge;
}
String parentHandle = bridge.getParentHandle(node.getHandleIdentifier(), forcedBridge == null);
if (forcedBridge == null) {
for (String contentType : ContextCore.getChildContentTypes(bridge.getContentType())) {
AbstractContextStructureBridge childBridge = ContextCore.getStructureBridge(contentType);
Object resolved = childBridge.getObjectForHandle(parentHandle);
if (resolved != null) {
AbstractContextStructureBridge canonicalBridge = ContextCore.getStructureBridge(resolved);
if (!canonicalBridge.getContentType().equals(ContextCore.CONTENT_TYPE_RESOURCE)) {
bridge = canonicalBridge;
}
}
}
}
if (parentHandle != null) {
String parentContentType = bridge.getContentType(parentHandle);
IInteractionElement parentElement = interactionContext.get(parentHandle);
float parentPreviousInterest = 0;
if (parentElement != null && parentElement.getInterest() != null) {
parentPreviousInterest = parentElement.getInterest().getValue();
}
float increment = interactionContext.getScaling().getInteresting();
if (parentPreviousInterest < node.getInterest().getValue()) {
increment = node.getInterest().getValue() - parentPreviousInterest;
InteractionEvent propagationEvent = new InteractionEvent(InteractionEvent.Kind.PROPAGATION,
parentContentType, parentHandle, SOURCE_ID_MODEL_PROPAGATION,
InteractionContextManager.CONTAINMENT_PROPAGATION_ID, increment);
if (!handles.contains(parentHandle)) {
handles.add(parentHandle);
parentElement = addInteractionEvent(interactionContext, propagationEvent);
} else {
parentElement = interactionContext.get(parentHandle);
}
}
if (parentElement != null && kind.isUserEvent()
&& parentElement.getInterest().getValue() < ContextCore.getCommonContextScaling().getInteresting()) {
float parentOffset = ContextCore.getCommonContextScaling().getInteresting()
- parentElement.getInterest().getValue() + increment;
if (!handles.contains(parentHandle)) {
handles.add(parentHandle);
addInteractionEvent(interactionContext, new InteractionEvent(InteractionEvent.Kind.MANIPULATION,
parentElement.getContentType(), parentElement.getHandleIdentifier(),
SOURCE_ID_DECAY_CORRECTION, parentOffset));
} else {
parentElement = interactionContext.get(parentElement.getHandleIdentifier());
}
}
if (parentElement != null
&& isInterestDelta(parentPreviousInterest, parentElement.getInterest().isPredicted(),
parentElement.getInterest().isPropagated(), parentElement)) {
interestDelta.add(0, parentElement);
}
propegateInterestToParents(interactionContext, kind, parentElement, parentPreviousInterest, decayOffset,
level, interestDelta, origin, forcedBridge, handles);
}
}
public void removeActivityMetaContextListener(AbstractContextListener listener) {
activityMetaContextListeners.remove(listener);
}
public void removeAllListeners() {
waitingContextListeners.clear();
contextListeners.clear();
}
@SuppressWarnings("deprecation")
public void removeErrorPredictedInterest(String handle, String kind, boolean notify) {
if (activeContext.getContextMap().isEmpty()) {
return;
}
if (handle == null) {
return;
}
final IInteractionElement element = activeContext.get(handle);
if (element != null && element.getInterest().isInteresting() && errorElementHandles.contains(handle)) {
InteractionEvent errorEvent = new InteractionEvent(InteractionEvent.Kind.MANIPULATION, kind, handle,
SOURCE_ID_MODEL_ERROR,
((InteractionContextScaling) ContextCore.getCommonContextScaling()).getErrorInterest());
processInteractionEvent(errorEvent, true);
numInterestingErrors--;
errorElementHandles.remove(handle);
if (notify) {
for (final AbstractContextListener listener : contextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN,
"Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
List<IInteractionElement> changed = new ArrayList<IInteractionElement>();
changed.add(element);
listener.interestChanged(changed);
}
});
}
}
}
}
public void removeGlobalContext(IInteractionContext context) {
globalContexts.remove(context);
}
public void removeListener(AbstractContextListener listener) {
waitingContextListeners.remove(listener);
contextListeners.remove(listener);
}
public void resetActivityMetaContext() {
try {
metaContextLock.acquire();
activityMetaContext = new InteractionContext(InteractionContextManager.CONTEXT_HISTORY_FILE_NAME,
ContextCore.getCommonContextScaling());
saveActivityMetaContext();
} finally {
metaContextLock.release();
}
}
public void resetLandmarkRelationshipsOfKind(String reltationKind) {
for (IInteractionElement landmark : activeContext.getLandmarks()) {
for (IInteractionRelation edge : landmark.getRelations()) {
if (edge.getRelationshipHandle().equals(reltationKind)) {
landmark.clearRelations();
}
}
}
for (final AbstractContextListener listener : contextListeners) {
if (listener instanceof IRelationsListener) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
((IRelationsListener) listener).relationsChanged(null);
}
});
}
}
}
public void setActivationHistorySuppressed(boolean activationHistorySuppressed) {
this.activationHistorySuppressed = activationHistorySuppressed;
}
public void setActiveSearchEnabled(boolean enabled) {
for (AbstractRelationProvider provider : ContextCorePlugin.getDefault().getRelationProviders()) {
provider.setEnabled(enabled);
}
}
public void setContextCapturePaused(boolean paused) {
synchronized (InteractionContextManager.this) {
this.contextCapturePaused = paused;
}
}
public void updateHandle(final IInteractionElement element, String newHandle) {
if (element == null) {
return;
}
final IInteractionContext context = getActiveContext();
context.updateElementHandle(element, newHandle);
final List<IInteractionElement> changed = Collections.singletonList(element);
for (final AbstractContextListener listener : contextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
ContextChangeEvent event = new ContextChangeEvent(ContextChangeKind.INTEREST_CHANGED,
context.getHandleIdentifier(), context, changed);
listener.contextChanged(event);
}
});
}
if (element.getInterest().isLandmark()) {
for (final AbstractContextListener listener : contextListeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.WARNING, ContextCorePlugin.ID_PLUGIN, "Listener failed: "
+ listener.getClass(), e));
}
public void run() throws Exception {
List<IInteractionElement> changed = new ArrayList<IInteractionElement>();
changed.add(element);
ContextChangeEvent event = new ContextChangeEvent(ContextChangeKind.LANDMARKS_ADDED,
context.getHandleIdentifier(), context, changed);
listener.contextChanged(event);
}
});
}
}
}
}
|
public MenuManager getSubMenuManager(final List<IRepositoryElement> selectedElements) {
singleTaskSelection = null;
taskListElementsToSchedule.clear();
final MenuManager subMenuManager = new MenuManager(Messages.ScheduleTaskMenuContributor_Schedule_for);
if (selectedElements.size() == 1) {
IRepositoryElement selectedElement = selectedElements.get(0);
if (selectedElement instanceof ITask) {
singleTaskSelection = (AbstractTask) selectedElement;
}
}
for (IRepositoryElement selectedElement : selectedElements) {
if (selectedElement instanceof ITask) {
taskListElementsToSchedule.add(selectedElement);
}
}
if (selectionIncludesCompletedTasks()) {
Action action = new Action() {
@Override
public void run() {
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Cannot_schedule_completed_tasks);
action.setEnabled(false);
subMenuManager.add(action);
return subMenuManager;
}
WeekDateRange week = TaskActivityUtil.getCurrentWeek();
int days = 0;
for (DateRange day : week.getDaysOfWeek()) {
if (day.includes(TaskActivityUtil.getCalendar())) {
days++;
Action action = createDateSelectionAction(day, CommonImages.SCHEDULE_DAY);
subMenuManager.add(action);
if (singleTaskSelection != null && isPastReminder(singleTaskSelection)) {
action.setChecked(true);
}
} else if (day.after(TaskActivityUtil.getCalendar())) {
days++;
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
}
int toAdd = 7 - days;
WeekDateRange nextWeek = TaskActivityUtil.getNextWeek();
for (int x = 0; x < toAdd; x++) {
int next = TasksUiPlugin.getTaskActivityManager().getWeekStartDay() + x;
if (next > Calendar.SATURDAY) {
next = x;
}
DateRange day = nextWeek.getDayOfWeek(next);
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
Action action = createDateSelectionAction(week, CommonImages.SCHEDULE_WEEK);
subMenuManager.add(action);
if (isThisWeek(singleTaskSelection)) {
action.setChecked(true);
}
action = createDateSelectionAction(week.next(), null);
subMenuManager.add(action);
action = createDateSelectionAction(week.next().next(), null);
subMenuManager.add(action);
if (singleTaskSelection != null && getScheduledForDate(singleTaskSelection) != null) {
DateRange range = getScheduledForDate(singleTaskSelection);
if (range.equals(TaskActivityUtil.getNextWeek().next())
|| TaskActivityUtil.getNextWeek().next().includes(range)) {
action.setChecked(true);
}
if (getScheduledForDate(singleTaskSelection).after(week.next().next().getEndDate())
&& !(getScheduledForDate(singleTaskSelection) instanceof WeekDateRange)) {
action = new Action() {
@Override
public void run() {
}
};
action.setChecked(true);
action.setText(Messages.ScheduleTaskMenuContributor_Future);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar theCalendar = TaskActivityUtil.getCalendar();
if (getScheduledForDate(singleTaskSelection) != null) {
theCalendar.setTime(getScheduledForDate(singleTaskSelection).getStartDate().getTime());
}
Shell shell = null;
if (subMenuManager != null && subMenuManager.getMenu() != null) {
shell = subMenuManager.getMenu().getShell();
}
if (shell == null) {
shell = WorkbenchUtil.getShell();
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(shell, theCalendar,
DatePicker.TITLE_DIALOG, false, TasksUiPlugin.getDefault().getPreferenceStore().getInt(
ITasksUiPreferenceConstants.PLANNING_ENDHOUR));
int result = reminderDialog.open();
if (result == Window.OK) {
DateRange range = null;
if (reminderDialog.getDate() != null) {
range = TaskActivityUtil.getDayOf(reminderDialog.getDate());
}
setScheduledDate(range);
}
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Choose_Date_);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
setScheduledDate(null);
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Not_Scheduled);
action.setChecked(false);
if (singleTaskSelection != null) {
if (getScheduledForDate(singleTaskSelection) == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
| public MenuManager getSubMenuManager(final List<IRepositoryElement> selectedElements) {
singleTaskSelection = null;
taskListElementsToSchedule.clear();
final MenuManager subMenuManager = new MenuManager(Messages.ScheduleTaskMenuContributor_Schedule_for);
if (selectedElements.size() == 1) {
IRepositoryElement selectedElement = selectedElements.get(0);
if (selectedElement instanceof ITask) {
singleTaskSelection = (AbstractTask) selectedElement;
}
}
for (IRepositoryElement selectedElement : selectedElements) {
if (selectedElement instanceof ITask) {
taskListElementsToSchedule.add(selectedElement);
}
}
if (selectionIncludesCompletedTasks()) {
Action action = new Action() {
@Override
public void run() {
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Cannot_schedule_completed_tasks);
action.setEnabled(false);
subMenuManager.add(action);
return subMenuManager;
}
WeekDateRange week = TaskActivityUtil.getCurrentWeek();
int days = 0;
for (DateRange day : week.getDaysOfWeek()) {
if (day.includes(TaskActivityUtil.getCalendar())) {
days++;
Action action = createDateSelectionAction(day, CommonImages.SCHEDULE_DAY);
subMenuManager.add(action);
if (singleTaskSelection != null && isPastReminder(singleTaskSelection)) {
action.setChecked(true);
}
} else if (day.after(TaskActivityUtil.getCalendar())) {
days++;
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
}
int toAdd = 7 - days;
WeekDateRange nextWeek = TaskActivityUtil.getNextWeek();
for (int x = 0; x < toAdd; x++) {
int next = TasksUiPlugin.getTaskActivityManager().getWeekStartDay() + x;
if (next > Calendar.SATURDAY) {
next = x;
}
DateRange day = nextWeek.getDayOfWeek(next);
Action action = createDateSelectionAction(day, null);
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
Action action = createDateSelectionAction(week, CommonImages.SCHEDULE_WEEK);
subMenuManager.add(action);
if (isThisWeek(singleTaskSelection)) {
action.setChecked(true);
}
action = createDateSelectionAction(week.next(), null);
subMenuManager.add(action);
action = createDateSelectionAction(week.next().next(), null);
subMenuManager.add(action);
if (singleTaskSelection != null && getScheduledForDate(singleTaskSelection) != null) {
DateRange range = getScheduledForDate(singleTaskSelection);
if (range.equals(TaskActivityUtil.getNextWeek().next())
|| TaskActivityUtil.getNextWeek().next().includes(range)) {
action.setChecked(true);
}
if (getScheduledForDate(singleTaskSelection).after(week.next().next().getEndDate())
&& !(getScheduledForDate(singleTaskSelection) instanceof WeekDateRange)) {
action = new Action() {
@Override
public void run() {
}
};
action.setChecked(true);
action.setText(Messages.ScheduleTaskMenuContributor_Future);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar theCalendar = TaskActivityUtil.getCalendar();
if (getScheduledForDate(singleTaskSelection) != null) {
theCalendar.setTime(getScheduledForDate(singleTaskSelection).getStartDate().getTime());
}
Shell shell = null;
if (subMenuManager != null && subMenuManager.getMenu() != null && subMenuManager.getMenu().isDisposed()) {
shell = subMenuManager.getMenu().getShell();
}
if (shell == null) {
shell = WorkbenchUtil.getShell();
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(shell, theCalendar,
DatePicker.TITLE_DIALOG, false, TasksUiPlugin.getDefault().getPreferenceStore().getInt(
ITasksUiPreferenceConstants.PLANNING_ENDHOUR));
int result = reminderDialog.open();
if (result == Window.OK) {
DateRange range = null;
if (reminderDialog.getDate() != null) {
range = TaskActivityUtil.getDayOf(reminderDialog.getDate());
}
setScheduledDate(range);
}
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Choose_Date_);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
setScheduledDate(null);
}
};
action.setText(Messages.ScheduleTaskMenuContributor_Not_Scheduled);
action.setChecked(false);
if (singleTaskSelection != null) {
if (getScheduledForDate(singleTaskSelection) == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
|
public String getDemoText()
{
return "/* Block comment */\n" +
"<KEYWORD>package</KEYWORD> hello\n" +
"\n" +
"<KEYWORD>import</KEYWORD> napile.io.Console // line comment\n" +
"\n" +
"/~\n" +
" ~ Doc comment here for `MyClass`\n" +
" ~/\n" +
"<ANNOTATION>@Deprecated</ANNOTATION>\n" +
"<KEYWORD>covered</KEYWORD> class <CLASS>MyClass</CLASS><<TYPE_PARAMETER>T</TYPE_PARAMETER>> : <CLASS>Iterable</CLASS><<TYPE_PARAMETER>T</TYPE_PARAMETER>>\n" +
"{" +
"\n" +
" <KEYWORD>static</KEYWORD> val <STATIC_VARIABLE>MY_VALUE</STATIC_VARIABLE> : Int = 1" +
"\n" +
"\n" +
" var <INSTANCE_VARIABLE>myVar</INSTANCE_VARIABLE> : Int" +
"\n" +
" {" +
"\n" +
" <KEYWORD>local</KEYWORD> <KEYWORD>set</KEYWORD>" +
"\n" +
" } = 0" +
"\n" +
"\n" +
" meth <METHOD_DECLARATION>test</METHOD_DECLARATION>(<PARAMETER>nullable</PARAMETER> : <CLASS>String</CLASS>?, <PARAMETER>f</PARAMETER> : <METHOD_LITERAL_BRACES_AND_ARROW>{</METHOD_LITERAL_BRACES_AND_ARROW>(<PARAMETER>el</PARAMETER> : <CLASS>Int</CLASS>) <METHOD_LITERAL_BRACES_AND_ARROW>-></METHOD_LITERAL_BRACES_AND_ARROW> <CLASS>Int</CLASS><METHOD_LITERAL_BRACES_AND_ARROW>}</METHOD_LITERAL_BRACES_AND_ARROW>)" +
"\n" +
" {\n" +
" <CLASS>Console</CLASS>.<METHOD_CALL><STATIC_METHOD_CALL>writeLine</STATIC_METHOD_CALL></METHOD_CALL>(\"Hello world !!!\")\n" +
" val <LOCAL_VARIABLE>ints</LOCAL_VARIABLE> = napile.collection.<CLASS>ArrayList</CLASS><<CLASS>Int</CLASS>?>(2)\n" +
" <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>[0] = 102 + <PARAMETER>f</PARAMETER>()\n" +
" var <LOCAL_VARIABLE>testIt</LOCAL_VARIABLE> = <METHOD_CALL>test</METHOD_CALL>(<KEYWORD>null</KEYWORD>, <METHOD_LITERAL_BRACES_AND_ARROW>{<AUTO_GENERATED_VAR>value</AUTO_GENERATED_VAR>}</METHOD_LITERAL_BRACES_AND_ARROW>)" +
"\n" +
" }" +
"\n" +
"\n" +
" meth <METHOD_DECLARATION>test2</METHOD_DECLARATION>()" +
"\n" +
" {" +
"\n" +
" var obj : <CLASS>String</CLASS> = /<KEYWORD>text</KEYWORD>/ {<INJECTION_BLOCK>Hello my friends. This is my var <INJECTION_INNER_EXPRESSION_MARK>#{</INJECTION_INNER_EXPRESSION_MARK>myVar<INJECTION_INNER_EXPRESSION_MARK>}</INJECTION_INNER_EXPRESSION_MARK></INJECTION_BLOCK>}" +
"\n" +
" var escape = \"This is valid string escape <VALID_STRING_ESCAPE>\\n</VALID_STRING_ESCAPE> but this is invalid <INVALID_STRING_ESCAPE>\\str</INVALID_STRING_ESCAPE> \"\n" +
" <MACRO_CALL>myMacro</MACRO_CALL>()" +
"\n" +
" }" +
"\n" +
"\n" +
" <KEYWORD>local</KEYWORD> macro <METHOD_DECLARATION>myMacro</METHOD_DECLARATION>()" +
"\n" +
" {" +
"\n" +
" return" +
"\n" +
" }" +
"\n" +
"}" +
"\n" +
"\n" +
"<KEYWORD>heritable</KEYWORD> <KEYWORD>abstract</KEYWORD> class <ABSTRACT_CLASS>Abstract</ABSTRACT_CLASS>" +
"\n" +
"{" +
"\n" +
"}" +
"\n" +
"\n" +
" Bad character: \\n\n";
}
| public String getDemoText()
{
return "/* Block comment */\n" +
"<KEYWORD>package</KEYWORD> hello\n" +
"\n" +
"<KEYWORD>import</KEYWORD> napile.io.Console // line comment\n" +
"\n" +
"/~\n" +
" ~ Doc comment here for `MyClass`\n" +
" ~/\n" +
"<ANNOTATION>@Deprecated</ANNOTATION>\n" +
"<KEYWORD>covered</KEYWORD> class <CLASS>MyClass</CLASS><<TYPE_PARAMETER>T</TYPE_PARAMETER>> : <CLASS>Iterable</CLASS><<TYPE_PARAMETER>T</TYPE_PARAMETER>>\n" +
"{" +
"\n" +
" <KEYWORD>static</KEYWORD> val <STATIC_VARIABLE>MY_VALUE</STATIC_VARIABLE> : Int = 1" +
"\n" +
"\n" +
" var <INSTANCE_VARIABLE>myVar</INSTANCE_VARIABLE> : Int" +
"\n" +
" {" +
"\n" +
" <KEYWORD>local</KEYWORD> <KEYWORD>set</KEYWORD>" +
"\n" +
" } = 0" +
"\n" +
"\n" +
" meth <METHOD_DECLARATION>test</METHOD_DECLARATION>(<PARAMETER>nullable</PARAMETER> : <CLASS>String</CLASS>?, <PARAMETER>f</PARAMETER> : <METHOD_LITERAL_BRACES_AND_ARROW>{</METHOD_LITERAL_BRACES_AND_ARROW>(<PARAMETER>el</PARAMETER> : <CLASS>Int</CLASS>) <METHOD_LITERAL_BRACES_AND_ARROW>-></METHOD_LITERAL_BRACES_AND_ARROW> <CLASS>Int</CLASS><METHOD_LITERAL_BRACES_AND_ARROW>}</METHOD_LITERAL_BRACES_AND_ARROW>)" +
"\n" +
" {\n" +
" <CLASS>Console</CLASS>.<METHOD_CALL><STATIC_METHOD_CALL>writeLine</STATIC_METHOD_CALL></METHOD_CALL>(\"Hello world !!!\")\n" +
" val <LOCAL_VARIABLE>ints</LOCAL_VARIABLE> = napile.collection.<CLASS>ArrayList</CLASS><<CLASS>Int</CLASS>?>(2)\n" +
" <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>[0] = 102 + <PARAMETER>f</PARAMETER>()\n" +
" var <LOCAL_VARIABLE>testIt</LOCAL_VARIABLE> = <METHOD_CALL>test</METHOD_CALL>(<KEYWORD>null</KEYWORD>, <METHOD_LITERAL_BRACES_AND_ARROW>{<AUTO_GENERATED_VAR>value</AUTO_GENERATED_VAR>}</METHOD_LITERAL_BRACES_AND_ARROW>)" +
"\n" +
" }" +
"\n" +
"\n" +
" meth <METHOD_DECLARATION>test2</METHOD_DECLARATION>()" +
"\n" +
" {" +
"\n" +
" var obj : <CLASS>String</CLASS> = /:<KEYWORD>text</KEYWORD> <INJECTION_BLOCK>Hello my friends. This is my var <INJECTION_INNER_EXPRESSION_MARK>#{</INJECTION_INNER_EXPRESSION_MARK>myVar<INJECTION_INNER_EXPRESSION_MARK>}</INJECTION_INNER_EXPRESSION_MARK></INJECTION_BLOCK>:/" +
"\n" +
" var escape = \"This is valid string escape <VALID_STRING_ESCAPE>\\n</VALID_STRING_ESCAPE> but this is invalid <INVALID_STRING_ESCAPE>\\str</INVALID_STRING_ESCAPE> \"\n" +
" <MACRO_CALL>myMacro</MACRO_CALL>()" +
"\n" +
" }" +
"\n" +
"\n" +
" <KEYWORD>local</KEYWORD> macro <METHOD_DECLARATION>myMacro</METHOD_DECLARATION>()" +
"\n" +
" {" +
"\n" +
" return" +
"\n" +
" }" +
"\n" +
"}" +
"\n" +
"\n" +
"<KEYWORD>heritable</KEYWORD> <KEYWORD>abstract</KEYWORD> class <ABSTRACT_CLASS>Abstract</ABSTRACT_CLASS>" +
"\n" +
"{" +
"\n" +
"}" +
"\n" +
"\n" +
" Bad character: \\n\n";
}
|
private List<AbstractNode> getPodcastChildNodes(String url) {
List<AbstractNode> podcastEntryNodes = null;
Cache podcastEntriesCache = cacheManager.getCache("podcastEntries");
if (podcastEntriesCache.get(url) == null) {
XmlReader reader = null;
try {
URL feedSource = new URL(url);
reader = new XmlReader(feedSource);
List<SyndEntry> rssEntries = new SyndFeedInput().build(reader).getEntries();
if (rssEntries != null && !rssEntries.isEmpty()) {
podcastEntryNodes = new ArrayList<AbstractNode>();
for (SyndEntry rssEntry : rssEntries) {
if (rssEntry.getEnclosures() != null && !rssEntry.getEnclosures().isEmpty()) {
for (SyndEnclosure enclosure : (List<SyndEnclosure>) rssEntry.getEnclosures()) {
PodcastEntryNode podcastEntryNode = new PodcastEntryNode();
podcastEntryNode.setId(UUID.randomUUID().toString());
podcastEntryNode.setName(rssEntry.getTitle());
if (rssEntry.getPublishedDate() != null) {
podcastEntryNode.setModifedDate(formatUpnpDate(rssEntry.getPublishedDate().getTime()));
}
if (enclosure.getType() != null) {
podcastEntryNode.setMimeType(new MimeType(enclosure.getType()));
}
podcastEntryNode.setSize(enclosure.getLength());
podcastEntryNode.setUrl(enclosure.getUrl());
podcastEntryNodes.add(podcastEntryNode);
}
}
}
}
}
catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
}
catch (IOException e) {
logger.error(e.getMessage(), e);
}
catch (IllegalArgumentException e) {
logger.error(e.getMessage(), e);
}
catch (FeedException e) {
logger.error(e.getMessage(), e);
}
finally {
try {
if (reader != null) reader.close();
}
catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
podcastEntriesCache.put(new Element(url, podcastEntryNodes));
}
else {
podcastEntryNodes = (List<AbstractNode>) (podcastEntriesCache.get(url).getValue());
}
return podcastEntryNodes;
}
| private List<AbstractNode> getPodcastChildNodes(String url) {
List<AbstractNode> podcastEntryNodes = null;
Cache podcastEntriesCache = cacheManager.getCache("podcastEntries");
if (podcastEntriesCache == null || podcastEntriesCache.get(url) == null) {
XmlReader reader = null;
try {
URL feedSource = new URL(url);
reader = new XmlReader(feedSource);
List<SyndEntry> rssEntries = new SyndFeedInput().build(reader).getEntries();
if (rssEntries != null && !rssEntries.isEmpty()) {
podcastEntryNodes = new ArrayList<AbstractNode>();
for (SyndEntry rssEntry : rssEntries) {
if (rssEntry.getEnclosures() != null && !rssEntry.getEnclosures().isEmpty()) {
for (SyndEnclosure enclosure : (List<SyndEnclosure>) rssEntry.getEnclosures()) {
PodcastEntryNode podcastEntryNode = new PodcastEntryNode();
podcastEntryNode.setId(UUID.randomUUID().toString());
podcastEntryNode.setName(rssEntry.getTitle());
if (rssEntry.getPublishedDate() != null) {
podcastEntryNode.setModifedDate(formatUpnpDate(rssEntry.getPublishedDate().getTime()));
}
if (enclosure.getType() != null) {
podcastEntryNode.setMimeType(new MimeType(enclosure.getType()));
}
podcastEntryNode.setSize(enclosure.getLength());
podcastEntryNode.setUrl(enclosure.getUrl());
podcastEntryNodes.add(podcastEntryNode);
}
}
}
}
}
catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
}
catch (IOException e) {
logger.error(e.getMessage(), e);
}
catch (IllegalArgumentException e) {
logger.error(e.getMessage(), e);
}
catch (FeedException e) {
logger.error(e.getMessage(), e);
}
finally {
try {
if (reader != null) reader.close();
}
catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
if (podcastEntriesCache != null) podcastEntriesCache.put(new Element(url, podcastEntryNodes));
}
else {
podcastEntryNodes = (List<AbstractNode>) (podcastEntriesCache.get(url).getValue());
}
return podcastEntryNodes;
}
|
public final void publishToLines(ArrayList<Line> lines, LineCreationParams params) {
Line line = Line.getLastLine(lines, params);
final LineWhiteSpace space = RenderingStyle.getTextPaint(params.content, line.getHeight()).space;
float remaining = params.maxLineWidth - (line.width + space.width);
if (remaining <= 0) {
line = new Line(params.maxLineWidth, params.jm);
lines.add(line);
remaining = params.maxLineWidth;
}
if (params.extraSpace > 0 && LengthUtils.isEmpty(line.elements)) {
line.append(new LineFixedWhiteSpace(params.extraSpace, 0));
}
if (this.width <= remaining) {
if (line.hasNonWhiteSpaces() && params.insertSpace) {
line.append(space);
}
line.append(this);
} else {
final AbstractLineElement[] splitted = split(remaining);
if (splitted != null && splitted.length > 1) {
if (line.hasNonWhiteSpaces() && params.insertSpace) {
line.append(space);
}
for (int i = 0; i < splitted.length - 1; i++) {
line.append(splitted[i]);
}
}
line = new Line(params.maxLineWidth, params.jm);
if (params.extraSpace > 0 && LengthUtils.isEmpty(line.elements)) {
line.append(new LineFixedWhiteSpace(params.extraSpace, 0));
}
lines.add(line);
if (splitted == null) {
line.append(this);
} else {
splitted[splitted.length - 1].publishToLines(lines, params);
}
}
params.insertSpace = true;
}
| public final void publishToLines(ArrayList<Line> lines, LineCreationParams params) {
Line line = Line.getLastLine(lines, params);
final LineWhiteSpace space = RenderingStyle.getTextPaint(params.content, Math.max(line.getHeight(), height)).space;
float remaining = params.maxLineWidth - (line.width + space.width);
if (remaining <= 0) {
line = new Line(params.maxLineWidth, params.jm);
lines.add(line);
remaining = params.maxLineWidth;
}
if (params.extraSpace > 0 && LengthUtils.isEmpty(line.elements)) {
line.append(new LineFixedWhiteSpace(params.extraSpace, 0));
}
if (this.width <= remaining) {
if (line.hasNonWhiteSpaces() && params.insertSpace) {
line.append(space);
}
line.append(this);
} else {
final AbstractLineElement[] splitted = split(remaining);
if (splitted != null && splitted.length > 1) {
if (line.hasNonWhiteSpaces() && params.insertSpace) {
line.append(space);
}
for (int i = 0; i < splitted.length - 1; i++) {
line.append(splitted[i]);
}
}
line = new Line(params.maxLineWidth, params.jm);
if (params.extraSpace > 0 && LengthUtils.isEmpty(line.elements)) {
line.append(new LineFixedWhiteSpace(params.extraSpace, 0));
}
lines.add(line);
if (splitted == null) {
line.append(this);
} else {
splitted[splitted.length - 1].publishToLines(lines, params);
}
}
params.insertSpace = true;
}
|