diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/PatchSetComplexDisclosurePanel.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/PatchSetComplexDisclosurePanel.java
index efa971b12..364d710c5 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/PatchSetComplexDisclosurePanel.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/PatchSetComplexDisclosurePanel.java
@@ -1,649 +1,650 @@
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.changes;
import com.google.gerrit.client.Dispatcher;
import com.google.gerrit.client.FormatUtil;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.ui.AccountDashboardLink;
import com.google.gerrit.client.ui.ComplexDisclosurePanel;
import com.google.gerrit.client.ui.ListenableAccountDiffPreference;
import com.google.gerrit.common.data.ChangeDetail;
import com.google.gerrit.common.data.GitwebLink;
import com.google.gerrit.common.data.PatchSetDetail;
import com.google.gerrit.reviewdb.Account;
import com.google.gerrit.reviewdb.AccountDiffPreference;
import com.google.gerrit.reviewdb.AccountGeneralPreferences;
import com.google.gerrit.reviewdb.ApprovalCategory;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.ChangeMessage;
import com.google.gerrit.reviewdb.Patch;
import com.google.gerrit.reviewdb.PatchSet;
import com.google.gerrit.reviewdb.PatchSetInfo;
import com.google.gerrit.reviewdb.Project;
import com.google.gerrit.reviewdb.UserIdentity;
import com.google.gerrit.reviewdb.AccountGeneralPreferences.DownloadCommand;
import com.google.gerrit.reviewdb.AccountGeneralPreferences.DownloadScheme;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwtexpui.clippy.client.CopyableLabel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class PatchSetComplexDisclosurePanel extends ComplexDisclosurePanel implements OpenHandler<DisclosurePanel> {
private static final int R_AUTHOR = 0;
private static final int R_COMMITTER = 1;
private static final int R_PARENTS = 2;
private static final int R_DOWNLOAD = 3;
private static final int R_CNT = 4;
private final ChangeScreen changeScreen;
private final ChangeDetail changeDetail;
private final PatchSet patchSet;
private final FlowPanel body;
private Grid infoTable;
private Panel actionsPanel;
private PatchTable patchTable;
private final Set<ClickHandler> registeredClickHandler = new HashSet<ClickHandler>();
private PatchSet.Id diffBaseId;
/**
* Creates a closed complex disclosure panel for a patch set.
* The patch set details are loaded when the complex disclosure panel is opened.
*/
PatchSetComplexDisclosurePanel(final ChangeScreen parent, final ChangeDetail detail,
final PatchSet ps) {
this(parent, detail, ps, false);
addOpenHandler(this);
}
/**
* Creates an open complex disclosure panel for a patch set.
*/
PatchSetComplexDisclosurePanel(final ChangeScreen parent, final ChangeDetail detail,
final PatchSetDetail psd) {
this(parent, detail, psd.getPatchSet(), true);
ensureLoaded(psd);
}
private PatchSetComplexDisclosurePanel(final ChangeScreen parent, final ChangeDetail detail,
final PatchSet ps, boolean isOpen) {
super(Util.M.patchSetHeader(ps.getPatchSetId()), isOpen);
changeScreen = parent;
changeDetail = detail;
patchSet = ps;
body = new FlowPanel();
setContent(body);
final GitwebLink gw = Gerrit.getConfig().getGitwebLink();
final InlineLabel revtxt = new InlineLabel(ps.getRevision().get() + " ");
revtxt.addStyleName(Gerrit.RESOURCES.css().patchSetRevision());
getHeader().add(revtxt);
if (gw != null) {
final Anchor revlink =
new Anchor("(gitweb)", false, gw.toRevision(detail.getChange()
.getProject(), ps));
revlink.addStyleName(Gerrit.RESOURCES.css().patchSetLink());
getHeader().add(revlink);
}
}
public void setDiffBaseId(PatchSet.Id diffBaseId) {
this.diffBaseId = diffBaseId;
}
/**
* Display the table showing the Author, Committer and Download links,
* followed by the action buttons.
*/
public void ensureLoaded(final PatchSetDetail detail) {
infoTable = new Grid(R_CNT, 2);
infoTable.setStyleName(Gerrit.RESOURCES.css().infoBlock());
infoTable.addStyleName(Gerrit.RESOURCES.css().patchSetInfoBlock());
initRow(R_AUTHOR, Util.C.patchSetInfoAuthor());
initRow(R_COMMITTER, Util.C.patchSetInfoCommitter());
initRow(R_PARENTS, Util.C.patchSetInfoParents());
initRow(R_DOWNLOAD, Util.C.patchSetInfoDownload());
final CellFormatter itfmt = infoTable.getCellFormatter();
itfmt.addStyleName(0, 0, Gerrit.RESOURCES.css().topmost());
itfmt.addStyleName(0, 1, Gerrit.RESOURCES.css().topmost());
itfmt.addStyleName(R_CNT - 1, 0, Gerrit.RESOURCES.css().bottomheader());
itfmt.addStyleName(R_AUTHOR, 1, Gerrit.RESOURCES.css().useridentity());
itfmt.addStyleName(R_COMMITTER, 1, Gerrit.RESOURCES.css().useridentity());
itfmt.addStyleName(R_DOWNLOAD, 1, Gerrit.RESOURCES.css()
.downloadLinkListCell());
final PatchSetInfo info = detail.getInfo();
displayUserIdentity(R_AUTHOR, info.getAuthor());
displayUserIdentity(R_COMMITTER, info.getCommitter());
displayParents(info.getParents());
displayDownload();
body.add(infoTable);
if (!patchSet.getId().equals(diffBaseId)) {
patchTable = new PatchTable();
patchTable.setSavePointerId("PatchTable " + patchSet.getId());
patchTable.setPatchSetIdToCompareWith(diffBaseId);
patchTable.display(detail);
actionsPanel = new FlowPanel();
actionsPanel.setStyleName(Gerrit.RESOURCES.css().patchSetActions());
body.add(actionsPanel);
if (Gerrit.isSignedIn()) {
populateReviewAction();
if (changeDetail.isCurrentPatchSet(detail)) {
populateActions(detail);
}
}
populateDiffAllActions(detail);
body.add(patchTable);
for(ClickHandler clickHandler : registeredClickHandler) {
patchTable.addClickHandler(clickHandler);
}
}
}
private void displayDownload() {
final Project.NameKey projectKey = changeDetail.getChange().getProject();
final String projectName = projectKey.get();
final CopyableLabel copyLabel = new CopyableLabel("");
final DownloadCommandPanel commands = new DownloadCommandPanel();
final DownloadUrlPanel urls = new DownloadUrlPanel(commands);
final Set<DownloadScheme> allowedSchemes = Gerrit.getConfig().getDownloadSchemes();
copyLabel.setStyleName(Gerrit.RESOURCES.css().downloadLinkCopyLabel());
if (changeDetail.isAllowsAnonymous()
&& Gerrit.getConfig().getGitDaemonUrl() != null
- && allowedSchemes.contains(DownloadScheme.ANON_GIT)) {
+ && (allowedSchemes.contains(DownloadScheme.ANON_GIT) ||
+ allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
StringBuilder r = new StringBuilder();
r.append(Gerrit.getConfig().getGitDaemonUrl());
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.ANON_GIT, Util.M
.anonymousDownload("Git"), r.toString()));
}
if (changeDetail.isAllowsAnonymous()
&& (allowedSchemes.contains(DownloadScheme.ANON_HTTP) ||
allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
StringBuilder r = new StringBuilder();
r.append(GWT.getHostPageBaseURL());
r.append("p/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.ANON_HTTP, Util.M
.anonymousDownload("HTTP"), r.toString()));
}
if (Gerrit.getConfig().getSshdAddress() != null && Gerrit.isSignedIn()
&& Gerrit.getUserAccount().getUserName() != null
&& Gerrit.getUserAccount().getUserName().length() > 0
&& (allowedSchemes.contains(DownloadScheme.SSH) ||
allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
String sshAddr = Gerrit.getConfig().getSshdAddress();
final StringBuilder r = new StringBuilder();
r.append("ssh://");
r.append(Gerrit.getUserAccount().getUserName());
r.append("@");
if (sshAddr.startsWith("*:") || "".equals(sshAddr)) {
r.append(Window.Location.getHostName());
}
if (sshAddr.startsWith("*")) {
sshAddr = sshAddr.substring(1);
}
r.append(sshAddr);
r.append("/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.SSH, "SSH", r.toString()));
}
if (Gerrit.isSignedIn() && Gerrit.getUserAccount().getUserName() != null
&& Gerrit.getUserAccount().getUserName().length() > 0
&& (allowedSchemes.contains(DownloadScheme.HTTP) ||
allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
String base = GWT.getHostPageBaseURL();
int p = base.indexOf("://");
int s = base.indexOf('/', p + 3);
if (s < 0) {
s = base.length();
}
String host = base.substring(p + 3, s);
if (host.contains("@")) {
host = host.substring(host.indexOf('@') + 1);
}
final StringBuilder r = new StringBuilder();
r.append(base.substring(0, p + 3));
r.append(Gerrit.getUserAccount().getUserName());
r.append('@');
r.append(host);
r.append(base.substring(s));
r.append("p/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.HTTP, "HTTP", r.toString()));
}
if (allowedSchemes.contains(DownloadScheme.REPO_DOWNLOAD)) {
// This site prefers usage of the 'repo' tool, so suggest
// that for easy fetch.
//
final StringBuilder r = new StringBuilder();
r.append("repo download ");
r.append(projectName);
r.append(" ");
r.append(changeDetail.getChange().getChangeId());
r.append("/");
r.append(patchSet.getPatchSetId());
final String cmd = r.toString();
commands.add(new DownloadCommandLink(DownloadCommand.REPO_DOWNLOAD,
"repo download") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(false);
copyLabel.setText(cmd);
}
});
}
if (!urls.isEmpty()) {
commands.add(new DownloadCommandLink(DownloadCommand.CHECKOUT, "checkout") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git fetch " + link.urlData
+ " && git checkout FETCH_HEAD");
}
});
commands.add(new DownloadCommandLink(DownloadCommand.PULL, "pull") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git pull " + link.urlData);
}
});
commands.add(new DownloadCommandLink(DownloadCommand.CHERRY_PICK,
"cherry-pick") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git fetch " + link.urlData
+ " && git cherry-pick FETCH_HEAD");
}
});
commands.add(new DownloadCommandLink(DownloadCommand.FORMAT_PATCH,
"patch") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git fetch " + link.urlData
+ " && git format-patch -1 --stdout FETCH_HEAD");
}
});
}
final FlowPanel fp = new FlowPanel();
if (!commands.isEmpty()) {
final AccountGeneralPreferences pref;
if (Gerrit.isSignedIn()) {
pref = Gerrit.getUserAccount().getGeneralPreferences();
} else {
pref = new AccountGeneralPreferences();
pref.resetToDefaults();
}
commands.select(pref.getDownloadCommand());
urls.select(pref.getDownloadUrl());
FlowPanel p = new FlowPanel();
p.setStyleName(Gerrit.RESOURCES.css().downloadLinkHeader());
p.add(commands);
final InlineLabel glue = new InlineLabel();
glue.setStyleName(Gerrit.RESOURCES.css().downloadLinkHeaderGap());
p.add(glue);
p.add(urls);
fp.add(p);
fp.add(copyLabel);
}
infoTable.setWidget(R_DOWNLOAD, 1, fp);
}
private void displayUserIdentity(final int row, final UserIdentity who) {
if (who == null) {
infoTable.clearCell(row, 1);
return;
}
final FlowPanel fp = new FlowPanel();
fp.setStyleName(Gerrit.RESOURCES.css().patchSetUserIdentity());
if (who.getName() != null) {
final Account.Id aId = who.getAccount();
if (aId != null) {
fp.add(new AccountDashboardLink(who.getName(), aId));
} else {
final InlineLabel lbl = new InlineLabel(who.getName());
lbl.setStyleName(Gerrit.RESOURCES.css().accountName());
fp.add(lbl);
}
}
if (who.getEmail() != null) {
fp.add(new InlineLabel("<" + who.getEmail() + ">"));
}
if (who.getDate() != null) {
fp.add(new InlineLabel(FormatUtil.mediumFormat(who.getDate())));
}
infoTable.setWidget(row, 1, fp);
}
private void displayParents(final List<PatchSetInfo.ParentInfo> parents) {
if (parents.size() == 0) {
infoTable.setWidget(R_PARENTS, 1, new InlineLabel(Util.C.initialCommit()));
return;
}
final Grid parentsTable = new Grid(parents.size(), 2);
parentsTable.setStyleName(Gerrit.RESOURCES.css().parentsTable());
parentsTable.addStyleName(Gerrit.RESOURCES.css().noborder());
final CellFormatter ptfmt = parentsTable.getCellFormatter();
int row = 0;
for (PatchSetInfo.ParentInfo parent : parents) {
parentsTable.setWidget(row, 0, new InlineLabel(parent.id.get()));
ptfmt.addStyleName(row, 0, Gerrit.RESOURCES.css().noborder());
ptfmt.addStyleName(row, 0, Gerrit.RESOURCES.css().monospace());
parentsTable.setWidget(row, 1, new InlineLabel(parent.shortMessage));
ptfmt.addStyleName(row, 1, Gerrit.RESOURCES.css().noborder());
row++;
}
infoTable.setWidget(R_PARENTS, 1, parentsTable);
}
private void populateActions(final PatchSetDetail detail) {
final boolean isOpen = changeDetail.getChange().getStatus().isOpen();
Set<ApprovalCategory.Id> allowed = changeDetail.getCurrentActions();
if (allowed == null) {
allowed = Collections.emptySet();
}
if (isOpen && allowed.contains(ApprovalCategory.SUBMIT)) {
final Button b =
new Button(Util.M
.submitPatchSet(detail.getPatchSet().getPatchSetId()));
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
b.setEnabled(false);
Util.MANAGE_SVC.submit(patchSet.getId(),
new GerritCallback<ChangeDetail>() {
public void onSuccess(ChangeDetail result) {
onSubmitResult(result);
}
@Override
public void onFailure(Throwable caught) {
b.setEnabled(true);
super.onFailure(caught);
}
});
}
});
actionsPanel.add(b);
}
if (changeDetail.canRevert()) {
final Button b = new Button(Util.C.buttonRevertChangeBegin());
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
b.setEnabled(false);
new CommentedChangeActionDialog(patchSet.getId(), createCommentedCallback(b),
Util.C.revertChangeTitle(), Util.C.headingRevertMessage(),
Util.C.buttonRevertChangeSend(), Util.C.buttonRevertChangeCancel(),
Gerrit.RESOURCES.css().revertChangeDialog(), Gerrit.RESOURCES.css().revertMessage(),
Util.M.revertChangeDefaultMessage(detail.getInfo().getSubject(), detail.getPatchSet().getRevision().get())) {
public void onSend() {
Util.MANAGE_SVC.revertChange(getPatchSetId() , getMessageText(), createCallback());
}
}.center();
}
});
actionsPanel.add(b);
}
if (changeDetail.canAbandon()) {
final Button b = new Button(Util.C.buttonAbandonChangeBegin());
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
b.setEnabled(false);
new CommentedChangeActionDialog(patchSet.getId(), createCommentedCallback(b),
Util.C.abandonChangeTitle(), Util.C.headingAbandonMessage(),
Util.C.buttonAbandonChangeSend(), Util.C.buttonAbandonChangeCancel(),
Gerrit.RESOURCES.css().abandonChangeDialog(), Gerrit.RESOURCES.css().abandonMessage()) {
public void onSend() {
Util.MANAGE_SVC.abandonChange(getPatchSetId() , getMessageText(), createCallback());
}
}.center();
}
});
actionsPanel.add(b);
}
if (changeDetail.canRestore()) {
final Button b = new Button(Util.C.buttonRestoreChangeBegin());
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
b.setEnabled(false);
new CommentedChangeActionDialog(patchSet.getId(), createCommentedCallback(b),
Util.C.restoreChangeTitle(), Util.C.headingRestoreMessage(),
Util.C.buttonRestoreChangeSend(), Util.C.buttonRestoreChangeCancel(),
Gerrit.RESOURCES.css().abandonChangeDialog(), Gerrit.RESOURCES.css().abandonMessage()) {
public void onSend() {
Util.MANAGE_SVC.restoreChange(getPatchSetId(), getMessageText(), createCallback());
}
}.center();
}
});
actionsPanel.add(b);
}
}
private void populateDiffAllActions(final PatchSetDetail detail) {
final Button diffAllSideBySide = new Button(Util.C.buttonDiffAllSideBySide());
diffAllSideBySide.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for (Patch p : detail.getPatches()) {
Window.open(Window.Location.getPath() + "#"
+ Dispatcher.toPatchSideBySide(p.getKey()), "_blank", null);
}
}
});
actionsPanel.add(diffAllSideBySide);
final Button diffAllUnified = new Button(Util.C.buttonDiffAllUnified());
diffAllUnified.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for (Patch p : detail.getPatches()) {
Window.open(Window.Location.getPath() + "#"
+ Dispatcher.toPatchUnified(p.getKey()), "_blank", null);
}
}
});
actionsPanel.add(diffAllUnified);
}
private void populateReviewAction() {
final Button b = new Button(Util.C.buttonReview());
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
Gerrit.display("change,publish," + patchSet.getId().toString(),
new PublishCommentScreen(patchSet.getId()));
}
});
actionsPanel.add(b);
}
public void refresh() {
AccountDiffPreference diffPrefs;
if (patchTable == null) {
diffPrefs = new ListenableAccountDiffPreference().get();
} else {
diffPrefs = patchTable.getPreferences().get();
}
Util.DETAIL_SVC.patchSetDetail(patchSet.getId(), diffBaseId, diffPrefs,
new GerritCallback<PatchSetDetail>() {
@Override
public void onSuccess(PatchSetDetail result) {
if (patchSet.getId().equals(diffBaseId)) {
patchTable.setVisible(false);
actionsPanel.setVisible(false);
} else {
if (patchTable != null) {
patchTable.removeFromParent();
}
patchTable = new PatchTable();
patchTable.setPatchSetIdToCompareWith(diffBaseId);
patchTable.display(result);
body.add(patchTable);
for (ClickHandler clickHandler : registeredClickHandler) {
patchTable.addClickHandler(clickHandler);
}
}
}
});
}
@Override
public void onOpen(final OpenEvent<DisclosurePanel> event) {
if (infoTable == null) {
AccountDiffPreference diffPrefs;
if (diffBaseId == null) {
diffPrefs = null;
} else {
diffPrefs = new ListenableAccountDiffPreference().get();
}
Util.DETAIL_SVC.patchSetDetail(patchSet.getId(), diffBaseId, diffPrefs,
new GerritCallback<PatchSetDetail>() {
public void onSuccess(final PatchSetDetail result) {
ensureLoaded(result);
patchTable.setRegisterKeys(true);
}
});
}
}
private void initRow(final int row, final String name) {
infoTable.setText(row, 0, name);
infoTable.getCellFormatter().addStyleName(row, 0,
Gerrit.RESOURCES.css().header());
}
private void onSubmitResult(final ChangeDetail result) {
if (result.getChange().getStatus() == Change.Status.NEW) {
// The submit failed. Try to locate the message and display
// it to the user, it should be the last one created by Gerrit.
//
ChangeMessage msg = null;
if (result.getMessages() != null && result.getMessages().size() > 0) {
for (int i = result.getMessages().size() - 1; i >= 0; i--) {
if (result.getMessages().get(i).getAuthor() == null) {
msg = result.getMessages().get(i);
break;
}
}
}
if (msg != null) {
new SubmitFailureDialog(result, msg).center();
}
}
changeScreen.update(result);
}
public PatchSet getPatchSet() {
return patchSet;
}
/**
* Adds a click handler to the patch table.
* If the patch table is not yet initialized it is guaranteed that the click handler
* is added to the patch table after initialization.
*/
public void addClickHandler(final ClickHandler clickHandler) {
registeredClickHandler.add(clickHandler);
if (patchTable != null) {
patchTable.addClickHandler(clickHandler);
}
}
/** Activates / Deactivates the key navigation and the highlighting of the current row for the patch table */
public void setActive(boolean active) {
if (patchTable != null) {
patchTable.setActive(active);
}
}
private AsyncCallback<ChangeDetail> createCommentedCallback(final Button b) {
return new AsyncCallback<ChangeDetail>() {
public void onSuccess(ChangeDetail result) {
changeScreen.update(result);
}
public void onFailure(Throwable caught) {
b.setEnabled(true);
}
};
}
}
| true | true | private void displayDownload() {
final Project.NameKey projectKey = changeDetail.getChange().getProject();
final String projectName = projectKey.get();
final CopyableLabel copyLabel = new CopyableLabel("");
final DownloadCommandPanel commands = new DownloadCommandPanel();
final DownloadUrlPanel urls = new DownloadUrlPanel(commands);
final Set<DownloadScheme> allowedSchemes = Gerrit.getConfig().getDownloadSchemes();
copyLabel.setStyleName(Gerrit.RESOURCES.css().downloadLinkCopyLabel());
if (changeDetail.isAllowsAnonymous()
&& Gerrit.getConfig().getGitDaemonUrl() != null
&& allowedSchemes.contains(DownloadScheme.ANON_GIT)) {
StringBuilder r = new StringBuilder();
r.append(Gerrit.getConfig().getGitDaemonUrl());
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.ANON_GIT, Util.M
.anonymousDownload("Git"), r.toString()));
}
if (changeDetail.isAllowsAnonymous()
&& (allowedSchemes.contains(DownloadScheme.ANON_HTTP) ||
allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
StringBuilder r = new StringBuilder();
r.append(GWT.getHostPageBaseURL());
r.append("p/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.ANON_HTTP, Util.M
.anonymousDownload("HTTP"), r.toString()));
}
if (Gerrit.getConfig().getSshdAddress() != null && Gerrit.isSignedIn()
&& Gerrit.getUserAccount().getUserName() != null
&& Gerrit.getUserAccount().getUserName().length() > 0
&& (allowedSchemes.contains(DownloadScheme.SSH) ||
allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
String sshAddr = Gerrit.getConfig().getSshdAddress();
final StringBuilder r = new StringBuilder();
r.append("ssh://");
r.append(Gerrit.getUserAccount().getUserName());
r.append("@");
if (sshAddr.startsWith("*:") || "".equals(sshAddr)) {
r.append(Window.Location.getHostName());
}
if (sshAddr.startsWith("*")) {
sshAddr = sshAddr.substring(1);
}
r.append(sshAddr);
r.append("/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.SSH, "SSH", r.toString()));
}
if (Gerrit.isSignedIn() && Gerrit.getUserAccount().getUserName() != null
&& Gerrit.getUserAccount().getUserName().length() > 0
&& (allowedSchemes.contains(DownloadScheme.HTTP) ||
allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
String base = GWT.getHostPageBaseURL();
int p = base.indexOf("://");
int s = base.indexOf('/', p + 3);
if (s < 0) {
s = base.length();
}
String host = base.substring(p + 3, s);
if (host.contains("@")) {
host = host.substring(host.indexOf('@') + 1);
}
final StringBuilder r = new StringBuilder();
r.append(base.substring(0, p + 3));
r.append(Gerrit.getUserAccount().getUserName());
r.append('@');
r.append(host);
r.append(base.substring(s));
r.append("p/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.HTTP, "HTTP", r.toString()));
}
if (allowedSchemes.contains(DownloadScheme.REPO_DOWNLOAD)) {
// This site prefers usage of the 'repo' tool, so suggest
// that for easy fetch.
//
final StringBuilder r = new StringBuilder();
r.append("repo download ");
r.append(projectName);
r.append(" ");
r.append(changeDetail.getChange().getChangeId());
r.append("/");
r.append(patchSet.getPatchSetId());
final String cmd = r.toString();
commands.add(new DownloadCommandLink(DownloadCommand.REPO_DOWNLOAD,
"repo download") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(false);
copyLabel.setText(cmd);
}
});
}
if (!urls.isEmpty()) {
commands.add(new DownloadCommandLink(DownloadCommand.CHECKOUT, "checkout") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git fetch " + link.urlData
+ " && git checkout FETCH_HEAD");
}
});
commands.add(new DownloadCommandLink(DownloadCommand.PULL, "pull") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git pull " + link.urlData);
}
});
commands.add(new DownloadCommandLink(DownloadCommand.CHERRY_PICK,
"cherry-pick") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git fetch " + link.urlData
+ " && git cherry-pick FETCH_HEAD");
}
});
commands.add(new DownloadCommandLink(DownloadCommand.FORMAT_PATCH,
"patch") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git fetch " + link.urlData
+ " && git format-patch -1 --stdout FETCH_HEAD");
}
});
}
final FlowPanel fp = new FlowPanel();
if (!commands.isEmpty()) {
final AccountGeneralPreferences pref;
if (Gerrit.isSignedIn()) {
pref = Gerrit.getUserAccount().getGeneralPreferences();
} else {
pref = new AccountGeneralPreferences();
pref.resetToDefaults();
}
commands.select(pref.getDownloadCommand());
urls.select(pref.getDownloadUrl());
FlowPanel p = new FlowPanel();
p.setStyleName(Gerrit.RESOURCES.css().downloadLinkHeader());
p.add(commands);
final InlineLabel glue = new InlineLabel();
glue.setStyleName(Gerrit.RESOURCES.css().downloadLinkHeaderGap());
p.add(glue);
p.add(urls);
fp.add(p);
fp.add(copyLabel);
}
infoTable.setWidget(R_DOWNLOAD, 1, fp);
}
| private void displayDownload() {
final Project.NameKey projectKey = changeDetail.getChange().getProject();
final String projectName = projectKey.get();
final CopyableLabel copyLabel = new CopyableLabel("");
final DownloadCommandPanel commands = new DownloadCommandPanel();
final DownloadUrlPanel urls = new DownloadUrlPanel(commands);
final Set<DownloadScheme> allowedSchemes = Gerrit.getConfig().getDownloadSchemes();
copyLabel.setStyleName(Gerrit.RESOURCES.css().downloadLinkCopyLabel());
if (changeDetail.isAllowsAnonymous()
&& Gerrit.getConfig().getGitDaemonUrl() != null
&& (allowedSchemes.contains(DownloadScheme.ANON_GIT) ||
allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
StringBuilder r = new StringBuilder();
r.append(Gerrit.getConfig().getGitDaemonUrl());
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.ANON_GIT, Util.M
.anonymousDownload("Git"), r.toString()));
}
if (changeDetail.isAllowsAnonymous()
&& (allowedSchemes.contains(DownloadScheme.ANON_HTTP) ||
allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
StringBuilder r = new StringBuilder();
r.append(GWT.getHostPageBaseURL());
r.append("p/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.ANON_HTTP, Util.M
.anonymousDownload("HTTP"), r.toString()));
}
if (Gerrit.getConfig().getSshdAddress() != null && Gerrit.isSignedIn()
&& Gerrit.getUserAccount().getUserName() != null
&& Gerrit.getUserAccount().getUserName().length() > 0
&& (allowedSchemes.contains(DownloadScheme.SSH) ||
allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
String sshAddr = Gerrit.getConfig().getSshdAddress();
final StringBuilder r = new StringBuilder();
r.append("ssh://");
r.append(Gerrit.getUserAccount().getUserName());
r.append("@");
if (sshAddr.startsWith("*:") || "".equals(sshAddr)) {
r.append(Window.Location.getHostName());
}
if (sshAddr.startsWith("*")) {
sshAddr = sshAddr.substring(1);
}
r.append(sshAddr);
r.append("/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.SSH, "SSH", r.toString()));
}
if (Gerrit.isSignedIn() && Gerrit.getUserAccount().getUserName() != null
&& Gerrit.getUserAccount().getUserName().length() > 0
&& (allowedSchemes.contains(DownloadScheme.HTTP) ||
allowedSchemes.contains(DownloadScheme.DEFAULT_DOWNLOADS))) {
String base = GWT.getHostPageBaseURL();
int p = base.indexOf("://");
int s = base.indexOf('/', p + 3);
if (s < 0) {
s = base.length();
}
String host = base.substring(p + 3, s);
if (host.contains("@")) {
host = host.substring(host.indexOf('@') + 1);
}
final StringBuilder r = new StringBuilder();
r.append(base.substring(0, p + 3));
r.append(Gerrit.getUserAccount().getUserName());
r.append('@');
r.append(host);
r.append(base.substring(s));
r.append("p/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
urls.add(new DownloadUrlLink(DownloadScheme.HTTP, "HTTP", r.toString()));
}
if (allowedSchemes.contains(DownloadScheme.REPO_DOWNLOAD)) {
// This site prefers usage of the 'repo' tool, so suggest
// that for easy fetch.
//
final StringBuilder r = new StringBuilder();
r.append("repo download ");
r.append(projectName);
r.append(" ");
r.append(changeDetail.getChange().getChangeId());
r.append("/");
r.append(patchSet.getPatchSetId());
final String cmd = r.toString();
commands.add(new DownloadCommandLink(DownloadCommand.REPO_DOWNLOAD,
"repo download") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(false);
copyLabel.setText(cmd);
}
});
}
if (!urls.isEmpty()) {
commands.add(new DownloadCommandLink(DownloadCommand.CHECKOUT, "checkout") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git fetch " + link.urlData
+ " && git checkout FETCH_HEAD");
}
});
commands.add(new DownloadCommandLink(DownloadCommand.PULL, "pull") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git pull " + link.urlData);
}
});
commands.add(new DownloadCommandLink(DownloadCommand.CHERRY_PICK,
"cherry-pick") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git fetch " + link.urlData
+ " && git cherry-pick FETCH_HEAD");
}
});
commands.add(new DownloadCommandLink(DownloadCommand.FORMAT_PATCH,
"patch") {
@Override
void setCurrentUrl(DownloadUrlLink link) {
urls.setVisible(true);
copyLabel.setText("git fetch " + link.urlData
+ " && git format-patch -1 --stdout FETCH_HEAD");
}
});
}
final FlowPanel fp = new FlowPanel();
if (!commands.isEmpty()) {
final AccountGeneralPreferences pref;
if (Gerrit.isSignedIn()) {
pref = Gerrit.getUserAccount().getGeneralPreferences();
} else {
pref = new AccountGeneralPreferences();
pref.resetToDefaults();
}
commands.select(pref.getDownloadCommand());
urls.select(pref.getDownloadUrl());
FlowPanel p = new FlowPanel();
p.setStyleName(Gerrit.RESOURCES.css().downloadLinkHeader());
p.add(commands);
final InlineLabel glue = new InlineLabel();
glue.setStyleName(Gerrit.RESOURCES.css().downloadLinkHeaderGap());
p.add(glue);
p.add(urls);
fp.add(p);
fp.add(copyLabel);
}
infoTable.setWidget(R_DOWNLOAD, 1, fp);
}
|
diff --git a/jsf-ri/systest/src/com/sun/faces/systest/tags/EventTestCase.java b/jsf-ri/systest/src/com/sun/faces/systest/tags/EventTestCase.java
index b192366d6..c5c54379b 100644
--- a/jsf-ri/systest/src/com/sun/faces/systest/tags/EventTestCase.java
+++ b/jsf-ri/systest/src/com/sun/faces/systest/tags/EventTestCase.java
@@ -1,164 +1,164 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.systest.tags;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import junit.framework.Test;
import junit.framework.TestSuite;
import com.sun.faces.htmlunit.AbstractTestCase;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSpan;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
/**
* Validate new EL features such as the component implicit object
*/
public class EventTestCase extends AbstractTestCase {
public EventTestCase(String name) {
super(name);
}
/**
* Set up instance variables required by this test case.
*/
public void setUp() throws Exception {
super.setUp();
}
/**
* Return the tests included in this test suite.
*/
public static Test suite() {
return (new TestSuite(EventTestCase.class));
}
/**
* Tear down instance variables required by this test case.
*/
public void tearDown() {
super.tearDown();
}
// ------------------------------------------------------------ Test Methods
public void testValidEvents() throws Exception {
HtmlPage page = getPage("/faces/eventTag.xhtml");
List<HtmlSpan> outputs = new ArrayList<HtmlSpan>(4);
getAllElementsOfGivenClass(page, outputs, HtmlSpan.class);
assertTrue(outputs.size() == 6);
validateOutput(outputs);
HtmlSubmitInput submit = (HtmlSubmitInput) getInputContainingGivenId(page, "click");
assertNotNull(submit);
page = submit.click();
outputs.clear();
getAllElementsOfGivenClass(page, outputs, HtmlSpan.class);
assertTrue(outputs.size() == 6);
validateOutput(outputs);
}
public void testBeforeViewRender() throws Exception {
HtmlPage page = getPage("/faces/eventTag01.xhtml");
assertTrue(-1 != page.asText().indexOf("class javax.faces.component.UIViewRoot before render"));
}
public void testInvalidEvent() throws Exception {
try {
getPage("/faces/eventTagInvalid.xhtml");
fail ("An exception should be thrown for an invalid event name in Development mode");
} catch (FailingHttpStatusCodeException fail) {
//
}
}
public static void main (String... args) {
try {
EventTestCase etc = new EventTestCase("foo");
etc.setUp();
etc.testValidEvents();
etc.testInvalidEvent();
etc.tearDown();
} catch (Exception ex) {
Logger.getLogger(EventTestCase.class.getName()).log(Level.SEVERE, null, ex);
}
}
// --------------------------------------------------------- Private Methods
private void validateOutput(List<HtmlSpan> outputs) {
HtmlSpan s;
// Short name
s = outputs.get(0);
assertTrue(("The 'javax.faces.event.BeforeRenderEvent' event fired!").equals(s.asText()));
// Long name
s = outputs.get(1);
assertTrue(("The 'javax.faces.event.BeforeRenderEvent' event fired!").equals(s.asText()));
// Short Name
s = outputs.get(2);
assertTrue(("The 'javax.faces.event.AfterAddToViewEvent' event fired!").equals(s.asText()));
// Long name
s = outputs.get(3);
assertTrue(("The 'javax.faces.event.AfterAddToViewEvent' event fired!").equals(s.asText()));
// Fully-qualified class name
s = outputs.get(4);
- assertTrue(("The 'javax.faces.event.AfterAddToParentEvent' event fired!").equals(s.asText()));
+ assertTrue(("The 'javax.faces.event.BeforeRenderEvent' event fired!").equals(s.asText()));
// No-arg
s = outputs.get(5);
assertTrue(("The no-arg event fired!").equals(s.asText()));
}
}
| true | true | private void validateOutput(List<HtmlSpan> outputs) {
HtmlSpan s;
// Short name
s = outputs.get(0);
assertTrue(("The 'javax.faces.event.BeforeRenderEvent' event fired!").equals(s.asText()));
// Long name
s = outputs.get(1);
assertTrue(("The 'javax.faces.event.BeforeRenderEvent' event fired!").equals(s.asText()));
// Short Name
s = outputs.get(2);
assertTrue(("The 'javax.faces.event.AfterAddToViewEvent' event fired!").equals(s.asText()));
// Long name
s = outputs.get(3);
assertTrue(("The 'javax.faces.event.AfterAddToViewEvent' event fired!").equals(s.asText()));
// Fully-qualified class name
s = outputs.get(4);
assertTrue(("The 'javax.faces.event.AfterAddToParentEvent' event fired!").equals(s.asText()));
// No-arg
s = outputs.get(5);
assertTrue(("The no-arg event fired!").equals(s.asText()));
}
| private void validateOutput(List<HtmlSpan> outputs) {
HtmlSpan s;
// Short name
s = outputs.get(0);
assertTrue(("The 'javax.faces.event.BeforeRenderEvent' event fired!").equals(s.asText()));
// Long name
s = outputs.get(1);
assertTrue(("The 'javax.faces.event.BeforeRenderEvent' event fired!").equals(s.asText()));
// Short Name
s = outputs.get(2);
assertTrue(("The 'javax.faces.event.AfterAddToViewEvent' event fired!").equals(s.asText()));
// Long name
s = outputs.get(3);
assertTrue(("The 'javax.faces.event.AfterAddToViewEvent' event fired!").equals(s.asText()));
// Fully-qualified class name
s = outputs.get(4);
assertTrue(("The 'javax.faces.event.BeforeRenderEvent' event fired!").equals(s.asText()));
// No-arg
s = outputs.get(5);
assertTrue(("The no-arg event fired!").equals(s.asText()));
}
|
diff --git a/src/com/android/camera/ui/CameraSwitcher.java b/src/com/android/camera/ui/CameraSwitcher.java
index d7227681..185accd3 100644
--- a/src/com/android/camera/ui/CameraSwitcher.java
+++ b/src/com/android/camera/ui/CameraSwitcher.java
@@ -1,287 +1,287 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera.ui;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.android.camera.R;
import com.android.gallery3d.common.ApiHelper;
public class CameraSwitcher extends RotateImageView
implements OnClickListener, OnTouchListener {
private static final String TAG = "CAM_Switcher";
private static final int SWITCHER_POPUP_ANIM_DURATION = 200;
public interface CameraSwitchListener {
public void onCameraSelected(int i);
public void onShowSwitcherPopup();
}
private CameraSwitchListener mListener;
private int mCurrentIndex;
private int[] mDrawIds;
private int mItemSize;
private View mPopup;
private View mParent;
private boolean mShowingPopup;
private boolean mNeedsAnimationSetup;
private Drawable mIndicator;
private float mTranslationX = 0;
private float mTranslationY = 0;
private AnimatorListener mHideAnimationListener;
private AnimatorListener mShowAnimationListener;
public CameraSwitcher(Context context) {
super(context);
init(context);
}
public CameraSwitcher(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
mItemSize = context.getResources().getDimensionPixelSize(R.dimen.switcher_size);
setOnClickListener(this);
mIndicator = context.getResources().getDrawable(R.drawable.ic_switcher_menu_indicator);
}
public void setDrawIds(int[] drawids) {
mDrawIds = drawids;
}
public void setCurrentIndex(int i) {
mCurrentIndex = i;
setImageResource(mDrawIds[i]);
}
public void setSwitchListener(CameraSwitchListener l) {
mListener = l;
}
@Override
public void onClick(View v) {
showSwitcher();
mListener.onShowSwitcherPopup();
}
private void onCameraSelected(int ix) {
hidePopup();
if ((ix != mCurrentIndex) && (mListener != null)) {
setCurrentIndex(ix);
mListener.onCameraSelected(ix);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mIndicator.setBounds(getDrawable().getBounds());
mIndicator.draw(canvas);
}
private void initPopup() {
mParent = LayoutInflater.from(getContext()).inflate(R.layout.switcher_popup,
(ViewGroup) getParent());
LinearLayout content = (LinearLayout) mParent.findViewById(R.id.content);
mPopup = content;
mPopup.setVisibility(View.INVISIBLE);
mNeedsAnimationSetup = true;
for (int i = mDrawIds.length - 1; i >= 0; i--) {
RotateImageView item = new RotateImageView(getContext());
item.setImageResource(mDrawIds[i]);
item.setBackgroundResource(R.drawable.bg_pressed);
final int index = i;
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onCameraSelected(index);
}
});
switch (mDrawIds[i]) {
case R.drawable.ic_switch_camera:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_camera));
break;
case R.drawable.ic_switch_video:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_video));
break;
case R.drawable.ic_switch_pan:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_panorama));
break;
case R.drawable.ic_switch_photosphere:
item.setContentDescription(getContext().getResources().getString(
- R.string.accessibility_switch_to_photosphere));
+ R.string.accessibility_switch_to_new_panorama));
break;
default:
break;
}
content.addView(item, new LinearLayout.LayoutParams(mItemSize, mItemSize));
}
}
public boolean showsPopup() {
return mShowingPopup;
}
public boolean isInsidePopup(MotionEvent evt) {
if (!showsPopup()) return false;
return evt.getX() >= mPopup.getLeft()
&& evt.getX() < mPopup.getRight()
&& evt.getY() >= mPopup.getTop()
&& evt.getY() < mPopup.getBottom();
}
private void hidePopup() {
mShowingPopup = false;
setVisibility(View.VISIBLE);
if (mPopup != null && !animateHidePopup()) {
mPopup.setVisibility(View.INVISIBLE);
}
mParent.setOnTouchListener(null);
}
private void showSwitcher() {
mShowingPopup = true;
if (mPopup == null) {
initPopup();
}
mPopup.setVisibility(View.VISIBLE);
if (!animateShowPopup()) {
setVisibility(View.INVISIBLE);
}
mParent.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (showsPopup()) {
hidePopup();
}
return true;
}
@Override
public void setOrientation(int degree, boolean animate) {
super.setOrientation(degree, animate);
ViewGroup content = (ViewGroup) mPopup;
if (content == null) return;
for (int i = 0; i < content.getChildCount(); i++) {
RotateImageView iv = (RotateImageView) content.getChildAt(i);
iv.setOrientation(degree, animate);
}
}
private void updateInitialTranslations() {
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_PORTRAIT) {
mTranslationX = -getWidth() / 2 ;
mTranslationY = getHeight();
} else {
mTranslationX = getWidth();
mTranslationY = getHeight() / 2;
}
}
private void popupAnimationSetup() {
if (!ApiHelper.HAS_VIEW_PROPERTY_ANIMATOR) {
return;
}
updateInitialTranslations();
mPopup.setScaleX(0.3f);
mPopup.setScaleY(0.3f);
mPopup.setTranslationX(mTranslationX);
mPopup.setTranslationY(mTranslationY);
mNeedsAnimationSetup = false;
}
private boolean animateHidePopup() {
if (!ApiHelper.HAS_VIEW_PROPERTY_ANIMATOR) {
return false;
}
if (mHideAnimationListener == null) {
mHideAnimationListener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// Verify that we weren't canceled
if (!showsPopup()) {
mPopup.setVisibility(View.INVISIBLE);
}
}
};
}
mPopup.animate()
.alpha(0f)
.scaleX(0.3f).scaleY(0.3f)
.translationX(mTranslationX)
.translationY(mTranslationY)
.setDuration(SWITCHER_POPUP_ANIM_DURATION)
.setListener(mHideAnimationListener);
animate().alpha(1f).setDuration(SWITCHER_POPUP_ANIM_DURATION)
.setListener(null);
return true;
}
private boolean animateShowPopup() {
if (!ApiHelper.HAS_VIEW_PROPERTY_ANIMATOR) {
return false;
}
if (mNeedsAnimationSetup) {
popupAnimationSetup();
}
if (mShowAnimationListener == null) {
mShowAnimationListener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// Verify that we weren't canceled
if (showsPopup()) {
setVisibility(View.INVISIBLE);
}
}
};
}
mPopup.animate()
.alpha(1f)
.scaleX(1f).scaleY(1f)
.translationX(0)
.translationY(0)
.setDuration(SWITCHER_POPUP_ANIM_DURATION)
.setListener(null);
animate().alpha(0f).setDuration(SWITCHER_POPUP_ANIM_DURATION)
.setListener(mShowAnimationListener);
return true;
}
}
| true | true | private void initPopup() {
mParent = LayoutInflater.from(getContext()).inflate(R.layout.switcher_popup,
(ViewGroup) getParent());
LinearLayout content = (LinearLayout) mParent.findViewById(R.id.content);
mPopup = content;
mPopup.setVisibility(View.INVISIBLE);
mNeedsAnimationSetup = true;
for (int i = mDrawIds.length - 1; i >= 0; i--) {
RotateImageView item = new RotateImageView(getContext());
item.setImageResource(mDrawIds[i]);
item.setBackgroundResource(R.drawable.bg_pressed);
final int index = i;
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onCameraSelected(index);
}
});
switch (mDrawIds[i]) {
case R.drawable.ic_switch_camera:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_camera));
break;
case R.drawable.ic_switch_video:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_video));
break;
case R.drawable.ic_switch_pan:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_panorama));
break;
case R.drawable.ic_switch_photosphere:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_photosphere));
break;
default:
break;
}
content.addView(item, new LinearLayout.LayoutParams(mItemSize, mItemSize));
}
}
| private void initPopup() {
mParent = LayoutInflater.from(getContext()).inflate(R.layout.switcher_popup,
(ViewGroup) getParent());
LinearLayout content = (LinearLayout) mParent.findViewById(R.id.content);
mPopup = content;
mPopup.setVisibility(View.INVISIBLE);
mNeedsAnimationSetup = true;
for (int i = mDrawIds.length - 1; i >= 0; i--) {
RotateImageView item = new RotateImageView(getContext());
item.setImageResource(mDrawIds[i]);
item.setBackgroundResource(R.drawable.bg_pressed);
final int index = i;
item.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onCameraSelected(index);
}
});
switch (mDrawIds[i]) {
case R.drawable.ic_switch_camera:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_camera));
break;
case R.drawable.ic_switch_video:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_video));
break;
case R.drawable.ic_switch_pan:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_panorama));
break;
case R.drawable.ic_switch_photosphere:
item.setContentDescription(getContext().getResources().getString(
R.string.accessibility_switch_to_new_panorama));
break;
default:
break;
}
content.addView(item, new LinearLayout.LayoutParams(mItemSize, mItemSize));
}
}
|
diff --git a/src/main/java/net/deepbondi/minecraft/market/CommoditiesMarket.java b/src/main/java/net/deepbondi/minecraft/market/CommoditiesMarket.java
index fb8c63e..112294d 100644
--- a/src/main/java/net/deepbondi/minecraft/market/CommoditiesMarket.java
+++ b/src/main/java/net/deepbondi/minecraft/market/CommoditiesMarket.java
@@ -1,405 +1,403 @@
package net.deepbondi.minecraft.market;
import com.avaje.ebean.EbeanServer;
import com.iCo6.iConomy;
import com.iCo6.system.Account;
import com.iCo6.system.Accounts;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
import net.deepbondi.minecraft.market.commands.AdminCommand;
import net.deepbondi.minecraft.market.commands.BuyCommand;
import net.deepbondi.minecraft.market.commands.PriceCheckCommand;
import net.deepbondi.minecraft.market.commands.SellCommand;
import net.deepbondi.minecraft.market.exceptions.CommoditiesMarketException;
import net.deepbondi.minecraft.market.exceptions.NoSuchCommodityException;
import net.deepbondi.minecraft.market.exceptions.NotReadyException;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.Configuration;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.EventExecutor;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import javax.persistence.PersistenceException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
public class CommoditiesMarket extends JavaPlugin {
private static final Pattern COLON_PATTERN = Pattern.compile(":");
private Accounts accounts;
private PermissionHandler permissions;
private final PriceModel model = new BondilandPriceModel();
private int initialItemQty = 200;
@Override
public void onEnable() {
loadConfig();
setupDatabase();
registerPluginListener();
getCommand("commodities").setExecutor(new AdminCommand(this));
getCommand("pricecheck").setExecutor(new PriceCheckCommand(this));
getCommand("buy").setExecutor(new BuyCommand(this));
getCommand("sell").setExecutor(new SellCommand(this));
}
@Override
public void onDisable() {
saveConfig();
}
private void setupDatabase() {
try {
getDatabase().find(Commodity.class).findRowCount();
getDatabase().find(PlayerCommodityStats.class).findRowCount();
} catch (PersistenceException ex) {
installDDL();
}
}
@Override
public List<Class<?>> getDatabaseClasses() {
final List<Class<?>> list = new ArrayList<Class<?>>();
list.add(Commodity.class);
list.add(PlayerCommodityStats.class);
return list;
}
private void loadConfig() {
try {
final Configuration config = getConfig();
initialItemQty = config.getInt("itemdefaults.instock", initialItemQty);
} catch (Exception e) {
final String pluginName = getDescription().getName();
getServer()
.getLogger()
.severe("Exception while loading " + pluginName + "/config.yml");
}
}
@Override
public void saveConfig() {
getConfig().set("itemdefaults.instock", initialItemQty);
super.saveConfig();
}
private final PluginListener pl = new PluginListener();
private class PluginListener implements EventExecutor {
@Override
public void execute(final Listener l, final Event e) {
if (e instanceof PluginEnableEvent)
onPluginEnable((PluginEnableEvent) e);
if (e instanceof PluginDisableEvent)
onPluginDisable((PluginDisableEvent) e);
}
public void onPluginEnable(final PluginEnableEvent event) {
discover(event.getPlugin());
}
public void onPluginDisable(final PluginDisableEvent event) {
undiscover(event.getPlugin());
}
void discover(final Plugin plugin) {
discover(plugin, plugin);
}
void undiscover(final Plugin plugin) {
discover(plugin, null);
}
private void discover(final Plugin plugin, final Object surrogate) {
if (plugin instanceof iConomy) discoverEconomy();
if (plugin instanceof Permissions) discoverPermissions((Permissions) surrogate);
}
void discoverEconomy() {
accounts = new Accounts();
}
void discoverPermissions(final Permissions plugin) {
permissions = plugin.getHandler();
}
}
private void registerPluginListener() {
final PluginManager pm = getServer().getPluginManager();
pm.registerEvent(PluginEnableEvent.class, new Listener() {
}, EventPriority.MONITOR, pl, this);
final Plugin ic = pm.getPlugin("iConomy");
if (ic.isEnabled()) pl.discover(ic);
final Plugin perms = pm.getPlugin("Permissions");
if (perms.isEnabled()) pl.discover(perms);
}
public PriceModel getPriceModel() {
return model;
}
public Account getAccount(final String name)
throws NotReadyException {
if (accounts == null)
throw new NotReadyException(this, "iConomy is not yet enabled");
return accounts.get(name);
}
private PermissionHandler getPermissions()
throws NotReadyException {
if (permissions != null) return permissions;
throw new NotReadyException(this, "Permissions is not yet enabled");
}
public boolean hasPermission(final CommandSender sender, final String action)
throws NotReadyException {
return !(sender instanceof Player) || getPermissions().has((Player) sender, "commodities." + action);
}
private synchronized Commodity lookupCommodity(final Material material, final byte byteData) throws NoSuchCommodityException {
final Material fudgedMaterial = fudgeMaterial(material);
Commodity result = getDatabase().find(Commodity.class)
.where().eq("itemId", fudgedMaterial.getId())
.where().eq("byteData", byteData)
.findUnique();
if (result == null) {
// check without byteData, if it's unique accept it
try {
result = getDatabase().find(Commodity.class)
.where().eq("itemId", fudgedMaterial.getId())
.findUnique();
} catch (PersistenceException e) {
// ignore; it means the result wasn't unique
}
}
if (result == null) {
final String name = fudgedMaterial.name();
final String description = byteData == 0
? name
: name + ':' + byteData;
throw new NoSuchCommodityException("Can't find commodity [" + ChatColor.WHITE + description + ChatColor.RED + ']');
}
return result;
}
private static Material fudgeMaterial(final Material original) {
// when picking items by looking at them, we don't always get what the user expects.
// for the cases we've run across or thought of, we fudge them here.
//noinspection EnumSwitchStatementWhichMissesCases
switch (original) {
case BED_BLOCK:
return Material.BED;
case LAVA:
case STATIONARY_LAVA:
return Material.LAVA_BUCKET;
case REDSTONE_LAMP_ON:
return Material.REDSTONE_LAMP_OFF;
case REDSTONE_TORCH_ON:
return Material.REDSTONE_TORCH_OFF;
case PISTON_EXTENSION:
case PISTON_MOVING_PIECE:
return Material.PISTON_BASE;
case SIGN_POST:
case WALL_SIGN:
return Material.SIGN;
case STATIONARY_WATER:
case WATER:
return Material.WATER_BUCKET;
default:
return original;
}
}
public Commodity lookupCommodity(final CommandSender sender, final String name) throws NoSuchCommodityException {
// Accept a few context-dependent commodity name strings in addition to those recognized without a CommandSender
if (sender instanceof Player) {
final Player player = (Player) sender;
if (name.toLowerCase().equals("this")) {
final ItemStack thisStack = player.getItemInHand();
if (thisStack != null && thisStack.getType() != Material.AIR) {
return lookupCommodity(thisStack.getType(), thisStack.getData().getData());
} else {
throw new NoSuchCommodityException("You don't appear to be holding anything");
}
} else if (name.toLowerCase().equals("that")) {
final Block thatBlock = player.getTargetBlock(null, 100);
if (thatBlock != null && thatBlock.getType() != Material.AIR) {
return lookupCommodity(thatBlock.getType(), thatBlock.getData());
} else {
throw new NoSuchCommodityException("You don't appear to be pointing at anything");
}
}
}
return lookupCommodity(name);
}
private synchronized Commodity lookupCommodity(final String name) throws NoSuchCommodityException {
// Accept "names" in several forms:
// Material:byte and associated forms like in ScrapBukkit's /give
// Commodity name from database
final Commodity commodity = getDatabase()
.find(Commodity.class)
.where().ieq("name", name)
.findUnique();
if (commodity != null) {
return commodity;
}
final String[] parts = COLON_PATTERN.split(name);
final Material material;
byte byteData = 0;
switch (parts.length) {
case 2:
try {
byteData = (byte) Integer.parseInt(parts[1]);
} catch (NumberFormatException e) {
break;
}
// fall through
//noinspection fallthrough
case 1:
material = Material.matchMaterial(parts[0]);
if (material == null) break;
return lookupCommodity(material, byteData);
- default:
- break;
}
- return commodity;
+ throw new NoSuchCommodityException("Can't find commodity [" + ChatColor.WHITE + name + ChatColor.RED + ']');
}
public synchronized void addCommodity(final String name, final Material material, final byte byteData) throws CommoditiesMarketException {
final EbeanServer db = getDatabase();
db.beginTransaction();
try {
// Check if commodity already exists
boolean exists = true;
try {
lookupCommodity(name);
} catch (NoSuchCommodityException e) {
exists = false;
}
if (exists) {
throw new CommoditiesMarketException("Commodity already exists.");
} else {
final Commodity item = new Commodity();
item.setName(name);
item.setItemId(material.getId());
item.setByteData(byteData);
item.setInStock(initialItemQty);
db.save(item);
}
db.commitTransaction();
} finally {
db.endTransaction();
}
}
public synchronized void adjustStock(final String name, final long stockChange) throws CommoditiesMarketException {
final EbeanServer db = getDatabase();
db.beginTransaction();
try {
final Commodity item = lookupCommodity(name);
final long stock = item.getInStock() + stockChange;
if (stock < 0) {
throw new CommoditiesMarketException("Stock level cannot be reduced past zero.");
}
item.setInStock(stock);
db.update(item, adjStkUpdateProps);
db.commitTransaction();
} finally {
db.endTransaction();
}
}
private static final Set<String> pcsUpdateProps;
private static final Set<String> adjStkUpdateProps;
static {
pcsUpdateProps = new HashSet<String>();
pcsUpdateProps.add("numBought");
pcsUpdateProps.add("numSold");
pcsUpdateProps.add("moneySpent");
pcsUpdateProps.add("moneyGained");
adjStkUpdateProps = new HashSet<String>();
adjStkUpdateProps.add("inStock");
}
private PlayerCommodityStats lookupPlayerCommodityStats(final String playerName, final int commodityId) {
return getDatabase().find(PlayerCommodityStats.class).where()
.ieq("playerName", playerName)
.eq("commodityId", commodityId)
.findUnique();
}
public synchronized void recordPlayerCommodityStats(
final Player player,
final Commodity item,
final long numBought,
final long numSold,
final double moneySpent,
final double moneyGained) {
final EbeanServer db = getDatabase();
db.beginTransaction();
try {
final PlayerCommodityStats existing = lookupPlayerCommodityStats(player.getName(), item.getId());
if (existing != null) {
existing.update(numBought, numSold, moneySpent, moneyGained);
db.update(existing, pcsUpdateProps);
} else {
final PlayerCommodityStats stats = new PlayerCommodityStats(
player.getName(), item.getId(),
numBought, numSold, moneySpent, moneyGained);
db.save(stats);
}
db.commitTransaction();
} finally {
db.endTransaction();
}
}
}
| false | true | private synchronized Commodity lookupCommodity(final String name) throws NoSuchCommodityException {
// Accept "names" in several forms:
// Material:byte and associated forms like in ScrapBukkit's /give
// Commodity name from database
final Commodity commodity = getDatabase()
.find(Commodity.class)
.where().ieq("name", name)
.findUnique();
if (commodity != null) {
return commodity;
}
final String[] parts = COLON_PATTERN.split(name);
final Material material;
byte byteData = 0;
switch (parts.length) {
case 2:
try {
byteData = (byte) Integer.parseInt(parts[1]);
} catch (NumberFormatException e) {
break;
}
// fall through
//noinspection fallthrough
case 1:
material = Material.matchMaterial(parts[0]);
if (material == null) break;
return lookupCommodity(material, byteData);
default:
break;
}
return commodity;
}
| private synchronized Commodity lookupCommodity(final String name) throws NoSuchCommodityException {
// Accept "names" in several forms:
// Material:byte and associated forms like in ScrapBukkit's /give
// Commodity name from database
final Commodity commodity = getDatabase()
.find(Commodity.class)
.where().ieq("name", name)
.findUnique();
if (commodity != null) {
return commodity;
}
final String[] parts = COLON_PATTERN.split(name);
final Material material;
byte byteData = 0;
switch (parts.length) {
case 2:
try {
byteData = (byte) Integer.parseInt(parts[1]);
} catch (NumberFormatException e) {
break;
}
// fall through
//noinspection fallthrough
case 1:
material = Material.matchMaterial(parts[0]);
if (material == null) break;
return lookupCommodity(material, byteData);
}
throw new NoSuchCommodityException("Can't find commodity [" + ChatColor.WHITE + name + ChatColor.RED + ']');
}
|
diff --git a/activemq-broker/src/main/java/org/apache/activemq/broker/region/DestinationFilter.java b/activemq-broker/src/main/java/org/apache/activemq/broker/region/DestinationFilter.java
index a7613ef2d..ecf6cf75d 100644
--- a/activemq-broker/src/main/java/org/apache/activemq/broker/region/DestinationFilter.java
+++ b/activemq-broker/src/main/java/org/apache/activemq/broker/region/DestinationFilter.java
@@ -1,401 +1,400 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.region;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.broker.region.policy.DeadLetterStrategy;
import org.apache.activemq.broker.region.policy.SlowConsumerStrategy;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.MessageDispatchNotification;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.store.MessageStore;
import org.apache.activemq.usage.MemoryUsage;
import org.apache.activemq.usage.Usage;
import org.apache.activemq.util.SubscriptionKey;
/**
*
*
*/
public class DestinationFilter implements Destination {
protected final Destination next;
public DestinationFilter(Destination next) {
this.next = next;
}
@Override
public void acknowledge(ConnectionContext context, Subscription sub, MessageAck ack, MessageReference node) throws IOException {
next.acknowledge(context, sub, ack, node);
}
@Override
public void addSubscription(ConnectionContext context, Subscription sub) throws Exception {
next.addSubscription(context, sub);
}
@Override
public Message[] browse() {
return next.browse();
}
@Override
public void dispose(ConnectionContext context) throws IOException {
next.dispose(context);
}
@Override
public boolean isDisposed() {
return next.isDisposed();
}
@Override
public void gc() {
next.gc();
}
@Override
public void markForGC(long timeStamp) {
next.markForGC(timeStamp);
}
@Override
public boolean canGC() {
return next.canGC();
}
@Override
public long getInactiveTimoutBeforeGC() {
return next.getInactiveTimoutBeforeGC();
}
@Override
public ActiveMQDestination getActiveMQDestination() {
return next.getActiveMQDestination();
}
@Override
public DeadLetterStrategy getDeadLetterStrategy() {
return next.getDeadLetterStrategy();
}
@Override
public DestinationStatistics getDestinationStatistics() {
return next.getDestinationStatistics();
}
@Override
public String getName() {
return next.getName();
}
@Override
public MemoryUsage getMemoryUsage() {
return next.getMemoryUsage();
}
@Override
public void setMemoryUsage(MemoryUsage memoryUsage) {
next.setMemoryUsage(memoryUsage);
}
@Override
public void removeSubscription(ConnectionContext context, Subscription sub, long lastDeliveredSequenceId) throws Exception {
next.removeSubscription(context, sub, lastDeliveredSequenceId);
}
@Override
public void send(ProducerBrokerExchange context, Message messageSend) throws Exception {
next.send(context, messageSend);
}
@Override
public void start() throws Exception {
next.start();
}
@Override
public void stop() throws Exception {
next.stop();
}
@Override
public List<Subscription> getConsumers() {
return next.getConsumers();
}
/**
* Sends a message to the given destination which may be a wildcard
*
* @param context broker context
* @param message message to send
* @param destination possibly wildcard destination to send the message to
* @throws Exception on error
*/
protected void send(ProducerBrokerExchange context, Message message, ActiveMQDestination destination) throws Exception {
Broker broker = context.getConnectionContext().getBroker();
Set<Destination> destinations = broker.getDestinations(destination);
for (Destination dest : destinations) {
dest.send(context, message.copy());
}
}
@Override
public MessageStore getMessageStore() {
return next.getMessageStore();
}
@Override
public boolean isProducerFlowControl() {
return next.isProducerFlowControl();
}
@Override
public void setProducerFlowControl(boolean value) {
next.setProducerFlowControl(value);
}
@Override
public boolean isAlwaysRetroactive() {
return next.isAlwaysRetroactive();
}
@Override
public void setAlwaysRetroactive(boolean value) {
next.setAlwaysRetroactive(value);
}
@Override
public void setBlockedProducerWarningInterval(long blockedProducerWarningInterval) {
next.setBlockedProducerWarningInterval(blockedProducerWarningInterval);
}
@Override
public long getBlockedProducerWarningInterval() {
return next.getBlockedProducerWarningInterval();
}
@Override
public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
next.addProducer(context, info);
}
@Override
public void removeProducer(ConnectionContext context, ProducerInfo info) throws Exception {
next.removeProducer(context, info);
}
@Override
public int getMaxAuditDepth() {
return next.getMaxAuditDepth();
}
@Override
public int getMaxProducersToAudit() {
return next.getMaxProducersToAudit();
}
@Override
public boolean isEnableAudit() {
return next.isEnableAudit();
}
@Override
public void setEnableAudit(boolean enableAudit) {
next.setEnableAudit(enableAudit);
}
@Override
public void setMaxAuditDepth(int maxAuditDepth) {
next.setMaxAuditDepth(maxAuditDepth);
}
@Override
public void setMaxProducersToAudit(int maxProducersToAudit) {
next.setMaxProducersToAudit(maxProducersToAudit);
}
@Override
public boolean isActive() {
return next.isActive();
}
@Override
public int getMaxPageSize() {
return next.getMaxPageSize();
}
@Override
public void setMaxPageSize(int maxPageSize) {
next.setMaxPageSize(maxPageSize);
}
@Override
public boolean isUseCache() {
return next.isUseCache();
}
@Override
public void setUseCache(boolean useCache) {
next.setUseCache(useCache);
}
@Override
public int getMinimumMessageSize() {
return next.getMinimumMessageSize();
}
@Override
public void setMinimumMessageSize(int minimumMessageSize) {
next.setMinimumMessageSize(minimumMessageSize);
}
@Override
public void wakeup() {
next.wakeup();
}
@Override
public boolean isLazyDispatch() {
return next.isLazyDispatch();
}
@Override
public void setLazyDispatch(boolean value) {
next.setLazyDispatch(value);
}
public void messageExpired(ConnectionContext context, PrefetchSubscription prefetchSubscription, MessageReference node) {
next.messageExpired(context, prefetchSubscription, node);
}
@Override
public boolean iterate() {
return next.iterate();
}
@Override
public void fastProducer(ConnectionContext context, ProducerInfo producerInfo) {
next.fastProducer(context, producerInfo);
}
@Override
public void isFull(ConnectionContext context, Usage<?> usage) {
next.isFull(context, usage);
}
@Override
public void messageConsumed(ConnectionContext context, MessageReference messageReference) {
next.messageConsumed(context, messageReference);
}
@Override
public void messageDelivered(ConnectionContext context, MessageReference messageReference) {
next.messageDelivered(context, messageReference);
}
@Override
public void messageDiscarded(ConnectionContext context, Subscription sub, MessageReference messageReference) {
next.messageDiscarded(context, sub, messageReference);
}
@Override
public void slowConsumer(ConnectionContext context, Subscription subs) {
next.slowConsumer(context, subs);
}
@Override
public void messageExpired(ConnectionContext context, Subscription subs, MessageReference node) {
next.messageExpired(context, subs, node);
}
@Override
public int getMaxBrowsePageSize() {
return next.getMaxBrowsePageSize();
}
@Override
public void setMaxBrowsePageSize(int maxPageSize) {
next.setMaxBrowsePageSize(maxPageSize);
}
@Override
public void processDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception {
next.processDispatchNotification(messageDispatchNotification);
}
@Override
public int getCursorMemoryHighWaterMark() {
return next.getCursorMemoryHighWaterMark();
}
@Override
public void setCursorMemoryHighWaterMark(int cursorMemoryHighWaterMark) {
next.setCursorMemoryHighWaterMark(cursorMemoryHighWaterMark);
}
@Override
public boolean isPrioritizedMessages() {
return next.isPrioritizedMessages();
}
@Override
public SlowConsumerStrategy getSlowConsumerStrategy() {
return next.getSlowConsumerStrategy();
}
@Override
public boolean isDoOptimzeMessageStorage() {
return next.isDoOptimzeMessageStorage();
}
@Override
public void setDoOptimzeMessageStorage(boolean doOptimzeMessageStorage) {
next.setDoOptimzeMessageStorage(doOptimzeMessageStorage);
}
@Override
public void clearPendingMessages() {
next.clearPendingMessages();
}
@Override
public boolean isDLQ() {
return next.isDLQ();
}
public void deleteSubscription(ConnectionContext context, SubscriptionKey key) throws Exception {
- Destination target = next;
- while (target instanceof DestinationFilter) {
- target = ((DestinationFilter) target).next;
- }
- if (target instanceof Topic) {
- Topic topic = (Topic)target;
+ if (next instanceof DestinationFilter) {
+ DestinationFilter filter = (DestinationFilter) next;
+ filter.deleteSubscription(context, key);
+ } else if (next instanceof Topic) {
+ Topic topic = (Topic)next;
topic.deleteSubscription(context, key);
}
}
}
| true | true | public void deleteSubscription(ConnectionContext context, SubscriptionKey key) throws Exception {
Destination target = next;
while (target instanceof DestinationFilter) {
target = ((DestinationFilter) target).next;
}
if (target instanceof Topic) {
Topic topic = (Topic)target;
topic.deleteSubscription(context, key);
}
}
| public void deleteSubscription(ConnectionContext context, SubscriptionKey key) throws Exception {
if (next instanceof DestinationFilter) {
DestinationFilter filter = (DestinationFilter) next;
filter.deleteSubscription(context, key);
} else if (next instanceof Topic) {
Topic topic = (Topic)next;
topic.deleteSubscription(context, key);
}
}
|
diff --git a/trunk/mafiabot/src/com/googlecode/prmf/starter/MafiaListener.java b/trunk/mafiabot/src/com/googlecode/prmf/starter/MafiaListener.java
index 7a8c6d0..f43f503 100644
--- a/trunk/mafiabot/src/com/googlecode/prmf/starter/MafiaListener.java
+++ b/trunk/mafiabot/src/com/googlecode/prmf/starter/MafiaListener.java
@@ -1,159 +1,159 @@
package com.googlecode.prmf.starter;
import java.io.File;
import java.util.Scanner;
import com.googlecode.prmf.Game;
import com.googlecode.prmf.Player;
public class MafiaListener implements Listener {
private Game game;
private String botName;
public MafiaListener(String botName) {
super();
this.botName = botName;
}
//TODO: need to clean this massive pile of if/else up
public void receiveLine(String in, IOThread inputThread)
{
String[] msg = in.split(" ",4);
String user = "";
if(msg[0].indexOf("!") > 1)
user = msg[0].substring(1,msg[0].indexOf("!"));
- if(msg.length >=2 && (msg[1].startsWith("KICK") || msg[1].startsWith("PART") || msg[1].startsWith("QUIT") ))
+ if(msg.length >=2 && game != null && (msg[1].startsWith("KICK") || msg[1].startsWith("PART") || msg[1].startsWith("QUIT") ))
{
game.receiveMessage(in);
return;
}
else if(msg.length >=2 && msg[1].startsWith("NICK"))
{
game.receiveMessage(in);
return;
}
if (msg.length >= 2 && !msg[1].equals("PRIVMSG"))
return;
if (msg.length >= 4 && msg[2].equals(botName) && msg[3].startsWith(":~"))
game.receiveMessage(in);
if(msg.length >= 4)
msg[3] = msg[3].toLowerCase();
if(msg.length >= 4 && msg[3].equalsIgnoreCase(":~mafia") && (game == null || game.getPostgame() != null))
{
game = new Game(user, inputThread);
inputThread.sendMessage(inputThread.getChannel(), "Mafia game started by " + user + "!");
game.receiveMessage(":" + user + "! PRIVMSG " + inputThread.getChannel() + " :~join"); // TODO H4X is bad
}
else if(msg.length >= 4 && msg[3].equals(":~stats") && game != null)
{
game.getState().status();
}
else if(msg.length >= 4 && msg[3].equals(":~join") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].equals(":~end") && game != null)
{
if(user.equals(game.getGameStarter()))
{
inputThread.sendMessage(inputThread.getChannel(), "Mafia game ended!");
game.stopTimer();
game = null;
}
else
inputThread.sendMessage(inputThread.getChannel(), "The game can only be ended by " + game.getGameStarter());
}
else if(msg.length >= 4 && msg[3].equals(":~quit") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].equals(":~start") && game != null)
{
if(game.getPlayerList().length < 3)
{
inputThread.sendMessage(inputThread.getChannel(), "Game should have at least 3 people!");
}
else
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~lynch") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~nolynch") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~unvote") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~help"))
{
inputThread.sendMessage(inputThread.getChannel(), "MafiaBot has the following commands: mafia, join, quit, start, lynch, nolynch, unvote, stats, help");
}
else if(msg.length >= 4 && msg[3].equalsIgnoreCase(":~save"))
{
inputThread.sendMessage(inputThread.getChannel(), "~save not implemented yet");
}
else if(msg.length >= 4 && msg[3].startsWith(":~load") && game != null)
{
Scanner prof = null;
try{
prof = new Scanner(new File("profiles.txt"));
if(msg[3].equalsIgnoreCase(":~load"))
{
//int profileNum = 1;
StringBuilder currProfile = new StringBuilder();
currProfile.append("List of saved profiles: ");
while(prof.hasNextLine())
{
String profileLine = prof.nextLine();
String profMsg[] = profileLine.split(" ",3);
//String roleMsg[] = profMsg[2].split(",");
currProfile.append(" "+ profMsg[1]);
/**
for(int i=0;i<roleMsg.length;++i)
{
currProfile.append(" "+roleMsg[i].trim());
}
**/
}
inputThread.sendMessage(user, currProfile.toString());
}
else
{
while(prof.hasNextLine())
{
String profileLine = prof.nextLine();
String profMsg[] = profileLine.split(" ",3);
String roleMsg[] = profMsg[2].split(",");
for(int i=0;i<roleMsg.length;++i)
roleMsg[i] = roleMsg[i].trim();
String[] msgLoad = msg[3].split(" ",2);
String ProfDesired = msgLoad[1];
if(ProfDesired.equalsIgnoreCase(profMsg[1]))
{
game.getPregame().loadRoleProfile(roleMsg);
break;
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
inputThread.sendMessage(inputThread.getChannel(), "profiles.txt file not found");
}
}
}
public void timerMessage()
{
game.stopTimer();
}
}
| true | true | public void receiveLine(String in, IOThread inputThread)
{
String[] msg = in.split(" ",4);
String user = "";
if(msg[0].indexOf("!") > 1)
user = msg[0].substring(1,msg[0].indexOf("!"));
if(msg.length >=2 && (msg[1].startsWith("KICK") || msg[1].startsWith("PART") || msg[1].startsWith("QUIT") ))
{
game.receiveMessage(in);
return;
}
else if(msg.length >=2 && msg[1].startsWith("NICK"))
{
game.receiveMessage(in);
return;
}
if (msg.length >= 2 && !msg[1].equals("PRIVMSG"))
return;
if (msg.length >= 4 && msg[2].equals(botName) && msg[3].startsWith(":~"))
game.receiveMessage(in);
if(msg.length >= 4)
msg[3] = msg[3].toLowerCase();
if(msg.length >= 4 && msg[3].equalsIgnoreCase(":~mafia") && (game == null || game.getPostgame() != null))
{
game = new Game(user, inputThread);
inputThread.sendMessage(inputThread.getChannel(), "Mafia game started by " + user + "!");
game.receiveMessage(":" + user + "! PRIVMSG " + inputThread.getChannel() + " :~join"); // TODO H4X is bad
}
else if(msg.length >= 4 && msg[3].equals(":~stats") && game != null)
{
game.getState().status();
}
else if(msg.length >= 4 && msg[3].equals(":~join") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].equals(":~end") && game != null)
{
if(user.equals(game.getGameStarter()))
{
inputThread.sendMessage(inputThread.getChannel(), "Mafia game ended!");
game.stopTimer();
game = null;
}
else
inputThread.sendMessage(inputThread.getChannel(), "The game can only be ended by " + game.getGameStarter());
}
else if(msg.length >= 4 && msg[3].equals(":~quit") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].equals(":~start") && game != null)
{
if(game.getPlayerList().length < 3)
{
inputThread.sendMessage(inputThread.getChannel(), "Game should have at least 3 people!");
}
else
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~lynch") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~nolynch") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~unvote") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~help"))
{
inputThread.sendMessage(inputThread.getChannel(), "MafiaBot has the following commands: mafia, join, quit, start, lynch, nolynch, unvote, stats, help");
}
else if(msg.length >= 4 && msg[3].equalsIgnoreCase(":~save"))
{
inputThread.sendMessage(inputThread.getChannel(), "~save not implemented yet");
}
else if(msg.length >= 4 && msg[3].startsWith(":~load") && game != null)
{
Scanner prof = null;
try{
prof = new Scanner(new File("profiles.txt"));
if(msg[3].equalsIgnoreCase(":~load"))
{
//int profileNum = 1;
StringBuilder currProfile = new StringBuilder();
currProfile.append("List of saved profiles: ");
while(prof.hasNextLine())
{
String profileLine = prof.nextLine();
String profMsg[] = profileLine.split(" ",3);
//String roleMsg[] = profMsg[2].split(",");
currProfile.append(" "+ profMsg[1]);
/**
for(int i=0;i<roleMsg.length;++i)
{
currProfile.append(" "+roleMsg[i].trim());
}
**/
}
inputThread.sendMessage(user, currProfile.toString());
}
else
{
while(prof.hasNextLine())
{
String profileLine = prof.nextLine();
String profMsg[] = profileLine.split(" ",3);
String roleMsg[] = profMsg[2].split(",");
for(int i=0;i<roleMsg.length;++i)
roleMsg[i] = roleMsg[i].trim();
String[] msgLoad = msg[3].split(" ",2);
String ProfDesired = msgLoad[1];
if(ProfDesired.equalsIgnoreCase(profMsg[1]))
{
game.getPregame().loadRoleProfile(roleMsg);
break;
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
inputThread.sendMessage(inputThread.getChannel(), "profiles.txt file not found");
}
}
}
| public void receiveLine(String in, IOThread inputThread)
{
String[] msg = in.split(" ",4);
String user = "";
if(msg[0].indexOf("!") > 1)
user = msg[0].substring(1,msg[0].indexOf("!"));
if(msg.length >=2 && game != null && (msg[1].startsWith("KICK") || msg[1].startsWith("PART") || msg[1].startsWith("QUIT") ))
{
game.receiveMessage(in);
return;
}
else if(msg.length >=2 && msg[1].startsWith("NICK"))
{
game.receiveMessage(in);
return;
}
if (msg.length >= 2 && !msg[1].equals("PRIVMSG"))
return;
if (msg.length >= 4 && msg[2].equals(botName) && msg[3].startsWith(":~"))
game.receiveMessage(in);
if(msg.length >= 4)
msg[3] = msg[3].toLowerCase();
if(msg.length >= 4 && msg[3].equalsIgnoreCase(":~mafia") && (game == null || game.getPostgame() != null))
{
game = new Game(user, inputThread);
inputThread.sendMessage(inputThread.getChannel(), "Mafia game started by " + user + "!");
game.receiveMessage(":" + user + "! PRIVMSG " + inputThread.getChannel() + " :~join"); // TODO H4X is bad
}
else if(msg.length >= 4 && msg[3].equals(":~stats") && game != null)
{
game.getState().status();
}
else if(msg.length >= 4 && msg[3].equals(":~join") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].equals(":~end") && game != null)
{
if(user.equals(game.getGameStarter()))
{
inputThread.sendMessage(inputThread.getChannel(), "Mafia game ended!");
game.stopTimer();
game = null;
}
else
inputThread.sendMessage(inputThread.getChannel(), "The game can only be ended by " + game.getGameStarter());
}
else if(msg.length >= 4 && msg[3].equals(":~quit") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].equals(":~start") && game != null)
{
if(game.getPlayerList().length < 3)
{
inputThread.sendMessage(inputThread.getChannel(), "Game should have at least 3 people!");
}
else
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~lynch") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~nolynch") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~unvote") && game != null)
{
game.receiveMessage(in);
}
else if(msg.length >= 4 && msg[3].startsWith(":~help"))
{
inputThread.sendMessage(inputThread.getChannel(), "MafiaBot has the following commands: mafia, join, quit, start, lynch, nolynch, unvote, stats, help");
}
else if(msg.length >= 4 && msg[3].equalsIgnoreCase(":~save"))
{
inputThread.sendMessage(inputThread.getChannel(), "~save not implemented yet");
}
else if(msg.length >= 4 && msg[3].startsWith(":~load") && game != null)
{
Scanner prof = null;
try{
prof = new Scanner(new File("profiles.txt"));
if(msg[3].equalsIgnoreCase(":~load"))
{
//int profileNum = 1;
StringBuilder currProfile = new StringBuilder();
currProfile.append("List of saved profiles: ");
while(prof.hasNextLine())
{
String profileLine = prof.nextLine();
String profMsg[] = profileLine.split(" ",3);
//String roleMsg[] = profMsg[2].split(",");
currProfile.append(" "+ profMsg[1]);
/**
for(int i=0;i<roleMsg.length;++i)
{
currProfile.append(" "+roleMsg[i].trim());
}
**/
}
inputThread.sendMessage(user, currProfile.toString());
}
else
{
while(prof.hasNextLine())
{
String profileLine = prof.nextLine();
String profMsg[] = profileLine.split(" ",3);
String roleMsg[] = profMsg[2].split(",");
for(int i=0;i<roleMsg.length;++i)
roleMsg[i] = roleMsg[i].trim();
String[] msgLoad = msg[3].split(" ",2);
String ProfDesired = msgLoad[1];
if(ProfDesired.equalsIgnoreCase(profMsg[1]))
{
game.getPregame().loadRoleProfile(roleMsg);
break;
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
inputThread.sendMessage(inputThread.getChannel(), "profiles.txt file not found");
}
}
}
|
diff --git a/src/plugins/XMLLibrarian/Progress.java b/src/plugins/XMLLibrarian/Progress.java
index 3f17b57..00a55b3 100644
--- a/src/plugins/XMLLibrarian/Progress.java
+++ b/src/plugins/XMLLibrarian/Progress.java
@@ -1,122 +1,124 @@
package plugins.XMLLibrarian;
import freenet.client.events.ClientEventListener;
import freenet.client.events.ClientEvent;
import freenet.client.async.ClientContext;
import freenet.node.RequestClient;
import com.db4o.ObjectContainer;
import freenet.client.HighLevelSimpleClient;
import freenet.client.FetchContext;
import freenet.support.MultiValueTable;
import freenet.node.RequestStarter;
import freenet.pluginmanager.PluginRespirator;
/**
* Stores and provides access to status of searches
* @author MikeB
*/
public class Progress implements ClientEventListener
{
private final String search;
private final String index;
private HighLevelSimpleClient hlsc;
private boolean retrieved;
private boolean complete;
private String msg;
private String result;
private String eventDescription;
public Progress(String search, String indexuri, String initialmsg, PluginRespirator pr){
this.search = search;
retrieved = false;
complete = false;
msg = initialmsg;
index = indexuri;
hlsc = pr.getNode().clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS);
hlsc.addEventHook(this);
}
public HighLevelSimpleClient getHLSC(){
return hlsc;
}
public void set(String _msg){
msg = _msg;
retrieved = false;
}
public void done(String msg){
done(msg, null);
}
public void done(String msg, String result){
retrieved = false;
complete = true;
this.msg = msg;
this.result = (result==null) ? "" : result;
}
public boolean isdone(){
return complete;
}
// TODO better status format
public String get(String format){
// probably best to do this with a lock
// look for a progress update
while(retrieved && !complete) // whilst theres no new msg
try{
Thread.sleep(500);
}catch(java.lang.InterruptedException e){
}
retrieved = true;
+ String ed = eventDescription;
+ if(ed == null) ed = "";
if(format.equals("html")){
if(complete){
- return "<html><body>"+msg+" - <a href=\"/plugins/plugins.XMLLibrarian.XMLLibrarian?search="+search+"&index="+index+"\" target=\"_parent\">Click to reload & view results</a><br />"+eventDescription+"</body></html>";
+ return "<html><body>"+msg+" - <a href=\"/plugins/plugins.XMLLibrarian.XMLLibrarian?search="+search+"&index="+index+"\" target=\"_parent\">Click to reload & view results</a><br />"+ed+"</body></html>";
}else
- return "<html><head><meta http-equiv=\"refresh\" content=\"1\" /></head><body>"+msg+"<br />"+eventDescription+"</body></html>";
+ return "<html><head><meta http-equiv=\"refresh\" content=\"1\" /></head><body>"+msg+"<br />"+ed+"</body></html>";
}else if(format.equals("coded")){
if(complete)
- return msg+"<br />"+eventDescription;
+ return msg+"<br />"+ed;
else
- return "."+msg+"<br />"+eventDescription;
+ return "."+msg+"<br />"+ed;
}else
- return msg+"<br />"+eventDescription;
+ return msg+"<br />"+ed;
}
public String getresult(){
while(!complete) // whilst theres no results
try{
Thread.sleep(500);
}catch(java.lang.InterruptedException e){
}
return result;
}
/**
* Hears an event.
* @param container The database context the event was generated in.
* NOTE THAT IT MAY NOT HAVE BEEN GENERATED IN A DATABASE CONTEXT AT ALL:
* In this case, container will be null, and you should use context to schedule a DBJob.
**/
public void receive(ClientEvent ce, ObjectContainer maybeContainer, ClientContext context){
if(eventDescription != ce.getDescription()){
eventDescription = ce.getDescription();
retrieved = false;
}
}
/**
* Called when the EventProducer gets removeFrom(ObjectContainer).
* If the listener is the main listener which probably called removeFrom(), it should do nothing.
* If it's a tag-along but request specific listener, it may need to remove itself.
*/
public void onRemoveEventProducer(ObjectContainer container){
}
}
| false | true | public String get(String format){
// probably best to do this with a lock
// look for a progress update
while(retrieved && !complete) // whilst theres no new msg
try{
Thread.sleep(500);
}catch(java.lang.InterruptedException e){
}
retrieved = true;
if(format.equals("html")){
if(complete){
return "<html><body>"+msg+" - <a href=\"/plugins/plugins.XMLLibrarian.XMLLibrarian?search="+search+"&index="+index+"\" target=\"_parent\">Click to reload & view results</a><br />"+eventDescription+"</body></html>";
}else
return "<html><head><meta http-equiv=\"refresh\" content=\"1\" /></head><body>"+msg+"<br />"+eventDescription+"</body></html>";
}else if(format.equals("coded")){
if(complete)
return msg+"<br />"+eventDescription;
else
return "."+msg+"<br />"+eventDescription;
}else
return msg+"<br />"+eventDescription;
}
| public String get(String format){
// probably best to do this with a lock
// look for a progress update
while(retrieved && !complete) // whilst theres no new msg
try{
Thread.sleep(500);
}catch(java.lang.InterruptedException e){
}
retrieved = true;
String ed = eventDescription;
if(ed == null) ed = "";
if(format.equals("html")){
if(complete){
return "<html><body>"+msg+" - <a href=\"/plugins/plugins.XMLLibrarian.XMLLibrarian?search="+search+"&index="+index+"\" target=\"_parent\">Click to reload & view results</a><br />"+ed+"</body></html>";
}else
return "<html><head><meta http-equiv=\"refresh\" content=\"1\" /></head><body>"+msg+"<br />"+ed+"</body></html>";
}else if(format.equals("coded")){
if(complete)
return msg+"<br />"+ed;
else
return "."+msg+"<br />"+ed;
}else
return msg+"<br />"+ed;
}
|
diff --git a/Client2D/src/com/pi/client/net/NetClientHandler.java b/Client2D/src/com/pi/client/net/NetClientHandler.java
index 36ae083..e27e609 100644
--- a/Client2D/src/com/pi/client/net/NetClientHandler.java
+++ b/Client2D/src/com/pi/client/net/NetClientHandler.java
@@ -1,123 +1,122 @@
package com.pi.client.net;
import javax.swing.JOptionPane;
import com.pi.client.Client;
import com.pi.client.entity.ClientEntity;
import com.pi.common.database.Location;
import com.pi.common.database.SectorLocation;
import com.pi.common.debug.PILogger;
import com.pi.common.game.Entity;
import com.pi.common.net.NetHandler;
import com.pi.common.net.packet.Packet;
import com.pi.common.net.packet.Packet0Disconnect;
import com.pi.common.net.packet.Packet10EntityDataRequest;
import com.pi.common.net.packet.Packet11LocalEntityID;
import com.pi.common.net.packet.Packet13EntityDef;
import com.pi.common.net.packet.Packet15GameState;
import com.pi.common.net.packet.Packet16EntityMove;
import com.pi.common.net.packet.Packet2Alert;
import com.pi.common.net.packet.Packet4Sector;
import com.pi.common.net.packet.Packet6BlankSector;
import com.pi.common.net.packet.Packet7EntityTeleport;
import com.pi.common.net.packet.Packet8EntityDispose;
import com.pi.common.net.packet.Packet9EntityData;
public class NetClientHandler extends NetHandler {
private final NetClient netClient;
private final Client client;
public NetClientHandler(NetClient netClient, Client client) {
this.client = client;
this.netClient = netClient;
}
@Override
protected PILogger getLog() {
return client.getLog();
}
@Override
public void process(Packet p) {
}
public void process(Packet0Disconnect p) {
JOptionPane.showMessageDialog(null, ((Packet0Disconnect) p).reason
+ "\n" + ((Packet0Disconnect) p).details);
netClient.dispose();
}
public void process(Packet2Alert p) {
client.getDisplayManager().getRenderLoop().alert(p.message);
}
public void process(Packet4Sector p) {
client.getWorld().getSectorManager().setSector(p.sector);
}
public void process(Packet6BlankSector p) {
client.getWorld()
.getSectorManager()
.flagSectorAsBlack(
new SectorLocation(p.baseX, p.baseY, p.baseZ));
}
public void process(Packet7EntityTeleport p) {
Entity ent = client.getEntityManager().getEntity(p.entityID);
if (ent == null) {
ent = new Entity();
ent.setEntityID(p.entityID);
client.getEntityManager().saveEntity(ent);
client.getNetwork().send(
Packet10EntityDataRequest.create(p.entityID));
}
ent.setLocation(p.moved);
ent.setLayer(p.entityLayer);
}
public void process(Packet16EntityMove p) {
ClientEntity ent = client.getEntityManager().getEntity(p.entity);
if (ent == null) {
ent = new ClientEntity();
ent.setEntityID(p.entity);
client.getEntityManager().saveEntity(ent);
client.getNetwork()
.send(Packet10EntityDataRequest.create(p.entity));
}
Location l = p.apply(ent);
ent.teleportShort(l);
- if (ent != client.getEntityManager().getLocalEntity()
- || !ent.isMoving())
+ if (ent != client.getEntityManager().getLocalEntity())
ent.forceStartMoveLoop();
}
public void process(Packet8EntityDispose p) {
client.getEntityManager().deRegisterEntity(p.entityID);
}
public void process(Packet9EntityData p) {
Entity ent = client.getEntityManager().getEntity(p.entID);
if (ent == null) {
ent = new Entity();
client.getLog().info("setid:" + ent.setEntityID(p.entID));
}
ent.setEntityDef(p.defID);
ent.setLocation(p.loc);
ent.setLayer(p.layer);
client.getEntityManager().saveEntity(ent);
}
public void process(Packet11LocalEntityID p) {
client.getLog().info("LocalID: " + p.entityID);
client.getEntityManager().setLocalEntityID(p.entityID);
}
public void process(Packet13EntityDef p) {
client.getDefs().getEntityLoader().setDef(p.entityID, p.def);
}
public void process(Packet15GameState p) {
if (p.state != null)
client.setGameState(p.state);
}
}
| true | true | public void process(Packet16EntityMove p) {
ClientEntity ent = client.getEntityManager().getEntity(p.entity);
if (ent == null) {
ent = new ClientEntity();
ent.setEntityID(p.entity);
client.getEntityManager().saveEntity(ent);
client.getNetwork()
.send(Packet10EntityDataRequest.create(p.entity));
}
Location l = p.apply(ent);
ent.teleportShort(l);
if (ent != client.getEntityManager().getLocalEntity()
|| !ent.isMoving())
ent.forceStartMoveLoop();
}
| public void process(Packet16EntityMove p) {
ClientEntity ent = client.getEntityManager().getEntity(p.entity);
if (ent == null) {
ent = new ClientEntity();
ent.setEntityID(p.entity);
client.getEntityManager().saveEntity(ent);
client.getNetwork()
.send(Packet10EntityDataRequest.create(p.entity));
}
Location l = p.apply(ent);
ent.teleportShort(l);
if (ent != client.getEntityManager().getLocalEntity())
ent.forceStartMoveLoop();
}
|
diff --git a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/extensionpoint/LocalStorageService.java b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/extensionpoint/LocalStorageService.java
index 58e81fd..5b20f0f 100644
--- a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/extensionpoint/LocalStorageService.java
+++ b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/extensionpoint/LocalStorageService.java
@@ -1,789 +1,796 @@
package com.uwusoft.timesheet.extensionpoint;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.commands.common.EventManager;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.ui.PlatformUI;
import com.uwusoft.timesheet.Activator;
import com.uwusoft.timesheet.SystemShutdownTimeCaptureService;
import com.uwusoft.timesheet.TimesheetApp;
import com.uwusoft.timesheet.extensionpoint.model.DailySubmissionEntry;
import com.uwusoft.timesheet.extensionpoint.model.SubmissionEntry;
import com.uwusoft.timesheet.model.AllDayTasks;
import com.uwusoft.timesheet.model.Project;
import com.uwusoft.timesheet.model.Project_;
import com.uwusoft.timesheet.model.Task;
import com.uwusoft.timesheet.model.TaskEntry;
import com.uwusoft.timesheet.model.TaskEntry_;
import com.uwusoft.timesheet.model.Task_;
import com.uwusoft.timesheet.submission.model.SubmissionProject;
import com.uwusoft.timesheet.submission.model.SubmissionTask;
import com.uwusoft.timesheet.util.BusinessDayUtil;
import com.uwusoft.timesheet.util.ExtensionManager;
import com.uwusoft.timesheet.util.MessageBox;
import com.uwusoft.timesheet.util.StorageSystemSetup;
public class LocalStorageService extends EventManager implements ImportTaskService {
private static final String PERSISTENCE_UNIT_NAME = "timesheet";
public static EntityManagerFactory factory;
private static EntityManager em;
private Map<String,String> submissionSystems;
private Job firstImportJob, syncEntriesJob, syncTasksJob;
private static LocalStorageService instance;
private static StorageService storageService;
private String submissionSystem;
private ILog logger;
private static ISchedulingRule mutex = new Mutex();
private LocalStorageService() {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
String timesheetName = StorageService.TIMESHEET_PREFIX + cal.get(Calendar.YEAR);
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, getConfigOverrides(timesheetName));
em = factory.createEntityManager();
submissionSystems = TimesheetApp.getSubmissionSystems();
logger = Activator.getDefault().getLog();
if (StringUtils.isEmpty(preferenceStore.getString(StorageService.PROPERTY)))
StorageSystemSetup.execute();
final Date lastTaskEntryDate = getLastTaskEntryDate();
final Date importedEndDate = importLastEntryDate(lastTaskEntryDate);
firstImportJob = new Job("Importing entries") {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (getStorageService() == null)
return Status.CANCEL_STATUS;
Calendar cal = GregorianCalendar.getInstance();
cal.set(cal.get(Calendar.YEAR), Calendar.JANUARY, 1);
Date startDate = cal.getTime();
- if (lastTaskEntryDate != null) startDate = lastTaskEntryDate;
+ if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
+ cal.set(cal.get(Calendar.YEAR), Calendar.JANUARY, 2);
+ startDate = cal.getTime();
+ }
+ cal.setFirstDayOfWeek(Calendar.MONDAY);
+ cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
+ if (lastTaskEntryDate != null && getTaskEntries(startDate, cal.getTime()).size() > 0) // if already imported
+ startDate = lastTaskEntryDate;
if (!DateUtils.truncate(startDate, Calendar.DATE).equals(BusinessDayUtil.getNextBusinessDay(new Date(), false))) {
cal.setTime(startDate);
int startWeek = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(new Date());
int endWeek = cal.get(Calendar.WEEK_OF_YEAR);
monitor.beginTask("Import " + (endWeek - startWeek) + " weeks", endWeek - startWeek);
for (int i = startWeek; i <= endWeek; i++) {
logger.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "import task entries for week " + i));
cal.set(Calendar.WEEK_OF_YEAR, i + 1);
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Date endDate = DateUtils.truncate(cal.getTime(), Calendar.DATE);
if (endDate != null && !endDate.before(importedEndDate))
endDate = BusinessDayUtil.getPreviousBusinessDay(importedEndDate);
if (startDate != null && startDate.after(endDate))
startDate = endDate;
List<TaskEntry> entries = storageService.getTaskEntries(startDate, endDate);
for (TaskEntry entry : entries) {
entry.setRowNum(entry.getId());
entry.setSyncStatus(true);
logger.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "import task entry: " + entry));
createOrUpdate(entry);
}
cal.set(Calendar.WEEK_OF_YEAR, i + 2);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
startDate = DateUtils.truncate(cal.getTime(), Calendar.DATE);
monitor.worked(1);
}
monitor.done();
- final int lastWeek = cal.get(Calendar.WEEK_OF_YEAR) - 2;
+ final int lastWeek = cal.get(Calendar.WEEK_OF_YEAR) - 3;
firePropertyChangeEvent(new PropertyChangeEvent(this, PROPERTY_WEEK, null, lastWeek));
}
return Status.OK_STATUS;
}
};
firstImportJob.setRule(mutex);
firstImportJob.schedule();
syncEntriesJob = new Job("Synchronizing entries") {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (getStorageService() == null)
return Status.CANCEL_STATUS;
boolean active = false;
try {
synchronized (em) {
em.getTransaction().begin();
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<TaskEntry> query = criteria.createQuery(TaskEntry.class);
Root<TaskEntry> taskEntry = query.from(TaskEntry.class);
query.where(criteria.notEqual(taskEntry.get(TaskEntry_.syncStatus), true));
query.orderBy(criteria.asc(taskEntry.get(TaskEntry_.dateTime)));
List<TaskEntry> entries = em.createQuery(query).getResultList();
monitor.beginTask("Synchronize " + entries.size() + " entries", entries.size());
Calendar cal = new GregorianCalendar();
cal.setFirstDayOfWeek(Calendar.MONDAY);
TaskEntry lastEntry = getLastTaskEntry();
int startDay = 0;
int startWeek = 0;
int endDay = 0;
int endWeek = 0;
for (TaskEntry entry : entries) {
if (lastEntry.getDateTime() != null) {
cal.setTime(lastEntry.getDateTime());
startDay = cal.get(Calendar.DAY_OF_YEAR);
startWeek = cal.get(Calendar.WEEK_OF_YEAR);
}
if (entry.getDateTime() != null) {
cal.setTime(entry.getDateTime());
endDay = cal.get(Calendar.DAY_OF_YEAR);
endWeek = cal.get(Calendar.WEEK_OF_YEAR);
}
else {
endDay = startDay;
endWeek = startWeek;
}
if (entry.getRowNum() == null) {
if (!lastEntry.isAllDay() && startDay != 0 && startDay < endDay)
storageService.handleDayChange();
if (startWeek != 0 && startWeek < endWeek)
storageService.handleWeekChange();
entry.setRowNum(storageService.createTaskEntry(entry));
calculateTotal(entry);
}
else
storageService.updateTaskEntry(entry);
entry.setSyncStatus(true);
em.persist(entry);
monitor.worked(1);
lastEntry = entry;
}
}
monitor.done();
} catch (CoreException e) {
MessageBox.setError("Remote storage service", e.getMessage());
return Status.CANCEL_STATUS;
}
if (!active) em.getTransaction().commit();
return Status.OK_STATUS;
}
};
syncEntriesJob.setRule(mutex);
syncTasksJob = new Job("Synchronizing tasks") {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (getStorageService() == null)
return Status.CANCEL_STATUS;
synchronized (em) {
em.getTransaction().begin();
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<Task> query = criteria.createQuery(Task.class);
Root<Task> rootTask = query.from(Task.class);
query.where(criteria.notEqual(rootTask.get(Task_.syncStatus), true));
List<Task> tasks = em.createQuery(query).getResultList();
Map<String, SubmissionProject> submissionProjects = new HashMap<String, SubmissionProject>();
for (Task task : tasks) {
SubmissionProject submissionProject = submissionProjects.get(task.getProject().getName());
if (submissionProject == null)
submissionProject = new SubmissionProject(task.getProject().getExternalId(), task.getProject().getName());
submissionProject.addTask(new SubmissionTask(task.getExternalId(), task.getName()));
submissionProjects.put(submissionProject.getName(), submissionProject);
}
if (!submissionProjects.isEmpty()) {
if (storageService.importTasks(submissionSystem, submissionProjects.values()))
for (Task task : tasks) {
task.setSyncStatus(true);
task.getProject().setSyncStatus(true);
em.persist(task);
}
}
em.getTransaction().commit();
}
return Status.OK_STATUS;
}
};
syncTasksJob.setRule(mutex);
}
private Map<String, Object> getConfigOverrides(String timesheetName) {
Map<String, Object> configOverrides = new HashMap<String, Object>();
String dataBasePath;
if (Activator.googleDrive.exists() && Activator.getDefault().getPreferenceStore() instanceof PreferenceStore)
dataBasePath = Activator.timesheetPath + "/Databases/" + timesheetName;
else
dataBasePath = SystemShutdownTimeCaptureService.lckDir + "/databases/" + timesheetName;
configOverrides.put("javax.persistence.jdbc.url", "jdbc:derby:" + dataBasePath + ";create=true");
return configOverrides;
}
private Date importLastEntryDate(final Date lastTaskEntryDate) {
if (lastTaskEntryDate == null) {
synchronized (em) {
em.getTransaction().begin();
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<Task> taskQuery = criteria.createQuery(Task.class);
Root<Task> taskRoot = taskQuery.from(Task.class);
taskQuery.where(criteria.equal(taskRoot.get(Task_.name), CHECK_IN));
List<Task> tasks = em.createQuery(taskQuery).getResultList();
if (tasks.isEmpty()) {
Task task = new Task(CHECK_IN);
task.setSyncStatus(true);
em.persist(task);
}
taskQuery.where(criteria.equal(taskRoot.get(Task_.name), BREAK));
tasks = em.createQuery(taskQuery).getResultList();
if (tasks.isEmpty()) {
Task task = new Task(BREAK);
task.setSyncStatus(true);
em.persist(task);
}
taskQuery.where(criteria.equal(taskRoot.get(Task_.name), AllDayTasks.BEGIN_ADT));
tasks = em.createQuery(taskQuery).getResultList();
if (tasks.isEmpty()) {
Task task = new Task(AllDayTasks.BEGIN_ADT);
task.setSyncStatus(true);
em.persist(task);
}
em.getTransaction().commit();
}
for (String system : submissionSystems.keySet()) {
if (!StringUtils.isEmpty(system) && getProjects(system).isEmpty()) {
if (getStorageService() != null)
importTasks(system, storageService.getImportedProjects(system), true);
}
}
if (getStorageService() != null) {
TaskEntry lastTask = storageService.getLastTask();
if (lastTask != null) {
lastTask.setRowNum(lastTask.getId());
lastTask.setSyncStatus(true);
createTaskEntry(lastTask);
}
Date date = storageService.getLastTaskEntryDate();
if (date != null) {
List<TaskEntry> entries = storageService.getTaskEntries(date, date);
for (TaskEntry entry : entries) {
entry.setRowNum(entry.getId());
entry.setSyncStatus(true);
createTaskEntry(entry);
}
return DateUtils.truncate(date, Calendar.DATE);
}
}
}
else {
if (getStorageService() != null) {
TaskEntry lastTask = storageService.getLastTask();
if (lastTask != null && getLastTask() != null && !lastTask.getId().equals(getLastTask().getRowNum())) {
lastTask.setRowNum(lastTask.getId());
lastTask.setSyncStatus(true);
createTaskEntry(lastTask);
Date date = storageService.getLastTaskEntryDate();
if (date != null && date.after(lastTaskEntryDate)) {
List<TaskEntry> entries = storageService.getTaskEntries(date, date);
synchronized (entries) {
for (TaskEntry entry : entries) {
entry.setRowNum(entry.getId());
entry.setSyncStatus(true);
createOrUpdate(entry);
}
}
}
return DateUtils.truncate(date, Calendar.DATE);
}
}
}
return new Date();
}
public static LocalStorageService getInstance() {
if (instance == null)
instance = new LocalStorageService();
return instance;
}
public List<String> getProjects(String system) {
List<String> projects = new ArrayList<String>();
for (Project project : getProjectList(system)) projects.add(project.getName());
return projects;
}
private List<Project> getProjectList(String system) {
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<Project> query = criteria.createQuery(Project.class);
Root<Project> project = query.from(Project.class);
query.where(criteria.equal(project.get(Project_.system), system));
return em.createQuery(query).getResultList();
}
public Collection<SubmissionProject> getImportedProjects(String system) {
List<SubmissionProject> projects = new ArrayList<SubmissionProject>();
for (Project project : getProjectList(system)) {
SubmissionProject submissionProject = new SubmissionProject(project.getExternalId(), project.getName());
for (Task task : project.getTasks())
submissionProject.addTask(new SubmissionTask(task.getExternalId(), task.getName()));
projects.add(submissionProject);
}
return projects;
}
public List<String> findTasksBySystemAndProject(String system, String project) {
List<Task> taskList = findTasksByProjectAndSystem(project, system);
List<String> tasks = new ArrayList<String>();
for (Task task : taskList) tasks.add(task.getName());
return tasks;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
addListenerObject(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
removeListenerObject(listener);
}
protected void firePropertyChangeEvent(final PropertyChangeEvent event) {
if (event == null) {
throw new NullPointerException();
}
synchronized (getListeners()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (!PlatformUI.getWorkbench().getDisplay().isDisposed())
for (Object listener : getListeners()) {
((PropertyChangeListener) listener).propertyChange(event);
}
}
});
}
}
public List<TaskEntry> getTaskEntries(Date startDate, Date endDate) {
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<TaskEntry> query = criteria.createQuery(TaskEntry.class);
Root<TaskEntry> entry = query.from(TaskEntry.class);
Path<Task> task = entry.get(TaskEntry_.task);
query.where(criteria.and(criteria.notEqual(task.get(Task_.name), AllDayTasks.BEGIN_ADT),
criteria.greaterThanOrEqualTo(entry.get(TaskEntry_.dateTime), new Timestamp(startDate.getTime())),
criteria.lessThanOrEqualTo(entry.get(TaskEntry_.dateTime), new Timestamp(endDate.getTime()))));
query.orderBy(criteria.asc(entry.get(TaskEntry_.dateTime)));
return em.createQuery(query).getResultList();
}
public String[] getUsedCommentsForTask(String task, String project, String system) {
Set<String> comments = new HashSet<String>();
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<TaskEntry> query = criteria.createQuery(TaskEntry.class);
Root<TaskEntry> taskEntry = query.from(TaskEntry.class);
Path<Task> rootTask = taskEntry.get(TaskEntry_.task);
Path<Project> rootProject = rootTask.get(Task_.project);
query.where(criteria.and(criteria.equal(rootTask.get(Task_.name), task),
criteria.equal(rootProject.get(Project_.name), project),
criteria.equal(rootProject.get(Project_.system), system)));
List<TaskEntry> results = em.createQuery(query).getResultList();
for (TaskEntry entry : results)
if (entry.getComment() != null)
comments.add(entry.getComment());
return comments.toArray(new String[comments.size()]);
}
public void createTaskEntry(TaskEntry task) {
createTaskEntry(task, true);
}
private void createTaskEntry(TaskEntry entry, boolean firePropertyChangeEvent) {
boolean active = false;
synchronized (entry) {
if (em.getTransaction().isActive()) active = true;
else em.getTransaction().begin();
entry.setTask(findTaskByNameProjectAndSystem(entry.getTask().getName(),
entry.getTask().getProject() == null ? null : entry.getTask().getProject().getName(),
entry.getTask().getProject() == null ? null : entry.getTask().getProject().getSystem()));
em.persist(entry);
if (!active) em.getTransaction().commit();
}
if (firePropertyChangeEvent) {
Calendar cal = new GregorianCalendar();
cal.setTime(entry.getDateTime() == null ? new Date() : entry.getDateTime());
firePropertyChangeEvent(new PropertyChangeEvent(this, PROPERTY_WEEK, null, cal.get(Calendar.WEEK_OF_YEAR)));
}
}
public void updateTaskEntry(TaskEntry entry) {
boolean active = false;
Calendar cal = new GregorianCalendar();
synchronized (entry) {
if (em.getTransaction().isActive()) active = true;
else em.getTransaction().begin();
entry.setSyncStatus(false);
if (calculateTotal(entry))
cal.setTime(entry.getDateTime());
else cal.setTime(new Date());
em.persist(entry);
if (!active) em.getTransaction().commit();
}
firePropertyChangeEvent(new PropertyChangeEvent(this, PROPERTY_WEEK, null, cal.get(Calendar.WEEK_OF_YEAR)));
}
private boolean calculateTotal(TaskEntry entry) {
if (entry.getDateTime() == null || entry.isAllDay() || CHECK_IN.equals(entry.getTask().getName()) || BREAK.equals(entry.getTask().getName()))
return false;
try {
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<TaskEntry> query = criteria.createQuery(TaskEntry.class);
Root<TaskEntry> taskEntry = query.from(TaskEntry.class);
query.where(criteria.equal(taskEntry.get(TaskEntry_.rowNum), entry.getRowNum() - 1));
TaskEntry previousEntry = (TaskEntry) em.createQuery(query).getSingleResult();
entry.setTotal((entry.getDateTime().getTime() - previousEntry.getDateTime().getTime()) / 1000f / 60f / 60f);
query.where(criteria.equal(taskEntry.get(TaskEntry_.rowNum), entry.getRowNum() + 1));
TaskEntry nextEntry = (TaskEntry) em.createQuery(query).getSingleResult();
if (nextEntry.getDateTime() != null && !nextEntry.isAllDay() && !CHECK_IN.equals(nextEntry.getTask().getName()) && !BREAK.equals(nextEntry.getTask().getName()))
nextEntry.setTotal((nextEntry.getDateTime().getTime() - entry.getDateTime().getTime()) / 1000f / 60f / 60f);
} catch (Exception e) {}
return true;
}
protected void createOrUpdate(TaskEntry entry) {
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<TaskEntry> query = criteria.createQuery(TaskEntry.class);
Root<TaskEntry> taskEntry = query.from(TaskEntry.class);
query.where(criteria.equal(taskEntry.get(TaskEntry_.rowNum), entry.getId()));
List<TaskEntry> availableEntries = em.createQuery(query).getResultList();
if (availableEntries.size() == 1) {
TaskEntry availableEntry = availableEntries.iterator().next();
synchronized (availableEntry) {
em.getTransaction().begin();
availableEntry.setDateTime(entry.getDateTime());
availableEntry.setTask(findTaskByNameProjectAndSystem(entry.getTask().getName(),
entry.getTask().getProject() == null ? null : entry.getTask().getProject().getName(),
entry.getTask().getProject() == null ? null : entry.getTask().getProject().getSystem()));
calculateTotal(availableEntry);
availableEntry.setComment(entry.getComment());
em.persist(availableEntry);
em.getTransaction().commit();
}
}
else {
if (availableEntries.size() > 1) {
synchronized (availableEntries) {
em.getTransaction().begin();
for (TaskEntry availableEntry : availableEntries)
em.remove(availableEntry);
em.getTransaction().commit();
}
}
entry.setRowNum(entry.getId());
createTaskEntry(entry);
}
}
/**
* @return the last (incomplete) task entry
*/
public TaskEntry getLastTask() {
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<TaskEntry> query = criteria.createQuery(TaskEntry.class);
Root<TaskEntry> entry = query.from(TaskEntry.class);
query.where(criteria.isNull(entry.get(TaskEntry_.dateTime)));
query.orderBy(criteria.desc(entry.get(TaskEntry_.id)));
List<TaskEntry> taskEntries = em.createQuery(query).getResultList();
if (taskEntries.isEmpty()) return null;
return taskEntries.iterator().next();
}
public Date getLastTaskEntryDate() {
TaskEntry entry = getLastTaskEntry();
if (entry == null) return null;
return entry.getDateTime();
}
/**
* @return the last complete task entry
*/
public TaskEntry getLastTaskEntry() {
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<TaskEntry> query = criteria.createQuery(TaskEntry.class);
Root<TaskEntry> entry = query.from(TaskEntry.class);
query.where(criteria.and(entry.get(TaskEntry_.rowNum).isNotNull(), // only synchronized
entry.get(TaskEntry_.dateTime).isNotNull()));
query.orderBy(criteria.desc(entry.get(TaskEntry_.dateTime)));
List<TaskEntry> taskEntries = em.createQuery(query).getResultList();
if (taskEntries.isEmpty()) return null;
return taskEntries.iterator().next();
}
public void handleYearChange(int lastWeek) {
if (getStorageService() == null) return;
storageService.handleYearChange(lastWeek);
if (lastWeek != 0) {
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<Project> query = criteria.createQuery(Project.class);
List<Project> projects = em.createQuery(query).getResultList();
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.add(Calendar.YEAR, 1);
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, getConfigOverrides(StorageService.TIMESHEET_PREFIX + cal.get(Calendar.YEAR)));
em = factory.createEntityManager();
em.getTransaction().begin();
// TODO maybe roll over tasks and projects to new year
for (Project project : projects) {
em.persist(project);
for (Task task : project.getTasks())
em.persist(task);
}
em.getTransaction().commit();
syncTasksJob.schedule();
}
}
public boolean importTasks(String submissionSystem, Collection<SubmissionProject> projects) {
importTasks(submissionSystem, projects, false);
return true;
}
private void importTasks(String submissionSystem, Collection<SubmissionProject> projects, boolean isSynchronized) {
for (SubmissionProject submissionProject : projects) {
for (SubmissionTask submissionTask : submissionProject.getTasks()) {
Task foundTask = findTaskByNameProjectAndSystem(submissionTask.getName(), submissionProject.getName(), submissionSystem);
if (foundTask == null) {
synchronized (em) {
em.getTransaction().begin();
Project foundProject = findProjectByNameAndSystem(submissionProject.getName(), submissionSystem);
if (foundProject == null) {
foundProject = new Project(submissionProject.getName(), submissionSystem);
foundProject.setExternalId(submissionProject.getId());
em.persist(foundProject);
if (isSynchronized) foundProject.setSyncStatus(true);
}
Task task = new Task(submissionTask.getName(), foundProject);
task.setExternalId(submissionTask.getId());
if (isSynchronized) task.setSyncStatus(true);
logger.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Import task: " + submissionTask.getName() + " id=" + submissionTask.getId()
+ " (" + submissionProject.getName() + " id=" + submissionProject.getId() + ") "));
em.persist(task);
em.getTransaction().commit();
}
}
}
}
if (!isSynchronized) {
this.submissionSystem = submissionSystem;
syncTasksJob.schedule();
}
}
public Set<String> submitEntries(Date startDate, Date endDate) {
waitUntilJobsFinished();
Set<String> systems = new HashSet<String>();
synchronized (em) {
em.getTransaction().begin();
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<TaskEntry> query = criteria.createQuery(TaskEntry.class);
Root<TaskEntry> entry = query.from(TaskEntry.class);
Path<Task> task = entry.get(TaskEntry_.task);
query.where(criteria.and(criteria.notEqual(entry.get(TaskEntry_.status), true),
criteria.notEqual(task.get(Task_.name), AllDayTasks.BEGIN_ADT),
//criteria.notEqual(task.get(Task_.name), CHECK_IN),
//criteria.notEqual(task.get(Task_.name), BREAK),
entry.get(TaskEntry_.dateTime).isNotNull(),
criteria.greaterThanOrEqualTo(entry.get(TaskEntry_.dateTime), new Timestamp(startDate.getTime())),
criteria.lessThanOrEqualTo(entry.get(TaskEntry_.dateTime), new Timestamp(endDate.getTime()))));
query.orderBy(criteria.asc(entry.get(TaskEntry_.dateTime)));
List<TaskEntry> entries = em.createQuery(query).getResultList();
if (entries.isEmpty()) return systems;
Date lastDate = DateUtils.truncate(entries.iterator().next().getDateTime(), Calendar.DATE);
DailySubmissionEntry submissionEntry = new DailySubmissionEntry(lastDate);
for (TaskEntry taskEntry : entries) {
Date date = DateUtils.truncate(taskEntry.getDateTime(), Calendar.DATE);
if (!date.equals(lastDate)) { // another day
submissionEntry.submitEntries();
submissionEntry = new DailySubmissionEntry(date);
lastDate = date;
}
String system = taskEntry.getTask().getProject() == null ? null : taskEntry.getTask().getProject().getSystem();
if (submissionSystems.containsKey(system)) {
systems.add(system);
SubmissionEntry submissionTask = new SubmissionEntry(taskEntry.getTask().getProject().getExternalId(), taskEntry.getTask().getExternalId(),
taskEntry.getTask().getName(), taskEntry.getTask().getProject().getName(), system);
submissionEntry.addSubmissionEntry(submissionTask, taskEntry.getTotal());
}
taskEntry.setStatus(true);
taskEntry.setSyncStatus(false);
em.persist(taskEntry);
}
submissionEntry.submitEntries();
em.getTransaction().commit();
}
return systems;
}
public void submitFillTask(Date date) {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
if (!StringUtils.isEmpty(preferenceStore.getString(TimesheetApp.DAILY_TASK))) {
Task task = TimesheetApp.createTask(TimesheetApp.DAILY_TASK);
if (submissionSystems.containsKey(task.getProject().getSystem())) {
SubmissionEntry submissionTask = getSubmissionTask(task.getName(), task.getProject().getName(), task.getProject().getSystem());
if (submissionTask != null)
new ExtensionManager<SubmissionService>(SubmissionService.SERVICE_ID).getService(submissionSystems.get(task.getProject().getSystem()))
.submit(date, submissionTask, Double.parseDouble(preferenceStore.getString(TimesheetApp.DAILY_TASK_TOTAL)));
}
}
}
private SubmissionEntry getSubmissionTask(String task, String project, String system) {
try {
Task defaultTask = findTaskByNameProjectAndSystem(task, project, system);
return new SubmissionEntry(defaultTask.getProject().getExternalId(), defaultTask.getExternalId(), defaultTask.getName(), defaultTask.getProject().getName(), system);
} catch (Exception e) {
return null;
}
}
public void openUrl(String openBrowser) {
if (getStorageService() == null) return;
storageService.openUrl(openBrowser);
}
public Project findProjectByNameAndSystem(String name, String system) {
try {
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<Project> query = criteria.createQuery(Project.class);
Root<Project> project = query.from(Project.class);
query.where(criteria.and(criteria.equal(project.get(Project_.name), name),
criteria.equal(project.get(Project_.system), system)));
return (Project) em.createQuery(query).getSingleResult();
} catch (Exception e) {
return null;
}
}
public List<Task> findTasksByProjectAndSystem(String project, String system) {
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<Task> query = criteria.createQuery(Task.class);
Root<Task> task = query.from(Task.class);
Path<Project> proj = task.get(Task_.project);
query.where(criteria.and(criteria.equal(proj.get(Project_.name), project),
criteria.equal(proj.get(Project_.system), system)));
return em.createQuery(query).getResultList();
}
public Task findTaskByNameProjectAndSystem(String name, String project, String system) {
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<Task> query = criteria.createQuery(Task.class);
Root<Task> task = query.from(Task.class);
Predicate p = criteria.equal(task.get(Task_.name), name);
if (project == null)
query.where(p);
else {
Path<Project> proj = task.get(Task_.project);
query.where(criteria.and(p, criteria.equal(proj.get(Project_.name), project),
criteria.equal(proj.get(Project_.system), system)));
}
try {
return em.createQuery(query).getSingleResult();
} catch (Exception e) {
return null;
}
}
public void synchronize() {
if (getStorageService() == null) return;
syncEntriesJob.schedule();
}
public void reload() {
if (getStorageService() == null) return;
storageService.reload();
}
private StorageService getStorageService() {
//checks for connection to the internet through dummy request (http://stackoverflow.com/q/1139547)
try {
URL url = new URL("http://www.google.com"); // TODO storageService.getServiceUrlString()
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
urlConnect.setConnectTimeout(1000);
//trying to retrieve data from the source. If there
//is no connection, this line will fail
urlConnect.getContent();
} catch (UnknownHostException e) {
MessageBox.setError("Storage service", e.getMessage());
return null;
}
catch (IOException e) {
MessageBox.setError("Storage service", e.getMessage());
return null;
}
if (storageService == null) {
storageService = new ExtensionManager<StorageService>(StorageService.SERVICE_ID)
.getService(Activator.getDefault().getPreferenceStore().getString(StorageService.PROPERTY));
if (storageService == null) MessageBox.setError("Storage service", "Can't reach remote storage service");
}
return storageService;
}
public void waitUntilJobsFinished() {
try {
firstImportJob.join();
syncTasksJob.join();
syncEntriesJob.join();
} catch (InterruptedException e) {
MessageBox.setError("Remote storage service", e.getMessage());
}
}
// see http://stackoverflow.com/a/9110269:
private static class Mutex implements ISchedulingRule {
public boolean contains(ISchedulingRule rule) {
return (rule == this);
}
public boolean isConflicting(ISchedulingRule rule) {
return (rule == this);
}
}
}
| false | true | private LocalStorageService() {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
String timesheetName = StorageService.TIMESHEET_PREFIX + cal.get(Calendar.YEAR);
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, getConfigOverrides(timesheetName));
em = factory.createEntityManager();
submissionSystems = TimesheetApp.getSubmissionSystems();
logger = Activator.getDefault().getLog();
if (StringUtils.isEmpty(preferenceStore.getString(StorageService.PROPERTY)))
StorageSystemSetup.execute();
final Date lastTaskEntryDate = getLastTaskEntryDate();
final Date importedEndDate = importLastEntryDate(lastTaskEntryDate);
firstImportJob = new Job("Importing entries") {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (getStorageService() == null)
return Status.CANCEL_STATUS;
Calendar cal = GregorianCalendar.getInstance();
cal.set(cal.get(Calendar.YEAR), Calendar.JANUARY, 1);
Date startDate = cal.getTime();
if (lastTaskEntryDate != null) startDate = lastTaskEntryDate;
if (!DateUtils.truncate(startDate, Calendar.DATE).equals(BusinessDayUtil.getNextBusinessDay(new Date(), false))) {
cal.setTime(startDate);
int startWeek = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(new Date());
int endWeek = cal.get(Calendar.WEEK_OF_YEAR);
monitor.beginTask("Import " + (endWeek - startWeek) + " weeks", endWeek - startWeek);
for (int i = startWeek; i <= endWeek; i++) {
logger.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "import task entries for week " + i));
cal.set(Calendar.WEEK_OF_YEAR, i + 1);
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Date endDate = DateUtils.truncate(cal.getTime(), Calendar.DATE);
if (endDate != null && !endDate.before(importedEndDate))
endDate = BusinessDayUtil.getPreviousBusinessDay(importedEndDate);
if (startDate != null && startDate.after(endDate))
startDate = endDate;
List<TaskEntry> entries = storageService.getTaskEntries(startDate, endDate);
for (TaskEntry entry : entries) {
entry.setRowNum(entry.getId());
entry.setSyncStatus(true);
logger.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "import task entry: " + entry));
createOrUpdate(entry);
}
cal.set(Calendar.WEEK_OF_YEAR, i + 2);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
startDate = DateUtils.truncate(cal.getTime(), Calendar.DATE);
monitor.worked(1);
}
monitor.done();
final int lastWeek = cal.get(Calendar.WEEK_OF_YEAR) - 2;
firePropertyChangeEvent(new PropertyChangeEvent(this, PROPERTY_WEEK, null, lastWeek));
}
return Status.OK_STATUS;
}
};
firstImportJob.setRule(mutex);
firstImportJob.schedule();
syncEntriesJob = new Job("Synchronizing entries") {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (getStorageService() == null)
return Status.CANCEL_STATUS;
boolean active = false;
try {
synchronized (em) {
em.getTransaction().begin();
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<TaskEntry> query = criteria.createQuery(TaskEntry.class);
Root<TaskEntry> taskEntry = query.from(TaskEntry.class);
query.where(criteria.notEqual(taskEntry.get(TaskEntry_.syncStatus), true));
query.orderBy(criteria.asc(taskEntry.get(TaskEntry_.dateTime)));
List<TaskEntry> entries = em.createQuery(query).getResultList();
monitor.beginTask("Synchronize " + entries.size() + " entries", entries.size());
Calendar cal = new GregorianCalendar();
cal.setFirstDayOfWeek(Calendar.MONDAY);
TaskEntry lastEntry = getLastTaskEntry();
int startDay = 0;
int startWeek = 0;
int endDay = 0;
int endWeek = 0;
for (TaskEntry entry : entries) {
if (lastEntry.getDateTime() != null) {
cal.setTime(lastEntry.getDateTime());
startDay = cal.get(Calendar.DAY_OF_YEAR);
startWeek = cal.get(Calendar.WEEK_OF_YEAR);
}
if (entry.getDateTime() != null) {
cal.setTime(entry.getDateTime());
endDay = cal.get(Calendar.DAY_OF_YEAR);
endWeek = cal.get(Calendar.WEEK_OF_YEAR);
}
else {
endDay = startDay;
endWeek = startWeek;
}
if (entry.getRowNum() == null) {
if (!lastEntry.isAllDay() && startDay != 0 && startDay < endDay)
storageService.handleDayChange();
if (startWeek != 0 && startWeek < endWeek)
storageService.handleWeekChange();
entry.setRowNum(storageService.createTaskEntry(entry));
calculateTotal(entry);
}
else
storageService.updateTaskEntry(entry);
entry.setSyncStatus(true);
em.persist(entry);
monitor.worked(1);
lastEntry = entry;
}
}
monitor.done();
} catch (CoreException e) {
MessageBox.setError("Remote storage service", e.getMessage());
return Status.CANCEL_STATUS;
}
if (!active) em.getTransaction().commit();
return Status.OK_STATUS;
}
};
syncEntriesJob.setRule(mutex);
syncTasksJob = new Job("Synchronizing tasks") {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (getStorageService() == null)
return Status.CANCEL_STATUS;
synchronized (em) {
em.getTransaction().begin();
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<Task> query = criteria.createQuery(Task.class);
Root<Task> rootTask = query.from(Task.class);
query.where(criteria.notEqual(rootTask.get(Task_.syncStatus), true));
List<Task> tasks = em.createQuery(query).getResultList();
Map<String, SubmissionProject> submissionProjects = new HashMap<String, SubmissionProject>();
for (Task task : tasks) {
SubmissionProject submissionProject = submissionProjects.get(task.getProject().getName());
if (submissionProject == null)
submissionProject = new SubmissionProject(task.getProject().getExternalId(), task.getProject().getName());
submissionProject.addTask(new SubmissionTask(task.getExternalId(), task.getName()));
submissionProjects.put(submissionProject.getName(), submissionProject);
}
if (!submissionProjects.isEmpty()) {
if (storageService.importTasks(submissionSystem, submissionProjects.values()))
for (Task task : tasks) {
task.setSyncStatus(true);
task.getProject().setSyncStatus(true);
em.persist(task);
}
}
em.getTransaction().commit();
}
return Status.OK_STATUS;
}
};
syncTasksJob.setRule(mutex);
}
| private LocalStorageService() {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
String timesheetName = StorageService.TIMESHEET_PREFIX + cal.get(Calendar.YEAR);
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, getConfigOverrides(timesheetName));
em = factory.createEntityManager();
submissionSystems = TimesheetApp.getSubmissionSystems();
logger = Activator.getDefault().getLog();
if (StringUtils.isEmpty(preferenceStore.getString(StorageService.PROPERTY)))
StorageSystemSetup.execute();
final Date lastTaskEntryDate = getLastTaskEntryDate();
final Date importedEndDate = importLastEntryDate(lastTaskEntryDate);
firstImportJob = new Job("Importing entries") {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (getStorageService() == null)
return Status.CANCEL_STATUS;
Calendar cal = GregorianCalendar.getInstance();
cal.set(cal.get(Calendar.YEAR), Calendar.JANUARY, 1);
Date startDate = cal.getTime();
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
cal.set(cal.get(Calendar.YEAR), Calendar.JANUARY, 2);
startDate = cal.getTime();
}
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
if (lastTaskEntryDate != null && getTaskEntries(startDate, cal.getTime()).size() > 0) // if already imported
startDate = lastTaskEntryDate;
if (!DateUtils.truncate(startDate, Calendar.DATE).equals(BusinessDayUtil.getNextBusinessDay(new Date(), false))) {
cal.setTime(startDate);
int startWeek = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(new Date());
int endWeek = cal.get(Calendar.WEEK_OF_YEAR);
monitor.beginTask("Import " + (endWeek - startWeek) + " weeks", endWeek - startWeek);
for (int i = startWeek; i <= endWeek; i++) {
logger.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "import task entries for week " + i));
cal.set(Calendar.WEEK_OF_YEAR, i + 1);
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Date endDate = DateUtils.truncate(cal.getTime(), Calendar.DATE);
if (endDate != null && !endDate.before(importedEndDate))
endDate = BusinessDayUtil.getPreviousBusinessDay(importedEndDate);
if (startDate != null && startDate.after(endDate))
startDate = endDate;
List<TaskEntry> entries = storageService.getTaskEntries(startDate, endDate);
for (TaskEntry entry : entries) {
entry.setRowNum(entry.getId());
entry.setSyncStatus(true);
logger.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "import task entry: " + entry));
createOrUpdate(entry);
}
cal.set(Calendar.WEEK_OF_YEAR, i + 2);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
startDate = DateUtils.truncate(cal.getTime(), Calendar.DATE);
monitor.worked(1);
}
monitor.done();
final int lastWeek = cal.get(Calendar.WEEK_OF_YEAR) - 3;
firePropertyChangeEvent(new PropertyChangeEvent(this, PROPERTY_WEEK, null, lastWeek));
}
return Status.OK_STATUS;
}
};
firstImportJob.setRule(mutex);
firstImportJob.schedule();
syncEntriesJob = new Job("Synchronizing entries") {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (getStorageService() == null)
return Status.CANCEL_STATUS;
boolean active = false;
try {
synchronized (em) {
em.getTransaction().begin();
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<TaskEntry> query = criteria.createQuery(TaskEntry.class);
Root<TaskEntry> taskEntry = query.from(TaskEntry.class);
query.where(criteria.notEqual(taskEntry.get(TaskEntry_.syncStatus), true));
query.orderBy(criteria.asc(taskEntry.get(TaskEntry_.dateTime)));
List<TaskEntry> entries = em.createQuery(query).getResultList();
monitor.beginTask("Synchronize " + entries.size() + " entries", entries.size());
Calendar cal = new GregorianCalendar();
cal.setFirstDayOfWeek(Calendar.MONDAY);
TaskEntry lastEntry = getLastTaskEntry();
int startDay = 0;
int startWeek = 0;
int endDay = 0;
int endWeek = 0;
for (TaskEntry entry : entries) {
if (lastEntry.getDateTime() != null) {
cal.setTime(lastEntry.getDateTime());
startDay = cal.get(Calendar.DAY_OF_YEAR);
startWeek = cal.get(Calendar.WEEK_OF_YEAR);
}
if (entry.getDateTime() != null) {
cal.setTime(entry.getDateTime());
endDay = cal.get(Calendar.DAY_OF_YEAR);
endWeek = cal.get(Calendar.WEEK_OF_YEAR);
}
else {
endDay = startDay;
endWeek = startWeek;
}
if (entry.getRowNum() == null) {
if (!lastEntry.isAllDay() && startDay != 0 && startDay < endDay)
storageService.handleDayChange();
if (startWeek != 0 && startWeek < endWeek)
storageService.handleWeekChange();
entry.setRowNum(storageService.createTaskEntry(entry));
calculateTotal(entry);
}
else
storageService.updateTaskEntry(entry);
entry.setSyncStatus(true);
em.persist(entry);
monitor.worked(1);
lastEntry = entry;
}
}
monitor.done();
} catch (CoreException e) {
MessageBox.setError("Remote storage service", e.getMessage());
return Status.CANCEL_STATUS;
}
if (!active) em.getTransaction().commit();
return Status.OK_STATUS;
}
};
syncEntriesJob.setRule(mutex);
syncTasksJob = new Job("Synchronizing tasks") {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (getStorageService() == null)
return Status.CANCEL_STATUS;
synchronized (em) {
em.getTransaction().begin();
CriteriaBuilder criteria = em.getCriteriaBuilder();
CriteriaQuery<Task> query = criteria.createQuery(Task.class);
Root<Task> rootTask = query.from(Task.class);
query.where(criteria.notEqual(rootTask.get(Task_.syncStatus), true));
List<Task> tasks = em.createQuery(query).getResultList();
Map<String, SubmissionProject> submissionProjects = new HashMap<String, SubmissionProject>();
for (Task task : tasks) {
SubmissionProject submissionProject = submissionProjects.get(task.getProject().getName());
if (submissionProject == null)
submissionProject = new SubmissionProject(task.getProject().getExternalId(), task.getProject().getName());
submissionProject.addTask(new SubmissionTask(task.getExternalId(), task.getName()));
submissionProjects.put(submissionProject.getName(), submissionProject);
}
if (!submissionProjects.isEmpty()) {
if (storageService.importTasks(submissionSystem, submissionProjects.values()))
for (Task task : tasks) {
task.setSyncStatus(true);
task.getProject().setSyncStatus(true);
em.persist(task);
}
}
em.getTransaction().commit();
}
return Status.OK_STATUS;
}
};
syncTasksJob.setRule(mutex);
}
|
diff --git a/kernel/src/main/java/org/vosao/filter/LanguageFilter.java b/kernel/src/main/java/org/vosao/filter/LanguageFilter.java
index 8f626cf..95aece1 100644
--- a/kernel/src/main/java/org/vosao/filter/LanguageFilter.java
+++ b/kernel/src/main/java/org/vosao/filter/LanguageFilter.java
@@ -1,73 +1,73 @@
/**
* Vosao CMS. Simple CMS for Google App Engine.
* Copyright (C) 2009 Vosao development team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* email: [email protected]
*/
package org.vosao.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.vosao.common.VosaoContext;
import org.vosao.entity.LanguageEntity;
public class LanguageFilter extends AbstractFilter implements Filter {
private static final String LANGUAGE_SESSION_ATTR = "language";
public LanguageFilter() {
super();
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpSession session = httpRequest.getSession(true);
VosaoContext ctx = VosaoContext.getInstance();
if (session.getAttribute(LANGUAGE_SESSION_ATTR) == null) {
String language = request.getLocale().getLanguage();
//logger.info("Initial language set " + language);
ctx.setLanguage(language);
session.setAttribute(LANGUAGE_SESSION_ATTR, language);
}
else {
ctx.setLanguage((String)session.getAttribute(LANGUAGE_SESSION_ATTR));
}
if (httpRequest.getParameter("language") != null) {
String languageCode = httpRequest.getParameter("language");
LanguageEntity language = getDao().getLanguageDao().getByCode(
languageCode);
if (language != null) {
//logger.info("Set language " + language + " by parameter");
ctx.setLanguage(languageCode);
- session.setAttribute(LANGUAGE_SESSION_ATTR, language);
+ session.setAttribute(LANGUAGE_SESSION_ATTR, language.getCode());
}
}
chain.doFilter(request, response);
}
}
| true | true | public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpSession session = httpRequest.getSession(true);
VosaoContext ctx = VosaoContext.getInstance();
if (session.getAttribute(LANGUAGE_SESSION_ATTR) == null) {
String language = request.getLocale().getLanguage();
//logger.info("Initial language set " + language);
ctx.setLanguage(language);
session.setAttribute(LANGUAGE_SESSION_ATTR, language);
}
else {
ctx.setLanguage((String)session.getAttribute(LANGUAGE_SESSION_ATTR));
}
if (httpRequest.getParameter("language") != null) {
String languageCode = httpRequest.getParameter("language");
LanguageEntity language = getDao().getLanguageDao().getByCode(
languageCode);
if (language != null) {
//logger.info("Set language " + language + " by parameter");
ctx.setLanguage(languageCode);
session.setAttribute(LANGUAGE_SESSION_ATTR, language);
}
}
chain.doFilter(request, response);
}
| public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpSession session = httpRequest.getSession(true);
VosaoContext ctx = VosaoContext.getInstance();
if (session.getAttribute(LANGUAGE_SESSION_ATTR) == null) {
String language = request.getLocale().getLanguage();
//logger.info("Initial language set " + language);
ctx.setLanguage(language);
session.setAttribute(LANGUAGE_SESSION_ATTR, language);
}
else {
ctx.setLanguage((String)session.getAttribute(LANGUAGE_SESSION_ATTR));
}
if (httpRequest.getParameter("language") != null) {
String languageCode = httpRequest.getParameter("language");
LanguageEntity language = getDao().getLanguageDao().getByCode(
languageCode);
if (language != null) {
//logger.info("Set language " + language + " by parameter");
ctx.setLanguage(languageCode);
session.setAttribute(LANGUAGE_SESSION_ATTR, language.getCode());
}
}
chain.doFilter(request, response);
}
|
diff --git a/src/main/java/net/minecraft/server/ServerConfigurationManager.java b/src/main/java/net/minecraft/server/ServerConfigurationManager.java
index 5ca09fc..061ad9f 100755
--- a/src/main/java/net/minecraft/server/ServerConfigurationManager.java
+++ b/src/main/java/net/minecraft/server/ServerConfigurationManager.java
@@ -1,972 +1,972 @@
package net.minecraft.server;
import java.net.SocketAddress;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.canarymod.Canary;
import net.canarymod.ToolBox;
import net.canarymod.Translator;
import net.canarymod.api.CanaryConfigurationManager;
import net.canarymod.api.CanaryPacket;
import net.canarymod.api.PlayerListEntry;
import net.canarymod.api.entity.living.humanoid.CanaryPlayer;
import net.canarymod.api.world.CanaryWorld;
import net.canarymod.api.world.position.Location;
import net.canarymod.bansystem.Ban;
import net.canarymod.config.Configuration;
import net.canarymod.config.ServerConfiguration;
import net.canarymod.hook.player.ConnectionHook;
import net.canarymod.hook.player.PlayerListEntryHook;
import net.canarymod.hook.player.PlayerRespawnHook;
import net.canarymod.hook.player.PreConnectionHook;
import net.canarymod.hook.player.TeleportHook;
import net.canarymod.hook.system.ServerShutdownHook;
public abstract class ServerConfigurationManager {
private static final SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd \'at\' HH:mm:ss z");
private final MinecraftServer e;
public final List a = new ArrayList();
// private final BanList f = new BanList(new File("banned-players.txt"));
// private final BanList g = new BanList(new File("banned-ips.txt"));
private Set h = new HashSet();
private Set i = new HashSet();
private IPlayerFileData j;
private boolean k;
protected int b;
protected int c;
private EnumGameType l;
private boolean m;
private int n = 0;
// CanaryMod
protected CanaryConfigurationManager configurationmanager;
private HashMap<String, IPlayerFileData> playerFileData = new HashMap<String, IPlayerFileData>();
//
public ServerConfigurationManager(MinecraftServer minecraftserver) {
this.e = minecraftserver;
// this.f.a(false);
// this.g.a(false);
this.b = Configuration.getServerConfig().getMaxPlayers();
configurationmanager = new CanaryConfigurationManager(this);
}
// XXX LOGIN
public void a(INetworkManager inetworkmanager, EntityPlayerMP entityplayermp) {
NBTTagCompound nbttagcompound = this.a(entityplayermp);
CanaryWorld w;
boolean firstTime = true;
if (nbttagcompound != null) {
w = (CanaryWorld) Canary.getServer().getWorldManager().getWorld(nbttagcompound.i("LevelName"), net.canarymod.api.world.DimensionType.fromId(nbttagcompound.e("Dimension")), true);
firstTime = false;
} else {
w = (CanaryWorld) Canary.getServer().getDefaultWorld();
}
entityplayermp.a(w.getHandle());
entityplayermp.c.a((WorldServer) entityplayermp.q);
String s0 = "local";
if (inetworkmanager.c() != null) {
s0 = inetworkmanager.c().toString();
}
this.e.an().a(entityplayermp.c_() + "[" + s0 + "] logged in with entity id " + entityplayermp.k + " at (" + entityplayermp.u + ", " + entityplayermp.v + ", " + entityplayermp.w + ")");
// CanaryMod: Use world we got from players NBT data
WorldServer worldserver = (WorldServer) w.getHandle();
ChunkCoordinates chunkcoordinates = worldserver.K();
this.a(entityplayermp, (EntityPlayerMP) null, worldserver);
NetServerHandler netserverhandler = new NetServerHandler(this.e, inetworkmanager, entityplayermp);
netserverhandler.b(new Packet1Login(entityplayermp.k, worldserver.N().u(), entityplayermp.c.b(), worldserver.N().t(), worldserver.t.i, worldserver.r, worldserver.R(), this.l()));
netserverhandler.b(new Packet6SpawnPosition(chunkcoordinates.a, chunkcoordinates.b, chunkcoordinates.c));
netserverhandler.b(new Packet202PlayerAbilities(entityplayermp.bG));
netserverhandler.b(new Packet16BlockItemSwitch(entityplayermp.bn.c));
this.a((ServerScoreboard) worldserver.X(), entityplayermp);
this.b(entityplayermp, worldserver);
// CanaryMod Connection hook
ConnectionHook hook = (ConnectionHook) new ConnectionHook(entityplayermp.getPlayer(), ChatMessageComponent.b("multiplayer.player.joined", new Object[]{ entityplayermp.aw() }).a(EnumChatFormatting.o).toString(), firstTime).call();
if (!hook.isHidden()) {
this.a((Packet) (new Packet3Chat(ChatMessageComponent.e(hook.getMessage()))));
}
// CanaryMod end
this.c(entityplayermp);
netserverhandler.a(entityplayermp.u, entityplayermp.v, entityplayermp.w, entityplayermp.A, entityplayermp.B, w.getType().getId(), w.getName(), TeleportHook.TeleportCause.RESPAWN);
this.e.ag().a(netserverhandler);
netserverhandler.b(new Packet4UpdateTime(worldserver.I(), worldserver.J(), worldserver.O().b("doDaylightCycle")));
if (this.e.S().length() > 0) {
entityplayermp.a(this.e.S(), this.e.U());
}
Iterator iterator = entityplayermp.aH().iterator();
while (iterator.hasNext()) {
PotionEffect potioneffect = (PotionEffect) iterator.next();
netserverhandler.b(new Packet41EntityEffect(entityplayermp.k, potioneffect));
}
entityplayermp.d();
if (nbttagcompound != null && nbttagcompound.b("Riding")) {
Entity entity = EntityList.a(nbttagcompound.l("Riding"), worldserver);
if (entity != null) {
entity.p = true;
worldserver.d(entity);
entityplayermp.a(entity);
entity.p = false;
}
}
}
protected void a(ServerScoreboard serverscoreboard, EntityPlayerMP entityplayermp) {
HashSet hashset = new HashSet();
Iterator iterator = serverscoreboard.g().iterator();
while (iterator.hasNext()) {
ScorePlayerTeam scoreplayerteam = (ScorePlayerTeam) iterator.next();
entityplayermp.a.b(new Packet209SetPlayerTeam(scoreplayerteam, 0));
}
for (int i0 = 0; i0 < 3; ++i0) {
ScoreObjective scoreobjective = serverscoreboard.a(i0);
if (scoreobjective != null && !hashset.contains(scoreobjective)) {
List list = serverscoreboard.d(scoreobjective);
Iterator iterator1 = list.iterator();
while (iterator1.hasNext()) {
Packet packet = (Packet) iterator1.next();
entityplayermp.a.b(packet);
}
hashset.add(scoreobjective);
}
}
}
public void a(WorldServer[] server) {
// CanaryMod Multiworld
playerFileData.put(server[0].getCanaryWorld().getName(), server[0].M().e()); // XXX May need to review this
//
}
public void a(EntityPlayerMP entityplayermp, WorldServer worldserver) {
WorldServer worldserver1 = entityplayermp.p();
if (worldserver != null) {
worldserver.s().c(entityplayermp);
}
worldserver1.s().a(entityplayermp);
worldserver1.b.c((int) entityplayermp.u >> 4, (int) entityplayermp.w >> 4);
}
public int a() {
return PlayerManager.a(this.o());
}
public NBTTagCompound a(EntityPlayerMP entityplayermp) {
NBTTagCompound nbttagcompound = entityplayermp.getCanaryWorld().getHandle().N().i();
NBTTagCompound nbttagcompound1;
if (entityplayermp.c_().equals(this.e.J()) && nbttagcompound != null) {
entityplayermp.f(nbttagcompound);
nbttagcompound1 = nbttagcompound;
System.out.println("loading single player");
} else {
// CanaryMod Multiworld
nbttagcompound1 = playerFileData.get(entityplayermp.getCanaryWorld().getName()).b(entityplayermp);
//
}
return nbttagcompound1;
}
// CanaryMod: get player data for name
public static NBTTagCompound getPlayerDatByName(String name) {
ISaveHandler handler = ((CanaryWorld) Canary.getServer().getDefaultWorld()).getHandle().M();
if (handler instanceof SaveHandler) {
SaveHandler saves = (SaveHandler) handler;
return saves.a(name);
} else {
throw new RuntimeException("ISaveHandler is not of type SaveHandler! Failing to laod playerdata");
}
}
protected void b(EntityPlayerMP entityplayermp) {
// CanaryMod Multiworld
playerFileData.get(entityplayermp.getCanaryWorld().getName()).a(entityplayermp);
//
}
public void c(EntityPlayerMP entityplayermp) {
// CanaryMod: PlayerListEntry
if (Configuration.getServerConfig().isPlayerListEnabled()) {
// Get PlayerListEntry
PlayerListEntry plentry = entityplayermp.getPlayer().getPlayerListEntry(true);
plentry.setPing(1000); // Set the ping for the initial connection
for (int i0 = 0; i0 < this.a.size(); ++i0) {
EntityPlayerMP entityplayermp1 = (EntityPlayerMP) this.a.get(i0);
// Clone the entry so that each receiver will start with the given data
PlayerListEntry clone = plentry.clone();
// Call PlayerListEntryHook
new PlayerListEntryHook(clone, entityplayermp1.getPlayer()).call();
// Send Packet
entityplayermp1.a.b(new Packet201PlayerInfo(plentry.getName(), plentry.isShown(), 1000)); // Ping ignored
}
}
//
this.a.add(entityplayermp);
// CanaryMod: Directly use playerworld instead
WorldServer worldserver = (WorldServer) entityplayermp.getCanaryWorld().getHandle(); // this.e.a(entityplayermp.ar);
worldserver.d(entityplayermp);
this.a(entityplayermp, (WorldServer) null);
// CanaryMod: PlayerListEntry
if (Configuration.getServerConfig().isPlayerListEnabled()) {
for (int i0 = 0; i0 < this.a.size(); ++i0) {
EntityPlayerMP entityplayermp1 = (EntityPlayerMP) this.a.get(i0);
// Get the PlayerListEntry
PlayerListEntry plentry = entityplayermp1.getPlayer().getPlayerListEntry(true);
// Call PlayerListEntryHook
new PlayerListEntryHook(plentry, entityplayermp.getPlayer()).call();
// Send Packet
entityplayermp.a.b(new Packet201PlayerInfo(plentry.getName(), plentry.isShown(), plentry.getPing()));
}
}
//
}
public void d(EntityPlayerMP entityplayermp) {
entityplayermp.p().s().d(entityplayermp);
}
public void e(EntityPlayerMP entityplayermp) {
this.b(entityplayermp);
WorldServer worldserver = entityplayermp.p();
if (entityplayermp.o != null) {
worldserver.f(entityplayermp.o);
// System.out.println("removing player mount"); Mojang Debug
}
worldserver.e(entityplayermp);
worldserver.s().c(entityplayermp);
this.a.remove(entityplayermp);
// CanaryMod: PlayerListEntry
if (Configuration.getServerConfig().isPlayerListEnabled()) {
// Get PlayerListEntry
PlayerListEntry plentry = entityplayermp.getPlayer().getPlayerListEntry(false);
for (int i0 = 0; i0 < this.a.size(); ++i0) {
EntityPlayerMP entityplayermp1 = (EntityPlayerMP) this.a.get(i0);
// Clone the entry so that each receiver will start with the given data
PlayerListEntry clone = plentry.clone();
// Call PlayerListEntryHook
new PlayerListEntryHook(clone, entityplayermp1.getPlayer()).call();
// Send Packet
entityplayermp1.a.b(new Packet201PlayerInfo(plentry.getName(), plentry.isShown(), plentry.getPing()));
}
}
//
}
public String a(SocketAddress socketaddress, String s0) {
// CanaryMod, redo the whole thing
String s2 = socketaddress.toString();
s2 = s2.substring(s2.indexOf("/") + 1);
s2 = s2.substring(0, s2.indexOf(":"));
PreConnectionHook hook = (PreConnectionHook) new PreConnectionHook(s2, s0, net.canarymod.api.world.DimensionType.fromId(0), Canary.getServer().getDefaultWorldName()).call();
if (hook.getKickReason() != null) {
return hook.getKickReason();
}
ServerConfiguration srv = Configuration.getServerConfig();
if (Canary.bans().isBanned(s0)) {
Ban ban = Canary.bans().getBan(s0);
if (ban.getTimestamp() != -1) {
return ban.getReason() + ", " +
srv.getBanExpireDateMessage() + ToolBox.formatTimestamp(ban.getTimestamp());
}
return ban.getReason();
}
if (Canary.bans().isIpBanned(s2)) {
return Translator.translate(srv.getDefaultBannedMessage());
}
if (!Canary.whitelist().isWhitelisted(s0) && Configuration.getServerConfig().isWhitelistEnabled()) {
return srv.getNotWhitelistedMessage();
}
if (this.a.size() >= this.b) {
if (Canary.reservelist().isSlotReserved(s0) && Configuration.getServerConfig().isReservelistEnabled()) {
return null;
}
return srv.getServerFullMessage();
}
return null;
// if (this.f.a(s0)) {
// BanEntry banentry = (BanEntry) this.f.c().get(s0);
// String s1 = "You are banned from this server!\nReason: " + banentry.f();
//
// if (banentry.d() != null) {
// s1 = s1 + "\nYour ban will be removed on " + d.format(banentry.d());
// }
//
// return s1;
// } else if (!this.d(s0)) {
// return "You are not white-listed on this server!";
// } else {
// if (this.g.a(s2)) {
// BanEntry banentry1 = (BanEntry) this.g.c().get(s2);
// String s3 = "Your IP address is banned from this server!\nReason: " + banentry1.f();
//
// if (banentry1.d() != null) {
// s3 = s3 + "\nYour ban will be removed on " + d.format(banentry1.d());
// }
//
// return s3;
// } else {
// return this.a.size() >= this.b ? "The server is full!" : null;
// }
// }
}
public EntityPlayerMP a(String playername) {
ArrayList arraylist = new ArrayList();
EntityPlayerMP entityplayermp;
for (int i0 = 0; i0 < this.a.size(); ++i0) {
entityplayermp = (EntityPlayerMP) this.a.get(i0);
if (entityplayermp.c_().equalsIgnoreCase(playername)) {
arraylist.add(entityplayermp);
}
}
Iterator iterator = arraylist.iterator();
while (iterator.hasNext()) {
entityplayermp = (EntityPlayerMP) iterator.next();
entityplayermp.a.c("You logged in from another location");
}
// CanaryMod read the players dat file to find out the world it was last in
String worldName = Canary.getServer().getDefaultWorldName();
net.canarymod.api.world.DimensionType worldtype = net.canarymod.api.world.DimensionType.fromId(0);
NBTTagCompound playertag = getPlayerDatByName(playername);
if (playertag != null) {
net.canarymod.api.nbt.CanaryCompoundTag canarycompound = new net.canarymod.api.nbt.CanaryCompoundTag(playertag);
worldName = canarycompound.getString("LevelName");
if (worldName == null || worldName.isEmpty()) {
worldName = Canary.getServer().getDefaultWorldName();
}
worldtype = net.canarymod.api.world.DimensionType.fromId(canarycompound.getInt("Dimension"));
}
WorldServer world = (WorldServer) ((CanaryWorld) Canary.getServer().getWorldManager().getWorld(worldName, worldtype, true)).getHandle();
Object object;
if (this.e.O()) {
object = new DemoWorldManager(world);
} else {
object = new ItemInWorldManager(world);
}
return new EntityPlayerMP(this.e, world, playername, (ItemInWorldManager) object);
}
public EntityPlayerMP a(EntityPlayerMP entityplayermp, int i, boolean flag) {
return this.a(entityplayermp, i, flag, null);
}
// XXX IMPORTANT, HERE IS WORLD SWITCHING GOING ON!
public EntityPlayerMP a(EntityPlayerMP entityplayermp, int i0, boolean flag0, Location loc) {
entityplayermp.p().q().a(entityplayermp);
entityplayermp.p().q().b(entityplayermp);
entityplayermp.p().s().c(entityplayermp);
this.a.remove(entityplayermp);
- this.e.a(entityplayermp.ar).f(entityplayermp);
+ this.e.getWorld(entityplayermp.getCanaryWorld().getName(), entityplayermp.ar).f(entityplayermp); // CanaryMod: added multiworld support
// ChunkCoordinates chunkcoordinates = entityplayermp.bA(); //CanaryMod removed in favor of a real location
Location respawnLocation = entityplayermp.getRespawnLocation();
boolean flag1 = entityplayermp.bB();
boolean isBedSpawn = respawnLocation != null;
entityplayermp.ar = i0;
Object object;
String name = entityplayermp.getCanaryWorld().getName();
net.canarymod.api.world.DimensionType type = net.canarymod.api.world.DimensionType.fromId(i0);
// CanaryMod: PlayerRespawn
PlayerRespawnHook hook = (PlayerRespawnHook) new PlayerRespawnHook(entityplayermp.getPlayer(), loc, isBedSpawn).call();
loc = hook.getRespawnLocation();
WorldServer worldserver = (WorldServer) (loc == null ? (WorldServer) ((CanaryWorld) Canary.getServer().getWorldManager().getWorld(name, type, true)).getHandle() : ((CanaryWorld) loc.getWorld()).getHandle());
// CanaryMod changes to accommodate multiworld bed spawns
ChunkCoordinates chunkcoordinates = null;
if (respawnLocation != null) {
chunkcoordinates = new ChunkCoordinates(respawnLocation.getBlockX(), respawnLocation.getBlockY(), respawnLocation.getBlockZ());
// Check if the spawn world differs from the expected one and adjust
if (!worldserver.equals(((CanaryWorld) respawnLocation.getWorld()).getHandle())) {
worldserver = (WorldServer) ((CanaryWorld) respawnLocation.getWorld()).getHandle();
}
}
if (loc != null) {
chunkcoordinates = new ChunkCoordinates(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
// Check if the spawn world differs from the expected one and adjust
if (!worldserver.equals(((CanaryWorld) loc.getWorld()).getHandle())) {
worldserver = (WorldServer) ((CanaryWorld) loc.getWorld()).getHandle();
}
respawnLocation = loc;
}
//
if (this.e.O()) {
object = new DemoWorldManager(worldserver);
} else {
object = new ItemInWorldManager(worldserver);
}
EntityPlayerMP entityplayermp1 = new EntityPlayerMP(this.e, worldserver, entityplayermp.c_(), (ItemInWorldManager) object);
// Copy netserverhandler as the connection is still the same
entityplayermp1.a = entityplayermp.a;
entityplayermp1.a(entityplayermp, flag0);
entityplayermp1.k = entityplayermp.k;
entityplayermp1.a.c = entityplayermp1;
this.a(entityplayermp1, entityplayermp, worldserver); // XXX
ChunkCoordinates chunkcoordinates1;
if (chunkcoordinates != null) {
chunkcoordinates1 = EntityPlayer.a(worldserver, chunkcoordinates, flag1);
if (chunkcoordinates1 != null) {
entityplayermp1.b((double) ((float) chunkcoordinates1.a + 0.5F), (double) ((float) chunkcoordinates1.b + 0.1F), (double) ((float) chunkcoordinates1.c + 0.5F), 0.0F, 0.0F);
entityplayermp1.a(chunkcoordinates, flag1);
} else {
if (isBedSpawn) {
entityplayermp1.a.b(new Packet70GameEvent(0, 0));
}
}
}
worldserver.b.c((int) entityplayermp1.u >> 4, (int) entityplayermp1.w >> 4);
entityplayermp1.a.b(new Packet9Respawn(entityplayermp1.ar, (byte) entityplayermp1.q.r, entityplayermp1.q.N().u(), entityplayermp1.q.R(), entityplayermp1.c.b()));
entityplayermp1.a.b(new Packet9Respawn(entityplayermp1.ar, (byte) entityplayermp1.q.r, entityplayermp1.q.N().u(), entityplayermp1.q.R(), entityplayermp1.c.b()));
// CanaryMod: Adjust the data for the respawn packet by using player coordinates instead!
chunkcoordinates1 = worldserver.K();
// CanaryMod changed old logic with this one, this suffices and is, for some reason, more reliable
while (worldserver.getCanaryWorld().getBlockAt(ToolBox.floorToBlock(entityplayermp1.u), ToolBox.floorToBlock(entityplayermp1.v + 1), ToolBox.floorToBlock(entityplayermp1.w)).getTypeId() != 0) {
entityplayermp1.v = entityplayermp1.v + 1D;
}
entityplayermp1.a.a(entityplayermp1.u, entityplayermp1.v, entityplayermp1.w, entityplayermp1.A, entityplayermp1.B, entityplayermp1.getCanaryWorld().getType().getId(), entityplayermp1.getCanaryWorld().getName(), TeleportHook.TeleportCause.RESPAWN);
entityplayermp1.a.b(new Packet6SpawnPosition((int) entityplayermp1.u, (int) entityplayermp1.v, (int) entityplayermp1.w)); // CanaryMod changed used data to player coords
entityplayermp1.a.b(new Packet43Experience(entityplayermp1.bJ, entityplayermp1.bI, entityplayermp1.bH));
this.b(entityplayermp1, worldserver);
worldserver.s().a(entityplayermp1);
worldserver.d(entityplayermp1);
this.a.add(entityplayermp1);
entityplayermp1.d();
entityplayermp1.g(entityplayermp1.aJ());
//
return entityplayermp1;
}
@Deprecated
public void a(EntityPlayerMP entityplayermp, int i0) {
throw new UnsupportedOperationException("a(EntityPlayerMP, int) is deprecated. please use a(EntityPlayerMP, String, int))");
}
// XXX IMPORTANT, HERE IS DIMENSION SWITCHING GOING ON!
public void a(EntityPlayerMP entityplayermp, String worldName, int i0) {
int i1 = entityplayermp.ar;
WorldServer worldserver = (WorldServer) entityplayermp.getCanaryWorld().getHandle();
entityplayermp.ar = i0;
net.canarymod.api.world.DimensionType type = net.canarymod.api.world.DimensionType.fromId(i0);
WorldServer worldserver1 = (WorldServer) ((CanaryWorld) Canary.getServer().getWorldManager().getWorld(worldName, type, true)).getHandle();
// Pre-load a chunk in the new world, makes spawning there a little faster
worldserver1.b.c((int) entityplayermp.u >> 4, (int) entityplayermp.w >> 4);
entityplayermp.a.b(new Packet9Respawn(i0, (byte) entityplayermp.q.r, worldserver1.N().u(), worldserver1.R(), entityplayermp.c.b()));
worldserver.f(entityplayermp);
entityplayermp.M = false;
this.a(entityplayermp, i1, worldserver, worldserver1); // i1
this.a(entityplayermp, worldserver);
// TP player to position
entityplayermp.a.a(entityplayermp.u, entityplayermp.v, entityplayermp.w, entityplayermp.A, entityplayermp.B, entityplayermp.getCanaryWorld().getType().getId(), entityplayermp.getCanaryWorld().getName(), TeleportHook.TeleportCause.PORTAL);
entityplayermp.c.a(worldserver1);
this.b(entityplayermp, worldserver1);
this.f(entityplayermp);
Iterator iterator = entityplayermp.aH().iterator();
while (iterator.hasNext()) {
PotionEffect potioneffect = (PotionEffect) iterator.next();
entityplayermp.a.b(new Packet41EntityEffect(entityplayermp.k, potioneffect));
}
}
public void a(Entity entity, int i0, WorldServer worldserver, WorldServer worldserver1) {
double d0 = entity.u;
double d1 = entity.w;
double d2 = 8.0D;
double d3 = entity.u;
double d4 = entity.v;
double d5 = entity.w;
float f0 = entity.A;
worldserver.C.a("moving");
if (entity.ar == -1) {
d0 /= d2;
d1 /= d2;
entity.b(d0, entity.v, d1, entity.A, entity.B);
if (entity.R()) {
worldserver.a(entity, false);
}
} else if (entity.ar == 0) {
d0 *= d2;
d1 *= d2;
entity.b(d0, entity.v, d1, entity.A, entity.B);
if (entity.R()) {
worldserver.a(entity, false);
}
} else {
ChunkCoordinates chunkcoordinates;
if (i0 == 1) {
chunkcoordinates = worldserver1.K();
} else {
chunkcoordinates = worldserver1.l();
}
d0 = (double) chunkcoordinates.a;
entity.v = (double) chunkcoordinates.b;
d1 = (double) chunkcoordinates.c;
entity.b(d0, entity.v, d1, 90.0F, 0.0F);
if (entity.R()) {
worldserver.a(entity, false);
}
}
worldserver.C.b();
if (i0 != 1) {
worldserver.C.a("placing");
d0 = (double) MathHelper.a((int) d0, -29999872, 29999872);
d1 = (double) MathHelper.a((int) d1, -29999872, 29999872);
if (entity.R()) {
worldserver1.d(entity);
entity.b(d0, entity.v, d1, entity.A, entity.B);
worldserver1.a(entity, false);
worldserver1.t().a(entity, d3, d4, d5, f0);
}
worldserver.C.b();
}
entity.a((World) worldserver1);
}
public void b() {
if (++this.n > Configuration.getServerConfig().getPlayerlistTicks()) {
this.n = 0;
}
// CanaryMod: PlayerListEntry
if (Configuration.getServerConfig().isPlayerListEnabled() && this.n < this.a.size()) {
EntityPlayerMP entityplayermp = (EntityPlayerMP) this.a.get(this.n);
// Get PlayerListEntry
PlayerListEntry plentry = entityplayermp.getPlayer().getPlayerListEntry(true);
for (int i0 = 0; i0 < this.a.size(); ++i0) {
EntityPlayerMP entityplayermp1 = (EntityPlayerMP) this.a.get(i0);
// Clone the entry so that each receiver will start with the given data
PlayerListEntry clone = plentry.clone();
// Call PlayerListEntryHook
new PlayerListEntryHook(clone, entityplayermp1.getPlayer()).call();
// Send Packet
entityplayermp1.a.b(new Packet201PlayerInfo(plentry.getName(), plentry.isShown(), plentry.getPing()));
}
}
//
}
public void a(Packet packet) {
for (int i0 = 0; i0 < this.a.size(); ++i0) {
((EntityPlayerMP) this.a.get(i0)).a.b(packet);
}
}
// CanaryMod re-route packets properly
public void sendPacketToDimension(Packet packet, String world, int i) {
for (int j = 0; j < this.a.size(); ++j) {
EntityPlayerMP entityplayermp = (EntityPlayerMP) this.a.get(j);
if (world.equals(entityplayermp.getCanaryWorld().getName()) && entityplayermp.ar == i) {
// TODO check: CanaryMod re-route time updates to world-specific entity trackers
entityplayermp.a.b(packet);
}
}
}
// CanaryMod end
@Deprecated
public void a(Packet packet, int i0) {
throw new UnsupportedOperationException("a(packet, int) has been deprecated. use sendPacketToDimension instead!");
}
public String c() {
String s0 = "";
for (int i0 = 0; i0 < this.a.size(); ++i0) {
if (i0 > 0) {
s0 = s0 + ", ";
}
s0 = s0 + ((EntityPlayerMP) this.a.get(i0)).c_();
}
return s0;
}
public String[] d() {
String[] astring = new String[this.a.size()];
for (int i0 = 0; i0 < this.a.size(); ++i0) {
astring[i0] = ((EntityPlayerMP) this.a.get(i0)).c_();
}
return astring;
}
public BanList e() {
// CanaryMod this is unused
throw new UnsupportedOperationException("SCM.e() is deprecated");
}
public BanList f() {
// CanaryMod this is unused
throw new UnsupportedOperationException("SCM.f() is deprecated");
}
public void b(String s0) {
Canary.ops().addPlayer(s0); // CanaryMod: Re-route to our Ops listing
}
public void c(String s0) {
Canary.ops().removePlayer(s0); // CanaryMod: Re-route to our Ops listing
}
public boolean d(String s0) {
return !this.k || Canary.ops().isOpped(s0); // CanaryMod: Re-route to our Ops listing
}
public boolean e(String s0) {
WorldServer srv = (WorldServer) ((CanaryWorld) Canary.getServer().getDefaultWorld()).getHandle();
// CanaryMod: Added Re-route to our Ops listing
return Canary.ops().isOpped(s0) || this.e.K() && srv.N().v() && this.e.J().equalsIgnoreCase(s0) || this.m;
}
public EntityPlayerMP f(String s0) {
Iterator iterator = this.a.iterator();
EntityPlayerMP entityplayermp;
do {
if (!iterator.hasNext()) {
return null;
}
entityplayermp = (EntityPlayerMP) iterator.next();
}
while (!entityplayermp.c_().equalsIgnoreCase(s0));
return entityplayermp;
}
public List a(ChunkCoordinates chunkcoordinates, int i0, int i1, int i2, int i3, int i4, int i5, Map map, String s0, String s1, World world) {
if (this.a.isEmpty()) {
return null;
} else {
Object object = new ArrayList();
boolean flag0 = i2 < 0;
boolean flag1 = s0 != null && s0.startsWith("!");
boolean flag2 = s1 != null && s1.startsWith("!");
int i6 = i0 * i0;
int i7 = i1 * i1;
i2 = MathHelper.a(i2);
if (flag1) {
s0 = s0.substring(1);
}
if (flag2) {
s1 = s1.substring(1);
}
for (int i8 = 0; i8 < this.a.size(); ++i8) {
EntityPlayerMP entityplayermp = (EntityPlayerMP) this.a.get(i8);
if ((world == null || entityplayermp.q == world) && (s0 == null || flag1 != s0.equalsIgnoreCase(entityplayermp.al()))) {
if (s1 != null) {
ScorePlayerTeam scoreplayerteam = entityplayermp.bI();
String s2 = scoreplayerteam == null ? "" : scoreplayerteam.b();
if (flag2 == s1.equalsIgnoreCase(s2)) {
continue;
}
}
if (chunkcoordinates != null && (i0 > 0 || i1 > 0)) {
float f0 = chunkcoordinates.e(entityplayermp.b());
if (i0 > 0 && f0 < (float) i6 || i1 > 0 && f0 > (float) i7) {
continue;
}
}
if (this.a((EntityPlayer) entityplayermp, map) && (i3 == EnumGameType.a.a() || i3 == entityplayermp.c.b().a()) && (i4 <= 0 || entityplayermp.bH >= i4) && entityplayermp.bH <= i5) {
((List) object).add(entityplayermp);
}
}
}
if (chunkcoordinates != null) {
Collections.sort((List) object, new PlayerPositionComparator(chunkcoordinates));
}
if (flag0) {
Collections.reverse((List) object);
}
if (i2 > 0) {
object = ((List) object).subList(0, Math.min(i2, ((List) object).size()));
}
return (List) object;
}
}
private boolean a(EntityPlayer entityplayer, Map map) {
if (map != null && map.size() != 0) {
Iterator iterator = map.entrySet().iterator();
Entry entry;
boolean flag0;
int i0;
do {
if (!iterator.hasNext()) {
return true;
}
entry = (Entry) iterator.next();
String s0 = (String) entry.getKey();
flag0 = false;
if (s0.endsWith("_min") && s0.length() > 4) {
flag0 = true;
s0 = s0.substring(0, s0.length() - 4);
}
Scoreboard scoreboard = entityplayer.bH();
ScoreObjective scoreobjective = scoreboard.b(s0);
if (scoreobjective == null) {
return false;
}
Score score = entityplayer.bH().a(entityplayer.al(), scoreobjective);
i0 = score.c();
if (i0 < ((Integer) entry.getValue()).intValue() && flag0) {
return false;
}
}
while (i0 <= ((Integer) entry.getValue()).intValue() || flag0);
return false;
} else {
return true;
}
}
public void a(double d0, double d1, double d2, double d3, int i0, Packet packet) {
this.a((EntityPlayer) null, d0, d1, d2, d3, i0, packet);
}
public void a(EntityPlayer entityplayer, double d0, double d1, double d2, double d3, int i0, Packet packet) {
for (int i1 = 0; i1 < this.a.size(); ++i1) {
EntityPlayerMP entityplayermp = (EntityPlayerMP) this.a.get(i1);
if (entityplayermp != entityplayer && entityplayermp.ar == i0) {
double d4 = d0 - entityplayermp.u;
double d5 = d1 - entityplayermp.v;
double d6 = d2 - entityplayermp.w;
if (d4 * d4 + d5 * d5 + d6 * d6 < d3 * d3) {
entityplayermp.a.b(packet);
}
}
}
}
public void g() {
for (int i0 = 0; i0 < this.a.size(); ++i0) {
this.b((EntityPlayerMP) this.a.get(i0));
}
}
public void g(String s0) {
this.i.add(s0);
}
public void h(String s0) {
this.i.remove(s0);
}
public Set h() {
return this.i;
}
public Set i() {
return this.h;
}
public void j() {}
public void b(EntityPlayerMP entityplayermp, WorldServer worldserver) {
entityplayermp.a.b(new Packet4UpdateTime(worldserver.I(), worldserver.J(), worldserver.O().b("doDaylightCycle")));
if (worldserver.Q()) {
entityplayermp.a.b(new Packet70GameEvent(1, 0));
}
}
public void f(EntityPlayerMP entityplayermp) {
entityplayermp.a(entityplayermp.bo);
entityplayermp.m();
entityplayermp.a.b(new Packet16BlockItemSwitch(entityplayermp.bn.c));
}
public int k() {
return this.a.size();
}
public int l() {
return this.b;
}
public String[] m() {
WorldServer srv = (WorldServer) ((CanaryWorld) Canary.getServer().getDefaultWorld()).getHandle();
return srv.M().e().f();
}
public boolean n() {
return this.k;
}
public void a(boolean flag0) {
this.k = flag0;
}
public List i(String s0) {
ArrayList arraylist = new ArrayList();
Iterator iterator = this.a.iterator();
while (iterator.hasNext()) {
EntityPlayerMP entityplayermp = (EntityPlayerMP) iterator.next();
if (entityplayermp.q().equals(s0)) {
arraylist.add(entityplayermp);
}
}
return arraylist;
}
public int o() {
return this.c;
}
public MinecraftServer p() {
return this.e;
}
public NBTTagCompound q() {
return null;
}
private void a(EntityPlayerMP entityplayermp, EntityPlayerMP entityplayermp1, World world) {
// CanaryMod always use world!
// if (entityplayermp1 != null) {
// entityplayermp.c.a(entityplayermp1.c.b());
// } else if (this.l != null) {
// entityplayermp.c.a(this.l);
// }
entityplayermp.c.b(world.N().r());
}
public void a(ChatMessageComponent chatmessagecomponent) {
this.a(chatmessagecomponent, true);
}
public void r() {
// CanaryMod shutdown hook
ServerShutdownHook hook = (ServerShutdownHook) new ServerShutdownHook("Server closed").call();
//
while (!this.a.isEmpty()) {
((EntityPlayerMP) this.a.get(0)).a.c(hook.getReason());
}
}
public void a(ChatMessageComponent chatmessagecomponent, boolean flag0) {
this.e.a(chatmessagecomponent);
this.a((Packet) (new Packet3Chat(chatmessagecomponent, flag0)));
}
/**
* Get the configuration management wrapper
*
* @return the canary configuration manager
*/
public CanaryConfigurationManager getConfigurationManager() {
return configurationmanager;
}
// This is a CanaryMod method
/**
* Send a packet to a specified player.
*
* @param player
* @param packet
*/
public void sendPacketToPlayer(CanaryPlayer player, CanaryPacket packet) {
if (a.contains(player.getHandle())) {
player.getHandle().a.b(packet.getPacket());
}
}
}
| true | true | public EntityPlayerMP a(EntityPlayerMP entityplayermp, int i0, boolean flag0, Location loc) {
entityplayermp.p().q().a(entityplayermp);
entityplayermp.p().q().b(entityplayermp);
entityplayermp.p().s().c(entityplayermp);
this.a.remove(entityplayermp);
this.e.a(entityplayermp.ar).f(entityplayermp);
// ChunkCoordinates chunkcoordinates = entityplayermp.bA(); //CanaryMod removed in favor of a real location
Location respawnLocation = entityplayermp.getRespawnLocation();
boolean flag1 = entityplayermp.bB();
boolean isBedSpawn = respawnLocation != null;
entityplayermp.ar = i0;
Object object;
String name = entityplayermp.getCanaryWorld().getName();
net.canarymod.api.world.DimensionType type = net.canarymod.api.world.DimensionType.fromId(i0);
// CanaryMod: PlayerRespawn
PlayerRespawnHook hook = (PlayerRespawnHook) new PlayerRespawnHook(entityplayermp.getPlayer(), loc, isBedSpawn).call();
loc = hook.getRespawnLocation();
WorldServer worldserver = (WorldServer) (loc == null ? (WorldServer) ((CanaryWorld) Canary.getServer().getWorldManager().getWorld(name, type, true)).getHandle() : ((CanaryWorld) loc.getWorld()).getHandle());
// CanaryMod changes to accommodate multiworld bed spawns
ChunkCoordinates chunkcoordinates = null;
if (respawnLocation != null) {
chunkcoordinates = new ChunkCoordinates(respawnLocation.getBlockX(), respawnLocation.getBlockY(), respawnLocation.getBlockZ());
// Check if the spawn world differs from the expected one and adjust
if (!worldserver.equals(((CanaryWorld) respawnLocation.getWorld()).getHandle())) {
worldserver = (WorldServer) ((CanaryWorld) respawnLocation.getWorld()).getHandle();
}
}
if (loc != null) {
chunkcoordinates = new ChunkCoordinates(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
// Check if the spawn world differs from the expected one and adjust
if (!worldserver.equals(((CanaryWorld) loc.getWorld()).getHandle())) {
worldserver = (WorldServer) ((CanaryWorld) loc.getWorld()).getHandle();
}
respawnLocation = loc;
}
//
if (this.e.O()) {
object = new DemoWorldManager(worldserver);
} else {
object = new ItemInWorldManager(worldserver);
}
EntityPlayerMP entityplayermp1 = new EntityPlayerMP(this.e, worldserver, entityplayermp.c_(), (ItemInWorldManager) object);
// Copy netserverhandler as the connection is still the same
entityplayermp1.a = entityplayermp.a;
entityplayermp1.a(entityplayermp, flag0);
entityplayermp1.k = entityplayermp.k;
entityplayermp1.a.c = entityplayermp1;
this.a(entityplayermp1, entityplayermp, worldserver); // XXX
ChunkCoordinates chunkcoordinates1;
if (chunkcoordinates != null) {
chunkcoordinates1 = EntityPlayer.a(worldserver, chunkcoordinates, flag1);
if (chunkcoordinates1 != null) {
entityplayermp1.b((double) ((float) chunkcoordinates1.a + 0.5F), (double) ((float) chunkcoordinates1.b + 0.1F), (double) ((float) chunkcoordinates1.c + 0.5F), 0.0F, 0.0F);
entityplayermp1.a(chunkcoordinates, flag1);
} else {
if (isBedSpawn) {
entityplayermp1.a.b(new Packet70GameEvent(0, 0));
}
}
}
worldserver.b.c((int) entityplayermp1.u >> 4, (int) entityplayermp1.w >> 4);
entityplayermp1.a.b(new Packet9Respawn(entityplayermp1.ar, (byte) entityplayermp1.q.r, entityplayermp1.q.N().u(), entityplayermp1.q.R(), entityplayermp1.c.b()));
entityplayermp1.a.b(new Packet9Respawn(entityplayermp1.ar, (byte) entityplayermp1.q.r, entityplayermp1.q.N().u(), entityplayermp1.q.R(), entityplayermp1.c.b()));
// CanaryMod: Adjust the data for the respawn packet by using player coordinates instead!
chunkcoordinates1 = worldserver.K();
// CanaryMod changed old logic with this one, this suffices and is, for some reason, more reliable
while (worldserver.getCanaryWorld().getBlockAt(ToolBox.floorToBlock(entityplayermp1.u), ToolBox.floorToBlock(entityplayermp1.v + 1), ToolBox.floorToBlock(entityplayermp1.w)).getTypeId() != 0) {
entityplayermp1.v = entityplayermp1.v + 1D;
}
entityplayermp1.a.a(entityplayermp1.u, entityplayermp1.v, entityplayermp1.w, entityplayermp1.A, entityplayermp1.B, entityplayermp1.getCanaryWorld().getType().getId(), entityplayermp1.getCanaryWorld().getName(), TeleportHook.TeleportCause.RESPAWN);
entityplayermp1.a.b(new Packet6SpawnPosition((int) entityplayermp1.u, (int) entityplayermp1.v, (int) entityplayermp1.w)); // CanaryMod changed used data to player coords
entityplayermp1.a.b(new Packet43Experience(entityplayermp1.bJ, entityplayermp1.bI, entityplayermp1.bH));
this.b(entityplayermp1, worldserver);
worldserver.s().a(entityplayermp1);
worldserver.d(entityplayermp1);
this.a.add(entityplayermp1);
entityplayermp1.d();
entityplayermp1.g(entityplayermp1.aJ());
//
return entityplayermp1;
}
| public EntityPlayerMP a(EntityPlayerMP entityplayermp, int i0, boolean flag0, Location loc) {
entityplayermp.p().q().a(entityplayermp);
entityplayermp.p().q().b(entityplayermp);
entityplayermp.p().s().c(entityplayermp);
this.a.remove(entityplayermp);
this.e.getWorld(entityplayermp.getCanaryWorld().getName(), entityplayermp.ar).f(entityplayermp); // CanaryMod: added multiworld support
// ChunkCoordinates chunkcoordinates = entityplayermp.bA(); //CanaryMod removed in favor of a real location
Location respawnLocation = entityplayermp.getRespawnLocation();
boolean flag1 = entityplayermp.bB();
boolean isBedSpawn = respawnLocation != null;
entityplayermp.ar = i0;
Object object;
String name = entityplayermp.getCanaryWorld().getName();
net.canarymod.api.world.DimensionType type = net.canarymod.api.world.DimensionType.fromId(i0);
// CanaryMod: PlayerRespawn
PlayerRespawnHook hook = (PlayerRespawnHook) new PlayerRespawnHook(entityplayermp.getPlayer(), loc, isBedSpawn).call();
loc = hook.getRespawnLocation();
WorldServer worldserver = (WorldServer) (loc == null ? (WorldServer) ((CanaryWorld) Canary.getServer().getWorldManager().getWorld(name, type, true)).getHandle() : ((CanaryWorld) loc.getWorld()).getHandle());
// CanaryMod changes to accommodate multiworld bed spawns
ChunkCoordinates chunkcoordinates = null;
if (respawnLocation != null) {
chunkcoordinates = new ChunkCoordinates(respawnLocation.getBlockX(), respawnLocation.getBlockY(), respawnLocation.getBlockZ());
// Check if the spawn world differs from the expected one and adjust
if (!worldserver.equals(((CanaryWorld) respawnLocation.getWorld()).getHandle())) {
worldserver = (WorldServer) ((CanaryWorld) respawnLocation.getWorld()).getHandle();
}
}
if (loc != null) {
chunkcoordinates = new ChunkCoordinates(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
// Check if the spawn world differs from the expected one and adjust
if (!worldserver.equals(((CanaryWorld) loc.getWorld()).getHandle())) {
worldserver = (WorldServer) ((CanaryWorld) loc.getWorld()).getHandle();
}
respawnLocation = loc;
}
//
if (this.e.O()) {
object = new DemoWorldManager(worldserver);
} else {
object = new ItemInWorldManager(worldserver);
}
EntityPlayerMP entityplayermp1 = new EntityPlayerMP(this.e, worldserver, entityplayermp.c_(), (ItemInWorldManager) object);
// Copy netserverhandler as the connection is still the same
entityplayermp1.a = entityplayermp.a;
entityplayermp1.a(entityplayermp, flag0);
entityplayermp1.k = entityplayermp.k;
entityplayermp1.a.c = entityplayermp1;
this.a(entityplayermp1, entityplayermp, worldserver); // XXX
ChunkCoordinates chunkcoordinates1;
if (chunkcoordinates != null) {
chunkcoordinates1 = EntityPlayer.a(worldserver, chunkcoordinates, flag1);
if (chunkcoordinates1 != null) {
entityplayermp1.b((double) ((float) chunkcoordinates1.a + 0.5F), (double) ((float) chunkcoordinates1.b + 0.1F), (double) ((float) chunkcoordinates1.c + 0.5F), 0.0F, 0.0F);
entityplayermp1.a(chunkcoordinates, flag1);
} else {
if (isBedSpawn) {
entityplayermp1.a.b(new Packet70GameEvent(0, 0));
}
}
}
worldserver.b.c((int) entityplayermp1.u >> 4, (int) entityplayermp1.w >> 4);
entityplayermp1.a.b(new Packet9Respawn(entityplayermp1.ar, (byte) entityplayermp1.q.r, entityplayermp1.q.N().u(), entityplayermp1.q.R(), entityplayermp1.c.b()));
entityplayermp1.a.b(new Packet9Respawn(entityplayermp1.ar, (byte) entityplayermp1.q.r, entityplayermp1.q.N().u(), entityplayermp1.q.R(), entityplayermp1.c.b()));
// CanaryMod: Adjust the data for the respawn packet by using player coordinates instead!
chunkcoordinates1 = worldserver.K();
// CanaryMod changed old logic with this one, this suffices and is, for some reason, more reliable
while (worldserver.getCanaryWorld().getBlockAt(ToolBox.floorToBlock(entityplayermp1.u), ToolBox.floorToBlock(entityplayermp1.v + 1), ToolBox.floorToBlock(entityplayermp1.w)).getTypeId() != 0) {
entityplayermp1.v = entityplayermp1.v + 1D;
}
entityplayermp1.a.a(entityplayermp1.u, entityplayermp1.v, entityplayermp1.w, entityplayermp1.A, entityplayermp1.B, entityplayermp1.getCanaryWorld().getType().getId(), entityplayermp1.getCanaryWorld().getName(), TeleportHook.TeleportCause.RESPAWN);
entityplayermp1.a.b(new Packet6SpawnPosition((int) entityplayermp1.u, (int) entityplayermp1.v, (int) entityplayermp1.w)); // CanaryMod changed used data to player coords
entityplayermp1.a.b(new Packet43Experience(entityplayermp1.bJ, entityplayermp1.bI, entityplayermp1.bH));
this.b(entityplayermp1, worldserver);
worldserver.s().a(entityplayermp1);
worldserver.d(entityplayermp1);
this.a.add(entityplayermp1);
entityplayermp1.d();
entityplayermp1.g(entityplayermp1.aJ());
//
return entityplayermp1;
}
|
diff --git a/MarketSim/src/Market.java b/MarketSim/src/Market.java
index 6e42ceb..cbf2957 100644
--- a/MarketSim/src/Market.java
+++ b/MarketSim/src/Market.java
@@ -1,265 +1,259 @@
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Market {
public Commodity[] commodities;
public Agent[] agents;
public BufferedWriter bwMarket;
public BufferedWriter bwCommodities;
private HashMap<Commodity, ArrayList<Bid>> buyBids;
private HashMap<Commodity, ArrayList<Bid>> sellBids;
private HashMap<Commodity, ArrayList<Bid>> shuffledSellBids;
private HashMap<Commodity, ArrayList<Bid>> shuffledBuyBids;
public Market()
{
}
/**
* Goes through one round.
* Clears the bids, updates the agents, and completes transactions.
*/
public void update()
{
emptyBidLists();
requestAgentBids();
shuffleBids();
matchAndExecuteTrades();
printMarketInformation();
}
private void emptyBidLists(){
buyBids = new HashMap<Commodity, ArrayList<Bid>>();
sellBids = new HashMap<Commodity, ArrayList<Bid>>();
shuffledBuyBids = new HashMap<Commodity, ArrayList<Bid>>();
shuffledSellBids = new HashMap<Commodity, ArrayList<Bid>>();
for (Commodity commodity : commodities){
buyBids.put(commodity, new ArrayList<Bid>());
sellBids.put(commodity, new ArrayList<Bid>());
shuffledBuyBids.put(commodity, new ArrayList<Bid>());
shuffledSellBids.put(commodity, new ArrayList<Bid>());
}
}
/**
* Tell the agents to update themselves and submit their bids
*/
private void requestAgentBids(){
for (Commodity commodity : commodities){
commodity.consumption = 0;
}
for (Agent agent : agents) {
agent.update();
}
}
/**
* Prints out the current simulation information TODO: turn datapoints into csv / excell file to analyze
*/
public void printMarketInformation(){
System.out.println("Trading cycle complete");
System.out.println("______________________");
System.out.println("Current market prices:");
String marketcsvline = "";
String entitiescsvline = "";
for (Commodity commodity : commodities){
System.out.println(commodity.name + ": " + commodity.marketprice);
marketcsvline = marketcsvline + commodity.marketprice + ",";
entitiescsvline = entitiescsvline + commodity.consumption + ",";
}
double budgetvar = budgetVariance();
entitiescsvline = entitiescsvline + budgetvar;
System.out.println("Current budgets:");
for (Agent agent : agents) {
System.out.println(agent.name + ": " + agent.budget);
}
System.out.println("______________________");
try {
bwMarket.write(marketcsvline.substring(0, marketcsvline.length()-1));
bwCommodities.write(entitiescsvline);
bwMarket.newLine();
bwMarket.flush();
bwCommodities.newLine();
bwCommodities.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public double budgetVariance()
{
double avg = 0;
for(Agent agent: agents)
{
avg = avg + agent.budget;
}
avg = avg / agents.length;
double variance = 0;
for(Agent agent: agents)
{
variance = variance + Math.pow(avg - agent.budget, 2);
}
variance = variance / agents.length;
return variance;
}
/**
* Accept a bid submitted by a user
* @param bid
*/
public void acceptBid(Bid bid)
{
Commodity bidCommodity = bid.commodity;
switch(bid.type){
case BUY:
ArrayList<Bid> buyBidList = buyBids.get(bidCommodity);
buyBidList.add(bid);
buyBids.put(bidCommodity, buyBidList);
break;
case SELL:
ArrayList<Bid> sellBidList = sellBids.get(bidCommodity);
sellBidList.add(bid);
sellBids.put(bidCommodity, sellBidList);
break;
}
}
/**
* Shuffles the submitted bids and processes transactions for matches.
*/
private void shuffleBids()
{
/*
Shuffle sell bids and buy bids
*/
for (Commodity commodity : commodities){
ArrayList<Bid> listOfBuyBidsToShuffle = buyBids.get(commodity);
Collections.shuffle(listOfBuyBidsToShuffle);
shuffledBuyBids.put(commodity,listOfBuyBidsToShuffle);
ArrayList<Bid> listOfSellBidsToShuffle = sellBids.get(commodity);
Collections.shuffle(listOfSellBidsToShuffle);
shuffledSellBids.put(commodity, listOfSellBidsToShuffle);
}
}
/**
* Calculates the current market price. TODO: Configurable
*/
private void matchAndExecuteTrades(){
for (Commodity commodity : commodities){
{
double newMarketPrice = 0;
int quantitySold = 0;
ArrayList<Bid> buyList = shuffledBuyBids.get(commodity);
ArrayList<Bid> sellList = shuffledSellBids.get(commodity);
for (Bid buyBid : buyList) {
for (Bid sellBid : sellList) {
if (sellBid.quantity != 0 && buyBid.price >= sellBid.price) {
int maxBuyAmount = (int) Math.ceil((Math.log(sellBid.price * 1.0 / buyBid.price) / Math.log(1 / buyBid.marginalscalefactor))) + 1;
int maxBuyAmount2 = (int) (buyBid.spendingcap / sellBid.price);
- maxBuyAmount = Math.min(maxBuyAmount, maxBuyAmount2);
- int buyAmount = 0;
- if (maxBuyAmount >= sellBid.quantity) {
- buyAmount = buyBid.quantity;
- } else {
- buyAmount = maxBuyAmount;
- }
+ int buyAmount = Math.min(Math.min(maxBuyAmount, maxBuyAmount2), sellBid.quantity);
if (buyAmount > 0) {
if (buyAmount >= sellBid.quantity) {
transaction(buyBid.agent, sellBid.agent, sellBid.commodity, sellBid.quantity, sellBid.quantity * sellBid.price);
buyBid.spendingcap = buyBid.spendingcap - sellBid.quantity * sellBid.price;
buyBid.price = buyBid.price * Math.pow((1 / buyBid.marginalscalefactor), sellBid.quantity);
quantitySold = quantitySold + sellBid.quantity;
newMarketPrice = newMarketPrice + sellBid.quantity * sellBid.price;
buyBid.quantity = buyBid.quantity - sellBid.quantity;
sellBid.quantity = 0;
- if (buyBid.quantity == 0) {
+ if (buyBid.quantity <= 0) {
break;
}
} else {
transaction(buyBid.agent, sellBid.agent, sellBid.commodity, buyAmount, buyAmount * sellBid.price);
buyBid.spendingcap = buyBid.spendingcap - buyAmount * sellBid.price;
buyBid.price = buyBid.price * Math.pow((1 / buyBid.marginalscalefactor), buyAmount);
quantitySold = quantitySold + buyAmount;
newMarketPrice = newMarketPrice + buyAmount * sellBid.price;
sellBid.quantity = sellBid.quantity - buyAmount;
buyBid.quantity = buyBid.quantity - buyAmount;
- if (buyBid.quantity == 0) {
+ if (buyBid.quantity <= 0) {
break;
}
}
}
}
}
}
if (quantitySold > 0)
{
newMarketPrice = newMarketPrice / quantitySold;
}
else
{
double highestbuy = 0;
double lowestsell = Double.MAX_VALUE;
for (Bid buybid : buyList) {
if (buybid.price > highestbuy) {
highestbuy = buybid.price;
}
}
for (Bid sellBid : sellList) {
if (sellBid.price < lowestsell) {
lowestsell = sellBid.price;
}
}
if (highestbuy > 0)
{
if(lowestsell < Double.MAX_VALUE)
newMarketPrice = (highestbuy + lowestsell) / 2;
else
newMarketPrice = highestbuy;
}
else
{
if(lowestsell < Double.MAX_VALUE)
newMarketPrice = lowestsell;
else
newMarketPrice = -1;
}
}
commodity.marketprice = newMarketPrice;
}
}
}
/**
* Services a transaction between a buyer and a seller
* @param buyer
* @param seller
* @param commodity
* @param quantity
* @param price
*/
private void transaction(Agent buyer, Agent seller, Commodity commodity, int quantity, double price)
{
buyer.budget = buyer.budget - price;
seller.budget = seller.budget + price;
buyer.inventory.put(commodity, buyer.inventory.get(commodity) + quantity);
seller.inventory.put(commodity, seller.inventory.get(commodity) - quantity);
System.out.println(buyer.name + " bought " + quantity + " units of " + commodity.name + " from " + seller.name + " at " + price/quantity + " galactic intracredits each");
}
}
| false | true | private void matchAndExecuteTrades(){
for (Commodity commodity : commodities){
{
double newMarketPrice = 0;
int quantitySold = 0;
ArrayList<Bid> buyList = shuffledBuyBids.get(commodity);
ArrayList<Bid> sellList = shuffledSellBids.get(commodity);
for (Bid buyBid : buyList) {
for (Bid sellBid : sellList) {
if (sellBid.quantity != 0 && buyBid.price >= sellBid.price) {
int maxBuyAmount = (int) Math.ceil((Math.log(sellBid.price * 1.0 / buyBid.price) / Math.log(1 / buyBid.marginalscalefactor))) + 1;
int maxBuyAmount2 = (int) (buyBid.spendingcap / sellBid.price);
maxBuyAmount = Math.min(maxBuyAmount, maxBuyAmount2);
int buyAmount = 0;
if (maxBuyAmount >= sellBid.quantity) {
buyAmount = buyBid.quantity;
} else {
buyAmount = maxBuyAmount;
}
if (buyAmount > 0) {
if (buyAmount >= sellBid.quantity) {
transaction(buyBid.agent, sellBid.agent, sellBid.commodity, sellBid.quantity, sellBid.quantity * sellBid.price);
buyBid.spendingcap = buyBid.spendingcap - sellBid.quantity * sellBid.price;
buyBid.price = buyBid.price * Math.pow((1 / buyBid.marginalscalefactor), sellBid.quantity);
quantitySold = quantitySold + sellBid.quantity;
newMarketPrice = newMarketPrice + sellBid.quantity * sellBid.price;
buyBid.quantity = buyBid.quantity - sellBid.quantity;
sellBid.quantity = 0;
if (buyBid.quantity == 0) {
break;
}
} else {
transaction(buyBid.agent, sellBid.agent, sellBid.commodity, buyAmount, buyAmount * sellBid.price);
buyBid.spendingcap = buyBid.spendingcap - buyAmount * sellBid.price;
buyBid.price = buyBid.price * Math.pow((1 / buyBid.marginalscalefactor), buyAmount);
quantitySold = quantitySold + buyAmount;
newMarketPrice = newMarketPrice + buyAmount * sellBid.price;
sellBid.quantity = sellBid.quantity - buyAmount;
buyBid.quantity = buyBid.quantity - buyAmount;
if (buyBid.quantity == 0) {
break;
}
}
}
}
}
}
if (quantitySold > 0)
{
newMarketPrice = newMarketPrice / quantitySold;
}
else
{
double highestbuy = 0;
double lowestsell = Double.MAX_VALUE;
for (Bid buybid : buyList) {
if (buybid.price > highestbuy) {
highestbuy = buybid.price;
}
}
for (Bid sellBid : sellList) {
if (sellBid.price < lowestsell) {
lowestsell = sellBid.price;
}
}
if (highestbuy > 0)
{
if(lowestsell < Double.MAX_VALUE)
newMarketPrice = (highestbuy + lowestsell) / 2;
else
newMarketPrice = highestbuy;
}
else
{
if(lowestsell < Double.MAX_VALUE)
newMarketPrice = lowestsell;
else
newMarketPrice = -1;
}
}
commodity.marketprice = newMarketPrice;
}
}
}
| private void matchAndExecuteTrades(){
for (Commodity commodity : commodities){
{
double newMarketPrice = 0;
int quantitySold = 0;
ArrayList<Bid> buyList = shuffledBuyBids.get(commodity);
ArrayList<Bid> sellList = shuffledSellBids.get(commodity);
for (Bid buyBid : buyList) {
for (Bid sellBid : sellList) {
if (sellBid.quantity != 0 && buyBid.price >= sellBid.price) {
int maxBuyAmount = (int) Math.ceil((Math.log(sellBid.price * 1.0 / buyBid.price) / Math.log(1 / buyBid.marginalscalefactor))) + 1;
int maxBuyAmount2 = (int) (buyBid.spendingcap / sellBid.price);
int buyAmount = Math.min(Math.min(maxBuyAmount, maxBuyAmount2), sellBid.quantity);
if (buyAmount > 0) {
if (buyAmount >= sellBid.quantity) {
transaction(buyBid.agent, sellBid.agent, sellBid.commodity, sellBid.quantity, sellBid.quantity * sellBid.price);
buyBid.spendingcap = buyBid.spendingcap - sellBid.quantity * sellBid.price;
buyBid.price = buyBid.price * Math.pow((1 / buyBid.marginalscalefactor), sellBid.quantity);
quantitySold = quantitySold + sellBid.quantity;
newMarketPrice = newMarketPrice + sellBid.quantity * sellBid.price;
buyBid.quantity = buyBid.quantity - sellBid.quantity;
sellBid.quantity = 0;
if (buyBid.quantity <= 0) {
break;
}
} else {
transaction(buyBid.agent, sellBid.agent, sellBid.commodity, buyAmount, buyAmount * sellBid.price);
buyBid.spendingcap = buyBid.spendingcap - buyAmount * sellBid.price;
buyBid.price = buyBid.price * Math.pow((1 / buyBid.marginalscalefactor), buyAmount);
quantitySold = quantitySold + buyAmount;
newMarketPrice = newMarketPrice + buyAmount * sellBid.price;
sellBid.quantity = sellBid.quantity - buyAmount;
buyBid.quantity = buyBid.quantity - buyAmount;
if (buyBid.quantity <= 0) {
break;
}
}
}
}
}
}
if (quantitySold > 0)
{
newMarketPrice = newMarketPrice / quantitySold;
}
else
{
double highestbuy = 0;
double lowestsell = Double.MAX_VALUE;
for (Bid buybid : buyList) {
if (buybid.price > highestbuy) {
highestbuy = buybid.price;
}
}
for (Bid sellBid : sellList) {
if (sellBid.price < lowestsell) {
lowestsell = sellBid.price;
}
}
if (highestbuy > 0)
{
if(lowestsell < Double.MAX_VALUE)
newMarketPrice = (highestbuy + lowestsell) / 2;
else
newMarketPrice = highestbuy;
}
else
{
if(lowestsell < Double.MAX_VALUE)
newMarketPrice = lowestsell;
else
newMarketPrice = -1;
}
}
commodity.marketprice = newMarketPrice;
}
}
}
|
diff --git a/openFacesInspectors/source/org/seleniuminspector/openfaces/InputTextFilterInspector.java b/openFacesInspectors/source/org/seleniuminspector/openfaces/InputTextFilterInspector.java
index 8f37db764..1ba2b2221 100644
--- a/openFacesInspectors/source/org/seleniuminspector/openfaces/InputTextFilterInspector.java
+++ b/openFacesInspectors/source/org/seleniuminspector/openfaces/InputTextFilterInspector.java
@@ -1,40 +1,40 @@
/*
* OpenFaces - JSF Component Library 2.0
* Copyright (C) 2007-2010, TeamDev Ltd.
* [email protected]
* Unless agreed in writing the contents of this file are subject to
* the GNU Lesser General Public License Version 2.1 (the "LGPL" License).
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* Please visit http://openfaces.org/licensing/ for more details.
*/
package org.seleniuminspector.openfaces;
import org.seleniuminspector.LoadingMode;
/**
* @author Andrii Gorbatov
*/
public class InputTextFilterInspector extends AbstractFilterInspector {
public InputTextFilterInspector(String locator, LoadingMode loadingMode) {
super(locator, loadingMode);
}
public InputTextInspector searchComponent() {
return new InputTextInspector(getLocator());
}
public void makeFiltering(String filterValue) {
InputTextInspector searchComponent = searchComponent();
searchComponent.type(filterValue);
searchComponent.setCursorPosition(0);
- sleep(100);
+ sleep(1000);
searchComponent.keyDown(13);
getLoadingMode().waitForLoad();
}
}
| true | true | public void makeFiltering(String filterValue) {
InputTextInspector searchComponent = searchComponent();
searchComponent.type(filterValue);
searchComponent.setCursorPosition(0);
sleep(100);
searchComponent.keyDown(13);
getLoadingMode().waitForLoad();
}
| public void makeFiltering(String filterValue) {
InputTextInspector searchComponent = searchComponent();
searchComponent.type(filterValue);
searchComponent.setCursorPosition(0);
sleep(1000);
searchComponent.keyDown(13);
getLoadingMode().waitForLoad();
}
|
diff --git a/grails-maven-plugin/src/main/java/org/grails/maven/plugin/AbstractGrailsMojo.java b/grails-maven-plugin/src/main/java/org/grails/maven/plugin/AbstractGrailsMojo.java
index 59732e9b3..6394c7531 100644
--- a/grails-maven-plugin/src/main/java/org/grails/maven/plugin/AbstractGrailsMojo.java
+++ b/grails-maven-plugin/src/main/java/org/grails/maven/plugin/AbstractGrailsMojo.java
@@ -1,357 +1,356 @@
/*
* Copyright 2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.grails.maven.plugin;
import org.grails.maven.plugin.tools.GrailsServices;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.ArtifactCollector;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.artifact.MavenMetadataSource;
import org.apache.maven.model.Dependency;
import org.codehaus.groovy.grails.cli.support.GrailsRootLoader;
import org.codehaus.groovy.grails.cli.support.GrailsBuildHelper;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.*;
/**
* Common services for all Mojos using Grails
*
* @author <a href="mailto:[email protected]">Arnaud HERITIER</a>
* @author Peter Ledbrook
* @version $Id$
*/
public abstract class AbstractGrailsMojo extends AbstractMojo {
/**
* The directory where is launched the mvn command.
*
* @parameter default-value="${basedir}"
* @required
*/
protected File basedir;
/**
* The Grails environment to use.
*
* @parameter expression="${grails.env}"
*/
protected String env;
/**
* The directory where is launched the mvn command.
*
* @parameter expression="${nonInteractive}" default-value="false"
* @required
*/
protected boolean nonInteractive;
/**
* POM
*
* @parameter expression="${project}"
* @readonly
* @required
*/
protected MavenProject project;
/**
* @component
*/
private ArtifactResolver artifactResolver;
/**
* @component
*/
private ArtifactFactory artifactFactory;
/**
* @component
*/
private ArtifactCollector artifactCollector;
/**
* @component
*/
private ArtifactMetadataSource artifactMetadataSource;
/**
* @parameter expression="${localRepository}"
* @required
* @readonly
*/
private ArtifactRepository localRepository;
/**
* @parameter expression="${project.remoteArtifactRepositories}"
* @required
* @readonly
*/
private List remoteRepositories;
/**
* @component
*/
private MavenProjectBuilder projectBuilder;
/**
* @component
* @readonly
*/
private GrailsServices grailsServices;
protected File getBasedir() {
if(basedir == null) {
throw new RuntimeException("Your subclass have a field called 'basedir'. Remove it and use getBasedir() " +
"instead.");
}
return this.basedir;
}
/**
* OutputStream to write the content of stdout.
*/
private OutputStream infoOutputStream = new OutputStream() {
StringBuffer buffer = new StringBuffer();
public void write(int b) throws IOException {
if (b == '\n') {
getLog().info(buffer.toString());
buffer.setLength(0);
} else {
buffer.append((char) b);
}
}
};
/**
* OutputStream to write the content of stderr.
*/
private OutputStream warnOutputStream = new OutputStream() {
StringBuffer buffer = new StringBuffer();
public void write(int b) throws IOException {
if (b == '\n') {
getLog().warn(buffer.toString());
buffer.setLength(0);
} else {
buffer.append((char) b);
}
}
};
protected GrailsServices getGrailsServices() throws MojoExecutionException {
grailsServices.setBasedir(basedir);
return grailsServices;
}
protected void runGrails(String targetName) throws MojoExecutionException {
runGrails(targetName, null, false);
}
protected void runGrails(String targetName, String args, boolean includeProjectDeps) throws MojoExecutionException {
// First get the dependencies specified by the plugin.
Set deps = getGrailsPluginDependencies();
// Now add the project dependencies if necessary.
if (includeProjectDeps) {
deps.addAll(this.project.getRuntimeArtifacts());
}
URL[] classpath;
try {
classpath = new URL[deps.size() + 1];
int index = 0;
for (Iterator iter = deps.iterator(); iter.hasNext();) {
classpath[index++] = ((Artifact) iter.next()).getFile().toURI().toURL();
}
// Add the "tools.jar" to the classpath so that the Grails
// scripts can run native2ascii. First assume that "java.home"
// points to a JRE within a JDK.
String javaHome = System.getProperty("java.home");
File toolsJar = new File(javaHome, "../lib/tools.jar");
if (!toolsJar.exists()) {
// The "tools.jar" cannot be found with that path, so
// now try with the assumption that "java.home" points
// to a JDK.
toolsJar = new File(javaHome, "tools.jar");
}
classpath[classpath.length - 1] = toolsJar.toURI().toURL();
- System.setProperty("base.dir", basedir.getAbsolutePath());
GrailsRootLoader rootLoader = new GrailsRootLoader(classpath, getClass().getClassLoader());
- GrailsBuildHelper helper = new GrailsBuildHelper(rootLoader);
+ GrailsBuildHelper helper = new GrailsBuildHelper(rootLoader, null, basedir.getAbsolutePath());
configureBuildSettings(helper);
// mainClass.getDeclaredMethod("setOut", new Class[]{ PrintStream.class }).invoke(
// scriptRunner,
// new Object[] { new PrintStream(infoOutputStream) });
// If the command is running in non-interactive mode, we
// need to pass on the relevant argument.
if (this.nonInteractive) {
args = args == null ? "--non-interactive" : "--non-interactive " + args;
}
int retval = helper.execute(targetName, args, env);
if (retval != 0) {
throw new MojoExecutionException("Grails returned non-zero value: " + retval);
}
} catch (MojoExecutionException ex) {
// Simply rethrow it.
throw ex;
} catch (Exception ex) {
throw new MojoExecutionException("Unable to start Grails", ex);
}
}
private Set getGrailsPluginDependencies() throws MojoExecutionException {
Artifact pluginArtifact = findArtifact(this.project.getPluginArtifacts(), "org.grails", "grails-maven-plugin");
MavenProject project = null;
try {
project = this.projectBuilder.buildFromRepository(pluginArtifact,
this.remoteRepositories,
this.localRepository);
} catch (ProjectBuildingException ex) {
throw new MojoExecutionException("Failed to get information about Grails Maven Plugin", ex);
}
List deps = artifactsByGroupId(dependenciesToArtifacts(project.getDependencies()), "org.grails");
Set pluginDependencies = new HashSet();
for (Iterator iter = deps.iterator(); iter.hasNext();) {
pluginDependencies.addAll(getPluginDependencies((Artifact) iter.next()));
}
return pluginDependencies;
}
private void configureBuildSettings(GrailsBuildHelper helper)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, MojoExecutionException, NoSuchMethodException, InvocationTargetException {
String targetDir = this.project.getBuild().getDirectory();
helper.setCompileDependencies(artifactsToFiles(this.project.getCompileArtifacts()));
helper.setTestDependencies(artifactsToFiles(this.project.getTestArtifacts()));
helper.setRuntimeDependencies(artifactsToFiles(this.project.getRuntimeArtifacts()));
helper.setProjectWorkDir(new File(targetDir));
helper.setClassesDir(new File(targetDir, "classes"));
helper.setTestClassesDir(new File(targetDir, "test-classes"));
helper.setResourcesDir(new File(targetDir, "resources"));
helper.setProjectPluginsDir(new File(this.project.getBasedir(), "plugins"));
}
private Set getPluginDependencies(Artifact pom) throws MojoExecutionException {
try {
MavenProject project = this.projectBuilder.buildFromRepository(pom,
this.remoteRepositories,
this.localRepository);
//get all of the dependencies for the executable project
List dependencies = project.getDependencies();
//make Artifacts of all the dependencies
Set dependencyArtifacts =
MavenMetadataSource.createArtifacts(this.artifactFactory, dependencies, null, null, null);
ArtifactResolutionResult result = artifactCollector.collect(
dependencyArtifacts,
project.getArtifact(),
this.localRepository,
this.remoteRepositories,
this.artifactMetadataSource,
null,
Collections.EMPTY_LIST);
dependencyArtifacts.addAll(result.getArtifacts());
//not forgetting the Artifact of the project itself
dependencyArtifacts.add(project.getArtifact());
//resolve all dependencies transitively to obtain a comprehensive list of assemblies
for (Iterator iter = dependencyArtifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
this.artifactResolver.resolve(artifact, this.remoteRepositories, this.localRepository);
}
return dependencyArtifacts;
} catch ( Exception ex ) {
throw new MojoExecutionException("Encountered problems resolving dependencies of the executable " +
"in preparation for its execution.", ex);
}
}
private List artifactsToFiles(Collection artifacts) {
List files = new ArrayList(artifacts.size());
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
files.add(((Artifact) iter.next()).getFile());
}
return files;
}
private Artifact findArtifact(Collection artifacts, String groupId, String artifactId) {
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
if (artifact.getGroupId().equals(groupId) && artifact.getArtifactId().equals(artifactId)) {
return artifact;
}
}
return null;
}
private List artifactsByGroupId(Collection artifacts, String groupId) {
List inGroup = new ArrayList(artifacts.size());
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
if (artifact.getGroupId().equals(groupId)) {
inGroup.add(artifact);
}
}
return inGroup;
}
private List dependenciesToArtifacts(Collection deps) {
List artifacts = new ArrayList(deps.size());
for (Iterator iter = deps.iterator(); iter.hasNext();) {
artifacts.add(dependencyToArtifact((Dependency) iter.next()));
}
return artifacts;
}
private Artifact dependencyToArtifact(Dependency dep) {
return this.artifactFactory.createBuildArtifact(
dep.getGroupId(),
dep.getArtifactId(),
dep.getVersion(),
"pom");
}
}
| false | true | protected void runGrails(String targetName, String args, boolean includeProjectDeps) throws MojoExecutionException {
// First get the dependencies specified by the plugin.
Set deps = getGrailsPluginDependencies();
// Now add the project dependencies if necessary.
if (includeProjectDeps) {
deps.addAll(this.project.getRuntimeArtifacts());
}
URL[] classpath;
try {
classpath = new URL[deps.size() + 1];
int index = 0;
for (Iterator iter = deps.iterator(); iter.hasNext();) {
classpath[index++] = ((Artifact) iter.next()).getFile().toURI().toURL();
}
// Add the "tools.jar" to the classpath so that the Grails
// scripts can run native2ascii. First assume that "java.home"
// points to a JRE within a JDK.
String javaHome = System.getProperty("java.home");
File toolsJar = new File(javaHome, "../lib/tools.jar");
if (!toolsJar.exists()) {
// The "tools.jar" cannot be found with that path, so
// now try with the assumption that "java.home" points
// to a JDK.
toolsJar = new File(javaHome, "tools.jar");
}
classpath[classpath.length - 1] = toolsJar.toURI().toURL();
System.setProperty("base.dir", basedir.getAbsolutePath());
GrailsRootLoader rootLoader = new GrailsRootLoader(classpath, getClass().getClassLoader());
GrailsBuildHelper helper = new GrailsBuildHelper(rootLoader);
configureBuildSettings(helper);
// mainClass.getDeclaredMethod("setOut", new Class[]{ PrintStream.class }).invoke(
// scriptRunner,
// new Object[] { new PrintStream(infoOutputStream) });
// If the command is running in non-interactive mode, we
// need to pass on the relevant argument.
if (this.nonInteractive) {
args = args == null ? "--non-interactive" : "--non-interactive " + args;
}
int retval = helper.execute(targetName, args, env);
if (retval != 0) {
throw new MojoExecutionException("Grails returned non-zero value: " + retval);
}
} catch (MojoExecutionException ex) {
// Simply rethrow it.
throw ex;
} catch (Exception ex) {
throw new MojoExecutionException("Unable to start Grails", ex);
}
}
| protected void runGrails(String targetName, String args, boolean includeProjectDeps) throws MojoExecutionException {
// First get the dependencies specified by the plugin.
Set deps = getGrailsPluginDependencies();
// Now add the project dependencies if necessary.
if (includeProjectDeps) {
deps.addAll(this.project.getRuntimeArtifacts());
}
URL[] classpath;
try {
classpath = new URL[deps.size() + 1];
int index = 0;
for (Iterator iter = deps.iterator(); iter.hasNext();) {
classpath[index++] = ((Artifact) iter.next()).getFile().toURI().toURL();
}
// Add the "tools.jar" to the classpath so that the Grails
// scripts can run native2ascii. First assume that "java.home"
// points to a JRE within a JDK.
String javaHome = System.getProperty("java.home");
File toolsJar = new File(javaHome, "../lib/tools.jar");
if (!toolsJar.exists()) {
// The "tools.jar" cannot be found with that path, so
// now try with the assumption that "java.home" points
// to a JDK.
toolsJar = new File(javaHome, "tools.jar");
}
classpath[classpath.length - 1] = toolsJar.toURI().toURL();
GrailsRootLoader rootLoader = new GrailsRootLoader(classpath, getClass().getClassLoader());
GrailsBuildHelper helper = new GrailsBuildHelper(rootLoader, null, basedir.getAbsolutePath());
configureBuildSettings(helper);
// mainClass.getDeclaredMethod("setOut", new Class[]{ PrintStream.class }).invoke(
// scriptRunner,
// new Object[] { new PrintStream(infoOutputStream) });
// If the command is running in non-interactive mode, we
// need to pass on the relevant argument.
if (this.nonInteractive) {
args = args == null ? "--non-interactive" : "--non-interactive " + args;
}
int retval = helper.execute(targetName, args, env);
if (retval != 0) {
throw new MojoExecutionException("Grails returned non-zero value: " + retval);
}
} catch (MojoExecutionException ex) {
// Simply rethrow it.
throw ex;
} catch (Exception ex) {
throw new MojoExecutionException("Unable to start Grails", ex);
}
}
|
diff --git a/user/src/com/google/gwt/user/client/ui/MenuBar.java b/user/src/com/google/gwt/user/client/ui/MenuBar.java
index 2a4c05c9d..b82d929ab 100644
--- a/user/src/com/google/gwt/user/client/ui/MenuBar.java
+++ b/user/src/com/google/gwt/user/client/ui/MenuBar.java
@@ -1,971 +1,970 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.client.ui;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.ui.PopupPanel.AnimationType;
import java.util.ArrayList;
import java.util.List;
/**
* A standard menu bar widget. A menu bar can contain any number of menu items,
* each of which can either fire a {@link com.google.gwt.user.client.Command} or
* open a cascaded menu bar.
*
* <p>
* <img class='gallery' src='MenuBar.png'/>
* </p>
*
* <h3>CSS Style Rules</h3>
* <ul class='css'>
* <li>.gwt-MenuBar { the menu bar itself }</li>
* <li>.gwt-MenuBar-horizontal { dependent style applied to horizontal menu
* bars }</li>
* <li>.gwt-MenuBar-vertical { dependent style applied to vertical menu bars }</li>
* <li>.gwt-MenuBar .gwt-MenuItem { menu items }</li>
* <li>.gwt-MenuBar .gwt-MenuItem-selected { selected menu items }</li>
* <li>.gwt-MenuBar .gwt-MenuItemSeparator { section breaks between menu items }
* </li>
* <li>.gwt-MenuBar .gwt-MenuItemSeparator .content { inner component of
* section separators } </li>
* </ul>
*
* <p>
* <h3>Example</h3>
* {@example com.google.gwt.examples.MenuBarExample}
* </p>
*/
public class MenuBar extends Widget implements PopupListener, HasAnimation {
/**
* An {@link ImageBundle} that provides images for {@link MenuBar}.
*/
public interface MenuBarImages extends ImageBundle {
/**
* An image indicating a {@link MenuItem} has an associated submenu.
*
* @return a prototype of this image
*/
AbstractImagePrototype menuBarSubMenuIcon();
}
/**
* A bundle containing the RTL versions of the images for MenuBar.
*
* Notice that this interface is package protected. This interface need not be
* publicly exposed, as it is only used by the MenuBar class to provide RTL
* versions of the images in the case the the user does not pass in their own
* bundle. However, we cannot make this class private, because the generated
* class needs to be able to extend this class.
*/
interface MenuBarImagesRTL extends MenuBarImages {
/**
* An image indicating a {@link MenuItem} has an associated submenu for
* a RTL context.
*
* @return a prototype of this image
*/
@Resource("menuBarSubMenuIcon_rtl.gif")
AbstractImagePrototype menuBarSubMenuIcon();
}
/**
* List of all {@link MenuItem}s and {@link MenuItemSeparator}s.
*/
private ArrayList<UIObject> allItems = new ArrayList<UIObject>();
/**
* List of {@link MenuItem}s, not including {@link MenuItemSeparator}s.
*/
private ArrayList<MenuItem> items = new ArrayList<MenuItem>();
private Element body;
private MenuBarImages images = null;
private boolean isAnimationEnabled = true;
private MenuBar parentMenu;
private PopupPanel popup;
private MenuItem selectedItem;
private MenuBar shownChildMenu;
private boolean vertical, autoOpen;
/**
* Creates an empty horizontal menu bar.
*/
public MenuBar() {
this(false);
}
/**
* Creates an empty horizontal menu bar that uses the specified image bundle
* for menu images.
*
* @param images a bundle that provides images for this menu
*/
public MenuBar(MenuBarImages images) {
this(false, images);
}
/**
* Creates an empty menu bar.
*
* @param vertical <code>true</code> to orient the menu bar vertically
*/
public MenuBar(boolean vertical) {
super();
if (LocaleInfo.getCurrentLocale().isRTL()) {
init(vertical, GWT.<MenuBarImagesRTL>create(MenuBarImagesRTL.class));
} else {
init(vertical, GWT.<MenuBarImages>create(MenuBarImages.class));
}
}
/**
* Creates an empty menu bar that uses the specified image bundle
* for menu images.
*
* @param vertical <code>true</code> to orient the menu bar vertically
* @param images a bundle that provides images for this menu
*/
public MenuBar(boolean vertical, MenuBarImages images) {
init(vertical, images);
}
/**
* Adds a menu item to the bar.
*
* @param item the item to be added
* @return the {@link MenuItem} object
*/
public MenuItem addItem(MenuItem item) {
addItemElement(item.getElement());
item.setParentMenu(this);
item.setSelectionStyle(false);
items.add(item);
allItems.add(item);
updateSubmenuIcon(item);
return item;
}
/**
* Adds a menu item to the bar, that will fire the given command when it is
* selected.
*
* @param text the item's text
* @param asHTML <code>true</code> to treat the specified text as html
* @param cmd the command to be fired
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, boolean asHTML, Command cmd) {
return addItem(new MenuItem(text, asHTML, cmd));
}
/**
* Adds a menu item to the bar, that will open the specified menu when it is
* selected.
*
* @param text the item's text
* @param asHTML <code>true</code> to treat the specified text as html
* @param popup the menu to be cascaded from it
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, boolean asHTML, MenuBar popup) {
return addItem(new MenuItem(text, asHTML, popup));
}
/**
* Adds a menu item to the bar, that will fire the given command when it is
* selected.
*
* @param text the item's text
* @param cmd the command to be fired
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, Command cmd) {
return addItem(new MenuItem(text, cmd));
}
/**
* Adds a menu item to the bar, that will open the specified menu when it is
* selected.
*
* @param text the item's text
* @param popup the menu to be cascaded from it
* @return the {@link MenuItem} object created
*/
public MenuItem addItem(String text, MenuBar popup) {
return addItem(new MenuItem(text, popup));
}
/**
* Adds a thin line to the {@link MenuBar} to separate sections of
* {@link MenuItem}s.
*
* @return the {@link MenuItemSeparator} object created
*/
public MenuItemSeparator addSeparator() {
return addSeparator(new MenuItemSeparator());
}
/**
* Adds a thin line to the {@link MenuBar} to separate sections of
* {@link MenuItem}s.
*
* @param separator the {@link MenuItemSeparator} to be added
* @return the {@link MenuItemSeparator} object
*/
public MenuItemSeparator addSeparator(MenuItemSeparator separator) {
if (vertical) {
setItemColSpan(separator, 2);
}
addItemElement(separator.getElement());
separator.setParentMenu(this);
allItems.add(separator);
return separator;
}
/**
* Removes all menu items from this menu bar.
*/
public void clearItems() {
// Deselect the current item
selectItem(null);
Element container = getItemContainerElement();
while (DOM.getChildCount(container) > 0) {
DOM.removeChild(container, DOM.getChild(container, 0));
}
// Set the parent of all items to null
for (UIObject item : allItems) {
setItemColSpan(item, 1);
if (item instanceof MenuItemSeparator) {
((MenuItemSeparator) item).setParentMenu(null);
} else {
((MenuItem) item).setParentMenu(null);
}
}
// Clear out all of the items and separators
items.clear();
allItems.clear();
}
/**
* Gets whether this menu bar's child menus will open when the mouse is moved
* over it.
*
* @return <code>true</code> if child menus will auto-open
*/
public boolean getAutoOpen() {
return autoOpen;
}
/**
* @see HasAnimation#isAnimationEnabled()
*/
public boolean isAnimationEnabled() {
return isAnimationEnabled;
}
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
MenuItem item = findItem(DOM.eventGetTarget(event));
switch (DOM.eventGetType(event)) {
case Event.ONCLICK: {
FocusPanel.impl.focus(getElement());
// Fire an item's command when the user clicks on it.
if (item != null) {
doItemAction(item, true);
}
break;
}
case Event.ONMOUSEOVER: {
if (item != null) {
itemOver(item);
}
break;
}
case Event.ONMOUSEOUT: {
if (item != null) {
itemOver(null);
}
break;
}
case Event.ONFOCUS: {
selectFirstItemIfNoneSelected();
break;
}
case Event.ONKEYDOWN: {
int keyCode = DOM.eventGetKeyCode(event);
switch (keyCode) {
case KeyboardListener.KEY_LEFT:
if (LocaleInfo.getCurrentLocale().isRTL()) {
moveToNextItem();
} else {
moveToPrevItem();
}
break;
case KeyboardListener.KEY_RIGHT:
if (LocaleInfo.getCurrentLocale().isRTL()) {
moveToPrevItem();
} else {
moveToNextItem();
}
break;
case KeyboardListener.KEY_UP:
moveUp();
break;
case KeyboardListener.KEY_DOWN:
moveDown();
break;
case KeyboardListener.KEY_ESCAPE:
closeAllParents();
break;
case KeyboardListener.KEY_ENTER:
if (!selectFirstItemIfNoneSelected()) {
doItemAction(selectedItem, true);
}
break;
} // end switch(keyCode)
break;
} // end case Event.ONKEYDOWN
} // end switch (DOM.eventGetType(event))
}
public void onPopupClosed(PopupPanel sender, boolean autoClosed) {
// If the menu popup was auto-closed, close all of its parents as well.
if (autoClosed) {
closeAllParents();
}
// When the menu popup closes, remember that no item is
// currently showing a popup menu.
onHide();
shownChildMenu = null;
popup = null;
}
/**
* Removes the specified menu item from the bar.
*
* @param item the item to be removed
*/
public void removeItem(MenuItem item) {
// Unselect if the item is currently selected
if (selectedItem == item) {
selectItem(null);
}
if (removeItemElement(item)) {
setItemColSpan(item, 1);
items.remove(item);
item.setParentMenu(null);
}
}
/**
* Removes the specified {@link MenuItemSeparator} from the bar.
*
* @param separator the separator to be removed
*/
public void removeSeparator(MenuItemSeparator separator) {
if (removeItemElement(separator)) {
separator.setParentMenu(null);
}
}
/**
* @see HasAnimation#setAnimationEnabled(boolean)
*/
public void setAnimationEnabled(boolean enable) {
isAnimationEnabled = enable;
}
/**
* Sets whether this menu bar's child menus will open when the mouse is moved
* over it.
*
* @param autoOpen <code>true</code> to cause child menus to auto-open
*/
public void setAutoOpen(boolean autoOpen) {
this.autoOpen = autoOpen;
}
/**
* Returns a list containing the <code>MenuItem</code> objects in the menu
* bar. If there are no items in the menu bar, then an empty <code>List</code>
* object will be returned.
*
* @return a list containing the <code>MenuItem</code> objects in the menu
* bar
*/
protected List<MenuItem> getItems() {
return this.items;
}
/**
* Returns the <code>MenuItem</code> that is currently selected
* (highlighted) by the user. If none of the items in the menu are currently
* selected, then <code>null</code> will be returned.
*
* @return the <code>MenuItem</code> that is currently selected, or
* <code>null</code> if no items are currently selected
*/
protected MenuItem getSelectedItem() {
return this.selectedItem;
}
@Override
protected void onDetach() {
// When the menu is detached, make sure to close all of its children.
if (popup != null) {
popup.hide();
}
super.onDetach();
}
/**
* <b>Affected Elements:</b>
* <ul>
* <li>-item# = the {@link MenuItem} at the specified index.</li>
* </ul>
*
* @see UIObject#onEnsureDebugId(String)
*/
@Override
protected void onEnsureDebugId(String baseID) {
super.onEnsureDebugId(baseID);
setMenuItemDebugIds(baseID);
}
/*
* Closes all parent menu popups.
*/
void closeAllParents() {
MenuBar curMenu = this;
while (curMenu.parentMenu != null) {
curMenu.close();
curMenu = curMenu.parentMenu;
}
}
/*
* Performs the action associated with the given menu item. If the item has a
* popup associated with it, the popup will be shown. If it has a command
* associated with it, and 'fireCommand' is true, then the command will be
* fired. Popups associated with other items will be hidden.
*
* @param item the item whose popup is to be shown. @param fireCommand <code>true</code>
* if the item's command should be fired, <code>false</code> otherwise.
*/
void doItemAction(final MenuItem item, boolean fireCommand) {
// If the given item is already showing its menu, we're done.
if ((shownChildMenu != null) && (item.getSubMenu() == shownChildMenu)) {
return;
}
// If another item is showing its menu, then hide it.
if (shownChildMenu != null) {
shownChildMenu.onHide();
popup.hide();
}
// If the item has no popup, optionally fire its command.
if ((item != null) && (item.getSubMenu() == null)) {
if (fireCommand) {
// Close this menu and all of its parents.
closeAllParents();
// Fire the item's command.
Command cmd = item.getCommand();
if (cmd != null) {
DeferredCommand.addCommand(cmd);
}
}
return;
}
// Ensure that the item is selected.
selectItem(item);
if (item == null) {
return;
}
// Create a new popup for this item, and position it next to
// the item (below if this is a horizontal menu bar, to the
// right if it's a vertical bar).
popup = new PopupPanel(true) {
{
setWidget(item.getSubMenu());
item.getSubMenu().onShow();
}
@Override
public boolean onEventPreview(Event event) {
// Hook the popup panel's event preview. We use this to keep it from
// auto-hiding when the parent menu is clicked.
switch (DOM.eventGetType(event)) {
case Event.ONCLICK:
// If the event target is part of the parent menu, suppress the
// event altogether.
Element target = DOM.eventGetTarget(event);
Element parentMenuElement = item.getParentMenu().getElement();
if (DOM.isOrHasChild(parentMenuElement, target)) {
return false;
}
break;
}
return super.onEventPreview(event);
}
};
popup.setAnimationType(AnimationType.ONE_WAY_CORNER);
popup.setStyleName("gwt-MenuBarPopup");
popup.addPopupListener(this);
shownChildMenu = item.getSubMenu();
item.getSubMenu().parentMenu = this;
// If any parent MenuBar has animations disabled, then do not animate
MenuBar parent = parentMenu;
boolean animate = isAnimationEnabled;
while (animate && parent != null) {
animate = parent.isAnimationEnabled();
parent = parent.parentMenu;
}
popup.setAnimationEnabled(animate);
// Show the popup, ensuring that the menubar's event preview remains on top
// of the popup's.
popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
public void setPosition(int offsetWidth, int offsetHeight) {
// depending on the bidi direction position a menu on the left or right
// of its base item
- if (LocaleInfo.getCurrentLocale().isRTL()) {
- int popableWidth = item.getSubMenu().getOffsetWidth();
+ if (LocaleInfo.getCurrentLocale().isRTL()) {
if (vertical) {
- popup.setPopupPosition(MenuBar.this.getAbsoluteLeft() - popableWidth + 1,
+ popup.setPopupPosition(MenuBar.this.getAbsoluteLeft() - offsetWidth + 1,
item.getAbsoluteTop());
} else {
- popup.setPopupPosition(item.getAbsoluteLeft() + item.getOffsetWidth() - popableWidth,
+ popup.setPopupPosition(item.getAbsoluteLeft() + item.getOffsetWidth() - offsetWidth,
MenuBar.this.getAbsoluteTop() + MenuBar.this.getOffsetHeight() - 1);
}
} else {
if (vertical) {
popup.setPopupPosition(MenuBar.this.getAbsoluteLeft() + MenuBar.this.getOffsetWidth() - 1,
item.getAbsoluteTop());
} else {
popup.setPopupPosition(item.getAbsoluteLeft(),
MenuBar.this.getAbsoluteTop() + MenuBar.this.getOffsetHeight() - 1);
}
}
}
});
shownChildMenu.focus();
}
void itemOver(MenuItem item) {
if (item == null) {
// Don't clear selection if the currently selected item's menu is showing.
if ((selectedItem != null)
&& (shownChildMenu == selectedItem.getSubMenu())) {
return;
}
}
// Style the item selected when the mouse enters.
selectItem(item);
// If child menus are being shown, or this menu is itself
// a child menu, automatically show an item's child menu
// when the mouse enters.
if (item != null) {
if ((shownChildMenu != null) || (parentMenu != null) || autoOpen) {
doItemAction(item, false);
}
}
}
void selectItem(MenuItem item) {
if (item == selectedItem) {
return;
}
if (selectedItem != null) {
selectedItem.setSelectionStyle(false);
// Set the style of the submenu indicator
if (vertical) {
Element tr = DOM.getParent(selectedItem.getElement());
if (DOM.getChildCount(tr) == 2) {
Element td = DOM.getChild(tr, 1);
setStyleName(td, "subMenuIcon-selected", false);
}
}
}
if (item != null) {
item.setSelectionStyle(true);
// Set the style of the submenu indicator
if (vertical) {
Element tr = DOM.getParent(item.getElement());
if (DOM.getChildCount(tr) == 2) {
Element td = DOM.getChild(tr, 1);
setStyleName(td, "subMenuIcon-selected", true);
}
}
Accessibility.setState(getElement(), Accessibility.STATE_ACTIVEDESCENDANT,
DOM.getElementAttribute(item.getElement(), "id"));
}
selectedItem = item;
}
/**
* Set the IDs of the menu items.
*
* @param baseID the base ID
*/
void setMenuItemDebugIds(String baseID) {
int itemCount = 0;
for (MenuItem item : items) {
item.ensureDebugId(baseID + "-item" + itemCount);
itemCount++;
}
}
/**
* Show or hide the icon used for items with a submenu.
*
* @param item the item with or without a submenu
*/
void updateSubmenuIcon(MenuItem item) {
// The submenu icon only applies to vertical menus
if (!vertical) {
return;
}
// Get the index of the MenuItem
int idx = allItems.indexOf(item);
if (idx == -1) {
return;
}
Element container = getItemContainerElement();
Element tr = DOM.getChild(container, idx);
int tdCount = DOM.getChildCount(tr);
MenuBar submenu = item.getSubMenu();
if (submenu == null) {
// Remove the submenu indicator
if (tdCount == 2) {
DOM.removeChild(tr, DOM.getChild(tr, 1));
}
setItemColSpan(item, 2);
} else if (tdCount == 1) {
// Show the submenu indicator
setItemColSpan(item, 1);
Element td = DOM.createTD();
DOM.setElementProperty(td, "vAlign", "middle");
DOM.setInnerHTML(td, images.menuBarSubMenuIcon().getHTML());
setStyleName(td, "subMenuIcon");
DOM.appendChild(tr, td);
}
}
/**
* Physically add the td element of a {@link MenuItem} or
* {@link MenuItemSeparator} to this {@link MenuBar}.
*
* @param tdElem the td element to be added
*/
private void addItemElement(Element tdElem) {
Element tr;
if (vertical) {
tr = DOM.createTR();
DOM.appendChild(body, tr);
} else {
tr = DOM.getChild(body, 0);
}
DOM.appendChild(tr, tdElem);
}
/**
* Closes this menu (if it is a popup).
*/
private void close() {
if (parentMenu != null) {
parentMenu.popup.hide();
}
}
private MenuItem findItem(Element hItem) {
for (MenuItem item : items) {
if (DOM.isOrHasChild(item.getElement(), hItem)) {
return item;
}
}
return null;
}
private void focus() {
FocusPanel.impl.focus(getElement());
}
private Element getItemContainerElement() {
if (vertical) {
return body;
} else {
return DOM.getChild(body, 0);
}
}
private void init(boolean vertical, MenuBarImages images) {
this.images = images;
Element table = DOM.createTable();
body = DOM.createTBody();
DOM.appendChild(table, body);
if (!vertical) {
Element tr = DOM.createTR();
DOM.appendChild(body, tr);
}
this.vertical = vertical;
Element outer = FocusPanel.impl.createFocusable();
DOM.appendChild(outer, table);
setElement(outer);
Accessibility.setRole(getElement(), Accessibility.ROLE_MENUBAR);
sinkEvents(Event.ONCLICK | Event.ONMOUSEOVER | Event.ONMOUSEOUT
| Event.ONFOCUS | Event.ONKEYDOWN);
setStyleName("gwt-MenuBar");
if (vertical) {
addStyleDependentName("vertical");
} else {
addStyleDependentName("horizontal");
}
DOM.setStyleAttribute(getElement(), "outline", "0px");
}
private void moveDown() {
if (selectFirstItemIfNoneSelected()) {
return;
}
if (vertical) {
selectNextItem();
} else {
if (selectedItem.getSubMenu() != null) {
doItemAction(selectedItem, false);
} else if (parentMenu != null) {
if (parentMenu.vertical) {
parentMenu.selectNextItem();
} else {
parentMenu.moveDown();
}
}
}
}
private void moveToNextItem() {
if (selectFirstItemIfNoneSelected()) {
return;
}
if (!vertical) {
selectNextItem();
} else {
if ((shownChildMenu == null) && (selectedItem.getSubMenu() != null)) {
doItemAction(selectedItem, false);
} else if (parentMenu != null) {
if (!parentMenu.vertical) {
parentMenu.selectNextItem();
} else {
parentMenu.moveToNextItem();
}
}
}
}
private void moveToPrevItem() {
if (selectFirstItemIfNoneSelected()) {
return;
}
if (!vertical) {
selectPrevItem();
} else {
if ((parentMenu != null) && (!parentMenu.vertical)) {
parentMenu.selectPrevItem();
} else {
close();
}
}
}
private void moveUp() {
if (selectFirstItemIfNoneSelected()) {
return;
}
if ((shownChildMenu == null) && vertical) {
selectPrevItem();
} else if ((parentMenu != null) && parentMenu.vertical) {
parentMenu.selectPrevItem();
} else {
close();
}
}
/*
* This method is called when a menu bar is hidden, so that it can hide any
* child popups that are currently being shown.
*/
private void onHide() {
if (shownChildMenu != null) {
shownChildMenu.onHide();
popup.hide();
focus();
}
}
/*
* This method is called when a menu bar is shown.
*/
private void onShow() {
// Select the first item when a menu is shown.
if (items.size() > 0) {
selectItem(items.get(0));
}
}
/**
* Removes the specified item from the {@link MenuBar} and the physical DOM
* structure.
*
* @param item the item to be removed
* @return true if the item was removed
*/
private boolean removeItemElement(UIObject item) {
int idx = allItems.indexOf(item);
if (idx == -1) {
return false;
}
Element container = getItemContainerElement();
DOM.removeChild(container, DOM.getChild(container, idx));
allItems.remove(idx);
return true;
}
/**
* Selects the first item in the menu if no items are currently selected. This method
* assumes that the menu has at least 1 item.
*
* @return true if no item was previously selected and the first item in the list was selected,
* false otherwise
*/
private boolean selectFirstItemIfNoneSelected() {
if (selectedItem == null) {
MenuItem nextItem = items.get(0);
selectItem(nextItem);
return true;
}
return false;
}
private void selectNextItem() {
if (selectedItem == null) {
return;
}
int index = items.indexOf(selectedItem);
// We know that selectedItem is set to an item that is contained in the items collection.
// Therefore, we know that index can never be -1.
assert (index != -1);
MenuItem itemToBeSelected;
if (index < items.size() - 1) {
itemToBeSelected = items.get(index + 1);
} else { // we're at the end, loop around to the start
itemToBeSelected = items.get(0);
}
selectItem(itemToBeSelected);
if (shownChildMenu != null) {
doItemAction(itemToBeSelected, false);
}
}
private void selectPrevItem() {
if (selectedItem == null) {
return;
}
int index = items.indexOf(selectedItem);
// We know that selectedItem is set to an item that is contained in the items collection.
// Therefore, we know that index can never be -1.
assert (index != -1);
MenuItem itemToBeSelected;
if (index > 0) {
itemToBeSelected = items.get(index - 1);
} else { // we're at the start, loop around to the end
itemToBeSelected = items.get(items.size() - 1);
}
selectItem(itemToBeSelected);
if (shownChildMenu != null) {
doItemAction(itemToBeSelected, false);
}
}
/**
* Set the colspan of a {@link MenuItem} or {@link MenuItemSeparator}.
*
* @param item the {@link MenuItem} or {@link MenuItemSeparator}
* @param colspan the colspan
*/
private void setItemColSpan(UIObject item, int colspan) {
DOM.setElementPropertyInt(item.getElement(), "colSpan", colspan);
}
}
| false | true | void doItemAction(final MenuItem item, boolean fireCommand) {
// If the given item is already showing its menu, we're done.
if ((shownChildMenu != null) && (item.getSubMenu() == shownChildMenu)) {
return;
}
// If another item is showing its menu, then hide it.
if (shownChildMenu != null) {
shownChildMenu.onHide();
popup.hide();
}
// If the item has no popup, optionally fire its command.
if ((item != null) && (item.getSubMenu() == null)) {
if (fireCommand) {
// Close this menu and all of its parents.
closeAllParents();
// Fire the item's command.
Command cmd = item.getCommand();
if (cmd != null) {
DeferredCommand.addCommand(cmd);
}
}
return;
}
// Ensure that the item is selected.
selectItem(item);
if (item == null) {
return;
}
// Create a new popup for this item, and position it next to
// the item (below if this is a horizontal menu bar, to the
// right if it's a vertical bar).
popup = new PopupPanel(true) {
{
setWidget(item.getSubMenu());
item.getSubMenu().onShow();
}
@Override
public boolean onEventPreview(Event event) {
// Hook the popup panel's event preview. We use this to keep it from
// auto-hiding when the parent menu is clicked.
switch (DOM.eventGetType(event)) {
case Event.ONCLICK:
// If the event target is part of the parent menu, suppress the
// event altogether.
Element target = DOM.eventGetTarget(event);
Element parentMenuElement = item.getParentMenu().getElement();
if (DOM.isOrHasChild(parentMenuElement, target)) {
return false;
}
break;
}
return super.onEventPreview(event);
}
};
popup.setAnimationType(AnimationType.ONE_WAY_CORNER);
popup.setStyleName("gwt-MenuBarPopup");
popup.addPopupListener(this);
shownChildMenu = item.getSubMenu();
item.getSubMenu().parentMenu = this;
// If any parent MenuBar has animations disabled, then do not animate
MenuBar parent = parentMenu;
boolean animate = isAnimationEnabled;
while (animate && parent != null) {
animate = parent.isAnimationEnabled();
parent = parent.parentMenu;
}
popup.setAnimationEnabled(animate);
// Show the popup, ensuring that the menubar's event preview remains on top
// of the popup's.
popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
public void setPosition(int offsetWidth, int offsetHeight) {
// depending on the bidi direction position a menu on the left or right
// of its base item
if (LocaleInfo.getCurrentLocale().isRTL()) {
int popableWidth = item.getSubMenu().getOffsetWidth();
if (vertical) {
popup.setPopupPosition(MenuBar.this.getAbsoluteLeft() - popableWidth + 1,
item.getAbsoluteTop());
} else {
popup.setPopupPosition(item.getAbsoluteLeft() + item.getOffsetWidth() - popableWidth,
MenuBar.this.getAbsoluteTop() + MenuBar.this.getOffsetHeight() - 1);
}
} else {
if (vertical) {
popup.setPopupPosition(MenuBar.this.getAbsoluteLeft() + MenuBar.this.getOffsetWidth() - 1,
item.getAbsoluteTop());
} else {
popup.setPopupPosition(item.getAbsoluteLeft(),
MenuBar.this.getAbsoluteTop() + MenuBar.this.getOffsetHeight() - 1);
}
}
}
});
shownChildMenu.focus();
}
| void doItemAction(final MenuItem item, boolean fireCommand) {
// If the given item is already showing its menu, we're done.
if ((shownChildMenu != null) && (item.getSubMenu() == shownChildMenu)) {
return;
}
// If another item is showing its menu, then hide it.
if (shownChildMenu != null) {
shownChildMenu.onHide();
popup.hide();
}
// If the item has no popup, optionally fire its command.
if ((item != null) && (item.getSubMenu() == null)) {
if (fireCommand) {
// Close this menu and all of its parents.
closeAllParents();
// Fire the item's command.
Command cmd = item.getCommand();
if (cmd != null) {
DeferredCommand.addCommand(cmd);
}
}
return;
}
// Ensure that the item is selected.
selectItem(item);
if (item == null) {
return;
}
// Create a new popup for this item, and position it next to
// the item (below if this is a horizontal menu bar, to the
// right if it's a vertical bar).
popup = new PopupPanel(true) {
{
setWidget(item.getSubMenu());
item.getSubMenu().onShow();
}
@Override
public boolean onEventPreview(Event event) {
// Hook the popup panel's event preview. We use this to keep it from
// auto-hiding when the parent menu is clicked.
switch (DOM.eventGetType(event)) {
case Event.ONCLICK:
// If the event target is part of the parent menu, suppress the
// event altogether.
Element target = DOM.eventGetTarget(event);
Element parentMenuElement = item.getParentMenu().getElement();
if (DOM.isOrHasChild(parentMenuElement, target)) {
return false;
}
break;
}
return super.onEventPreview(event);
}
};
popup.setAnimationType(AnimationType.ONE_WAY_CORNER);
popup.setStyleName("gwt-MenuBarPopup");
popup.addPopupListener(this);
shownChildMenu = item.getSubMenu();
item.getSubMenu().parentMenu = this;
// If any parent MenuBar has animations disabled, then do not animate
MenuBar parent = parentMenu;
boolean animate = isAnimationEnabled;
while (animate && parent != null) {
animate = parent.isAnimationEnabled();
parent = parent.parentMenu;
}
popup.setAnimationEnabled(animate);
// Show the popup, ensuring that the menubar's event preview remains on top
// of the popup's.
popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
public void setPosition(int offsetWidth, int offsetHeight) {
// depending on the bidi direction position a menu on the left or right
// of its base item
if (LocaleInfo.getCurrentLocale().isRTL()) {
if (vertical) {
popup.setPopupPosition(MenuBar.this.getAbsoluteLeft() - offsetWidth + 1,
item.getAbsoluteTop());
} else {
popup.setPopupPosition(item.getAbsoluteLeft() + item.getOffsetWidth() - offsetWidth,
MenuBar.this.getAbsoluteTop() + MenuBar.this.getOffsetHeight() - 1);
}
} else {
if (vertical) {
popup.setPopupPosition(MenuBar.this.getAbsoluteLeft() + MenuBar.this.getOffsetWidth() - 1,
item.getAbsoluteTop());
} else {
popup.setPopupPosition(item.getAbsoluteLeft(),
MenuBar.this.getAbsoluteTop() + MenuBar.this.getOffsetHeight() - 1);
}
}
}
});
shownChildMenu.focus();
}
|
diff --git a/src/station/JE802Station.java b/src/station/JE802Station.java
index 7a7efdd..721ac0e 100644
--- a/src/station/JE802Station.java
+++ b/src/station/JE802Station.java
@@ -1,344 +1,346 @@
/*
*
* This is Jemula.
*
* Copyright (c) 2009 Stefan Mangold, Fabian Dreier, Stefan Schmid
* All rights reserved. Urheberrechtlich geschuetzt.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of any affiliation of Stefan Mangold nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
*/
package station;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import kernel.JEEvent;
import kernel.JEEventScheduler;
import kernel.JETime;
import kernel.JEmula;
import layer0_medium.JEIWirelessMedium;
import layer1_802Phy.JE802Mobility;
import layer1_802Phy.JE802PhyMode;
import layer2_802Mac.JE802_Mac;
import layer2_80211Mac.JE802_11Mac;
import layer3_network.JE802RouteManager;
import layer4_transport.JE802TCPManager;
import layer5_application.JE802TrafficGen;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import emulator.JE802StatEval;
import gui.JE802Gui;
public class JE802Station extends JEmula {
private List<JE802TrafficGen> trafficGenerators;
private int address;
private JE802_Mac theMac;
// TODO: Roman: Shouldn't there be only one general map for all the macs?
private Map<Integer, JE802_11Mac> dot11MacMap;
private final JE802StatEval statEval;
private JE802Mobility mobility;
private List<Integer> wiredAddresses;
private JE802Sme sme;
private JE802RouteManager ipLayer;
private JE802TCPManager tcp;
private final XPath xpath = XPathFactory.newInstance().newXPath();
public JE802Station(JEEventScheduler aScheduler, JEIWirelessMedium aChannel, Random aGenerator, JE802Gui aGui,
JE802StatEval aStatEval, Node topLevelNode, List<JE802PhyMode> phyModes, double longitude, double latitude)
throws XPathExpressionException {
Element aTopLevelNode = (Element) topLevelNode;
this.theUniqueEventScheduler = aScheduler;
this.statEval = aStatEval;
if (aTopLevelNode.getNodeName().equals("JE802Station")) {
this.message("XML definition " + aTopLevelNode.getNodeName() + " found.", 1);
// get station address
this.address = Integer.parseInt(aTopLevelNode.getAttribute("address"));
String wiredStationsString = aTopLevelNode.getAttribute("wiredTo");
if (wiredStationsString.isEmpty()) {
this.wiredAddresses = null;
} else {
String[] addresses = wiredStationsString.split(",");
this.wiredAddresses = new ArrayList<Integer>(addresses.length);
for (String wired : addresses) {
Integer addr = new Integer(wired);
this.wiredAddresses.add(addr);
}
}
this.dot11MacMap = new HashMap<Integer, JE802_11Mac>();
this.trafficGenerators = new ArrayList<JE802TrafficGen>();
if (aTopLevelNode.hasChildNodes()) {
// -- create SME (Station Management Entity):
// ------------------------------------------------------------------------------------------------
Node smeNode = (Node) xpath.evaluate("JE802SME", aTopLevelNode, XPathConstants.NODE);
this.message("allocating " + smeNode.getNodeName(), 10);
this.sme = new JE802Sme(aScheduler, aGenerator, smeNode, this);
// -- create mobility:
// ----------------------------------------------------------------------------------------
Node mobNode = (Node) xpath.evaluate("JE802Mobility", aTopLevelNode, XPathConstants.NODE);
this.message("allocating " + mobNode.getNodeName(), 10);
this.mobility = new JE802Mobility(mobNode, longitude, latitude);
// -- create MACS:
// ----------------------------------------------------------------------------------------
// create 802_11 Macs, if any
NodeList macList = (NodeList) xpath.evaluate("JE80211MAC", aTopLevelNode, XPathConstants.NODESET);
if (macList.getLength() > 0) {
for (int i = 0; i < macList.getLength(); i++) {
Node macNode = macList.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
JE802_11Mac theMac = new JE802_11Mac(aScheduler, aStatEval, aGenerator, aGui, aChannel, macNode,
this.sme.getHandlerId());
this.dot11MacMap.put(theMac.getChannel(), (JE802_11Mac) theMac);
theMac.setMACAddress(this.address);
theMac.getPhy().setThePhyModeList(phyModes);
theMac.getMlme().getTheAlgorithm().compute();
theMac.getPhy().setMobility(this.mobility);
theMac.getPhy().send(new JEEvent("start_req", theMac.getPhy(), theUniqueEventScheduler.now()));
this.theMac = theMac;
}
// TODO: Roman: Why convert to ArrayList and then in sme
// build a HashMap again?
// Only this class uses the setMacs method...
sme.setMacs(new ArrayList<JE802_11Mac>(dot11MacMap.values()));
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80211Mac definition found", 10);
}
// create 802_15 Macs, if any
NodeList mac15List = (NodeList) xpath.evaluate("JE80215MAC", aTopLevelNode, XPathConstants.NODESET);
if (mac15List.getLength() > 0) {
for (int i = 0; i < mac15List.getLength(); i++) {
Node macNode = mac15List.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
theMac.setMACAddress(this.address);
theMac.getPhy().setThePhyModeList(phyModes);
theMac.getPhy().setMobility(this.mobility);
theMac.getPhy().send(new JEEvent("start_req", theMac.getPhy(), theUniqueEventScheduler.now()));
}
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80215Mac found", 10);
}
// create 802_15 Mac Low-Energy, if any
NodeList mac15LowEnergyList = (NodeList) xpath.evaluate("JE80215MAC_LowEnergy", aTopLevelNode,
XPathConstants.NODESET);
if (mac15LowEnergyList.getLength() > 0) {
for (int i = 0; i < mac15LowEnergyList.getLength(); i++) {
Node macNode = mac15LowEnergyList.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
theMac.setMACAddress(this.address);
theMac.getPhy().setThePhyModeList(phyModes);
theMac.getPhy().setMobility(this.mobility);
theMac.getPhy().send(new JEEvent("start_req", theMac.getPhy(), theUniqueEventScheduler.now()));
}
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80215Mac found", 10);
}
// TODO: Stefan, added LED MAC
// create 802 LED Macs, if any
NodeList macLEDList = (NodeList) xpath.evaluate("JE80215LEDMAC", aTopLevelNode, XPathConstants.NODESET);
if (macLEDList.getLength() > 0) {
for (int i = 0; i < macLEDList.getLength(); i++) {
Node macNode = macLEDList.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
// this.dot15MacMap.put(theMac.getChannel(),
// (JE802_15Mac) theMac);
theMac.setMACAddress(this.address);
// theMac.getPhy().setThePhyModeList(phyModes);
// theMac.getPhy().setMobility(this.mobility);
// theMac.getPhy().send(new JEEvent("start_req",
// theMac.getPhy(), theUniqueEventScheduler.now()));
}
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80215LEDMAC found", 10);
}
// -- create TCP Manager:
// ------------------------------------------------------------------------------------------------
Node tcpNode = (Node) xpath.evaluate("JE802TCP", aTopLevelNode, XPathConstants.NODE);
this.tcp = new JE802TCPManager(aScheduler, aGenerator, tcpNode, this.ipLayer, this.statEval);
this.ipLayer.setTcpHandlerId(tcp.getHandlerId());
/*
* for (Iterator<JE802_11Mac> iterator =
* macMap.values().iterator(); iterator.hasNext();) {
* JE802_11Mac currentMac = (JE802_11Mac) iterator.next(); }
* mac.setTcpHandlerId(this.tcp.getHandlerId());
*/
// -- create traffic generators:
// ----------------------------------------------------------------------------------------
NodeList tgList = (NodeList) xpath.evaluate("JE802TrafficGen", aTopLevelNode, XPathConstants.NODESET);
for (int i = 0; i < tgList.getLength(); i++) {
Node tgNode = tgList.item(i);
this.message("allocating " + tgNode.getNodeName(), 10);
JE802TrafficGen aNewTrafficGen = new JE802TrafficGen(aScheduler, aGenerator, tgNode, this.address, aStatEval,
tcp);
this.trafficGenerators.add(aNewTrafficGen);
// stop generating traffic, usually not used:
aNewTrafficGen.send(new JEEvent("stop_req", aNewTrafficGen, aNewTrafficGen.getStopTime()));
// start generating traffic:
aNewTrafficGen.send(new JEEvent("start_req", aNewTrafficGen, aNewTrafficGen.getStartTime()));
}
if (mac15List.getLength() > 0) {
this.sme.send(new JEEvent("start_req", this.sme.getHandlerId(), theUniqueEventScheduler.now()));
}
} else {
this.message("XML definition " + aTopLevelNode.getNodeName() + " has no child nodes!", 10);
}
} else {
this.message("XML definition " + aTopLevelNode.getNodeName() + " found, but JE802Station expected!", 10);
}
- aGui.setupStation(this.address);
+ if (aGui!=null) {
+ aGui.setupStation(this.address);
+ }
}
public JE802_Mac getMac() {
return theMac;
}
public double getXLocation(JETime time) {
return this.mobility.getXLocation(time);
}
public double getYLocation(JETime time) {
return this.mobility.getYLocation(time);
}
public double getZLocation(JETime time) {
return this.mobility.getZLocation(time);
}
public boolean isMobile() {
return this.mobility.isMobile();
}
public List<JE802TrafficGen> getTrafficGenList() {
return this.trafficGenerators;
}
public JE802StatEval getStatEval() {
return statEval;
}
public int getMacAddress() {
return this.address;
}
public JE802Sme getSme() {
return this.sme;
}
public int getFixedChannel() {
for (JE802_11Mac aMac : dot11MacMap.values()) {
if (aMac.isFixedChannel()) {
return aMac.getChannel();
}
}
return this.dot11MacMap.values().iterator().next().getPhy().getCurrentChannelNumberTX();
}
public double getTransmitPowerLeveldBm() {
// returns power level of first mac
return this.dot11MacMap.values().iterator().next().getPhy().getCurrentTransmitPowerLevel_dBm();
}
public JE802Mobility getMobility() {
return mobility;
}
public long getLostPackets() {
return tcp.getLostPackets();
}
public void setWiredStations(List<JE802Station> wiredStations) {
this.sme.setWiredStations(wiredStations);
}
public List<Integer> getWiredAddresses() {
return this.wiredAddresses;
}
public long getTransmittedPackets() {
return tcp.getTransmittedPackets();
}
public void displayLossrate() {
tcp.retransmissionRate();
}
@Override
public String toString() {
return Integer.toString(theMac.getMacAddress());
}
}
| true | true | public JE802Station(JEEventScheduler aScheduler, JEIWirelessMedium aChannel, Random aGenerator, JE802Gui aGui,
JE802StatEval aStatEval, Node topLevelNode, List<JE802PhyMode> phyModes, double longitude, double latitude)
throws XPathExpressionException {
Element aTopLevelNode = (Element) topLevelNode;
this.theUniqueEventScheduler = aScheduler;
this.statEval = aStatEval;
if (aTopLevelNode.getNodeName().equals("JE802Station")) {
this.message("XML definition " + aTopLevelNode.getNodeName() + " found.", 1);
// get station address
this.address = Integer.parseInt(aTopLevelNode.getAttribute("address"));
String wiredStationsString = aTopLevelNode.getAttribute("wiredTo");
if (wiredStationsString.isEmpty()) {
this.wiredAddresses = null;
} else {
String[] addresses = wiredStationsString.split(",");
this.wiredAddresses = new ArrayList<Integer>(addresses.length);
for (String wired : addresses) {
Integer addr = new Integer(wired);
this.wiredAddresses.add(addr);
}
}
this.dot11MacMap = new HashMap<Integer, JE802_11Mac>();
this.trafficGenerators = new ArrayList<JE802TrafficGen>();
if (aTopLevelNode.hasChildNodes()) {
// -- create SME (Station Management Entity):
// ------------------------------------------------------------------------------------------------
Node smeNode = (Node) xpath.evaluate("JE802SME", aTopLevelNode, XPathConstants.NODE);
this.message("allocating " + smeNode.getNodeName(), 10);
this.sme = new JE802Sme(aScheduler, aGenerator, smeNode, this);
// -- create mobility:
// ----------------------------------------------------------------------------------------
Node mobNode = (Node) xpath.evaluate("JE802Mobility", aTopLevelNode, XPathConstants.NODE);
this.message("allocating " + mobNode.getNodeName(), 10);
this.mobility = new JE802Mobility(mobNode, longitude, latitude);
// -- create MACS:
// ----------------------------------------------------------------------------------------
// create 802_11 Macs, if any
NodeList macList = (NodeList) xpath.evaluate("JE80211MAC", aTopLevelNode, XPathConstants.NODESET);
if (macList.getLength() > 0) {
for (int i = 0; i < macList.getLength(); i++) {
Node macNode = macList.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
JE802_11Mac theMac = new JE802_11Mac(aScheduler, aStatEval, aGenerator, aGui, aChannel, macNode,
this.sme.getHandlerId());
this.dot11MacMap.put(theMac.getChannel(), (JE802_11Mac) theMac);
theMac.setMACAddress(this.address);
theMac.getPhy().setThePhyModeList(phyModes);
theMac.getMlme().getTheAlgorithm().compute();
theMac.getPhy().setMobility(this.mobility);
theMac.getPhy().send(new JEEvent("start_req", theMac.getPhy(), theUniqueEventScheduler.now()));
this.theMac = theMac;
}
// TODO: Roman: Why convert to ArrayList and then in sme
// build a HashMap again?
// Only this class uses the setMacs method...
sme.setMacs(new ArrayList<JE802_11Mac>(dot11MacMap.values()));
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80211Mac definition found", 10);
}
// create 802_15 Macs, if any
NodeList mac15List = (NodeList) xpath.evaluate("JE80215MAC", aTopLevelNode, XPathConstants.NODESET);
if (mac15List.getLength() > 0) {
for (int i = 0; i < mac15List.getLength(); i++) {
Node macNode = mac15List.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
theMac.setMACAddress(this.address);
theMac.getPhy().setThePhyModeList(phyModes);
theMac.getPhy().setMobility(this.mobility);
theMac.getPhy().send(new JEEvent("start_req", theMac.getPhy(), theUniqueEventScheduler.now()));
}
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80215Mac found", 10);
}
// create 802_15 Mac Low-Energy, if any
NodeList mac15LowEnergyList = (NodeList) xpath.evaluate("JE80215MAC_LowEnergy", aTopLevelNode,
XPathConstants.NODESET);
if (mac15LowEnergyList.getLength() > 0) {
for (int i = 0; i < mac15LowEnergyList.getLength(); i++) {
Node macNode = mac15LowEnergyList.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
theMac.setMACAddress(this.address);
theMac.getPhy().setThePhyModeList(phyModes);
theMac.getPhy().setMobility(this.mobility);
theMac.getPhy().send(new JEEvent("start_req", theMac.getPhy(), theUniqueEventScheduler.now()));
}
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80215Mac found", 10);
}
// TODO: Stefan, added LED MAC
// create 802 LED Macs, if any
NodeList macLEDList = (NodeList) xpath.evaluate("JE80215LEDMAC", aTopLevelNode, XPathConstants.NODESET);
if (macLEDList.getLength() > 0) {
for (int i = 0; i < macLEDList.getLength(); i++) {
Node macNode = macLEDList.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
// this.dot15MacMap.put(theMac.getChannel(),
// (JE802_15Mac) theMac);
theMac.setMACAddress(this.address);
// theMac.getPhy().setThePhyModeList(phyModes);
// theMac.getPhy().setMobility(this.mobility);
// theMac.getPhy().send(new JEEvent("start_req",
// theMac.getPhy(), theUniqueEventScheduler.now()));
}
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80215LEDMAC found", 10);
}
// -- create TCP Manager:
// ------------------------------------------------------------------------------------------------
Node tcpNode = (Node) xpath.evaluate("JE802TCP", aTopLevelNode, XPathConstants.NODE);
this.tcp = new JE802TCPManager(aScheduler, aGenerator, tcpNode, this.ipLayer, this.statEval);
this.ipLayer.setTcpHandlerId(tcp.getHandlerId());
/*
* for (Iterator<JE802_11Mac> iterator =
* macMap.values().iterator(); iterator.hasNext();) {
* JE802_11Mac currentMac = (JE802_11Mac) iterator.next(); }
* mac.setTcpHandlerId(this.tcp.getHandlerId());
*/
// -- create traffic generators:
// ----------------------------------------------------------------------------------------
NodeList tgList = (NodeList) xpath.evaluate("JE802TrafficGen", aTopLevelNode, XPathConstants.NODESET);
for (int i = 0; i < tgList.getLength(); i++) {
Node tgNode = tgList.item(i);
this.message("allocating " + tgNode.getNodeName(), 10);
JE802TrafficGen aNewTrafficGen = new JE802TrafficGen(aScheduler, aGenerator, tgNode, this.address, aStatEval,
tcp);
this.trafficGenerators.add(aNewTrafficGen);
// stop generating traffic, usually not used:
aNewTrafficGen.send(new JEEvent("stop_req", aNewTrafficGen, aNewTrafficGen.getStopTime()));
// start generating traffic:
aNewTrafficGen.send(new JEEvent("start_req", aNewTrafficGen, aNewTrafficGen.getStartTime()));
}
if (mac15List.getLength() > 0) {
this.sme.send(new JEEvent("start_req", this.sme.getHandlerId(), theUniqueEventScheduler.now()));
}
} else {
this.message("XML definition " + aTopLevelNode.getNodeName() + " has no child nodes!", 10);
}
} else {
this.message("XML definition " + aTopLevelNode.getNodeName() + " found, but JE802Station expected!", 10);
}
aGui.setupStation(this.address);
}
| public JE802Station(JEEventScheduler aScheduler, JEIWirelessMedium aChannel, Random aGenerator, JE802Gui aGui,
JE802StatEval aStatEval, Node topLevelNode, List<JE802PhyMode> phyModes, double longitude, double latitude)
throws XPathExpressionException {
Element aTopLevelNode = (Element) topLevelNode;
this.theUniqueEventScheduler = aScheduler;
this.statEval = aStatEval;
if (aTopLevelNode.getNodeName().equals("JE802Station")) {
this.message("XML definition " + aTopLevelNode.getNodeName() + " found.", 1);
// get station address
this.address = Integer.parseInt(aTopLevelNode.getAttribute("address"));
String wiredStationsString = aTopLevelNode.getAttribute("wiredTo");
if (wiredStationsString.isEmpty()) {
this.wiredAddresses = null;
} else {
String[] addresses = wiredStationsString.split(",");
this.wiredAddresses = new ArrayList<Integer>(addresses.length);
for (String wired : addresses) {
Integer addr = new Integer(wired);
this.wiredAddresses.add(addr);
}
}
this.dot11MacMap = new HashMap<Integer, JE802_11Mac>();
this.trafficGenerators = new ArrayList<JE802TrafficGen>();
if (aTopLevelNode.hasChildNodes()) {
// -- create SME (Station Management Entity):
// ------------------------------------------------------------------------------------------------
Node smeNode = (Node) xpath.evaluate("JE802SME", aTopLevelNode, XPathConstants.NODE);
this.message("allocating " + smeNode.getNodeName(), 10);
this.sme = new JE802Sme(aScheduler, aGenerator, smeNode, this);
// -- create mobility:
// ----------------------------------------------------------------------------------------
Node mobNode = (Node) xpath.evaluate("JE802Mobility", aTopLevelNode, XPathConstants.NODE);
this.message("allocating " + mobNode.getNodeName(), 10);
this.mobility = new JE802Mobility(mobNode, longitude, latitude);
// -- create MACS:
// ----------------------------------------------------------------------------------------
// create 802_11 Macs, if any
NodeList macList = (NodeList) xpath.evaluate("JE80211MAC", aTopLevelNode, XPathConstants.NODESET);
if (macList.getLength() > 0) {
for (int i = 0; i < macList.getLength(); i++) {
Node macNode = macList.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
JE802_11Mac theMac = new JE802_11Mac(aScheduler, aStatEval, aGenerator, aGui, aChannel, macNode,
this.sme.getHandlerId());
this.dot11MacMap.put(theMac.getChannel(), (JE802_11Mac) theMac);
theMac.setMACAddress(this.address);
theMac.getPhy().setThePhyModeList(phyModes);
theMac.getMlme().getTheAlgorithm().compute();
theMac.getPhy().setMobility(this.mobility);
theMac.getPhy().send(new JEEvent("start_req", theMac.getPhy(), theUniqueEventScheduler.now()));
this.theMac = theMac;
}
// TODO: Roman: Why convert to ArrayList and then in sme
// build a HashMap again?
// Only this class uses the setMacs method...
sme.setMacs(new ArrayList<JE802_11Mac>(dot11MacMap.values()));
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80211Mac definition found", 10);
}
// create 802_15 Macs, if any
NodeList mac15List = (NodeList) xpath.evaluate("JE80215MAC", aTopLevelNode, XPathConstants.NODESET);
if (mac15List.getLength() > 0) {
for (int i = 0; i < mac15List.getLength(); i++) {
Node macNode = mac15List.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
theMac.setMACAddress(this.address);
theMac.getPhy().setThePhyModeList(phyModes);
theMac.getPhy().setMobility(this.mobility);
theMac.getPhy().send(new JEEvent("start_req", theMac.getPhy(), theUniqueEventScheduler.now()));
}
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80215Mac found", 10);
}
// create 802_15 Mac Low-Energy, if any
NodeList mac15LowEnergyList = (NodeList) xpath.evaluate("JE80215MAC_LowEnergy", aTopLevelNode,
XPathConstants.NODESET);
if (mac15LowEnergyList.getLength() > 0) {
for (int i = 0; i < mac15LowEnergyList.getLength(); i++) {
Node macNode = mac15LowEnergyList.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
theMac.setMACAddress(this.address);
theMac.getPhy().setThePhyModeList(phyModes);
theMac.getPhy().setMobility(this.mobility);
theMac.getPhy().send(new JEEvent("start_req", theMac.getPhy(), theUniqueEventScheduler.now()));
}
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80215Mac found", 10);
}
// TODO: Stefan, added LED MAC
// create 802 LED Macs, if any
NodeList macLEDList = (NodeList) xpath.evaluate("JE80215LEDMAC", aTopLevelNode, XPathConstants.NODESET);
if (macLEDList.getLength() > 0) {
for (int i = 0; i < macLEDList.getLength(); i++) {
Node macNode = macLEDList.item(i);
this.message("allocating " + macNode.getNodeName(), 10);
// this.dot15MacMap.put(theMac.getChannel(),
// (JE802_15Mac) theMac);
theMac.setMACAddress(this.address);
// theMac.getPhy().setThePhyModeList(phyModes);
// theMac.getPhy().setMobility(this.mobility);
// theMac.getPhy().send(new JEEvent("start_req",
// theMac.getPhy(), theUniqueEventScheduler.now()));
}
this.ipLayer = new JE802RouteManager(aScheduler, aGenerator, this.sme, statEval, this);
this.sme.setIpHandlerId(this.ipLayer.getHandlerId());
} else {
this.message("No JE80215LEDMAC found", 10);
}
// -- create TCP Manager:
// ------------------------------------------------------------------------------------------------
Node tcpNode = (Node) xpath.evaluate("JE802TCP", aTopLevelNode, XPathConstants.NODE);
this.tcp = new JE802TCPManager(aScheduler, aGenerator, tcpNode, this.ipLayer, this.statEval);
this.ipLayer.setTcpHandlerId(tcp.getHandlerId());
/*
* for (Iterator<JE802_11Mac> iterator =
* macMap.values().iterator(); iterator.hasNext();) {
* JE802_11Mac currentMac = (JE802_11Mac) iterator.next(); }
* mac.setTcpHandlerId(this.tcp.getHandlerId());
*/
// -- create traffic generators:
// ----------------------------------------------------------------------------------------
NodeList tgList = (NodeList) xpath.evaluate("JE802TrafficGen", aTopLevelNode, XPathConstants.NODESET);
for (int i = 0; i < tgList.getLength(); i++) {
Node tgNode = tgList.item(i);
this.message("allocating " + tgNode.getNodeName(), 10);
JE802TrafficGen aNewTrafficGen = new JE802TrafficGen(aScheduler, aGenerator, tgNode, this.address, aStatEval,
tcp);
this.trafficGenerators.add(aNewTrafficGen);
// stop generating traffic, usually not used:
aNewTrafficGen.send(new JEEvent("stop_req", aNewTrafficGen, aNewTrafficGen.getStopTime()));
// start generating traffic:
aNewTrafficGen.send(new JEEvent("start_req", aNewTrafficGen, aNewTrafficGen.getStartTime()));
}
if (mac15List.getLength() > 0) {
this.sme.send(new JEEvent("start_req", this.sme.getHandlerId(), theUniqueEventScheduler.now()));
}
} else {
this.message("XML definition " + aTopLevelNode.getNodeName() + " has no child nodes!", 10);
}
} else {
this.message("XML definition " + aTopLevelNode.getNodeName() + " found, but JE802Station expected!", 10);
}
if (aGui!=null) {
aGui.setupStation(this.address);
}
}
|
diff --git a/src/org/geometerplus/zlibrary/core/resources/ZLTreeResource.java b/src/org/geometerplus/zlibrary/core/resources/ZLTreeResource.java
index 61a51c31..53118ade 100644
--- a/src/org/geometerplus/zlibrary/core/resources/ZLTreeResource.java
+++ b/src/org/geometerplus/zlibrary/core/resources/ZLTreeResource.java
@@ -1,276 +1,277 @@
/*
* Copyright (C) 2007-2012 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.core.resources;
import java.util.*;
import org.geometerplus.zlibrary.core.xml.ZLStringMap;
import org.geometerplus.zlibrary.core.xml.ZLXMLReaderAdapter;
import org.geometerplus.zlibrary.core.filesystem.*;
final class ZLTreeResource extends ZLResource {
private static interface Condition {
abstract boolean accepts(int number);
}
private static class ValueCondition implements Condition {
private final int myValue;
ValueCondition(int value) {
myValue = value;
}
@Override
public boolean accepts(int number) {
return myValue == number;
}
}
private static class RangeCondition implements Condition {
private final int myMin;
private final int myMax;
RangeCondition(int min, int max) {
myMin = min;
myMax = max;
}
@Override
public boolean accepts(int number) {
return myMin <= number && number <= myMax;
}
}
private static class ModRangeCondition implements Condition {
private final int myMin;
private final int myMax;
private final int myBase;
ModRangeCondition(int min, int max, int base) {
myMin = min;
myMax = max;
myBase = base;
}
@Override
public boolean accepts(int number) {
number = number % myBase;
return myMin <= number && number <= myMax;
}
}
private static class ModCondition implements Condition {
private final int myMod;
private final int myBase;
ModCondition(int mod, int base) {
myMod = mod;
myBase = base;
}
@Override
public boolean accepts(int number) {
return number % myBase == myMod;
}
}
static private Condition parseCondition(String description) {
final String[] parts = description.split(" ");
try {
if ("range".equals(parts[0])) {
return new RangeCondition(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]));
} else if ("mod".equals(parts[0])) {
return new ModCondition(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]));
} else if ("modrange".equals(parts[0])) {
return new ModRangeCondition(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3]));
} else if ("value".equals(parts[0])) {
return new ValueCondition(Integer.parseInt(parts[1]));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
static volatile ZLTreeResource ourRoot;
private static final Object ourLock = new Object();
private static long ourTimeStamp = 0;
private static String ourLanguage = null;
private static String ourCountry = null;
private boolean myHasValue;
private String myValue;
private HashMap<String,ZLTreeResource> myChildren;
private LinkedHashMap<Condition,String> myConditionalValues;
static void buildTree() {
synchronized (ourLock) {
if (ourRoot == null) {
ourRoot = new ZLTreeResource("", null);
ourLanguage = "en";
ourCountry = "UK";
loadData();
}
}
}
private static void updateLanguage() {
final long timeStamp = System.currentTimeMillis();
if (timeStamp > ourTimeStamp + 1000) {
synchronized (ourLock) {
if (timeStamp > ourTimeStamp + 1000) {
ourTimeStamp = timeStamp;
final String language = Locale.getDefault().getLanguage();
final String country = Locale.getDefault().getCountry();
if ((language != null && !language.equals(ourLanguage)) ||
(country != null && !country.equals(ourCountry))) {
ourLanguage = language;
ourCountry = country;
loadData();
}
}
}
}
}
private static void loadData(ResourceTreeReader reader, String fileName) {
reader.readDocument(ourRoot, ZLResourceFile.createResourceFile("resources/zlibrary/" + fileName));
reader.readDocument(ourRoot, ZLResourceFile.createResourceFile("resources/application/" + fileName));
}
private static void loadData() {
ResourceTreeReader reader = new ResourceTreeReader();
loadData(reader, ourLanguage + ".xml");
loadData(reader, ourLanguage + "_" + ourCountry + ".xml");
}
private ZLTreeResource(String name, String value) {
super(name);
setValue(value);
}
private void setValue(String value) {
myHasValue = value != null;
myValue = value;
}
@Override
public boolean hasValue() {
return myHasValue;
}
@Override
public String getValue() {
updateLanguage();
return myHasValue ? myValue : ZLMissingResource.Value;
}
@Override
public String getValue(int number) {
updateLanguage();
if (myConditionalValues != null) {
for (Map.Entry<Condition,String> entry: myConditionalValues.entrySet()) {
if (entry.getKey().accepts(number)) {
return entry.getValue();
}
}
}
return myHasValue ? myValue : ZLMissingResource.Value;
}
@Override
public ZLResource getResource(String key) {
final HashMap<String,ZLTreeResource> children = myChildren;
if (children != null) {
ZLTreeResource child = children.get(key);
if (child != null) {
return child;
}
}
return ZLMissingResource.Instance;
}
private static class ResourceTreeReader extends ZLXMLReaderAdapter {
private static final String NODE = "node";
private final ArrayList<ZLTreeResource> myStack = new ArrayList<ZLTreeResource>();
public void readDocument(ZLTreeResource root, ZLFile file) {
myStack.clear();
myStack.add(root);
readQuietly(file);
}
@Override
public boolean dontCacheAttributeValues() {
return true;
}
@Override
public boolean startElementHandler(String tag, ZLStringMap attributes) {
final ArrayList<ZLTreeResource> stack = myStack;
if (!stack.isEmpty() && (NODE.equals(tag))) {
final String name = attributes.getValue("name");
final String condition = attributes.getValue("condition");
final String value = attributes.getValue("value");
final ZLTreeResource peek = stack.get(stack.size() - 1);
if (name != null) {
ZLTreeResource node;
HashMap<String,ZLTreeResource> children = peek.myChildren;
if (children == null) {
node = null;
children = new HashMap<String,ZLTreeResource>();
peek.myChildren = children;
} else {
node = children.get(name);
}
if (node == null) {
node = new ZLTreeResource(name, value);
children.put(name, node);
} else {
if (value != null) {
node.setValue(value);
+ node.myConditionalValues = null;
}
}
stack.add(node);
} else if (condition != null && value != null) {
final Condition compiled = parseCondition(condition);
if (compiled != null) {
if (peek.myConditionalValues == null) {
peek.myConditionalValues = new LinkedHashMap<Condition,String>();
}
peek.myConditionalValues.put(compiled, value);
}
stack.add(peek);
}
}
return false;
}
@Override
public boolean endElementHandler(String tag) {
final ArrayList<ZLTreeResource> stack = myStack;
if (!stack.isEmpty() && (NODE.equals(tag))) {
stack.remove(stack.size() - 1);
}
return false;
}
}
}
| true | true | public boolean startElementHandler(String tag, ZLStringMap attributes) {
final ArrayList<ZLTreeResource> stack = myStack;
if (!stack.isEmpty() && (NODE.equals(tag))) {
final String name = attributes.getValue("name");
final String condition = attributes.getValue("condition");
final String value = attributes.getValue("value");
final ZLTreeResource peek = stack.get(stack.size() - 1);
if (name != null) {
ZLTreeResource node;
HashMap<String,ZLTreeResource> children = peek.myChildren;
if (children == null) {
node = null;
children = new HashMap<String,ZLTreeResource>();
peek.myChildren = children;
} else {
node = children.get(name);
}
if (node == null) {
node = new ZLTreeResource(name, value);
children.put(name, node);
} else {
if (value != null) {
node.setValue(value);
}
}
stack.add(node);
} else if (condition != null && value != null) {
final Condition compiled = parseCondition(condition);
if (compiled != null) {
if (peek.myConditionalValues == null) {
peek.myConditionalValues = new LinkedHashMap<Condition,String>();
}
peek.myConditionalValues.put(compiled, value);
}
stack.add(peek);
}
}
return false;
}
| public boolean startElementHandler(String tag, ZLStringMap attributes) {
final ArrayList<ZLTreeResource> stack = myStack;
if (!stack.isEmpty() && (NODE.equals(tag))) {
final String name = attributes.getValue("name");
final String condition = attributes.getValue("condition");
final String value = attributes.getValue("value");
final ZLTreeResource peek = stack.get(stack.size() - 1);
if (name != null) {
ZLTreeResource node;
HashMap<String,ZLTreeResource> children = peek.myChildren;
if (children == null) {
node = null;
children = new HashMap<String,ZLTreeResource>();
peek.myChildren = children;
} else {
node = children.get(name);
}
if (node == null) {
node = new ZLTreeResource(name, value);
children.put(name, node);
} else {
if (value != null) {
node.setValue(value);
node.myConditionalValues = null;
}
}
stack.add(node);
} else if (condition != null && value != null) {
final Condition compiled = parseCondition(condition);
if (compiled != null) {
if (peek.myConditionalValues == null) {
peek.myConditionalValues = new LinkedHashMap<Condition,String>();
}
peek.myConditionalValues.put(compiled, value);
}
stack.add(peek);
}
}
return false;
}
|
diff --git a/desktop/src/restaurante/UI/Forms/FrmUsers.java b/desktop/src/restaurante/UI/Forms/FrmUsers.java
index 7812c74..858c8dc 100644
--- a/desktop/src/restaurante/UI/Forms/FrmUsers.java
+++ b/desktop/src/restaurante/UI/Forms/FrmUsers.java
@@ -1,332 +1,332 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* FrmUsers.java
*
* Created on 23/02/2013, 09:40:34
*/
package restaurante.UI.Forms;
import java.util.logging.Level;
import java.util.logging.Logger;
import restaurante.Beans.Branches;
import restaurante.Beans.Users;
import restaurante.Controller.BranchesController;
import restaurante.Controller.UsersController;
import restaurante.UI.Searchs.FrmUsersSearch;
import restaurante.Utils;
/**
*
* @author aluno
*/
public class FrmUsers extends FrmNavToolbar<Users> {
UsersController controller = new UsersController();
/** Creates new form FrmUsers */
public FrmUsers() {
initComponents();
initComboBox();
resetList();
initDefaultProperties();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSeparator1 = new javax.swing.JSeparator();
jPanel1 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
chkActive = new javax.swing.JCheckBox();
jLabel3 = new javax.swing.JLabel();
txtPasswordExpires = new javax.swing.JSpinner();
cboWorkUnit = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
txtName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtId = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
cboAccessLevel = new javax.swing.JComboBox();
txtPassword = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Usuários");
setLocationByPlatform(true);
setMinimumSize(new java.awt.Dimension(267, 251));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
- jPanel1.setMinimumSize(new java.awt.Dimension(267, 195));
- jPanel1.setPreferredSize(new java.awt.Dimension(267, 195));
+ jPanel1.setMinimumSize(new java.awt.Dimension(358, 195));
+ jPanel1.setPreferredSize(new java.awt.Dimension(358, 195));
jPanel1.setRequestFocusEnabled(false);
jLabel6.setText("Validade de senha");
chkActive.setSelected(true);
chkActive.setText("Ativo");
jLabel3.setText("Nome");
cboWorkUnit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "sfdfds", "tentie1", "aidsjids", "asjdi3ji" }));
cboWorkUnit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cboWorkUnitActionPerformed(evt);
}
});
jLabel4.setText("Senha");
jLabel1.setText("ID");
txtName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNameActionPerformed(evt);
}
});
jLabel2.setText("Nível de acesso");
txtId.setEditable(false);
txtId.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtIdActionPerformed(evt);
}
});
jLabel7.setText("Unidade de Trabalho");
cboAccessLevel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador", "Operador", "Usuário" }));
cboAccessLevel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cboAccessLevelActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel7)
.addComponent(jLabel6)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(chkActive))
.addComponent(cboAccessLevel, 0, 225, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
.addComponent(cboWorkUnit, 0, 224, Short.MAX_VALUE))
.addGap(1, 1, 1)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chkActive)
.addComponent(jLabel1))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(cboAccessLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(cboWorkUnit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addContainerGap(19, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
- .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
+ .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(56, 56, 56)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIdActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtIdActionPerformed
private void txtNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNameActionPerformed
private void cboWorkUnitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboWorkUnitActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cboWorkUnitActionPerformed
private void cboAccessLevelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboAccessLevelActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cboAccessLevelActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FrmUsers().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox cboAccessLevel;
private javax.swing.JComboBox cboWorkUnit;
private javax.swing.JCheckBox chkActive;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextField txtId;
private javax.swing.JTextField txtName;
private javax.swing.JPasswordField txtPassword;
private javax.swing.JSpinner txtPasswordExpires;
// End of variables declaration//GEN-END:variables
@Override
public boolean saveRegister() {
try {
int id = 0;
int branchId = 0;
branchId = Integer.valueOf(cboWorkUnit.getSelectedItem().toString().split(" - ")[0]);
id = !txtId.getText().equals("") ? Integer.valueOf(txtId.getText()) : 0;
id = controller.saveRecord(id, cboAccessLevel.getSelectedIndex(), txtName.getText(),
txtPassword.getText(), Integer.valueOf(txtPasswordExpires.getValue().toString()),
branchId, chkActive.isSelected());
txtId.setText(String.valueOf(id));
Utils.showInfoMessage(this, SAVE_SUCCESS);
resetList();
return true;
} catch (Exception ex) {
Logger.getLogger(FrmCustomers.class.getName()).log(Level.SEVERE, null, ex);
Utils.showErrorMessage(this, SAVE_ERROR);
}
return false;
}
@Override
public boolean deleteRegister() {
if(!Utils.showQuestionMessage(this, DELETE_CONFIRMATION)) { return false; }
try {
controller.inative(Integer.valueOf(txtId.getText()));
newRegister();
resetList();
return true;
} catch (Exception ex) {
Logger.getLogger(FrmCustomers.class.getName()).log(Level.SEVERE, null, ex);
Utils.showErrorMessage(this, DELETE_ERROR);
return false;
}
}
@Override
public void getValues(Users register) {
txtId.setText(String.valueOf(register.getId()));
cboAccessLevel.setSelectedIndex(register.getAccessLevel().ordinal());
txtName.setText(register.getName());
txtPassword.setText(register.getPassword());
cboWorkUnit.setSelectedItem(register.getBranch().getId() + " - " + register.getBranch().getName());
txtPasswordExpires.setValue(register.getPasswordExpires());
chkActive.setSelected(register.isActive());
controller.setNewRecord(false);
}
public final void resetList() {
try {
this.setList(controller.list());
newRegister();
} catch (Exception ex) {
Logger.getLogger(FrmCustomers.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void searchRegister() {
FrmUsersSearch search = new FrmUsersSearch();
search.show();
try {
getValues(controller.findById((Integer)search.getReturnId()));
} catch (Exception ex) {
Logger.getLogger(FrmCustomers.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void setNewRegisterInController() {
controller.setNewRecord(true);
}
/*
* Não é igual para todas as telas
*/
private void initComboBox() {
cboAccessLevel.removeAllItems();
for(String accessLevel : Users.AccessLevel.values) {
cboAccessLevel.addItem(accessLevel);
}
cboWorkUnit.removeAllItems();
try {
Branches[] branches = new BranchesController().list(true);
for(int i = 0; i < branches.length; i++) {
cboWorkUnit.addItem(branches[i].getId() + " - " + branches[i].getName());
}
} catch (Exception ex) {
Logger.getLogger(FrmUsers.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| false | true | private void initComponents() {
jSeparator1 = new javax.swing.JSeparator();
jPanel1 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
chkActive = new javax.swing.JCheckBox();
jLabel3 = new javax.swing.JLabel();
txtPasswordExpires = new javax.swing.JSpinner();
cboWorkUnit = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
txtName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtId = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
cboAccessLevel = new javax.swing.JComboBox();
txtPassword = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Usuários");
setLocationByPlatform(true);
setMinimumSize(new java.awt.Dimension(267, 251));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel1.setMinimumSize(new java.awt.Dimension(267, 195));
jPanel1.setPreferredSize(new java.awt.Dimension(267, 195));
jPanel1.setRequestFocusEnabled(false);
jLabel6.setText("Validade de senha");
chkActive.setSelected(true);
chkActive.setText("Ativo");
jLabel3.setText("Nome");
cboWorkUnit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "sfdfds", "tentie1", "aidsjids", "asjdi3ji" }));
cboWorkUnit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cboWorkUnitActionPerformed(evt);
}
});
jLabel4.setText("Senha");
jLabel1.setText("ID");
txtName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNameActionPerformed(evt);
}
});
jLabel2.setText("Nível de acesso");
txtId.setEditable(false);
txtId.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtIdActionPerformed(evt);
}
});
jLabel7.setText("Unidade de Trabalho");
cboAccessLevel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador", "Operador", "Usuário" }));
cboAccessLevel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cboAccessLevelActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel7)
.addComponent(jLabel6)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(chkActive))
.addComponent(cboAccessLevel, 0, 225, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
.addComponent(cboWorkUnit, 0, 224, Short.MAX_VALUE))
.addGap(1, 1, 1)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chkActive)
.addComponent(jLabel1))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(cboAccessLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(cboWorkUnit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addContainerGap(19, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(56, 56, 56)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jSeparator1 = new javax.swing.JSeparator();
jPanel1 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
chkActive = new javax.swing.JCheckBox();
jLabel3 = new javax.swing.JLabel();
txtPasswordExpires = new javax.swing.JSpinner();
cboWorkUnit = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
txtName = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtId = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
cboAccessLevel = new javax.swing.JComboBox();
txtPassword = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Usuários");
setLocationByPlatform(true);
setMinimumSize(new java.awt.Dimension(267, 251));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel1.setMinimumSize(new java.awt.Dimension(358, 195));
jPanel1.setPreferredSize(new java.awt.Dimension(358, 195));
jPanel1.setRequestFocusEnabled(false);
jLabel6.setText("Validade de senha");
chkActive.setSelected(true);
chkActive.setText("Ativo");
jLabel3.setText("Nome");
cboWorkUnit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "sfdfds", "tentie1", "aidsjids", "asjdi3ji" }));
cboWorkUnit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cboWorkUnitActionPerformed(evt);
}
});
jLabel4.setText("Senha");
jLabel1.setText("ID");
txtName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNameActionPerformed(evt);
}
});
jLabel2.setText("Nível de acesso");
txtId.setEditable(false);
txtId.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtIdActionPerformed(evt);
}
});
jLabel7.setText("Unidade de Trabalho");
cboAccessLevel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador", "Operador", "Usuário" }));
cboAccessLevel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cboAccessLevelActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel7)
.addComponent(jLabel6)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(chkActive))
.addComponent(cboAccessLevel, 0, 225, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
.addComponent(cboWorkUnit, 0, 224, Short.MAX_VALUE))
.addGap(1, 1, 1)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chkActive)
.addComponent(jLabel1))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(cboAccessLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(cboWorkUnit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(txtPasswordExpires, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addContainerGap(19, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(56, 56, 56)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/com/github/andlyticsproject/CommentsListAdapter.java b/src/com/github/andlyticsproject/CommentsListAdapter.java
index 4e60522..b1910da 100644
--- a/src/com/github/andlyticsproject/CommentsListAdapter.java
+++ b/src/com/github/andlyticsproject/CommentsListAdapter.java
@@ -1,344 +1,344 @@
package com.github.andlyticsproject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import com.github.andlyticsproject.model.Comment;
import com.github.andlyticsproject.model.CommentGroup;
import com.github.andlyticsproject.util.Utils;
public class CommentsListAdapter extends BaseExpandableListAdapter {
private static final int TYPE_COMMENT = 0;
private static final int TYPE_REPLY = 1;
private LayoutInflater layoutInflater;
private ArrayList<CommentGroup> commentGroups;
private CommentsActivity context;
private DateFormat commentDateFormat = DateFormat
.getDateInstance(DateFormat.FULL);
public CommentsListAdapter(CommentsActivity activity) {
this.setCommentGroups(new ArrayList<CommentGroup>());
this.layoutInflater = activity.getLayoutInflater();
this.context = activity;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final Comment comment = getChild(groupPosition, childPosition);
ViewHolderChild holder;
if (convertView == null) {
convertView = layoutInflater.inflate(
comment.isReply() ? R.layout.comments_list_item_reply
: R.layout.comments_list_item_comment, null);
holder = new ViewHolderChild();
holder.text = (TextView) convertView
.findViewById(R.id.comments_list_item_text);
holder.title = (TextView) convertView
.findViewById(R.id.comments_list_item_title);
holder.user = (TextView) convertView
.findViewById(R.id.comments_list_item_username);
holder.date = (TextView) convertView
.findViewById(R.id.comments_list_item_date);
holder.device = (TextView) convertView
.findViewById(R.id.comments_list_item_device);
holder.version = (TextView) convertView
.findViewById(R.id.comments_list_item_version);
holder.rating = (RatingBar) convertView
.findViewById(R.id.comments_list_item_app_ratingbar);
holder.deviceVersionContainer = (LinearLayout) convertView
.findViewById(R.id.comments_list_item_device_container);
holder.deviceIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_device);
holder.versionIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_version);
holder.language = (TextView) convertView
.findViewById(R.id.comments_list_item_language);
holder.languageIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_language);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
if (comment.isReply()) {
holder.date.setText(formatCommentDate(comment.getDate()));
holder.text.setText(comment.getText());
} else {
String commentText = comment.getText();
if (!Preferences.isShowCommentAutoTranslations(context)
&& comment.getOriginalText() != null) {
commentText = comment.getOriginalText();
}
String originalText[] = comment.getOriginalText().split("\\t");
if (originalText != null && originalText.length > 1) {
holder.title.setText(originalText[0]);
- if (!Preferences.isShowCommentAutoTranslations(context)) {
+ if (Preferences.isShowCommentAutoTranslations(context)) {
holder.text.setText(commentText);
} else {
holder.text.setText(originalText[1]);
}
holder.text.setVisibility(View.VISIBLE);
} else if (originalText != null && originalText.length == 1) {
holder.text.setText(commentText);
holder.title.setText(null);
holder.title.setVisibility(View.GONE);
}
holder.user.setText(comment.getUser() == null ? context
.getString(R.string.comment_no_user_info) : comment
.getUser());
String version = comment.getAppVersion();
String device = comment.getDevice();
String language = comment.getLanguage();
holder.deviceIcon.setVisibility(View.GONE);
holder.versionIcon.setVisibility(View.GONE);
holder.version.setVisibility(View.GONE);
holder.device.setVisibility(View.GONE);
holder.language.setVisibility(View.GONE);
holder.languageIcon.setVisibility(View.GONE);
boolean showInfoBox = false;
// building version/device
if (isNotEmptyOrNull(version)) {
holder.version.setText(version);
holder.versionIcon.setVisibility(View.VISIBLE);
holder.version.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (isNotEmptyOrNull(device)) {
holder.device.setText(device);
holder.deviceIcon.setVisibility(View.VISIBLE);
holder.device.setVisibility(View.VISIBLE);
showInfoBox = true;
}
// TODO better UI for language, option to show original text?
if (isNotEmptyOrNull(language)) {
holder.language.setText(formatLanguageString(comment
.getLanguage()));
holder.language.setVisibility(View.VISIBLE);
holder.languageIcon.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (showInfoBox) {
holder.deviceVersionContainer.setVisibility(View.VISIBLE);
} else {
holder.deviceVersionContainer.setVisibility(View.GONE);
}
int rating = comment.getRating();
if (rating > 0 && rating <= 5) {
holder.rating.setRating((float) rating);
}
}
convertView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
String text = comment.getText();
String displayLanguage = Locale.getDefault().getLanguage();
if (Preferences.isUseGoogleTranslateApp(context)
&& isGoogleTranslateInstalled()) {
sendToGoogleTranslate(text, displayLanguage);
return true;
}
String url = "http://translate.google.de/m/translate?hl=<<lang>>&vi=m&text=<<text>>&langpair=auto|<<lang>>";
try {
url = url.replaceAll("<<lang>>",
URLEncoder.encode(displayLanguage, "UTF-8"));
url = url.replaceAll("<<text>>",
URLEncoder.encode(text, "UTF-8"));
Log.d("CommentsTranslate", "lang: " + displayLanguage
+ " url: " + url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return true;
}
});
return convertView;
}
private boolean isGoogleTranslateInstalled() {
return Utils.isPackageInstalled(context,
"com.google.android.apps.translate");
}
private String formatLanguageString(String language) {
if (language != null && language.indexOf("_") > 0) {
String[] parts = language.split("_");
if (parts.length > 1
&& parts[0].toUpperCase(Locale.ENGLISH).equals(
parts[1].toUpperCase(Locale.ENGLISH))) {
return parts[1].toUpperCase(Locale.ENGLISH);
} else {
return language.replaceAll("_", "/");
}
} else {
return language;
}
}
private void sendToGoogleTranslate(String text, String displayLanguage) {
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.putExtra("key_text_input", text);
i.putExtra("key_text_output", "");
i.putExtra("key_language_from", "auto");
i.putExtra("key_language_to", displayLanguage);
i.putExtra("key_suggest_translation", "");
i.putExtra("key_from_floating_window", false);
i.setComponent(new ComponentName("com.google.android.apps.translate",
"com.google.android.apps.translate.translation.TranslateActivity"));
context.startActivity(i);
}
@Override
public int getChildType(int groupPosition, int childPosition) {
return getChild(groupPosition, childPosition).isReply() ? TYPE_REPLY
: TYPE_COMMENT;
}
@Override
public int getChildTypeCount() {
return 2;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
ViewHolderGroup holder;
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.comments_list_item_group_header, null);
holder = new ViewHolderGroup();
holder.date = (TextView) convertView
.findViewById(R.id.comments_list_item_date);
convertView.setTag(holder);
} else {
holder = (ViewHolderGroup) convertView.getTag();
}
CommentGroup commentGroup = getGroup(groupPosition);
holder.date.setText(formatCommentDate(commentGroup.getDate()));
return convertView;
}
private boolean isNotEmptyOrNull(String str) {
return str != null && str.length() > 0;
}
static class ViewHolderGroup {
TextView date;
}
static class ViewHolderChild {
RatingBar rating;
TextView text;
TextView title;
TextView user;
TextView date;
LinearLayout deviceVersionContainer;
ImageView deviceIcon;
ImageView versionIcon;
TextView device;
TextView version;
TextView language;
ImageView languageIcon;
}
@Override
public int getGroupCount() {
return getCommentGroups().size();
}
@Override
public int getChildrenCount(int groupPosition) {
return getCommentGroups().get(groupPosition).getComments().size();
}
@Override
public CommentGroup getGroup(int groupPosition) {
return getCommentGroups().get(groupPosition);
}
@Override
public Comment getChild(int groupPosition, int childPosition) {
return getCommentGroups().get(groupPosition).getComments()
.get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
public void setCommentGroups(ArrayList<CommentGroup> commentGroups) {
this.commentGroups = commentGroups;
}
public ArrayList<CommentGroup> getCommentGroups() {
return commentGroups;
}
private String formatCommentDate(Date date) {
return commentDateFormat.format(date);
}
}
| true | true | public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final Comment comment = getChild(groupPosition, childPosition);
ViewHolderChild holder;
if (convertView == null) {
convertView = layoutInflater.inflate(
comment.isReply() ? R.layout.comments_list_item_reply
: R.layout.comments_list_item_comment, null);
holder = new ViewHolderChild();
holder.text = (TextView) convertView
.findViewById(R.id.comments_list_item_text);
holder.title = (TextView) convertView
.findViewById(R.id.comments_list_item_title);
holder.user = (TextView) convertView
.findViewById(R.id.comments_list_item_username);
holder.date = (TextView) convertView
.findViewById(R.id.comments_list_item_date);
holder.device = (TextView) convertView
.findViewById(R.id.comments_list_item_device);
holder.version = (TextView) convertView
.findViewById(R.id.comments_list_item_version);
holder.rating = (RatingBar) convertView
.findViewById(R.id.comments_list_item_app_ratingbar);
holder.deviceVersionContainer = (LinearLayout) convertView
.findViewById(R.id.comments_list_item_device_container);
holder.deviceIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_device);
holder.versionIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_version);
holder.language = (TextView) convertView
.findViewById(R.id.comments_list_item_language);
holder.languageIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_language);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
if (comment.isReply()) {
holder.date.setText(formatCommentDate(comment.getDate()));
holder.text.setText(comment.getText());
} else {
String commentText = comment.getText();
if (!Preferences.isShowCommentAutoTranslations(context)
&& comment.getOriginalText() != null) {
commentText = comment.getOriginalText();
}
String originalText[] = comment.getOriginalText().split("\\t");
if (originalText != null && originalText.length > 1) {
holder.title.setText(originalText[0]);
if (!Preferences.isShowCommentAutoTranslations(context)) {
holder.text.setText(commentText);
} else {
holder.text.setText(originalText[1]);
}
holder.text.setVisibility(View.VISIBLE);
} else if (originalText != null && originalText.length == 1) {
holder.text.setText(commentText);
holder.title.setText(null);
holder.title.setVisibility(View.GONE);
}
holder.user.setText(comment.getUser() == null ? context
.getString(R.string.comment_no_user_info) : comment
.getUser());
String version = comment.getAppVersion();
String device = comment.getDevice();
String language = comment.getLanguage();
holder.deviceIcon.setVisibility(View.GONE);
holder.versionIcon.setVisibility(View.GONE);
holder.version.setVisibility(View.GONE);
holder.device.setVisibility(View.GONE);
holder.language.setVisibility(View.GONE);
holder.languageIcon.setVisibility(View.GONE);
boolean showInfoBox = false;
// building version/device
if (isNotEmptyOrNull(version)) {
holder.version.setText(version);
holder.versionIcon.setVisibility(View.VISIBLE);
holder.version.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (isNotEmptyOrNull(device)) {
holder.device.setText(device);
holder.deviceIcon.setVisibility(View.VISIBLE);
holder.device.setVisibility(View.VISIBLE);
showInfoBox = true;
}
// TODO better UI for language, option to show original text?
if (isNotEmptyOrNull(language)) {
holder.language.setText(formatLanguageString(comment
.getLanguage()));
holder.language.setVisibility(View.VISIBLE);
holder.languageIcon.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (showInfoBox) {
holder.deviceVersionContainer.setVisibility(View.VISIBLE);
} else {
holder.deviceVersionContainer.setVisibility(View.GONE);
}
int rating = comment.getRating();
if (rating > 0 && rating <= 5) {
holder.rating.setRating((float) rating);
}
}
convertView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
String text = comment.getText();
String displayLanguage = Locale.getDefault().getLanguage();
if (Preferences.isUseGoogleTranslateApp(context)
&& isGoogleTranslateInstalled()) {
sendToGoogleTranslate(text, displayLanguage);
return true;
}
String url = "http://translate.google.de/m/translate?hl=<<lang>>&vi=m&text=<<text>>&langpair=auto|<<lang>>";
try {
url = url.replaceAll("<<lang>>",
URLEncoder.encode(displayLanguage, "UTF-8"));
url = url.replaceAll("<<text>>",
URLEncoder.encode(text, "UTF-8"));
Log.d("CommentsTranslate", "lang: " + displayLanguage
+ " url: " + url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return true;
}
});
return convertView;
}
| public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final Comment comment = getChild(groupPosition, childPosition);
ViewHolderChild holder;
if (convertView == null) {
convertView = layoutInflater.inflate(
comment.isReply() ? R.layout.comments_list_item_reply
: R.layout.comments_list_item_comment, null);
holder = new ViewHolderChild();
holder.text = (TextView) convertView
.findViewById(R.id.comments_list_item_text);
holder.title = (TextView) convertView
.findViewById(R.id.comments_list_item_title);
holder.user = (TextView) convertView
.findViewById(R.id.comments_list_item_username);
holder.date = (TextView) convertView
.findViewById(R.id.comments_list_item_date);
holder.device = (TextView) convertView
.findViewById(R.id.comments_list_item_device);
holder.version = (TextView) convertView
.findViewById(R.id.comments_list_item_version);
holder.rating = (RatingBar) convertView
.findViewById(R.id.comments_list_item_app_ratingbar);
holder.deviceVersionContainer = (LinearLayout) convertView
.findViewById(R.id.comments_list_item_device_container);
holder.deviceIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_device);
holder.versionIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_version);
holder.language = (TextView) convertView
.findViewById(R.id.comments_list_item_language);
holder.languageIcon = (ImageView) convertView
.findViewById(R.id.comments_list_icon_language);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
if (comment.isReply()) {
holder.date.setText(formatCommentDate(comment.getDate()));
holder.text.setText(comment.getText());
} else {
String commentText = comment.getText();
if (!Preferences.isShowCommentAutoTranslations(context)
&& comment.getOriginalText() != null) {
commentText = comment.getOriginalText();
}
String originalText[] = comment.getOriginalText().split("\\t");
if (originalText != null && originalText.length > 1) {
holder.title.setText(originalText[0]);
if (Preferences.isShowCommentAutoTranslations(context)) {
holder.text.setText(commentText);
} else {
holder.text.setText(originalText[1]);
}
holder.text.setVisibility(View.VISIBLE);
} else if (originalText != null && originalText.length == 1) {
holder.text.setText(commentText);
holder.title.setText(null);
holder.title.setVisibility(View.GONE);
}
holder.user.setText(comment.getUser() == null ? context
.getString(R.string.comment_no_user_info) : comment
.getUser());
String version = comment.getAppVersion();
String device = comment.getDevice();
String language = comment.getLanguage();
holder.deviceIcon.setVisibility(View.GONE);
holder.versionIcon.setVisibility(View.GONE);
holder.version.setVisibility(View.GONE);
holder.device.setVisibility(View.GONE);
holder.language.setVisibility(View.GONE);
holder.languageIcon.setVisibility(View.GONE);
boolean showInfoBox = false;
// building version/device
if (isNotEmptyOrNull(version)) {
holder.version.setText(version);
holder.versionIcon.setVisibility(View.VISIBLE);
holder.version.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (isNotEmptyOrNull(device)) {
holder.device.setText(device);
holder.deviceIcon.setVisibility(View.VISIBLE);
holder.device.setVisibility(View.VISIBLE);
showInfoBox = true;
}
// TODO better UI for language, option to show original text?
if (isNotEmptyOrNull(language)) {
holder.language.setText(formatLanguageString(comment
.getLanguage()));
holder.language.setVisibility(View.VISIBLE);
holder.languageIcon.setVisibility(View.VISIBLE);
showInfoBox = true;
}
if (showInfoBox) {
holder.deviceVersionContainer.setVisibility(View.VISIBLE);
} else {
holder.deviceVersionContainer.setVisibility(View.GONE);
}
int rating = comment.getRating();
if (rating > 0 && rating <= 5) {
holder.rating.setRating((float) rating);
}
}
convertView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
String text = comment.getText();
String displayLanguage = Locale.getDefault().getLanguage();
if (Preferences.isUseGoogleTranslateApp(context)
&& isGoogleTranslateInstalled()) {
sendToGoogleTranslate(text, displayLanguage);
return true;
}
String url = "http://translate.google.de/m/translate?hl=<<lang>>&vi=m&text=<<text>>&langpair=auto|<<lang>>";
try {
url = url.replaceAll("<<lang>>",
URLEncoder.encode(displayLanguage, "UTF-8"));
url = url.replaceAll("<<text>>",
URLEncoder.encode(text, "UTF-8"));
Log.d("CommentsTranslate", "lang: " + displayLanguage
+ " url: " + url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return true;
}
});
return convertView;
}
|
diff --git a/opentestbed/src/ww10/RequestHandler.java b/opentestbed/src/ww10/RequestHandler.java
index 26a9bb8..e035fa3 100644
--- a/opentestbed/src/ww10/RequestHandler.java
+++ b/opentestbed/src/ww10/RequestHandler.java
@@ -1,536 +1,541 @@
package ww10;
import game.PublicPlayerInfo;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.biotools.meerkat.GameInfo;
import ww10.exception.InvalidInputException;
import ww10.exception.AuthorizationException;
import ww10.exception.TableFullException;
import ww10.DataModel;
import bots.prologbot.PrologBot;
public class RequestHandler implements Runnable {
private Socket clientSocket;
private PrologBotServer server;
public RequestHandler(Socket clientSocket, PrologBotServer server)
{
this.clientSocket = clientSocket;
this.server = server;
}
@Override
public void run() {
try {
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
handleRequest(inputStream, outputStream);
inputStream.close();
outputStream.close();
clientSocket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("Accept failed: 4444");
//System.exit(-1);
}
}
private void handleRequest(InputStream inputStream, OutputStream outputStream) {
DataOutputStream out = new DataOutputStream(outputStream);
try {
String request = IOUtils.toString(inputStream);
//TEST TODO: remove console feedback
System.out.println("Incoming request: " + request);
JSONObject requestO = new JSONObject(request).getJSONObject("request");
String requestType = requestO.getString("type");
String reply = null;
if(requestType.equals( "startTable")){
reply = handleStartTableRequest(requestO);
}
else if(requestType.equals( "joinTable")){
reply = handleJoinTableRequest(requestO);
}
else if(requestType.equals( "fetchData")){
reply = handleFetchDataRequest(requestO);
}
else if(requestType.equals("listTables")){
reply = handleListTablesRequest();
}
// Admin functionality
else if(requestType.equals("stopTable")){
reply = handleStopTableRequest(requestO);
}
else if(requestType.equals("killTable")){
reply = handleKillTableRequest(requestO);
}
else if(requestType.equals("killTestTable")){
reply = handleKillTestTableRequest(requestO);
}
else if(requestType.equals("resumeTable")){
reply = handleResumeTableRequest(requestO);
}
else if(requestType.equals("leaveTable")){
reply = handleLeaveTableRequest(requestO);
}
else if(requestType.equals("kickPlayer")){
reply = handleKickTableRequest(requestO);
}
else{
//requestType does not match any known request -> Error
throw new InvalidInputException("RequestType " + requestType +
" does not match any known request");
}
if(reply != null){
out.writeBytes(reply);
}
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("Could not parse from inputstream.");
//System.exit(-1);
} catch (JSONException e) {
+ System.out.println(e.getMessage());
+ e.printStackTrace();
try {
out.writeBytes(createError("JSON", "Could not parse from JSON"));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
} catch (InvalidInputException e){
+ System.out.println("Invalid input: "+e.getMessage());
try {
out.writeBytes(createError("InvalidInput", e.getMessage()));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
} catch (TableFullException e){
+ System.out.println("Table is full: "+e.getMessage());
try {
out.writeBytes(createError("TableFull", e.getMessage()));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
} catch (AuthorizationException e) {
+ System.out.println("Authorization failure: "+e.getMessage());
try {
out.writeBytes(createError("Authorization", e.getMessage()));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
}
System.out.println("Message handled");
- try {
- inputStream.close();
- } catch (IOException e) {
- System.out.println("Could not close inputstream");
- e.printStackTrace();
- }
+ try {
+ inputStream.close();
+ } catch (IOException e) {
+ System.out.println("Could not close inputstream");
+ e.printStackTrace();
+ }
}
private String handleFetchDataRequest(JSONObject requestO) throws JSONException, IOException, InvalidInputException {
String tableName = requestO.getString("tableName");
JSONObject results = new JSONObject();
JSONArray players = new JSONArray();
Table table = server.getTable(tableName);
if(table == null){
throw new InvalidInputException("Table " +tableName + " does not exist");
}
server.tableReceivedRequest(tableName);
DataModel tableResults = table.getDataModel();
for(String player: tableResults.getPlayerNames())
{
players.put(getPlayerStats(player, tableResults));
}
JSONObject player = new JSONObject();
player.put("player", players);
results.put("result", player);
if(table.isRunning())
{
results.put("gamesPerSec", tableResults.getGamesPerSecond());
}
else
{
results.put("gamesPerSec", 0);
}
results.put("bigBlind", server.getGameparameters().getBigBlind());
results.put("smallBlind", server.getGameparameters().getSmallBlind());
results.put("minimumRaise", server.getGameparameters().getBigBlind());
results.put("startMoney", server.getGameparameters().getInitialBankroll());
String reply = results.toString();
System.out.println("reply");
return reply;
}
private String handleStartTableRequest(JSONObject requestO) throws JSONException, InvalidInputException{
String tableName = requestO.getString("tableName");
int nbPlayers = requestO.getInt("nbPlayers");
if(server.getTable(tableName) != null){
throw new InvalidInputException("Table " + tableName + " already exists.");
}
if(nbPlayers <= 1 || nbPlayers >= 24){
throw new InvalidInputException("Can not support a table with " + nbPlayers + " players." +
"Only values between 2 and 23 are accepted.");
}
String pw = requestO.getString("password");
Table currTable =
new Table(tableName, nbPlayers, pw, server.getGameparameters());
currTable.run();
server.addTable(tableName, currTable);
System.out.println("Created table " + tableName + " for " + nbPlayers + " players.");
return createReply("Created table " + tableName + " for " + nbPlayers + " players.");
}
private String handleJoinTableRequest(JSONObject requestO)
throws JSONException, InvalidInputException, TableFullException{
String tableName = requestO.getString("tableName");
Table table = server.getTable(tableName);
if(table == null){
throw new InvalidInputException("Table " + tableName + " does not exist.");
}
server.tableReceivedRequest(tableName);
String playerName = requestO.getString("playerName");
onNewBot(requestO, table);
table.resume();
System.out.println("Player " + playerName + " has joined table " + tableName + ".");
return createReply("Player " + playerName + " has joined table " + tableName + ".");
}
private String handleLeaveTableRequest(JSONObject requestO) throws JSONException, InvalidInputException{
String tableName = requestO.getString("tableName");
Table table = server.getTable(tableName);
if(table == null)
{
if(table == null){
throw new InvalidInputException("Table " + tableName + " does not exist.");
}
}
server.tableReceivedRequest(tableName);
String playerName = requestO.getString("playerName");
onLeavingTable(playerName, table);
table.resume();
return createReply("Player " + playerName + " has left table " + tableName + ".");
}
private String handleKickTableRequest(JSONObject requestO) throws JSONException, InvalidInputException, AuthorizationException{
String tableName = requestO.getString("tableName");
String pw = requestO.getString("password");
Table table = server.getTable(tableName);
if(table == null)
{
if(table == null){
throw new InvalidInputException("Table " + tableName + " does not exist.");
}
}
if(table.passwordValid(pw)){
return handleLeaveTableRequest(requestO);
}
else{
throw new AuthorizationException("Password is incorrect.");
}
}
private String handleListTablesRequest() throws JSONException{
JSONObject result = new JSONObject();
JSONArray tables = new JSONArray();
for(String tableName: server.listTableNames()){
Table currTable = server.getTable(tableName);
JSONObject currTableJSON = new JSONObject();
currTableJSON.put("name", tableName);
currTableJSON.put("nbPlayers", currTable.getGameInfo().getNumPlayers());
currTableJSON.put("running", currTable.isRunning());
tables.put(currTableJSON);
}
result.put("tables", tables);
return result.toString();
}
private String handleStopTableRequest(JSONObject requestO) throws JSONException, InvalidInputException, AuthorizationException{
String tableName = requestO.getString("tableName");
Table table = server.getTable(tableName);
if(table==null){
throw new InvalidInputException("Simulation of table " + tableName + " cannot be stopped as " +
"it does not exist");
}
if(table.passwordValid(requestO.getString("password"))){
table.stop();
}
else
{
throw new AuthorizationException("Password is incorrect.");
}
return createReply("Stopped simulation of table " + tableName +
". Table data are still available");
}
private String handleKillTableRequest(JSONObject requestO) throws JSONException, InvalidInputException, AuthorizationException{
String tableName = requestO.getString("tableName");
Table table = server.getTable(tableName);
if(table==null){
throw new InvalidInputException("Data of table " + tableName + " cannot be removed as " +
"it does not exist");
}
if(table.passwordValid(requestO.getString("password"))){
table.terminate();
server.removeTable(tableName);
}
else
{
throw new AuthorizationException("Password is incorrect.");
}
return createReply("Removed table " + tableName +
" from records and stopped its simulation");
}
private String handleKillTestTableRequest(JSONObject requestO) throws InvalidInputException, JSONException{
String tableName = requestO.getString("tableName");
Table table = server.getTable(tableName);
if(table==null){
throw new InvalidInputException("Data of table " + tableName + " cannot be removed as " +
"it does not exist");
}
table.terminate();
server.removeTable(tableName);
return createReply("Removed test table " + tableName +
" from records and stopped its simulation");
}
private String handleResumeTableRequest(JSONObject requestO) throws JSONException, InvalidInputException, AuthorizationException{
String tableName = requestO.getString("tableName");
Table table = server.getTable(tableName);
if(table==null){
throw new InvalidInputException("Data of table " + tableName + " cannot be removed as " +
"it does not exist");
}
if(table.passwordValid(requestO.getString("password"))){
table.resume();
}
else
{
throw new AuthorizationException("Password is incorrect.");
}
return createReply("Resumed simulation of table " + tableName + ".");
}
private JSONObject getPlayerStats(String player, DataModel tableResults) throws JSONException{
JSONObject currPlayer = new JSONObject();
currPlayer.put("name", tableResults.getChosenName(player));
//Put average profit
double avg = tableResults.getAvgProfit(player);
currPlayer.put("avg profit", avg);
//Put actions
int nbFold = tableResults.getNbFolds(player);
int nbRaise = tableResults.getNbRaises(player);
int nbCall = tableResults.getNbCalls(player);
currPlayer.put("nbFolds", nbFold);
currPlayer.put("nbRaises", nbRaise);
currPlayer.put("nbCalls", nbCall);
//Put thinking time
long thinkingTime = tableResults.getRunTime(player);
currPlayer.put("time used", thinkingTime);
//Put rules used
HashMap<String, Integer> rulesUsed = tableResults.getRulesUsed(player);
JSONArray rulesJSON = new JSONArray();
for(String ruleName: rulesUsed.keySet()){
JSONObject rule = new JSONObject();
rule.put("name", ruleName);
rule.put("times", rulesUsed.get(ruleName));
rulesJSON.put(rule);
}
currPlayer.put("rulesUsed", rulesJSON);
//Put last submit time
currPlayer.put("lastSubmit", tableResults.getLastSubmit(player));
return currPlayer;
}
protected void onNewBot(JSONObject botDescr, Table table) throws JSONException, TableFullException {
String playerName = botDescr.getString("playerName");
String fixedName = table.getDataModel().getFixedName(playerName);
PublicPlayerInfo playerInfo = table.getGameInfo().getPlayer(playerName);
if(fixedName != null)
{
//player exists -- overwrite profile
playerInfo = table.getGameInfo().getPlayer(fixedName);
}
else
{
//player does not yet exist -- find and replace a callbot
int i=0;
boolean found = false;
while(!found && i< table.getGameInfo().getNumPlayers())
{
playerInfo = table.getGameInfo().getPlayer(i);
if(playerInfo.isCallbot()){
found = true;
}
i++;
}
if(!found){
//If neither, error, no player profile can be used
throw new TableFullException("There is no more room on the table");
}
}
PrologBot bot = (PrologBot) playerInfo.getBot();
//playerInfo.setName(playerName);
playerInfo.setCallbot(false);
bot.setProlog(botDescr.getString("description"));
table.getDataModel().onSubmit(bot.getName(), truncate(playerName));
}
protected void onLeavingTable(String playerName, Table table) throws InvalidInputException{
String fixedName = table.getDataModel().getFixedName(playerName);
if(fixedName == null){
throw new InvalidInputException("Player " + playerName + " is not playing at table " + table.getTableName());
}
PublicPlayerInfo playerInfo = table.getGameInfo().getPlayer(fixedName);
GameInfo gameInfo = playerInfo.getGameInfo();
PrologBot bot = (PrologBot) table.getBotRepository().createBot("PrologBot/PrologBot");
bot.setGameInfo(gameInfo);
bot.setIngameName(fixedName);
playerInfo.setBot(bot);
playerInfo.setCallbot(true);
table.getDataModel().onSubmit(fixedName, fixedName);
}
private String truncate(String name) {
if (name.length() > 20)
return name.substring(0, 20);
else
return name;
}
private String createError(String name, String message){
JSONObject error = new JSONObject();
try {
error.put("type", "error");
error.put("name", name);
error.put("message", message);
} catch (JSONException e) {
// Should not occur!
e.printStackTrace();
}
return error.toString();
}
private String createReply(String message){
JSONObject reply = new JSONObject();
try {
reply.put("type", "Acknowledge");
reply.put("message", message);
} catch (JSONException e) {
// Should not occur!
e.printStackTrace();
}
return reply.toString();
}
}
| false | true | private void handleRequest(InputStream inputStream, OutputStream outputStream) {
DataOutputStream out = new DataOutputStream(outputStream);
try {
String request = IOUtils.toString(inputStream);
//TEST TODO: remove console feedback
System.out.println("Incoming request: " + request);
JSONObject requestO = new JSONObject(request).getJSONObject("request");
String requestType = requestO.getString("type");
String reply = null;
if(requestType.equals( "startTable")){
reply = handleStartTableRequest(requestO);
}
else if(requestType.equals( "joinTable")){
reply = handleJoinTableRequest(requestO);
}
else if(requestType.equals( "fetchData")){
reply = handleFetchDataRequest(requestO);
}
else if(requestType.equals("listTables")){
reply = handleListTablesRequest();
}
// Admin functionality
else if(requestType.equals("stopTable")){
reply = handleStopTableRequest(requestO);
}
else if(requestType.equals("killTable")){
reply = handleKillTableRequest(requestO);
}
else if(requestType.equals("killTestTable")){
reply = handleKillTestTableRequest(requestO);
}
else if(requestType.equals("resumeTable")){
reply = handleResumeTableRequest(requestO);
}
else if(requestType.equals("leaveTable")){
reply = handleLeaveTableRequest(requestO);
}
else if(requestType.equals("kickPlayer")){
reply = handleKickTableRequest(requestO);
}
else{
//requestType does not match any known request -> Error
throw new InvalidInputException("RequestType " + requestType +
" does not match any known request");
}
if(reply != null){
out.writeBytes(reply);
}
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("Could not parse from inputstream.");
//System.exit(-1);
} catch (JSONException e) {
try {
out.writeBytes(createError("JSON", "Could not parse from JSON"));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
} catch (InvalidInputException e){
try {
out.writeBytes(createError("InvalidInput", e.getMessage()));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
} catch (TableFullException e){
try {
out.writeBytes(createError("TableFull", e.getMessage()));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
} catch (AuthorizationException e) {
try {
out.writeBytes(createError("Authorization", e.getMessage()));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
}
System.out.println("Message handled");
try {
inputStream.close();
} catch (IOException e) {
System.out.println("Could not close inputstream");
e.printStackTrace();
}
}
| private void handleRequest(InputStream inputStream, OutputStream outputStream) {
DataOutputStream out = new DataOutputStream(outputStream);
try {
String request = IOUtils.toString(inputStream);
//TEST TODO: remove console feedback
System.out.println("Incoming request: " + request);
JSONObject requestO = new JSONObject(request).getJSONObject("request");
String requestType = requestO.getString("type");
String reply = null;
if(requestType.equals( "startTable")){
reply = handleStartTableRequest(requestO);
}
else if(requestType.equals( "joinTable")){
reply = handleJoinTableRequest(requestO);
}
else if(requestType.equals( "fetchData")){
reply = handleFetchDataRequest(requestO);
}
else if(requestType.equals("listTables")){
reply = handleListTablesRequest();
}
// Admin functionality
else if(requestType.equals("stopTable")){
reply = handleStopTableRequest(requestO);
}
else if(requestType.equals("killTable")){
reply = handleKillTableRequest(requestO);
}
else if(requestType.equals("killTestTable")){
reply = handleKillTestTableRequest(requestO);
}
else if(requestType.equals("resumeTable")){
reply = handleResumeTableRequest(requestO);
}
else if(requestType.equals("leaveTable")){
reply = handleLeaveTableRequest(requestO);
}
else if(requestType.equals("kickPlayer")){
reply = handleKickTableRequest(requestO);
}
else{
//requestType does not match any known request -> Error
throw new InvalidInputException("RequestType " + requestType +
" does not match any known request");
}
if(reply != null){
out.writeBytes(reply);
}
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println("Could not parse from inputstream.");
//System.exit(-1);
} catch (JSONException e) {
System.out.println(e.getMessage());
e.printStackTrace();
try {
out.writeBytes(createError("JSON", "Could not parse from JSON"));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
} catch (InvalidInputException e){
System.out.println("Invalid input: "+e.getMessage());
try {
out.writeBytes(createError("InvalidInput", e.getMessage()));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
} catch (TableFullException e){
System.out.println("Table is full: "+e.getMessage());
try {
out.writeBytes(createError("TableFull", e.getMessage()));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
} catch (AuthorizationException e) {
System.out.println("Authorization failure: "+e.getMessage());
try {
out.writeBytes(createError("Authorization", e.getMessage()));
} catch (IOException e1) {
// Can not reach the webserver - not much can be done about this...
e1.printStackTrace();
}
}
System.out.println("Message handled");
try {
inputStream.close();
} catch (IOException e) {
System.out.println("Could not close inputstream");
e.printStackTrace();
}
}
|
diff --git a/CommandsEX/src/com/github/zathrus_writer/commandsex/helpers/ClosestMatches.java b/CommandsEX/src/com/github/zathrus_writer/commandsex/helpers/ClosestMatches.java
index 13dbd48..54dd559 100644
--- a/CommandsEX/src/com/github/zathrus_writer/commandsex/helpers/ClosestMatches.java
+++ b/CommandsEX/src/com/github/zathrus_writer/commandsex/helpers/ClosestMatches.java
@@ -1,174 +1,174 @@
package com.github.zathrus_writer.commandsex.helpers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Ocelot.Type;
import org.bukkit.entity.Villager.Profession;
public class ClosestMatches {
public static List<Material> material(String input) {
ArrayList<Material> values = new ArrayList<Material>();
ArrayList<Material> matches = new ArrayList<Material>();
for (Material mat : Material.values()){
if (!values.contains(mat)){
if (mat == Material.PISTON_STICKY_BASE && !values.contains(Material.PISTON_BASE)){
values.add(Material.PISTON_BASE);
values.add(Material.PISTON_STICKY_BASE);
} else if (mat == Material.REDSTONE_TORCH_OFF && !values.contains(Material.REDSTONE_TORCH_ON)){
values.add(Material.REDSTONE_TORCH_ON);
values.add(Material.REDSTONE_TORCH_OFF);
} else {
values.add(mat);
}
}
}
for (Material mat : values){
if ((mat.name().replace("_", "").toLowerCase().equals(input.toLowerCase()) || String.valueOf(mat.getId()).equals(input))){
return Arrays.asList(mat);
} else if (mat.name().replace("_", "").toLowerCase().contains(input.toLowerCase())){
matches.add(mat);
} else if ("stonebrick".contains(input.toLowerCase())){
return Arrays.asList(Material.SMOOTH_BRICK);
} else if ("stickypiston".contains(input.toLowerCase())){
return Arrays.asList(Material.PISTON_STICKY_BASE);
} else if ("doubleslab".contains(input.toLowerCase())){
return Arrays.asList(Material.DOUBLE_STEP);
}
}
return matches;
}
public static List<Profession> villagerProfessions(String input){
ArrayList<Profession> matches = new ArrayList<Profession>();
for (Profession prof : Profession.values()){
if ((prof.name().replace("_", "").toLowerCase().equals(input.toLowerCase()) || String.valueOf(prof.getId()).equals(input))){
return Arrays.asList(prof);
} else if (prof.name().replace("_", "").toLowerCase().contains(input.toLowerCase())){
matches.add(prof);
}
}
return matches;
}
public static List<EntityType> spawnableEntity(String input) {
ArrayList<EntityType> matches = new ArrayList<EntityType>();
for (EntityType en : EntityType.values()){
if (en.isSpawnable()){
if ((en.name().replace("_", "").toLowerCase().equals(input.toLowerCase()) || String.valueOf(en.getTypeId()).equals(input))){
return Arrays.asList(en);
} else if (en.name().replace("_", "").toLowerCase().contains(input.toLowerCase())){
matches.add(en);
}
}
}
return matches;
}
public static List<EntityType> livingEntity(String input) {
ArrayList<EntityType> matches = new ArrayList<EntityType>();
for (EntityType en : EntityType.values()){
if (en.isAlive() && en.isSpawnable()){
if ((en.name().replace("_", "").toLowerCase().equals(input.toLowerCase()) || String.valueOf(en.getTypeId()).equals(input))){
return Arrays.asList(en);
} else if (en.name().replace("_", "").toLowerCase().contains(input.toLowerCase())){
matches.add(en);
}
}
}
return matches;
}
public static List<DyeColor> dyeColor(String input){
ArrayList<DyeColor> matches = new ArrayList<DyeColor>();
for (DyeColor dye : DyeColor.values()){
if (dye.name().replace("_", "").toLowerCase().equals(input.toLowerCase())){
return Arrays.asList(dye);
} else if (dye.name().replace("_", "").toLowerCase().contains(input.toLowerCase())){
matches.add(dye);
}
}
return matches;
}
public static List<Type> catType(String input){
ArrayList<Type> matches = new ArrayList<Type>();
for (Type type : Type.values()){
if ((type.name().replace("_", "").toLowerCase().equals(input.toLowerCase()) || String.valueOf(type.getId()).equals(input))){
return Arrays.asList(type);
} else if (type.name().replace("_", "").toLowerCase().contains(input.toLowerCase())){
matches.add(type);
}
}
return matches;
}
public static List<World> world(String input){
List<World> matches = new ArrayList<World>();
for (World w : Bukkit.getWorlds()){
if ((w.getName().toLowerCase().equals(input.toLowerCase()) || String.valueOf(w.getUID()).equals(input))){
return Arrays.asList(w);
} else if (w.getName().toLowerCase().contains(input.toLowerCase())){
matches.add(w);
}
}
return matches;
}
public static List<World> intellWorld(String input, World currWorld){
List<World> matches = new ArrayList<World>();
input = input.toLowerCase();
if (input.equals("nether") || input.equals("thenether") || input.equals("the_nether")
|| input.equals("end") || input.equals("theend") || input.equals("the_end")
|| input.equals("overworld") || input.equals("theoverworld") || input.equals("the_overworld")){
String cWorld = currWorld.getName();
- String wBase = cWorld.split(":")[0];
+ String wBase = cWorld.split("_")[0];
String toWorld = null;
if (input.contains("nether")){
toWorld = wBase + "_nether";
}
if (input.contains("end")){
toWorld = wBase + "_the_end";
}
if (input.contains("overworld")){
toWorld = wBase;
}
World toSend = Bukkit.getWorld(toWorld);
if (toSend != null){
matches.add(toSend);
}
}
if (matches.size() == 0){
matches = world(input);
}
return matches;
}
}
| true | true | public static List<World> intellWorld(String input, World currWorld){
List<World> matches = new ArrayList<World>();
input = input.toLowerCase();
if (input.equals("nether") || input.equals("thenether") || input.equals("the_nether")
|| input.equals("end") || input.equals("theend") || input.equals("the_end")
|| input.equals("overworld") || input.equals("theoverworld") || input.equals("the_overworld")){
String cWorld = currWorld.getName();
String wBase = cWorld.split(":")[0];
String toWorld = null;
if (input.contains("nether")){
toWorld = wBase + "_nether";
}
if (input.contains("end")){
toWorld = wBase + "_the_end";
}
if (input.contains("overworld")){
toWorld = wBase;
}
World toSend = Bukkit.getWorld(toWorld);
if (toSend != null){
matches.add(toSend);
}
}
if (matches.size() == 0){
matches = world(input);
}
return matches;
}
| public static List<World> intellWorld(String input, World currWorld){
List<World> matches = new ArrayList<World>();
input = input.toLowerCase();
if (input.equals("nether") || input.equals("thenether") || input.equals("the_nether")
|| input.equals("end") || input.equals("theend") || input.equals("the_end")
|| input.equals("overworld") || input.equals("theoverworld") || input.equals("the_overworld")){
String cWorld = currWorld.getName();
String wBase = cWorld.split("_")[0];
String toWorld = null;
if (input.contains("nether")){
toWorld = wBase + "_nether";
}
if (input.contains("end")){
toWorld = wBase + "_the_end";
}
if (input.contains("overworld")){
toWorld = wBase;
}
World toSend = Bukkit.getWorld(toWorld);
if (toSend != null){
matches.add(toSend);
}
}
if (matches.size() == 0){
matches = world(input);
}
return matches;
}
|
diff --git a/ActiveObjects/test/net/java/ao/TestUtilities.java b/ActiveObjects/test/net/java/ao/TestUtilities.java
index 4127024..00bdba2 100644
--- a/ActiveObjects/test/net/java/ao/TestUtilities.java
+++ b/ActiveObjects/test/net/java/ao/TestUtilities.java
@@ -1,615 +1,615 @@
package net.java.ao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import test.schema.Authorship;
import test.schema.Book;
import test.schema.Comment;
import test.schema.Distribution;
import test.schema.Magazine;
import test.schema.OnlineDistribution;
import test.schema.Pen;
import test.schema.PersonSuit;
import test.schema.Photo;
import test.schema.Post;
import test.schema.PrintDistribution;
import test.schema.PublicationToDistribution;
/*
* Copyright 2007 Daniel Spiewak
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Daniel Spiewak
*/
public class TestUtilities {
public static final Test asTest(Class<?> clazz) {
return new JUnit4TestAdapter(clazz);
}
public static final DataStruct setUpEntityManager(EntityManager manager) throws SQLException {
DataStruct back = new DataStruct();
Logger logger = Logger.getLogger("net.java.ao");
Logger l = logger;
while ((l = l.getParent()) != null) {
for (Handler h : l.getHandlers()) {
l.removeHandler(h);
}
}
logger.setLevel(Level.FINE);
logger.addHandler(SQLLogMonitor.getInstance());
manager.setPolymorphicTypeMapper(new DefaultPolymorphicTypeMapper(manager.getTableNameConverter(),
Photo.class, Post.class, Book.class, Magazine.class, PrintDistribution.class, OnlineDistribution.class));
try {
manager.migrate(PersonSuit.class, Pen.class, Comment.class, Photo.class, Post.class,
Authorship.class, Book.class, Magazine.class,
PublicationToDistribution.class, PrintDistribution.class, OnlineDistribution.class);
} catch (Throwable t) {
t.printStackTrace();
}
Connection conn = manager.getProvider().getConnection();
try {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO company (companyID, name, cool) VALUES (?,?,?)");
stmt.setLong(1, back.companyID = System.currentTimeMillis());
stmt.setString(2, "Company Name");
stmt.setBoolean(3, false);
stmt.executeUpdate();
Thread.sleep(10);
int index = 0;
back.coolCompanyIDs = new long[3];
stmt.setLong(1, back.coolCompanyIDs[index++] = System.currentTimeMillis());
stmt.setString(2, "Cool Company");
stmt.setBoolean(3, true);
stmt.executeUpdate();
Thread.sleep(10);
stmt.setLong(1, back.coolCompanyIDs[index++] = System.currentTimeMillis());
stmt.setString(2, "Cool Company");
stmt.setBoolean(3, true);
stmt.executeUpdate();
Thread.sleep(10);
stmt.setLong(1, back.coolCompanyIDs[index++] = System.currentTimeMillis());
stmt.setString(2, "Cool Company");
stmt.setBoolean(3, true);
stmt.executeUpdate();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO person (firstName, companyID) VALUES (?, ?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Daniel");
stmt.setLong(2, back.companyID);
stmt.executeUpdate();
ResultSet res = stmt.getGeneratedKeys();
if (res.next()) {
back.personID = res.getInt(1);
}
res.close();
stmt.close();
back.penIDs = new int[3];
stmt = conn.prepareStatement("INSERT INTO pen (width,personID) VALUES (?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
index = 0;
stmt.setDouble(1, 0.5);
stmt.setInt(2, back.personID);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.penIDs[index++] = res.getInt(1);
}
res.close();
stmt.setDouble(1, 0.7);
stmt.setInt(2, back.personID);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.penIDs[index++] = res.getInt(1);
}
res.close();
stmt.setDouble(1, 1);
stmt.setInt(2, back.personID);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.penIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.defenceIDs = new int[3];
stmt = conn.prepareStatement("INSERT INTO personDefence (severity) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
index = 0;
stmt.setInt(1, 5);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.defenceIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, 7);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.defenceIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, 1);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.defenceIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.suitIDs = new int[3];
stmt = conn.prepareStatement("INSERT INTO personSuit (personID, personLegalDefenceID) VALUES (?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
index = 0;
stmt.setInt(1, back.personID);
stmt.setInt(2, back.defenceIDs[0]);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.suitIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, back.personID);
stmt.setInt(2, back.defenceIDs[1]);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.suitIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, back.personID);
stmt.setInt(2, back.defenceIDs[2]);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.suitIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO post (title) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postID = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO photo (depth) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setInt(1, 256);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.photoID = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO comment (title,text,commentableID,commentableType) VALUES (?,?,?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
back.postCommentIDs = new int[3];
back.photoCommentIDs = new int[2];
int postCommentIndex = 0;
int photoCommentIndex = 0;
index = 1;
stmt.setString(index++, "Test Post Comment 1");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.postID);
stmt.setString(index++, "post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postCommentIDs[postCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Post Comment 2");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.postID);
stmt.setString(index++, "post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postCommentIDs[postCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Photo Comment 1");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.photoID);
stmt.setString(index++, "photo");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.photoCommentIDs[photoCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Post Comment 3");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.postID);
stmt.setString(index++, "post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postCommentIDs[postCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Photo Comment 2");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.photoID);
stmt.setString(index++, "photo");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.photoCommentIDs[photoCommentIndex++] = res.getInt(1);
}
res.close();
stmt.close();
back.bookIDs = new int[2];
index = 0;
stmt = conn.prepareStatement("INSERT INTO book (title,hardcover) VALUES (?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Book 1");
stmt.setInt(2, 1);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookIDs[index++] = res.getInt(1);
}
res.close();
stmt.setString(1, "Test Book 2");
stmt.setInt(2, 1);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.magazineIDs = new int[2];
index = 0;
stmt = conn.prepareStatement("INSERT INTO magazine (title) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Magazine 1");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.magazineIDs[index++] = res.getInt(1);
}
res.close();
stmt.setString(1, "Test Magazine 2");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.magazineIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.bookAuthorIDs = new int[2][3];
index = 0;
for (int i = 0; i < back.bookIDs.length; i++) {
for (int subIndex = 0; subIndex < back.bookAuthorIDs[0].length; subIndex++) {
stmt = conn.prepareStatement("INSERT INTO author (name) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Book Author " + (subIndex + 1));
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookAuthorIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO authorship (publicationID,publicationType,authorID) VALUES (?,?,?)");
stmt.setInt(1, back.bookIDs[i]);
stmt.setString(2, "book");
stmt.setInt(3, back.bookAuthorIDs[i][subIndex]);
stmt.executeUpdate();
stmt.close();
}
}
back.magazineAuthorIDs = new int[2][3];
- for (int i = 0; i < back.bookIDs.length; i++) {
+ for (int i = 0; i < back.magazineIDs.length; i++) {
for (int subIndex = 0; subIndex < back.magazineAuthorIDs[0].length; subIndex++) {
stmt = conn.prepareStatement("INSERT INTO author (name) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Magazine Author " + (subIndex + 1));
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
- back.bookAuthorIDs[i][subIndex] = res.getInt(1);
+ back.magazineAuthorIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO authorship (publicationID,publicationType,authorID) VALUES (?,?,?)");
stmt.setInt(1, back.magazineIDs[i]);
stmt.setString(2, "magazine");
stmt.setInt(3, back.magazineAuthorIDs[i][subIndex]);
stmt.executeUpdate();
stmt.close();
}
}
back.bookDistributionIDs = new int[2][5];
back.bookDistributionTypes = new Class[2][5];
for (int i = 0; i < back.bookIDs.length; i++) {
for (int subIndex = 0; subIndex < back.bookDistributionIDs[0].length; subIndex++) {
Class<? extends Distribution> distType = (subIndex % 2 == 0 ? PrintDistribution.class
: OnlineDistribution.class);
String distTableName = manager.getTableNameConverter().getName(distType);
String params = null;
if (distType == PrintDistribution.class) {
params = " (copies) VALUES (?)";
} else if (distType == OnlineDistribution.class) {
params = " (url) VALUES (?)";
}
back.bookDistributionTypes[i][subIndex] = distType;
stmt = conn.prepareStatement("INSERT INTO " + distTableName + ' ' + params,
PreparedStatement.RETURN_GENERATED_KEYS);
if (distType == PrintDistribution.class) {
stmt.setInt(1, 20);
} else if (distType == OnlineDistribution.class) {
stmt.setString(1, "http://www.google.com");
}
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookDistributionIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO publicationToDistribution " +
"(publicationID,publicationType,distributionID,distributionType) VALUES (?,?,?,?)");
stmt.setInt(1, back.bookIDs[i]);
stmt.setString(2, "book");
stmt.setInt(3, back.bookDistributionIDs[i][subIndex]);
stmt.setString(4, manager.getPolymorphicTypeMapper().convert(distType));
stmt.executeUpdate();
stmt.close();
}
}
back.magazineDistributionIDs = new int[2][12];
back.magazineDistributionTypes = new Class[2][12];
- for (int i = 0; i < back.bookIDs.length; i++) {
+ for (int i = 0; i < back.magazineIDs.length; i++) {
for (int subIndex = 0; subIndex < back.magazineDistributionIDs[0].length; subIndex++) {
Class<? extends Distribution> distType = (subIndex % 2 == 0 ? PrintDistribution.class
: OnlineDistribution.class);
String distTableName = manager.getTableNameConverter().getName(distType);
String params = null;
if (distType == PrintDistribution.class) {
params = " (copies) VALUES (?)";
} else if (distType == OnlineDistribution.class) {
params = " (url) VALUES (?)";
}
back.magazineDistributionTypes[i][subIndex] = distType;
stmt = conn.prepareStatement("INSERT INTO " + distTableName + ' ' + params,
PreparedStatement.RETURN_GENERATED_KEYS);
if (distType == PrintDistribution.class) {
stmt.setInt(1, 20);
} else if (distType == OnlineDistribution.class) {
stmt.setString(1, "http://www.google.com");
}
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.magazineDistributionIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO publicationToDistribution " +
"(publicationID,publicationType,distributionID,distributionType) VALUES (?,?,?,?)");
stmt.setInt(1, back.magazineIDs[i]);
stmt.setString(2, "magazine");
stmt.setInt(3, back.magazineDistributionIDs[i][subIndex]);
stmt.setString(4, manager.getPolymorphicTypeMapper().convert(distType));
stmt.executeUpdate();
stmt.close();
}
}
for (int i = 0; i < 3; i++) { // add some extra, unrelated distributions
Class<? extends Distribution> distType = (i % 2 == 0 ? PrintDistribution.class
: OnlineDistribution.class);
String distTableName = manager.getTableNameConverter().getName(distType);
String params = null;
if (distType == PrintDistribution.class) {
params = " (copies) VALUES (?)";
} else if (distType == OnlineDistribution.class) {
params = " (url) VALUES (?)";
}
stmt = conn.prepareStatement("INSERT INTO " + distTableName + ' ' + params);
if (distType == PrintDistribution.class) {
stmt.setInt(1, 20);
} else if (distType == OnlineDistribution.class) {
stmt.setString(1, "http://www.dzone.com");
}
stmt.executeUpdate();
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InterruptedException e) {
} finally {
conn.close();
}
return back;
}
public static final void tearDownEntityManager(EntityManager manager) throws SQLException {
Connection conn = manager.getProvider().getConnection();
try {
Statement stmt = conn.createStatement();
stmt.executeUpdate("DELETE FROM pen");
stmt.executeUpdate("DELETE FROM personSuit");
stmt.executeUpdate("DELETE FROM personDefence");
stmt.executeUpdate("DELETE FROM person");
stmt.executeUpdate("DELETE FROM company");
stmt.executeUpdate("DELETE FROM comment");
stmt.executeUpdate("DELETE FROM post");
stmt.executeUpdate("DELETE FROM photo");
stmt.executeUpdate("DELETE FROM authorship");
stmt.executeUpdate("DELETE FROM author");
stmt.executeUpdate("DELETE FROM book");
stmt.executeUpdate("DELETE FROM magazine");
stmt.executeUpdate("DELETE FROM publicationToDistribution");
stmt.executeUpdate("DELETE FROM printDistribution");
stmt.executeUpdate("DELETE FROM onlineDistribution");
stmt.close();
} finally {
conn.close();
}
}
}
| false | true | public static final DataStruct setUpEntityManager(EntityManager manager) throws SQLException {
DataStruct back = new DataStruct();
Logger logger = Logger.getLogger("net.java.ao");
Logger l = logger;
while ((l = l.getParent()) != null) {
for (Handler h : l.getHandlers()) {
l.removeHandler(h);
}
}
logger.setLevel(Level.FINE);
logger.addHandler(SQLLogMonitor.getInstance());
manager.setPolymorphicTypeMapper(new DefaultPolymorphicTypeMapper(manager.getTableNameConverter(),
Photo.class, Post.class, Book.class, Magazine.class, PrintDistribution.class, OnlineDistribution.class));
try {
manager.migrate(PersonSuit.class, Pen.class, Comment.class, Photo.class, Post.class,
Authorship.class, Book.class, Magazine.class,
PublicationToDistribution.class, PrintDistribution.class, OnlineDistribution.class);
} catch (Throwable t) {
t.printStackTrace();
}
Connection conn = manager.getProvider().getConnection();
try {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO company (companyID, name, cool) VALUES (?,?,?)");
stmt.setLong(1, back.companyID = System.currentTimeMillis());
stmt.setString(2, "Company Name");
stmt.setBoolean(3, false);
stmt.executeUpdate();
Thread.sleep(10);
int index = 0;
back.coolCompanyIDs = new long[3];
stmt.setLong(1, back.coolCompanyIDs[index++] = System.currentTimeMillis());
stmt.setString(2, "Cool Company");
stmt.setBoolean(3, true);
stmt.executeUpdate();
Thread.sleep(10);
stmt.setLong(1, back.coolCompanyIDs[index++] = System.currentTimeMillis());
stmt.setString(2, "Cool Company");
stmt.setBoolean(3, true);
stmt.executeUpdate();
Thread.sleep(10);
stmt.setLong(1, back.coolCompanyIDs[index++] = System.currentTimeMillis());
stmt.setString(2, "Cool Company");
stmt.setBoolean(3, true);
stmt.executeUpdate();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO person (firstName, companyID) VALUES (?, ?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Daniel");
stmt.setLong(2, back.companyID);
stmt.executeUpdate();
ResultSet res = stmt.getGeneratedKeys();
if (res.next()) {
back.personID = res.getInt(1);
}
res.close();
stmt.close();
back.penIDs = new int[3];
stmt = conn.prepareStatement("INSERT INTO pen (width,personID) VALUES (?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
index = 0;
stmt.setDouble(1, 0.5);
stmt.setInt(2, back.personID);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.penIDs[index++] = res.getInt(1);
}
res.close();
stmt.setDouble(1, 0.7);
stmt.setInt(2, back.personID);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.penIDs[index++] = res.getInt(1);
}
res.close();
stmt.setDouble(1, 1);
stmt.setInt(2, back.personID);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.penIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.defenceIDs = new int[3];
stmt = conn.prepareStatement("INSERT INTO personDefence (severity) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
index = 0;
stmt.setInt(1, 5);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.defenceIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, 7);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.defenceIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, 1);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.defenceIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.suitIDs = new int[3];
stmt = conn.prepareStatement("INSERT INTO personSuit (personID, personLegalDefenceID) VALUES (?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
index = 0;
stmt.setInt(1, back.personID);
stmt.setInt(2, back.defenceIDs[0]);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.suitIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, back.personID);
stmt.setInt(2, back.defenceIDs[1]);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.suitIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, back.personID);
stmt.setInt(2, back.defenceIDs[2]);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.suitIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO post (title) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postID = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO photo (depth) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setInt(1, 256);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.photoID = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO comment (title,text,commentableID,commentableType) VALUES (?,?,?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
back.postCommentIDs = new int[3];
back.photoCommentIDs = new int[2];
int postCommentIndex = 0;
int photoCommentIndex = 0;
index = 1;
stmt.setString(index++, "Test Post Comment 1");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.postID);
stmt.setString(index++, "post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postCommentIDs[postCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Post Comment 2");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.postID);
stmt.setString(index++, "post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postCommentIDs[postCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Photo Comment 1");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.photoID);
stmt.setString(index++, "photo");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.photoCommentIDs[photoCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Post Comment 3");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.postID);
stmt.setString(index++, "post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postCommentIDs[postCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Photo Comment 2");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.photoID);
stmt.setString(index++, "photo");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.photoCommentIDs[photoCommentIndex++] = res.getInt(1);
}
res.close();
stmt.close();
back.bookIDs = new int[2];
index = 0;
stmt = conn.prepareStatement("INSERT INTO book (title,hardcover) VALUES (?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Book 1");
stmt.setInt(2, 1);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookIDs[index++] = res.getInt(1);
}
res.close();
stmt.setString(1, "Test Book 2");
stmt.setInt(2, 1);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.magazineIDs = new int[2];
index = 0;
stmt = conn.prepareStatement("INSERT INTO magazine (title) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Magazine 1");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.magazineIDs[index++] = res.getInt(1);
}
res.close();
stmt.setString(1, "Test Magazine 2");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.magazineIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.bookAuthorIDs = new int[2][3];
index = 0;
for (int i = 0; i < back.bookIDs.length; i++) {
for (int subIndex = 0; subIndex < back.bookAuthorIDs[0].length; subIndex++) {
stmt = conn.prepareStatement("INSERT INTO author (name) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Book Author " + (subIndex + 1));
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookAuthorIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO authorship (publicationID,publicationType,authorID) VALUES (?,?,?)");
stmt.setInt(1, back.bookIDs[i]);
stmt.setString(2, "book");
stmt.setInt(3, back.bookAuthorIDs[i][subIndex]);
stmt.executeUpdate();
stmt.close();
}
}
back.magazineAuthorIDs = new int[2][3];
for (int i = 0; i < back.bookIDs.length; i++) {
for (int subIndex = 0; subIndex < back.magazineAuthorIDs[0].length; subIndex++) {
stmt = conn.prepareStatement("INSERT INTO author (name) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Magazine Author " + (subIndex + 1));
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookAuthorIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO authorship (publicationID,publicationType,authorID) VALUES (?,?,?)");
stmt.setInt(1, back.magazineIDs[i]);
stmt.setString(2, "magazine");
stmt.setInt(3, back.magazineAuthorIDs[i][subIndex]);
stmt.executeUpdate();
stmt.close();
}
}
back.bookDistributionIDs = new int[2][5];
back.bookDistributionTypes = new Class[2][5];
for (int i = 0; i < back.bookIDs.length; i++) {
for (int subIndex = 0; subIndex < back.bookDistributionIDs[0].length; subIndex++) {
Class<? extends Distribution> distType = (subIndex % 2 == 0 ? PrintDistribution.class
: OnlineDistribution.class);
String distTableName = manager.getTableNameConverter().getName(distType);
String params = null;
if (distType == PrintDistribution.class) {
params = " (copies) VALUES (?)";
} else if (distType == OnlineDistribution.class) {
params = " (url) VALUES (?)";
}
back.bookDistributionTypes[i][subIndex] = distType;
stmt = conn.prepareStatement("INSERT INTO " + distTableName + ' ' + params,
PreparedStatement.RETURN_GENERATED_KEYS);
if (distType == PrintDistribution.class) {
stmt.setInt(1, 20);
} else if (distType == OnlineDistribution.class) {
stmt.setString(1, "http://www.google.com");
}
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookDistributionIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO publicationToDistribution " +
"(publicationID,publicationType,distributionID,distributionType) VALUES (?,?,?,?)");
stmt.setInt(1, back.bookIDs[i]);
stmt.setString(2, "book");
stmt.setInt(3, back.bookDistributionIDs[i][subIndex]);
stmt.setString(4, manager.getPolymorphicTypeMapper().convert(distType));
stmt.executeUpdate();
stmt.close();
}
}
back.magazineDistributionIDs = new int[2][12];
back.magazineDistributionTypes = new Class[2][12];
for (int i = 0; i < back.bookIDs.length; i++) {
for (int subIndex = 0; subIndex < back.magazineDistributionIDs[0].length; subIndex++) {
Class<? extends Distribution> distType = (subIndex % 2 == 0 ? PrintDistribution.class
: OnlineDistribution.class);
String distTableName = manager.getTableNameConverter().getName(distType);
String params = null;
if (distType == PrintDistribution.class) {
params = " (copies) VALUES (?)";
} else if (distType == OnlineDistribution.class) {
params = " (url) VALUES (?)";
}
back.magazineDistributionTypes[i][subIndex] = distType;
stmt = conn.prepareStatement("INSERT INTO " + distTableName + ' ' + params,
PreparedStatement.RETURN_GENERATED_KEYS);
if (distType == PrintDistribution.class) {
stmt.setInt(1, 20);
} else if (distType == OnlineDistribution.class) {
stmt.setString(1, "http://www.google.com");
}
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.magazineDistributionIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO publicationToDistribution " +
"(publicationID,publicationType,distributionID,distributionType) VALUES (?,?,?,?)");
stmt.setInt(1, back.magazineIDs[i]);
stmt.setString(2, "magazine");
stmt.setInt(3, back.magazineDistributionIDs[i][subIndex]);
stmt.setString(4, manager.getPolymorphicTypeMapper().convert(distType));
stmt.executeUpdate();
stmt.close();
}
}
for (int i = 0; i < 3; i++) { // add some extra, unrelated distributions
Class<? extends Distribution> distType = (i % 2 == 0 ? PrintDistribution.class
: OnlineDistribution.class);
String distTableName = manager.getTableNameConverter().getName(distType);
String params = null;
if (distType == PrintDistribution.class) {
params = " (copies) VALUES (?)";
} else if (distType == OnlineDistribution.class) {
params = " (url) VALUES (?)";
}
stmt = conn.prepareStatement("INSERT INTO " + distTableName + ' ' + params);
if (distType == PrintDistribution.class) {
stmt.setInt(1, 20);
} else if (distType == OnlineDistribution.class) {
stmt.setString(1, "http://www.dzone.com");
}
stmt.executeUpdate();
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InterruptedException e) {
} finally {
conn.close();
}
return back;
}
| public static final DataStruct setUpEntityManager(EntityManager manager) throws SQLException {
DataStruct back = new DataStruct();
Logger logger = Logger.getLogger("net.java.ao");
Logger l = logger;
while ((l = l.getParent()) != null) {
for (Handler h : l.getHandlers()) {
l.removeHandler(h);
}
}
logger.setLevel(Level.FINE);
logger.addHandler(SQLLogMonitor.getInstance());
manager.setPolymorphicTypeMapper(new DefaultPolymorphicTypeMapper(manager.getTableNameConverter(),
Photo.class, Post.class, Book.class, Magazine.class, PrintDistribution.class, OnlineDistribution.class));
try {
manager.migrate(PersonSuit.class, Pen.class, Comment.class, Photo.class, Post.class,
Authorship.class, Book.class, Magazine.class,
PublicationToDistribution.class, PrintDistribution.class, OnlineDistribution.class);
} catch (Throwable t) {
t.printStackTrace();
}
Connection conn = manager.getProvider().getConnection();
try {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO company (companyID, name, cool) VALUES (?,?,?)");
stmt.setLong(1, back.companyID = System.currentTimeMillis());
stmt.setString(2, "Company Name");
stmt.setBoolean(3, false);
stmt.executeUpdate();
Thread.sleep(10);
int index = 0;
back.coolCompanyIDs = new long[3];
stmt.setLong(1, back.coolCompanyIDs[index++] = System.currentTimeMillis());
stmt.setString(2, "Cool Company");
stmt.setBoolean(3, true);
stmt.executeUpdate();
Thread.sleep(10);
stmt.setLong(1, back.coolCompanyIDs[index++] = System.currentTimeMillis());
stmt.setString(2, "Cool Company");
stmt.setBoolean(3, true);
stmt.executeUpdate();
Thread.sleep(10);
stmt.setLong(1, back.coolCompanyIDs[index++] = System.currentTimeMillis());
stmt.setString(2, "Cool Company");
stmt.setBoolean(3, true);
stmt.executeUpdate();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO person (firstName, companyID) VALUES (?, ?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Daniel");
stmt.setLong(2, back.companyID);
stmt.executeUpdate();
ResultSet res = stmt.getGeneratedKeys();
if (res.next()) {
back.personID = res.getInt(1);
}
res.close();
stmt.close();
back.penIDs = new int[3];
stmt = conn.prepareStatement("INSERT INTO pen (width,personID) VALUES (?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
index = 0;
stmt.setDouble(1, 0.5);
stmt.setInt(2, back.personID);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.penIDs[index++] = res.getInt(1);
}
res.close();
stmt.setDouble(1, 0.7);
stmt.setInt(2, back.personID);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.penIDs[index++] = res.getInt(1);
}
res.close();
stmt.setDouble(1, 1);
stmt.setInt(2, back.personID);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.penIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.defenceIDs = new int[3];
stmt = conn.prepareStatement("INSERT INTO personDefence (severity) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
index = 0;
stmt.setInt(1, 5);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.defenceIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, 7);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.defenceIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, 1);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.defenceIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.suitIDs = new int[3];
stmt = conn.prepareStatement("INSERT INTO personSuit (personID, personLegalDefenceID) VALUES (?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
index = 0;
stmt.setInt(1, back.personID);
stmt.setInt(2, back.defenceIDs[0]);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.suitIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, back.personID);
stmt.setInt(2, back.defenceIDs[1]);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.suitIDs[index++] = res.getInt(1);
}
res.close();
stmt.setInt(1, back.personID);
stmt.setInt(2, back.defenceIDs[2]);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.suitIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO post (title) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postID = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO photo (depth) VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setInt(1, 256);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.photoID = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO comment (title,text,commentableID,commentableType) VALUES (?,?,?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
back.postCommentIDs = new int[3];
back.photoCommentIDs = new int[2];
int postCommentIndex = 0;
int photoCommentIndex = 0;
index = 1;
stmt.setString(index++, "Test Post Comment 1");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.postID);
stmt.setString(index++, "post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postCommentIDs[postCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Post Comment 2");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.postID);
stmt.setString(index++, "post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postCommentIDs[postCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Photo Comment 1");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.photoID);
stmt.setString(index++, "photo");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.photoCommentIDs[photoCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Post Comment 3");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.postID);
stmt.setString(index++, "post");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.postCommentIDs[postCommentIndex++] = res.getInt(1);
}
res.close();
index = 1;
stmt.setString(index++, "Test Photo Comment 2");
stmt.setString(index++, "Here's some test text");
stmt.setInt(index++, back.photoID);
stmt.setString(index++, "photo");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.photoCommentIDs[photoCommentIndex++] = res.getInt(1);
}
res.close();
stmt.close();
back.bookIDs = new int[2];
index = 0;
stmt = conn.prepareStatement("INSERT INTO book (title,hardcover) VALUES (?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Book 1");
stmt.setInt(2, 1);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookIDs[index++] = res.getInt(1);
}
res.close();
stmt.setString(1, "Test Book 2");
stmt.setInt(2, 1);
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.magazineIDs = new int[2];
index = 0;
stmt = conn.prepareStatement("INSERT INTO magazine (title) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Magazine 1");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.magazineIDs[index++] = res.getInt(1);
}
res.close();
stmt.setString(1, "Test Magazine 2");
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.magazineIDs[index++] = res.getInt(1);
}
res.close();
stmt.close();
back.bookAuthorIDs = new int[2][3];
index = 0;
for (int i = 0; i < back.bookIDs.length; i++) {
for (int subIndex = 0; subIndex < back.bookAuthorIDs[0].length; subIndex++) {
stmt = conn.prepareStatement("INSERT INTO author (name) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Book Author " + (subIndex + 1));
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookAuthorIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO authorship (publicationID,publicationType,authorID) VALUES (?,?,?)");
stmt.setInt(1, back.bookIDs[i]);
stmt.setString(2, "book");
stmt.setInt(3, back.bookAuthorIDs[i][subIndex]);
stmt.executeUpdate();
stmt.close();
}
}
back.magazineAuthorIDs = new int[2][3];
for (int i = 0; i < back.magazineIDs.length; i++) {
for (int subIndex = 0; subIndex < back.magazineAuthorIDs[0].length; subIndex++) {
stmt = conn.prepareStatement("INSERT INTO author (name) VALUES (?)",
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, "Test Magazine Author " + (subIndex + 1));
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.magazineAuthorIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO authorship (publicationID,publicationType,authorID) VALUES (?,?,?)");
stmt.setInt(1, back.magazineIDs[i]);
stmt.setString(2, "magazine");
stmt.setInt(3, back.magazineAuthorIDs[i][subIndex]);
stmt.executeUpdate();
stmt.close();
}
}
back.bookDistributionIDs = new int[2][5];
back.bookDistributionTypes = new Class[2][5];
for (int i = 0; i < back.bookIDs.length; i++) {
for (int subIndex = 0; subIndex < back.bookDistributionIDs[0].length; subIndex++) {
Class<? extends Distribution> distType = (subIndex % 2 == 0 ? PrintDistribution.class
: OnlineDistribution.class);
String distTableName = manager.getTableNameConverter().getName(distType);
String params = null;
if (distType == PrintDistribution.class) {
params = " (copies) VALUES (?)";
} else if (distType == OnlineDistribution.class) {
params = " (url) VALUES (?)";
}
back.bookDistributionTypes[i][subIndex] = distType;
stmt = conn.prepareStatement("INSERT INTO " + distTableName + ' ' + params,
PreparedStatement.RETURN_GENERATED_KEYS);
if (distType == PrintDistribution.class) {
stmt.setInt(1, 20);
} else if (distType == OnlineDistribution.class) {
stmt.setString(1, "http://www.google.com");
}
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.bookDistributionIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO publicationToDistribution " +
"(publicationID,publicationType,distributionID,distributionType) VALUES (?,?,?,?)");
stmt.setInt(1, back.bookIDs[i]);
stmt.setString(2, "book");
stmt.setInt(3, back.bookDistributionIDs[i][subIndex]);
stmt.setString(4, manager.getPolymorphicTypeMapper().convert(distType));
stmt.executeUpdate();
stmt.close();
}
}
back.magazineDistributionIDs = new int[2][12];
back.magazineDistributionTypes = new Class[2][12];
for (int i = 0; i < back.magazineIDs.length; i++) {
for (int subIndex = 0; subIndex < back.magazineDistributionIDs[0].length; subIndex++) {
Class<? extends Distribution> distType = (subIndex % 2 == 0 ? PrintDistribution.class
: OnlineDistribution.class);
String distTableName = manager.getTableNameConverter().getName(distType);
String params = null;
if (distType == PrintDistribution.class) {
params = " (copies) VALUES (?)";
} else if (distType == OnlineDistribution.class) {
params = " (url) VALUES (?)";
}
back.magazineDistributionTypes[i][subIndex] = distType;
stmt = conn.prepareStatement("INSERT INTO " + distTableName + ' ' + params,
PreparedStatement.RETURN_GENERATED_KEYS);
if (distType == PrintDistribution.class) {
stmt.setInt(1, 20);
} else if (distType == OnlineDistribution.class) {
stmt.setString(1, "http://www.google.com");
}
stmt.executeUpdate();
res = stmt.getGeneratedKeys();
if (res.next()) {
back.magazineDistributionIDs[i][subIndex] = res.getInt(1);
}
res.close();
stmt.close();
stmt = conn.prepareStatement("INSERT INTO publicationToDistribution " +
"(publicationID,publicationType,distributionID,distributionType) VALUES (?,?,?,?)");
stmt.setInt(1, back.magazineIDs[i]);
stmt.setString(2, "magazine");
stmt.setInt(3, back.magazineDistributionIDs[i][subIndex]);
stmt.setString(4, manager.getPolymorphicTypeMapper().convert(distType));
stmt.executeUpdate();
stmt.close();
}
}
for (int i = 0; i < 3; i++) { // add some extra, unrelated distributions
Class<? extends Distribution> distType = (i % 2 == 0 ? PrintDistribution.class
: OnlineDistribution.class);
String distTableName = manager.getTableNameConverter().getName(distType);
String params = null;
if (distType == PrintDistribution.class) {
params = " (copies) VALUES (?)";
} else if (distType == OnlineDistribution.class) {
params = " (url) VALUES (?)";
}
stmt = conn.prepareStatement("INSERT INTO " + distTableName + ' ' + params);
if (distType == PrintDistribution.class) {
stmt.setInt(1, 20);
} else if (distType == OnlineDistribution.class) {
stmt.setString(1, "http://www.dzone.com");
}
stmt.executeUpdate();
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InterruptedException e) {
} finally {
conn.close();
}
return back;
}
|
diff --git a/services/java/com/android/server/connectivity/Nat464Xlat.java b/services/java/com/android/server/connectivity/Nat464Xlat.java
index 59403c55..a15d6785 100644
--- a/services/java/com/android/server/connectivity/Nat464Xlat.java
+++ b/services/java/com/android/server/connectivity/Nat464Xlat.java
@@ -1,193 +1,200 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.connectivity;
import static android.net.ConnectivityManager.TYPE_MOBILE;
import java.net.Inet4Address;
import android.content.Context;
import android.net.IConnectivityManager;
import android.net.InterfaceConfiguration;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.NetworkStateTracker;
import android.net.NetworkUtils;
import android.net.RouteInfo;
import android.os.Handler;
import android.os.Message;
import android.os.INetworkManagementService;
import android.os.RemoteException;
import android.util.Slog;
import com.android.server.net.BaseNetworkObserver;
/**
* @hide
*
* Class to manage a 464xlat CLAT daemon.
*/
public class Nat464Xlat extends BaseNetworkObserver {
private Context mContext;
private INetworkManagementService mNMService;
private IConnectivityManager mConnService;
private NetworkStateTracker mTracker;
private Handler mHandler;
// Whether we started clatd and expect it to be running.
private boolean mIsStarted;
// Whether the clatd interface exists (i.e., clatd is running).
private boolean mIsRunning;
// The LinkProperties of the clat interface.
private LinkProperties mLP;
// This must match the interface name in clatd.conf.
private static final String CLAT_INTERFACE_NAME = "clat4";
private static final String TAG = "Nat464Xlat";
public Nat464Xlat(Context context, INetworkManagementService nmService,
IConnectivityManager connService, Handler handler) {
mContext = context;
mNMService = nmService;
mConnService = connService;
mHandler = handler;
mIsStarted = false;
mIsRunning = false;
mLP = new LinkProperties();
}
/**
* Determines whether an interface requires clat.
* @param netType the network type (one of the
* android.net.ConnectivityManager.TYPE_* constants)
* @param tracker the NetworkStateTracker corresponding to the network type.
* @return true if the interface requires clat, false otherwise.
*/
public boolean requiresClat(int netType, NetworkStateTracker tracker) {
LinkProperties lp = tracker.getLinkProperties();
// Only support clat on mobile for now.
Slog.d(TAG, "requiresClat: netType=" + netType + ", hasIPv4Address=" +
lp.hasIPv4Address());
return netType == TYPE_MOBILE && !lp.hasIPv4Address();
}
public static boolean isRunningClat(LinkProperties lp) {
return lp != null && lp.getAllInterfaceNames().contains(CLAT_INTERFACE_NAME);
}
/**
* Starts the clat daemon.
* @param lp The link properties of the interface to start clatd on.
*/
public void startClat(NetworkStateTracker tracker) {
if (mIsStarted) {
Slog.e(TAG, "startClat: already started");
return;
}
mTracker = tracker;
LinkProperties lp = mTracker.getLinkProperties();
String iface = lp.getInterfaceName();
Slog.i(TAG, "Starting clatd on " + iface + ", lp=" + lp);
try {
mNMService.startClatd(iface);
} catch(RemoteException e) {
Slog.e(TAG, "Error starting clat daemon: " + e);
}
mIsStarted = true;
}
/**
* Stops the clat daemon.
*/
public void stopClat() {
if (mIsStarted) {
Slog.i(TAG, "Stopping clatd");
try {
mNMService.stopClatd();
} catch(RemoteException e) {
Slog.e(TAG, "Error stopping clat daemon: " + e);
}
mIsStarted = false;
mIsRunning = false;
mTracker = null;
mLP.clear();
} else {
Slog.e(TAG, "stopClat: already stopped");
}
}
public boolean isStarted() {
return mIsStarted;
}
public boolean isRunning() {
return mIsRunning;
}
@Override
public void interfaceAdded(String iface) {
if (iface.equals(CLAT_INTERFACE_NAME)) {
Slog.i(TAG, "interface " + CLAT_INTERFACE_NAME +
" added, mIsRunning = " + mIsRunning + " -> true");
mIsRunning = true;
- // Get the network configuration of the clat interface, store it
- // in our link properties, and stack it on top of the interface
- // it's running on.
+ // Create the LinkProperties for the clat interface by fetching the
+ // IPv4 address for the interface and adding an IPv4 default route,
+ // then stack the LinkProperties on top of the link it's running on.
+ // Although the clat interface is a point-to-point tunnel, we don't
+ // point the route directly at the interface because some apps don't
+ // understand routes without gateways (see, e.g., http://b/9597256
+ // http://b/9597516). Instead, set the next hop of the route to the
+ // clat IPv4 address itself (for those apps, it doesn't matter what
+ // the IP of the gateway is, only that there is one).
try {
InterfaceConfiguration config = mNMService.getInterfaceConfig(iface);
+ LinkAddress clatAddress = config.getLinkAddress();
mLP.clear();
mLP.setInterfaceName(iface);
- RouteInfo ipv4Default = new RouteInfo(new LinkAddress(Inet4Address.ANY, 0), null,
- iface);
+ RouteInfo ipv4Default = new RouteInfo(new LinkAddress(Inet4Address.ANY, 0),
+ clatAddress.getAddress(), iface);
mLP.addRoute(ipv4Default);
- mLP.addLinkAddress(config.getLinkAddress());
+ mLP.addLinkAddress(clatAddress);
mTracker.addStackedLink(mLP);
Slog.i(TAG, "Adding stacked link. tracker LP: " +
mTracker.getLinkProperties());
} catch(RemoteException e) {
Slog.e(TAG, "Error getting link properties: " + e);
}
// Inform ConnectivityService that things have changed.
Message msg = mHandler.obtainMessage(
NetworkStateTracker.EVENT_CONFIGURATION_CHANGED,
mTracker.getNetworkInfo());
Slog.i(TAG, "sending message to ConnectivityService: " + msg);
msg.sendToTarget();
}
}
@Override
public void interfaceRemoved(String iface) {
if (iface == CLAT_INTERFACE_NAME) {
if (mIsRunning) {
NetworkUtils.resetConnections(
CLAT_INTERFACE_NAME,
NetworkUtils.RESET_IPV4_ADDRESSES);
}
Slog.i(TAG, "interface " + CLAT_INTERFACE_NAME +
" removed, mIsRunning = " + mIsRunning + " -> false");
mIsRunning = false;
mTracker.removeStackedLink(mLP);
mLP.clear();
Slog.i(TAG, "mLP = " + mLP);
}
}
};
| false | true | public void interfaceAdded(String iface) {
if (iface.equals(CLAT_INTERFACE_NAME)) {
Slog.i(TAG, "interface " + CLAT_INTERFACE_NAME +
" added, mIsRunning = " + mIsRunning + " -> true");
mIsRunning = true;
// Get the network configuration of the clat interface, store it
// in our link properties, and stack it on top of the interface
// it's running on.
try {
InterfaceConfiguration config = mNMService.getInterfaceConfig(iface);
mLP.clear();
mLP.setInterfaceName(iface);
RouteInfo ipv4Default = new RouteInfo(new LinkAddress(Inet4Address.ANY, 0), null,
iface);
mLP.addRoute(ipv4Default);
mLP.addLinkAddress(config.getLinkAddress());
mTracker.addStackedLink(mLP);
Slog.i(TAG, "Adding stacked link. tracker LP: " +
mTracker.getLinkProperties());
} catch(RemoteException e) {
Slog.e(TAG, "Error getting link properties: " + e);
}
// Inform ConnectivityService that things have changed.
Message msg = mHandler.obtainMessage(
NetworkStateTracker.EVENT_CONFIGURATION_CHANGED,
mTracker.getNetworkInfo());
Slog.i(TAG, "sending message to ConnectivityService: " + msg);
msg.sendToTarget();
}
}
| public void interfaceAdded(String iface) {
if (iface.equals(CLAT_INTERFACE_NAME)) {
Slog.i(TAG, "interface " + CLAT_INTERFACE_NAME +
" added, mIsRunning = " + mIsRunning + " -> true");
mIsRunning = true;
// Create the LinkProperties for the clat interface by fetching the
// IPv4 address for the interface and adding an IPv4 default route,
// then stack the LinkProperties on top of the link it's running on.
// Although the clat interface is a point-to-point tunnel, we don't
// point the route directly at the interface because some apps don't
// understand routes without gateways (see, e.g., http://b/9597256
// http://b/9597516). Instead, set the next hop of the route to the
// clat IPv4 address itself (for those apps, it doesn't matter what
// the IP of the gateway is, only that there is one).
try {
InterfaceConfiguration config = mNMService.getInterfaceConfig(iface);
LinkAddress clatAddress = config.getLinkAddress();
mLP.clear();
mLP.setInterfaceName(iface);
RouteInfo ipv4Default = new RouteInfo(new LinkAddress(Inet4Address.ANY, 0),
clatAddress.getAddress(), iface);
mLP.addRoute(ipv4Default);
mLP.addLinkAddress(clatAddress);
mTracker.addStackedLink(mLP);
Slog.i(TAG, "Adding stacked link. tracker LP: " +
mTracker.getLinkProperties());
} catch(RemoteException e) {
Slog.e(TAG, "Error getting link properties: " + e);
}
// Inform ConnectivityService that things have changed.
Message msg = mHandler.obtainMessage(
NetworkStateTracker.EVENT_CONFIGURATION_CHANGED,
mTracker.getNetworkInfo());
Slog.i(TAG, "sending message to ConnectivityService: " + msg);
msg.sendToTarget();
}
}
|
diff --git a/src/se/kth/maandree/utilsay/Wordwrap.java b/src/se/kth/maandree/utilsay/Wordwrap.java
index 13d8039..639b749 100644
--- a/src/se/kth/maandree/utilsay/Wordwrap.java
+++ b/src/se/kth/maandree/utilsay/Wordwrap.java
@@ -1,204 +1,204 @@
/**
* Wordwrap — Wraps text make words fit, unsplitted, sida an area
*
* Copyright © 2012 Mattias Andrée ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package se.kth.maandree.utilsay;
import java.io.*;
import java.util.*;
/**
* The main class of the Wordwrap program
*
* @author Mattias Andrée, <a href="mailto:[email protected]">[email protected]</a>
*/
public class Wordwrap
{
/**
* Non-constructor
*/
private Wordwrap()
{
assert false : "This class [Wordwrap] is not meant to be instansiated.";
}
/**
* This is the main entry point of the program
*
* @param args Startup arguments, <code>[--help | TERMINAL_WIDTH [SANE_WIDTH]]</code>
*
* @throws IOException On I/O exception
*/
public static void main(final String... args) throws IOException
{
if ((args.length > 0) && args[0].equals("--help"))
{
System.out.println("Wraps text make words fit, unsplitted, sida an area");
System.out.println();
System.out.println("USAGE: Wordwrap WIDTH < RAW > WRAPPED");
System.out.println();
System.out.println();
System.out.println("Copyright (C) 2012 Mattias Andrée <[email protected]>");
System.out.println();
System.out.println("This program is free software: you can redistribute it and/or modify");
System.out.println("it under the terms of the GNU General Public License as published by");
System.out.println("the Free Software Foundation, either version 3 of the License, or");
System.out.println("(at your option) any later version.");
System.out.println();
System.out.println("This program is distributed in the hope that it will be useful,");
System.out.println("but WITHOUT ANY WARRANTY; without even the implied warranty of");
System.out.println("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the");
System.out.println("GNU General Public License for more details.");
System.out.println();
System.out.println("You should have received a copy of the GNU General Public License");
System.out.println("along with this program. If not, see <http://www.gnu.org/licenses/>.");
System.out.println();
System.out.println();
return;
}
final int width = Integer.parseInt(args[0]);
byte[] buf = new byte[width << 1];
int ptr = 0, tabs = 0, d;
for (;;)
if (((d = System.in.read()) == '\n') || (d == -1))
{
int n = ptr;
byte[] expanded = new byte[n + tabs << 3];
ptr = 0;
for (int i = 0, c = 0; i < n; i++, c++)
if (buf[i] == '\t')
{
int w = 8 - (i & 7);
c += w - 1;
for (int j = 0; j < w; j++)
expanded[ptr++] = ' ';
}
else
expanded[ptr++] = buf[i];
wrap(expanded, ptr, width);
if (d == -1)
break;
System.out.write(d);
ptr = tabs = 0;
}
else
{
if (ptr == buf.length)
System.arraycopy(buf, 0, buf = new byte[ptr << 1], 0, ptr);
buf[ptr++] = (byte)d;
if (d == '\t')
tabs++;
}
}
public static void wrap(final byte[] buf, final int len, final int width)
{
final byte[] b = new byte[buf.length];
final int[] map = new int[buf.length];
int bi = 0, d, cols = 0, w = width;
int indent = -1, indentc = 0;
for (int i = 0; i <= len;)
if ((d = (i == len ? -1 : (buf[i++] & 255))) == 033)
{
b[bi++] = (byte)d;
d = (b[bi++] = buf[i++]) & 255;
if (d == '[')
for (;;)
{
d = (b[bi++] = buf[i++]) & 255;
if ((('a' <= d) && (d <= 'z')) || (('A' <= d) && (d <= 'Z')) || (d == '~'))
break;
}
else if (d == ']')
{
d = (b[bi++] = buf[i++]) & 255;
if (d == 'P')
for (int j = 0; j < 7; j++)
b[bi++] = buf[i++];
}
}
else if ((d != -1) && (d != ' '))
{
if (indent == -1)
{
indent = i - 1;
for (int j = 0; j < indent; j++)
if (buf[j] == ' ')
indentc++;
}
b[bi++] = (byte)d;
if ((d & 0xC0) != 0x80)
map[++cols] = bi;
}
else
{
int m, mm = 0;
- while ((w > 8) && (cols > w + 3))
+ while (/*(w > 8) &&*/ (cols > w + 3))
{
System.out.write(b, 0, m = map[mm += w - 1]);
- System.out.write('-');
+ System.out.write('̣');
System.out.write('\n');
cols -= w - 1;
- System.arraycopy(b, m += w - 1, b, 0, bi -= m);
+ System.arraycopy(b, m, b, 0, bi -= m);
w = width;
if (indent != -1)
{
System.out.write(buf, 0, indent);
w -= indentc;
}
}
if (cols > w)
{
System.out.write('\n');
w = width;
if (indent != -1)
{
System.out.write(buf, 0, indent);
w -= indentc;
}
}
System.out.write(b, 0, bi);
w -= cols;
cols = bi = 0;
if (d == -1)
i++;
else
if (w > 0)
{
System.out.write(' ');
w--;
}
else
{
System.out.write('\n');
w = width;
if (indent != -1)
{
System.out.write(buf, 0, indent);
w -= indentc;
}
}
}
}
}
| false | true | public static void wrap(final byte[] buf, final int len, final int width)
{
final byte[] b = new byte[buf.length];
final int[] map = new int[buf.length];
int bi = 0, d, cols = 0, w = width;
int indent = -1, indentc = 0;
for (int i = 0; i <= len;)
if ((d = (i == len ? -1 : (buf[i++] & 255))) == 033)
{
b[bi++] = (byte)d;
d = (b[bi++] = buf[i++]) & 255;
if (d == '[')
for (;;)
{
d = (b[bi++] = buf[i++]) & 255;
if ((('a' <= d) && (d <= 'z')) || (('A' <= d) && (d <= 'Z')) || (d == '~'))
break;
}
else if (d == ']')
{
d = (b[bi++] = buf[i++]) & 255;
if (d == 'P')
for (int j = 0; j < 7; j++)
b[bi++] = buf[i++];
}
}
else if ((d != -1) && (d != ' '))
{
if (indent == -1)
{
indent = i - 1;
for (int j = 0; j < indent; j++)
if (buf[j] == ' ')
indentc++;
}
b[bi++] = (byte)d;
if ((d & 0xC0) != 0x80)
map[++cols] = bi;
}
else
{
int m, mm = 0;
while ((w > 8) && (cols > w + 3))
{
System.out.write(b, 0, m = map[mm += w - 1]);
System.out.write('-');
System.out.write('\n');
cols -= w - 1;
System.arraycopy(b, m += w - 1, b, 0, bi -= m);
w = width;
if (indent != -1)
{
System.out.write(buf, 0, indent);
w -= indentc;
}
}
if (cols > w)
{
System.out.write('\n');
w = width;
if (indent != -1)
{
System.out.write(buf, 0, indent);
w -= indentc;
}
}
System.out.write(b, 0, bi);
w -= cols;
cols = bi = 0;
if (d == -1)
i++;
else
if (w > 0)
{
System.out.write(' ');
w--;
}
else
{
System.out.write('\n');
w = width;
if (indent != -1)
{
System.out.write(buf, 0, indent);
w -= indentc;
}
}
}
}
| public static void wrap(final byte[] buf, final int len, final int width)
{
final byte[] b = new byte[buf.length];
final int[] map = new int[buf.length];
int bi = 0, d, cols = 0, w = width;
int indent = -1, indentc = 0;
for (int i = 0; i <= len;)
if ((d = (i == len ? -1 : (buf[i++] & 255))) == 033)
{
b[bi++] = (byte)d;
d = (b[bi++] = buf[i++]) & 255;
if (d == '[')
for (;;)
{
d = (b[bi++] = buf[i++]) & 255;
if ((('a' <= d) && (d <= 'z')) || (('A' <= d) && (d <= 'Z')) || (d == '~'))
break;
}
else if (d == ']')
{
d = (b[bi++] = buf[i++]) & 255;
if (d == 'P')
for (int j = 0; j < 7; j++)
b[bi++] = buf[i++];
}
}
else if ((d != -1) && (d != ' '))
{
if (indent == -1)
{
indent = i - 1;
for (int j = 0; j < indent; j++)
if (buf[j] == ' ')
indentc++;
}
b[bi++] = (byte)d;
if ((d & 0xC0) != 0x80)
map[++cols] = bi;
}
else
{
int m, mm = 0;
while (/*(w > 8) &&*/ (cols > w + 3))
{
System.out.write(b, 0, m = map[mm += w - 1]);
System.out.write('̣');
System.out.write('\n');
cols -= w - 1;
System.arraycopy(b, m, b, 0, bi -= m);
w = width;
if (indent != -1)
{
System.out.write(buf, 0, indent);
w -= indentc;
}
}
if (cols > w)
{
System.out.write('\n');
w = width;
if (indent != -1)
{
System.out.write(buf, 0, indent);
w -= indentc;
}
}
System.out.write(b, 0, bi);
w -= cols;
cols = bi = 0;
if (d == -1)
i++;
else
if (w > 0)
{
System.out.write(' ');
w--;
}
else
{
System.out.write('\n');
w = width;
if (indent != -1)
{
System.out.write(buf, 0, indent);
w -= indentc;
}
}
}
}
|
diff --git a/source/ch/cyberduck/core/Preferences.java b/source/ch/cyberduck/core/Preferences.java
index 63f37c3b5..744703f70 100644
--- a/source/ch/cyberduck/core/Preferences.java
+++ b/source/ch/cyberduck/core/Preferences.java
@@ -1,578 +1,578 @@
package ch.cyberduck.core;
/*
* Copyright (c) 2005 David Kocher. All rights reserved.
* http://cyberduck.ch/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Bug fixes, suggestions and comments should be sent to:
* [email protected]
*/
import com.apple.cocoa.foundation.NSBundle;
import com.apple.cocoa.foundation.NSPathUtilities;
import com.apple.cocoa.foundation.NSArray;
import ch.cyberduck.ui.cocoa.CDBrowserTableDataSource;
import ch.cyberduck.ui.cocoa.CDPortablePreferencesImpl;
import ch.cyberduck.ui.cocoa.CDPreferencesImpl;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* Holding all application preferences. Default values get overwritten when loading
* the <code>PREFERENCES_FILE</code>.
* Singleton class.
*
* @version $Id$
*/
public abstract class Preferences {
private static Logger log = Logger.getLogger(Preferences.class);
private static Preferences current = null;
private Map<String, String> defaults;
/**
* TTL for DNS queries
*/
static {
System.setProperty("networkaddress.cache.ttl", "10");
System.setProperty("networkaddress.cache.negative.ttl", "5");
}
private static final Object lock = new Object();
/**
* @return The singleton instance of me.
*/
public static Preferences instance() {
synchronized(lock) {
if (null == current) {
if(null == NSBundle.mainBundle().objectForInfoDictionaryKey("application.preferences.path")) {
current = new CDPreferencesImpl();
}
else {
current = new CDPortablePreferencesImpl();
}
current.load();
current.setDefaults();
current.legacy();
}
return current;
}
}
/**
* Updates any legacy custom set preferences which are not longer
* valid as of this version
*/
protected void legacy() {
;
}
/**
* @param property The name of the property to overwrite
* @param value The new vlaue
*/
public abstract void setProperty(String property, Object value);
public abstract void deleteProperty(String property);
/**
* @param property The name of the property to overwrite
* @param v The new vlaue
*/
public void setProperty(String property, boolean v) {
this.setProperty(property, v ? String.valueOf(true) : String.valueOf(false));
}
/**
* @param property The name of the property to overwrite
* @param v The new vlaue
*/
public void setProperty(String property, int v) {
this.setProperty(property, String.valueOf(v));
}
/**
* @param property The name of the property to overwrite
* @param v The new vlaue
*/
public void setProperty(String property, float v) {
this.setProperty(property, String.valueOf(v));
}
/**
* setting the default prefs values
*/
protected void setDefaults() {
this.defaults = new HashMap<String, String>();
File APP_SUPPORT_DIR = null;
if(null == NSBundle.mainBundle().objectForInfoDictionaryKey("application.support.path")) {
APP_SUPPORT_DIR = new File(
NSPathUtilities.stringByExpandingTildeInPath("~/Library/Application Support/Cyberduck"));
APP_SUPPORT_DIR.mkdirs();
}
else {
APP_SUPPORT_DIR = new File(
NSPathUtilities.stringByExpandingTildeInPath(
(String)NSBundle.mainBundle().objectForInfoDictionaryKey("application.support.path")));
}
APP_SUPPORT_DIR.mkdirs();
defaults.put("application.support.path", APP_SUPPORT_DIR.getAbsolutePath());
/**
* The logging level (DEBUG, INFO, WARN, ERROR)
*/
defaults.put("logging", "ERROR");
final Level level = Level.toLevel(this.getProperty("logging"));
Logger.getLogger("ch.cyberduck").setLevel(level);
Logger.getLogger("httpclient.wire.content").setLevel(level);
Logger.getLogger("httpclient.wire.header").setLevel(Level.DEBUG);
defaults.put("version",
NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString").toString());
/**
* How many times the application was launched
*/
defaults.put("uses", "0");
/**
* True if donation dialog will be displayed before quit
*/
defaults.put("donate.reminder", String.valueOf(true));
defaults.put("defaulthandler.reminder", String.valueOf(true));
defaults.put("mail.feedback", "mailto:[email protected]");
defaults.put("website.donate", "http://cyberduck.ch/donate/");
defaults.put("website.home", "http://cyberduck.ch/");
defaults.put("website.forum", "http://forum.cyberduck.ch/");
defaults.put("website.help", "http://help.cyberduck.ch/" + this.locale());
defaults.put("website.bug", "http://trac.cyberduck.ch/newticket/");
defaults.put("rendezvous.enable", String.valueOf(true));
defaults.put("rendezvous.loopback.supress", String.valueOf(true));
defaults.put("growl.enable", String.valueOf(true));
/**
* Current default browser view is outline view (0-List view, 1-Outline view, 2-Column view)
*/
defaults.put("browser.view", "1");
/**
* Save browser sessions when quitting and restore upon relaunch
*/
defaults.put("browser.serialize", String.valueOf(true));
defaults.put("browser.view.autoexpand", String.valueOf(true));
defaults.put("browser.view.autoexpand.useDelay", String.valueOf(true));
defaults.put("browser.view.autoexpand.delay", "1.0"); // in seconds
defaults.put("browser.hidden.regex", "\\..*");
defaults.put("browser.openUntitled", String.valueOf(true));
defaults.put("browser.defaultBookmark", NSBundle.localizedString("None", ""));
defaults.put("browser.markInaccessibleFolders", String.valueOf(true));
/**
* Confirm closing the browsing connection
*/
defaults.put("browser.confirmDisconnect", String.valueOf(false));
/**
* Display only one info panel and change information according to selection in browser
*/
defaults.put("browser.info.isInspector", String.valueOf(true));
defaults.put("browser.columnKind", String.valueOf(false));
defaults.put("browser.columnSize", String.valueOf(true));
defaults.put("browser.columnModification", String.valueOf(true));
defaults.put("browser.columnOwner", String.valueOf(false));
defaults.put("browser.columnGroup", String.valueOf(false));
defaults.put("browser.columnPermissions", String.valueOf(false));
defaults.put("browser.sort.column", CDBrowserTableDataSource.FILENAME_COLUMN);
defaults.put("browser.sort.ascending", String.valueOf(true));
defaults.put("browser.alternatingRows", String.valueOf(false));
defaults.put("browser.verticalLines", String.valueOf(false));
defaults.put("browser.horizontalLines", String.valueOf(true));
/**
* Show hidden files in browser by default
*/
defaults.put("browser.showHidden", String.valueOf(false));
defaults.put("browser.charset.encoding", "UTF-8");
/**
* Edit double clicked files instead of downloading
*/
defaults.put("browser.doubleclick.edit", String.valueOf(false));
/**
* Rename files when return or enter key is pressed
*/
defaults.put("browser.enterkey.rename", String.valueOf(true));
/**
* Enable inline editing in browser
*/
defaults.put("browser.editable", String.valueOf(true));
defaults.put("browser.bookmarkDrawer.smallItems", String.valueOf(false));
/**
* Warn before renaming files
*/
defaults.put("browser.confirmMove", String.valueOf(false));
defaults.put("browser.logDrawer.isOpen", String.valueOf(false));
defaults.put("browser.logDrawer.size.height", String.valueOf(200));
defaults.put("info.toggle.permission", String.valueOf(1));
defaults.put("info.toggle.distribution", String.valueOf(0));
defaults.put("connection.toggle.options", String.valueOf(0));
defaults.put("bookmark.toggle.options", String.valueOf(0));
defaults.put("alert.toggle.transcript", String.valueOf(0));
defaults.put("transfer.toggle.details", String.valueOf(1));
/**
* Default editor
*/
defaults.put("editor.name", "TextMate");
defaults.put("editor.bundleIdentifier", "com.macromates.textmate");
/**
* Editor for the current selected file. Used to set the shortcut key in the menu delegate
*/
defaults.put("editor.kqueue.enable", "false");
defaults.put("editor.tmp.directory", NSPathUtilities.temporaryDirectory());
defaults.put("filetype.text.regex",
".*\\.txt|.*\\.cgi|.*\\.htm|.*\\.html|.*\\.shtml|.*\\.xml|.*\\.xsl|.*\\.php|.*\\.php3|" +
".*\\.js|.*\\.css|.*\\.asp|.*\\.java|.*\\.c|.*\\.cp|.*\\.cpp|.*\\.m|.*\\.h|.*\\.pl|.*\\.py|" +
".*\\.rb|.*\\.sh");
defaults.put("filetype.binary.regex",
".*\\.pdf|.*\\.ps|.*\\.exe|.*\\.bin|.*\\.jpeg|.*\\.jpg|.*\\.jp2|.*\\.gif|.*\\.tif|.*\\.ico|" +
".*\\.icns|.*\\.tiff|.*\\.bmp|.*\\.pict|.*\\.sgi|.*\\.tga|.*\\.png|.*\\.psd|" +
".*\\.hqx|.*\\.sea|.*\\.dmg|.*\\.zip|.*\\.sit|.*\\.tar|.*\\.gz|.*\\.tgz|.*\\.bz2|" +
".*\\.avi|.*\\.qtl|.*\\.bom|.*\\.pax|.*\\.pgp|.*\\.mpg|.*\\.mpeg|.*\\.mp3|.*\\.m4p|" +
".*\\.m4a|.*\\.mov|.*\\.avi|.*\\.qt|.*\\.ram|.*\\.aiff|.*\\.aif|.*\\.wav|.*\\.wma|" +
".*\\.doc|.*\\.xls|.*\\.ppt");
/**
* Save bookmarks in ~/Library
*/
defaults.put("favorites.save", String.valueOf(true));
defaults.put("queue.openByDefault", String.valueOf(false));
defaults.put("queue.save", String.valueOf(true));
defaults.put("queue.removeItemWhenComplete", String.valueOf(false));
/**
* The maximum number of concurrent transfers
*/
defaults.put("queue.maxtransfers", String.valueOf(5));
/**
* Open completed downloads
*/
defaults.put("queue.postProcessItemWhenComplete", String.valueOf(false));
defaults.put("queue.orderFrontOnStart", String.valueOf(true));
defaults.put("queue.orderBackOnStop", String.valueOf(false));
if(new File(NSPathUtilities.stringByExpandingTildeInPath("~/Downloads")).exists()) {
// For 10.5 this usually exists and should be preferrred
defaults.put("queue.download.folder", "~/Downloads");
}
else {
defaults.put("queue.download.folder", "~/Desktop");
}
/**
* Action when duplicate file exists
*/
defaults.put("queue.download.fileExists", TransferAction.ACTION_CALLBACK.toString());
defaults.put("queue.upload.fileExists", TransferAction.ACTION_CALLBACK.toString());
/**
* When triggered manually using 'Reload' in the Transfer window
*/
defaults.put("queue.download.reload.fileExists", TransferAction.ACTION_CALLBACK.toString());
defaults.put("queue.upload.reload.fileExists", TransferAction.ACTION_CALLBACK.toString());
defaults.put("queue.upload.changePermissions", String.valueOf(true));
defaults.put("queue.upload.permissions.useDefault", String.valueOf(false));
defaults.put("queue.upload.permissions.file.default", String.valueOf(644));
defaults.put("queue.upload.permissions.folder.default", String.valueOf(755));
defaults.put("queue.upload.preserveDate", String.valueOf(true));
defaults.put("queue.upload.skip.enable", String.valueOf(true));
defaults.put("queue.upload.skip.regex.default",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.upload.skip.regex",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.download.changePermissions", String.valueOf(true));
defaults.put("queue.download.permissions.useDefault", String.valueOf(false));
defaults.put("queue.download.permissions.file.default", String.valueOf(644));
defaults.put("queue.download.permissions.folder.default", String.valueOf(755));
defaults.put("queue.download.preserveDate", String.valueOf(true));
defaults.put("queue.download.skip.enable", String.valueOf(true));
defaults.put("queue.download.skip.regex.default",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.download.skip.regex",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.download.quarantine", String.valueOf(true));
/**
* Bandwidth throttle upload stream
*/
defaults.put("queue.upload.bandwidth.bytes", String.valueOf(-1));
/**
* Bandwidth throttle download stream
*/
defaults.put("queue.download.bandwidth.bytes", String.valueOf(-1));
/**
* While downloading, update the icon of the downloaded file as a progress indicator
*/
defaults.put("queue.download.updateIcon", String.valueOf(true));
/**
* Default synchronize action selected in the sync dialog
*/
defaults.put("queue.sync.action.default", SyncTransfer.ACTION_UPLOAD.toString());
defaults.put("queue.prompt.action.default", TransferAction.ACTION_OVERWRITE.toString());
defaults.put("queue.logDrawer.isOpen", String.valueOf(false));
defaults.put("queue.logDrawer.size.height", String.valueOf(200));
defaults.put("ftp.transfermode", com.enterprisedt.net.ftp.FTPTransferType.BINARY.toString());
/**
* Line seperator to use for ASCII transfers
*/
defaults.put("ftp.line.separator", "unix");
/**
* Send LIST -a
*/
defaults.put("ftp.sendExtendedListCommand", String.valueOf(true));
defaults.put("ftp.sendStatListCommand", String.valueOf(true));
/**
* Fallback to active or passive mode respectively
*/
defaults.put("ftp.connectmode.fallback", String.valueOf(true));
/**
* Protect the data channel by default
*/
defaults.put("ftp.tls.datachannel", "P"); //C
/**
* Still open connection if securing data channel fails
*/
defaults.put("ftp.tls.datachannel.failOnError", String.valueOf(false));
/**
* Do not accept certificates that can't be found in the Keychain
*/
defaults.put("ftp.tls.acceptAnyCertificate", String.valueOf(false));
/**
* If the parser should not trim whitespace from filenames
*/
defaults.put("ftp.parser.whitespaceAware", String.valueOf(true));
/**
* Default bucket location
*/
defaults.put("s3.location", "US");
/**
* Validaty for public S3 URLs
*/
defaults.put("s3.url.expire.seconds", String.valueOf(24 * 60 * 60)); //expiry time for public URL
/**
* Generate publicy accessible URLs when copying URLs in S3 browser
*/
defaults.put("s3.url.public", String.valueOf(false));
defaults.put("s3.tls.acceptAnyCertificate", String.valueOf(false));
// defaults.put("s3.crypto.algorithm", "PBEWithMD5AndDES");
defaults.put("webdav.followRedirects", String.valueOf(true));
defaults.put("webdav.tls.acceptAnyCertificate", String.valueOf(false));
/**
* Maximum concurrent connections to the same host
* Unlimited by default
*/
defaults.put("connection.host.max", String.valueOf(-1));
/**
* Default login name
*/
defaults.put("connection.login.name", System.getProperty("user.name"));
defaults.put("connection.login.anon.name", "anonymous");
defaults.put("connection.login.anon.pass", "[email protected]");
/**
* Search for passphrases in Keychain
*/
defaults.put("connection.login.useKeychain", String.valueOf(true));
defaults.put("connection.login.addKeychain", String.valueOf(true));
defaults.put("connection.port.default", String.valueOf(21));
defaults.put("connection.protocol.default", "ftp");
defaults.put("connection.timeout.seconds", String.valueOf(30));
/**
* Retry to connect after a I/O failure automatically
*/
defaults.put("connection.retry", String.valueOf(1));
defaults.put("connection.retry.delay", String.valueOf(10));
defaults.put("connection.hostname.default", "localhost");
/**
* Try to resolve the hostname when entered in connection dialog
*/
defaults.put("connection.hostname.check", String.valueOf(true)); //Check hostname reachability using NSNetworkDiagnostics
defaults.put("connection.hostname.idn", String.valueOf(true)); //Convert hostnames to Punycode
/**
* Normalize path names
*/
defaults.put("path.normalize", String.valueOf(true));
defaults.put("path.normalize.unicode", String.valueOf(false));
/**
* Use the SFTP subsystem or a SCP channel for file transfers over SSH
*/
defaults.put("ssh.transfer", Protocol.SFTP.getIdentifier()); // Session.SCP
/**
* Location of the openssh known_hosts file
*/
defaults.put("ssh.knownhosts", "~/.ssh/known_hosts");
defaults.put("ssh.CSEncryption", "blowfish-cbc"); //client -> server encryption cipher
defaults.put("ssh.SCEncryption", "blowfish-cbc"); //server -> client encryption cipher
defaults.put("ssh.CSAuthentication", "hmac-md5"); //client -> server message authentication
defaults.put("ssh.SCAuthentication", "hmac-md5"); //server -> client message authentication
defaults.put("ssh.publickey", "ssh-rsa");
defaults.put("ssh.compression", "none"); //zlib
defaults.put("archive.default", "tar.gz");
/**
* Archiver
*/
defaults.put("archive.command.create.tar", "tar -cvpPf {0}.tar {0}");
defaults.put("archive.command.create.tar.gz", "tar -czvpPf {0}.tar.gz {0}");
- defaults.put("archive.command.create.tar.bz2", "tar -cjvpPf {0}.tar.gz {0}");
- defaults.put("archive.command.create.zip", "zip -v {0}.zip {0}");
+ defaults.put("archive.command.create.tar.bz2", "tar -cjvpPf {0}.tar.bz2 {0}");
+ defaults.put("archive.command.create.zip", "zip -rv {0}.zip {0}");
defaults.put("archive.command.create.gz", "gzip -rv {0}");
defaults.put("archive.command.create.bz2", "bzip2 -zvk {0}");
/**
* Unarchiver
*/
defaults.put("archive.command.expand.tar", "tar -xvpPf {0} -C {1}");
defaults.put("archive.command.expand.tar.gz", "tar -xzvpPf {0} -C {1}");
defaults.put("archive.command.expand.tar.bz2", "tar -xjvpPf {0} -C {1}");
- defaults.put("archive.command.expand.zip", "unzip -v {0} -d {1}");
+ defaults.put("archive.command.expand.zip", "unzip -n {0} -d {1}");
defaults.put("archive.command.expand.gz", "gzip -dv {0}");
defaults.put("archive.command.expand.bz2", "bzip2 -dvk {0}");
defaults.put("update.check", String.valueOf(true));
final int DAY = 60*60*24;
defaults.put("update.check.interval", String.valueOf(DAY)); // periodic update check in seconds
}
/**
* Should be overriden by the implementation and only called if the property
* can't be found in the users's defaults table
*
* @param property The property to query.
* @return The value of the property
*/
public Object getObject(String property) {
Object value = defaults.get(property);
if (null == value) {
log.warn("No property with key '" + property + "'");
}
return value;
}
public String getProperty(String property) {
return this.getObject(property).toString();
}
public int getInteger(String property) {
return Integer.parseInt(this.getObject(property).toString());
}
public float getFloat(String property) {
return Float.parseFloat(this.getObject(property).toString());
}
public double getDouble(String property) {
return Double.parseDouble(this.getObject(property).toString());
}
public boolean getBoolean(String property) {
String value = this.getObject(property).toString();
if(value.equalsIgnoreCase(String.valueOf(true))) {
return true;
}
if(value.equalsIgnoreCase(String.valueOf(false))) {
return false;
}
if(value.equalsIgnoreCase(String.valueOf(1))) {
return true;
}
if(value.equalsIgnoreCase(String.valueOf(0))) {
return false;
}
try {
return value.equalsIgnoreCase("yes");
}
catch(NumberFormatException e) {
return false;
}
}
/**
* Store preferences; ensure perisistency
*/
public abstract void save();
/**
* Overriding the default values with prefs from the last session.
*/
protected abstract void load();
/**
* @return The preferred locale of all available in this application bundle
* for the currently logged in user
*/
private String locale() {
String locale = "en";
NSArray preferredLocalizations = NSBundle.preferredLocalizations(
NSBundle.mainBundle().localizations());
if(preferredLocalizations.count() > 0) {
locale = (String) preferredLocalizations.objectAtIndex(0);
}
return locale;
}
}
| false | true | protected void setDefaults() {
this.defaults = new HashMap<String, String>();
File APP_SUPPORT_DIR = null;
if(null == NSBundle.mainBundle().objectForInfoDictionaryKey("application.support.path")) {
APP_SUPPORT_DIR = new File(
NSPathUtilities.stringByExpandingTildeInPath("~/Library/Application Support/Cyberduck"));
APP_SUPPORT_DIR.mkdirs();
}
else {
APP_SUPPORT_DIR = new File(
NSPathUtilities.stringByExpandingTildeInPath(
(String)NSBundle.mainBundle().objectForInfoDictionaryKey("application.support.path")));
}
APP_SUPPORT_DIR.mkdirs();
defaults.put("application.support.path", APP_SUPPORT_DIR.getAbsolutePath());
/**
* The logging level (DEBUG, INFO, WARN, ERROR)
*/
defaults.put("logging", "ERROR");
final Level level = Level.toLevel(this.getProperty("logging"));
Logger.getLogger("ch.cyberduck").setLevel(level);
Logger.getLogger("httpclient.wire.content").setLevel(level);
Logger.getLogger("httpclient.wire.header").setLevel(Level.DEBUG);
defaults.put("version",
NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString").toString());
/**
* How many times the application was launched
*/
defaults.put("uses", "0");
/**
* True if donation dialog will be displayed before quit
*/
defaults.put("donate.reminder", String.valueOf(true));
defaults.put("defaulthandler.reminder", String.valueOf(true));
defaults.put("mail.feedback", "mailto:[email protected]");
defaults.put("website.donate", "http://cyberduck.ch/donate/");
defaults.put("website.home", "http://cyberduck.ch/");
defaults.put("website.forum", "http://forum.cyberduck.ch/");
defaults.put("website.help", "http://help.cyberduck.ch/" + this.locale());
defaults.put("website.bug", "http://trac.cyberduck.ch/newticket/");
defaults.put("rendezvous.enable", String.valueOf(true));
defaults.put("rendezvous.loopback.supress", String.valueOf(true));
defaults.put("growl.enable", String.valueOf(true));
/**
* Current default browser view is outline view (0-List view, 1-Outline view, 2-Column view)
*/
defaults.put("browser.view", "1");
/**
* Save browser sessions when quitting and restore upon relaunch
*/
defaults.put("browser.serialize", String.valueOf(true));
defaults.put("browser.view.autoexpand", String.valueOf(true));
defaults.put("browser.view.autoexpand.useDelay", String.valueOf(true));
defaults.put("browser.view.autoexpand.delay", "1.0"); // in seconds
defaults.put("browser.hidden.regex", "\\..*");
defaults.put("browser.openUntitled", String.valueOf(true));
defaults.put("browser.defaultBookmark", NSBundle.localizedString("None", ""));
defaults.put("browser.markInaccessibleFolders", String.valueOf(true));
/**
* Confirm closing the browsing connection
*/
defaults.put("browser.confirmDisconnect", String.valueOf(false));
/**
* Display only one info panel and change information according to selection in browser
*/
defaults.put("browser.info.isInspector", String.valueOf(true));
defaults.put("browser.columnKind", String.valueOf(false));
defaults.put("browser.columnSize", String.valueOf(true));
defaults.put("browser.columnModification", String.valueOf(true));
defaults.put("browser.columnOwner", String.valueOf(false));
defaults.put("browser.columnGroup", String.valueOf(false));
defaults.put("browser.columnPermissions", String.valueOf(false));
defaults.put("browser.sort.column", CDBrowserTableDataSource.FILENAME_COLUMN);
defaults.put("browser.sort.ascending", String.valueOf(true));
defaults.put("browser.alternatingRows", String.valueOf(false));
defaults.put("browser.verticalLines", String.valueOf(false));
defaults.put("browser.horizontalLines", String.valueOf(true));
/**
* Show hidden files in browser by default
*/
defaults.put("browser.showHidden", String.valueOf(false));
defaults.put("browser.charset.encoding", "UTF-8");
/**
* Edit double clicked files instead of downloading
*/
defaults.put("browser.doubleclick.edit", String.valueOf(false));
/**
* Rename files when return or enter key is pressed
*/
defaults.put("browser.enterkey.rename", String.valueOf(true));
/**
* Enable inline editing in browser
*/
defaults.put("browser.editable", String.valueOf(true));
defaults.put("browser.bookmarkDrawer.smallItems", String.valueOf(false));
/**
* Warn before renaming files
*/
defaults.put("browser.confirmMove", String.valueOf(false));
defaults.put("browser.logDrawer.isOpen", String.valueOf(false));
defaults.put("browser.logDrawer.size.height", String.valueOf(200));
defaults.put("info.toggle.permission", String.valueOf(1));
defaults.put("info.toggle.distribution", String.valueOf(0));
defaults.put("connection.toggle.options", String.valueOf(0));
defaults.put("bookmark.toggle.options", String.valueOf(0));
defaults.put("alert.toggle.transcript", String.valueOf(0));
defaults.put("transfer.toggle.details", String.valueOf(1));
/**
* Default editor
*/
defaults.put("editor.name", "TextMate");
defaults.put("editor.bundleIdentifier", "com.macromates.textmate");
/**
* Editor for the current selected file. Used to set the shortcut key in the menu delegate
*/
defaults.put("editor.kqueue.enable", "false");
defaults.put("editor.tmp.directory", NSPathUtilities.temporaryDirectory());
defaults.put("filetype.text.regex",
".*\\.txt|.*\\.cgi|.*\\.htm|.*\\.html|.*\\.shtml|.*\\.xml|.*\\.xsl|.*\\.php|.*\\.php3|" +
".*\\.js|.*\\.css|.*\\.asp|.*\\.java|.*\\.c|.*\\.cp|.*\\.cpp|.*\\.m|.*\\.h|.*\\.pl|.*\\.py|" +
".*\\.rb|.*\\.sh");
defaults.put("filetype.binary.regex",
".*\\.pdf|.*\\.ps|.*\\.exe|.*\\.bin|.*\\.jpeg|.*\\.jpg|.*\\.jp2|.*\\.gif|.*\\.tif|.*\\.ico|" +
".*\\.icns|.*\\.tiff|.*\\.bmp|.*\\.pict|.*\\.sgi|.*\\.tga|.*\\.png|.*\\.psd|" +
".*\\.hqx|.*\\.sea|.*\\.dmg|.*\\.zip|.*\\.sit|.*\\.tar|.*\\.gz|.*\\.tgz|.*\\.bz2|" +
".*\\.avi|.*\\.qtl|.*\\.bom|.*\\.pax|.*\\.pgp|.*\\.mpg|.*\\.mpeg|.*\\.mp3|.*\\.m4p|" +
".*\\.m4a|.*\\.mov|.*\\.avi|.*\\.qt|.*\\.ram|.*\\.aiff|.*\\.aif|.*\\.wav|.*\\.wma|" +
".*\\.doc|.*\\.xls|.*\\.ppt");
/**
* Save bookmarks in ~/Library
*/
defaults.put("favorites.save", String.valueOf(true));
defaults.put("queue.openByDefault", String.valueOf(false));
defaults.put("queue.save", String.valueOf(true));
defaults.put("queue.removeItemWhenComplete", String.valueOf(false));
/**
* The maximum number of concurrent transfers
*/
defaults.put("queue.maxtransfers", String.valueOf(5));
/**
* Open completed downloads
*/
defaults.put("queue.postProcessItemWhenComplete", String.valueOf(false));
defaults.put("queue.orderFrontOnStart", String.valueOf(true));
defaults.put("queue.orderBackOnStop", String.valueOf(false));
if(new File(NSPathUtilities.stringByExpandingTildeInPath("~/Downloads")).exists()) {
// For 10.5 this usually exists and should be preferrred
defaults.put("queue.download.folder", "~/Downloads");
}
else {
defaults.put("queue.download.folder", "~/Desktop");
}
/**
* Action when duplicate file exists
*/
defaults.put("queue.download.fileExists", TransferAction.ACTION_CALLBACK.toString());
defaults.put("queue.upload.fileExists", TransferAction.ACTION_CALLBACK.toString());
/**
* When triggered manually using 'Reload' in the Transfer window
*/
defaults.put("queue.download.reload.fileExists", TransferAction.ACTION_CALLBACK.toString());
defaults.put("queue.upload.reload.fileExists", TransferAction.ACTION_CALLBACK.toString());
defaults.put("queue.upload.changePermissions", String.valueOf(true));
defaults.put("queue.upload.permissions.useDefault", String.valueOf(false));
defaults.put("queue.upload.permissions.file.default", String.valueOf(644));
defaults.put("queue.upload.permissions.folder.default", String.valueOf(755));
defaults.put("queue.upload.preserveDate", String.valueOf(true));
defaults.put("queue.upload.skip.enable", String.valueOf(true));
defaults.put("queue.upload.skip.regex.default",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.upload.skip.regex",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.download.changePermissions", String.valueOf(true));
defaults.put("queue.download.permissions.useDefault", String.valueOf(false));
defaults.put("queue.download.permissions.file.default", String.valueOf(644));
defaults.put("queue.download.permissions.folder.default", String.valueOf(755));
defaults.put("queue.download.preserveDate", String.valueOf(true));
defaults.put("queue.download.skip.enable", String.valueOf(true));
defaults.put("queue.download.skip.regex.default",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.download.skip.regex",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.download.quarantine", String.valueOf(true));
/**
* Bandwidth throttle upload stream
*/
defaults.put("queue.upload.bandwidth.bytes", String.valueOf(-1));
/**
* Bandwidth throttle download stream
*/
defaults.put("queue.download.bandwidth.bytes", String.valueOf(-1));
/**
* While downloading, update the icon of the downloaded file as a progress indicator
*/
defaults.put("queue.download.updateIcon", String.valueOf(true));
/**
* Default synchronize action selected in the sync dialog
*/
defaults.put("queue.sync.action.default", SyncTransfer.ACTION_UPLOAD.toString());
defaults.put("queue.prompt.action.default", TransferAction.ACTION_OVERWRITE.toString());
defaults.put("queue.logDrawer.isOpen", String.valueOf(false));
defaults.put("queue.logDrawer.size.height", String.valueOf(200));
defaults.put("ftp.transfermode", com.enterprisedt.net.ftp.FTPTransferType.BINARY.toString());
/**
* Line seperator to use for ASCII transfers
*/
defaults.put("ftp.line.separator", "unix");
/**
* Send LIST -a
*/
defaults.put("ftp.sendExtendedListCommand", String.valueOf(true));
defaults.put("ftp.sendStatListCommand", String.valueOf(true));
/**
* Fallback to active or passive mode respectively
*/
defaults.put("ftp.connectmode.fallback", String.valueOf(true));
/**
* Protect the data channel by default
*/
defaults.put("ftp.tls.datachannel", "P"); //C
/**
* Still open connection if securing data channel fails
*/
defaults.put("ftp.tls.datachannel.failOnError", String.valueOf(false));
/**
* Do not accept certificates that can't be found in the Keychain
*/
defaults.put("ftp.tls.acceptAnyCertificate", String.valueOf(false));
/**
* If the parser should not trim whitespace from filenames
*/
defaults.put("ftp.parser.whitespaceAware", String.valueOf(true));
/**
* Default bucket location
*/
defaults.put("s3.location", "US");
/**
* Validaty for public S3 URLs
*/
defaults.put("s3.url.expire.seconds", String.valueOf(24 * 60 * 60)); //expiry time for public URL
/**
* Generate publicy accessible URLs when copying URLs in S3 browser
*/
defaults.put("s3.url.public", String.valueOf(false));
defaults.put("s3.tls.acceptAnyCertificate", String.valueOf(false));
// defaults.put("s3.crypto.algorithm", "PBEWithMD5AndDES");
defaults.put("webdav.followRedirects", String.valueOf(true));
defaults.put("webdav.tls.acceptAnyCertificate", String.valueOf(false));
/**
* Maximum concurrent connections to the same host
* Unlimited by default
*/
defaults.put("connection.host.max", String.valueOf(-1));
/**
* Default login name
*/
defaults.put("connection.login.name", System.getProperty("user.name"));
defaults.put("connection.login.anon.name", "anonymous");
defaults.put("connection.login.anon.pass", "[email protected]");
/**
* Search for passphrases in Keychain
*/
defaults.put("connection.login.useKeychain", String.valueOf(true));
defaults.put("connection.login.addKeychain", String.valueOf(true));
defaults.put("connection.port.default", String.valueOf(21));
defaults.put("connection.protocol.default", "ftp");
defaults.put("connection.timeout.seconds", String.valueOf(30));
/**
* Retry to connect after a I/O failure automatically
*/
defaults.put("connection.retry", String.valueOf(1));
defaults.put("connection.retry.delay", String.valueOf(10));
defaults.put("connection.hostname.default", "localhost");
/**
* Try to resolve the hostname when entered in connection dialog
*/
defaults.put("connection.hostname.check", String.valueOf(true)); //Check hostname reachability using NSNetworkDiagnostics
defaults.put("connection.hostname.idn", String.valueOf(true)); //Convert hostnames to Punycode
/**
* Normalize path names
*/
defaults.put("path.normalize", String.valueOf(true));
defaults.put("path.normalize.unicode", String.valueOf(false));
/**
* Use the SFTP subsystem or a SCP channel for file transfers over SSH
*/
defaults.put("ssh.transfer", Protocol.SFTP.getIdentifier()); // Session.SCP
/**
* Location of the openssh known_hosts file
*/
defaults.put("ssh.knownhosts", "~/.ssh/known_hosts");
defaults.put("ssh.CSEncryption", "blowfish-cbc"); //client -> server encryption cipher
defaults.put("ssh.SCEncryption", "blowfish-cbc"); //server -> client encryption cipher
defaults.put("ssh.CSAuthentication", "hmac-md5"); //client -> server message authentication
defaults.put("ssh.SCAuthentication", "hmac-md5"); //server -> client message authentication
defaults.put("ssh.publickey", "ssh-rsa");
defaults.put("ssh.compression", "none"); //zlib
defaults.put("archive.default", "tar.gz");
/**
* Archiver
*/
defaults.put("archive.command.create.tar", "tar -cvpPf {0}.tar {0}");
defaults.put("archive.command.create.tar.gz", "tar -czvpPf {0}.tar.gz {0}");
defaults.put("archive.command.create.tar.bz2", "tar -cjvpPf {0}.tar.gz {0}");
defaults.put("archive.command.create.zip", "zip -v {0}.zip {0}");
defaults.put("archive.command.create.gz", "gzip -rv {0}");
defaults.put("archive.command.create.bz2", "bzip2 -zvk {0}");
/**
* Unarchiver
*/
defaults.put("archive.command.expand.tar", "tar -xvpPf {0} -C {1}");
defaults.put("archive.command.expand.tar.gz", "tar -xzvpPf {0} -C {1}");
defaults.put("archive.command.expand.tar.bz2", "tar -xjvpPf {0} -C {1}");
defaults.put("archive.command.expand.zip", "unzip -v {0} -d {1}");
defaults.put("archive.command.expand.gz", "gzip -dv {0}");
defaults.put("archive.command.expand.bz2", "bzip2 -dvk {0}");
defaults.put("update.check", String.valueOf(true));
final int DAY = 60*60*24;
defaults.put("update.check.interval", String.valueOf(DAY)); // periodic update check in seconds
}
| protected void setDefaults() {
this.defaults = new HashMap<String, String>();
File APP_SUPPORT_DIR = null;
if(null == NSBundle.mainBundle().objectForInfoDictionaryKey("application.support.path")) {
APP_SUPPORT_DIR = new File(
NSPathUtilities.stringByExpandingTildeInPath("~/Library/Application Support/Cyberduck"));
APP_SUPPORT_DIR.mkdirs();
}
else {
APP_SUPPORT_DIR = new File(
NSPathUtilities.stringByExpandingTildeInPath(
(String)NSBundle.mainBundle().objectForInfoDictionaryKey("application.support.path")));
}
APP_SUPPORT_DIR.mkdirs();
defaults.put("application.support.path", APP_SUPPORT_DIR.getAbsolutePath());
/**
* The logging level (DEBUG, INFO, WARN, ERROR)
*/
defaults.put("logging", "ERROR");
final Level level = Level.toLevel(this.getProperty("logging"));
Logger.getLogger("ch.cyberduck").setLevel(level);
Logger.getLogger("httpclient.wire.content").setLevel(level);
Logger.getLogger("httpclient.wire.header").setLevel(Level.DEBUG);
defaults.put("version",
NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString").toString());
/**
* How many times the application was launched
*/
defaults.put("uses", "0");
/**
* True if donation dialog will be displayed before quit
*/
defaults.put("donate.reminder", String.valueOf(true));
defaults.put("defaulthandler.reminder", String.valueOf(true));
defaults.put("mail.feedback", "mailto:[email protected]");
defaults.put("website.donate", "http://cyberduck.ch/donate/");
defaults.put("website.home", "http://cyberduck.ch/");
defaults.put("website.forum", "http://forum.cyberduck.ch/");
defaults.put("website.help", "http://help.cyberduck.ch/" + this.locale());
defaults.put("website.bug", "http://trac.cyberduck.ch/newticket/");
defaults.put("rendezvous.enable", String.valueOf(true));
defaults.put("rendezvous.loopback.supress", String.valueOf(true));
defaults.put("growl.enable", String.valueOf(true));
/**
* Current default browser view is outline view (0-List view, 1-Outline view, 2-Column view)
*/
defaults.put("browser.view", "1");
/**
* Save browser sessions when quitting and restore upon relaunch
*/
defaults.put("browser.serialize", String.valueOf(true));
defaults.put("browser.view.autoexpand", String.valueOf(true));
defaults.put("browser.view.autoexpand.useDelay", String.valueOf(true));
defaults.put("browser.view.autoexpand.delay", "1.0"); // in seconds
defaults.put("browser.hidden.regex", "\\..*");
defaults.put("browser.openUntitled", String.valueOf(true));
defaults.put("browser.defaultBookmark", NSBundle.localizedString("None", ""));
defaults.put("browser.markInaccessibleFolders", String.valueOf(true));
/**
* Confirm closing the browsing connection
*/
defaults.put("browser.confirmDisconnect", String.valueOf(false));
/**
* Display only one info panel and change information according to selection in browser
*/
defaults.put("browser.info.isInspector", String.valueOf(true));
defaults.put("browser.columnKind", String.valueOf(false));
defaults.put("browser.columnSize", String.valueOf(true));
defaults.put("browser.columnModification", String.valueOf(true));
defaults.put("browser.columnOwner", String.valueOf(false));
defaults.put("browser.columnGroup", String.valueOf(false));
defaults.put("browser.columnPermissions", String.valueOf(false));
defaults.put("browser.sort.column", CDBrowserTableDataSource.FILENAME_COLUMN);
defaults.put("browser.sort.ascending", String.valueOf(true));
defaults.put("browser.alternatingRows", String.valueOf(false));
defaults.put("browser.verticalLines", String.valueOf(false));
defaults.put("browser.horizontalLines", String.valueOf(true));
/**
* Show hidden files in browser by default
*/
defaults.put("browser.showHidden", String.valueOf(false));
defaults.put("browser.charset.encoding", "UTF-8");
/**
* Edit double clicked files instead of downloading
*/
defaults.put("browser.doubleclick.edit", String.valueOf(false));
/**
* Rename files when return or enter key is pressed
*/
defaults.put("browser.enterkey.rename", String.valueOf(true));
/**
* Enable inline editing in browser
*/
defaults.put("browser.editable", String.valueOf(true));
defaults.put("browser.bookmarkDrawer.smallItems", String.valueOf(false));
/**
* Warn before renaming files
*/
defaults.put("browser.confirmMove", String.valueOf(false));
defaults.put("browser.logDrawer.isOpen", String.valueOf(false));
defaults.put("browser.logDrawer.size.height", String.valueOf(200));
defaults.put("info.toggle.permission", String.valueOf(1));
defaults.put("info.toggle.distribution", String.valueOf(0));
defaults.put("connection.toggle.options", String.valueOf(0));
defaults.put("bookmark.toggle.options", String.valueOf(0));
defaults.put("alert.toggle.transcript", String.valueOf(0));
defaults.put("transfer.toggle.details", String.valueOf(1));
/**
* Default editor
*/
defaults.put("editor.name", "TextMate");
defaults.put("editor.bundleIdentifier", "com.macromates.textmate");
/**
* Editor for the current selected file. Used to set the shortcut key in the menu delegate
*/
defaults.put("editor.kqueue.enable", "false");
defaults.put("editor.tmp.directory", NSPathUtilities.temporaryDirectory());
defaults.put("filetype.text.regex",
".*\\.txt|.*\\.cgi|.*\\.htm|.*\\.html|.*\\.shtml|.*\\.xml|.*\\.xsl|.*\\.php|.*\\.php3|" +
".*\\.js|.*\\.css|.*\\.asp|.*\\.java|.*\\.c|.*\\.cp|.*\\.cpp|.*\\.m|.*\\.h|.*\\.pl|.*\\.py|" +
".*\\.rb|.*\\.sh");
defaults.put("filetype.binary.regex",
".*\\.pdf|.*\\.ps|.*\\.exe|.*\\.bin|.*\\.jpeg|.*\\.jpg|.*\\.jp2|.*\\.gif|.*\\.tif|.*\\.ico|" +
".*\\.icns|.*\\.tiff|.*\\.bmp|.*\\.pict|.*\\.sgi|.*\\.tga|.*\\.png|.*\\.psd|" +
".*\\.hqx|.*\\.sea|.*\\.dmg|.*\\.zip|.*\\.sit|.*\\.tar|.*\\.gz|.*\\.tgz|.*\\.bz2|" +
".*\\.avi|.*\\.qtl|.*\\.bom|.*\\.pax|.*\\.pgp|.*\\.mpg|.*\\.mpeg|.*\\.mp3|.*\\.m4p|" +
".*\\.m4a|.*\\.mov|.*\\.avi|.*\\.qt|.*\\.ram|.*\\.aiff|.*\\.aif|.*\\.wav|.*\\.wma|" +
".*\\.doc|.*\\.xls|.*\\.ppt");
/**
* Save bookmarks in ~/Library
*/
defaults.put("favorites.save", String.valueOf(true));
defaults.put("queue.openByDefault", String.valueOf(false));
defaults.put("queue.save", String.valueOf(true));
defaults.put("queue.removeItemWhenComplete", String.valueOf(false));
/**
* The maximum number of concurrent transfers
*/
defaults.put("queue.maxtransfers", String.valueOf(5));
/**
* Open completed downloads
*/
defaults.put("queue.postProcessItemWhenComplete", String.valueOf(false));
defaults.put("queue.orderFrontOnStart", String.valueOf(true));
defaults.put("queue.orderBackOnStop", String.valueOf(false));
if(new File(NSPathUtilities.stringByExpandingTildeInPath("~/Downloads")).exists()) {
// For 10.5 this usually exists and should be preferrred
defaults.put("queue.download.folder", "~/Downloads");
}
else {
defaults.put("queue.download.folder", "~/Desktop");
}
/**
* Action when duplicate file exists
*/
defaults.put("queue.download.fileExists", TransferAction.ACTION_CALLBACK.toString());
defaults.put("queue.upload.fileExists", TransferAction.ACTION_CALLBACK.toString());
/**
* When triggered manually using 'Reload' in the Transfer window
*/
defaults.put("queue.download.reload.fileExists", TransferAction.ACTION_CALLBACK.toString());
defaults.put("queue.upload.reload.fileExists", TransferAction.ACTION_CALLBACK.toString());
defaults.put("queue.upload.changePermissions", String.valueOf(true));
defaults.put("queue.upload.permissions.useDefault", String.valueOf(false));
defaults.put("queue.upload.permissions.file.default", String.valueOf(644));
defaults.put("queue.upload.permissions.folder.default", String.valueOf(755));
defaults.put("queue.upload.preserveDate", String.valueOf(true));
defaults.put("queue.upload.skip.enable", String.valueOf(true));
defaults.put("queue.upload.skip.regex.default",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.upload.skip.regex",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.download.changePermissions", String.valueOf(true));
defaults.put("queue.download.permissions.useDefault", String.valueOf(false));
defaults.put("queue.download.permissions.file.default", String.valueOf(644));
defaults.put("queue.download.permissions.folder.default", String.valueOf(755));
defaults.put("queue.download.preserveDate", String.valueOf(true));
defaults.put("queue.download.skip.enable", String.valueOf(true));
defaults.put("queue.download.skip.regex.default",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.download.skip.regex",
".*~\\..*|\\.DS_Store|\\.svn|CVS");
defaults.put("queue.download.quarantine", String.valueOf(true));
/**
* Bandwidth throttle upload stream
*/
defaults.put("queue.upload.bandwidth.bytes", String.valueOf(-1));
/**
* Bandwidth throttle download stream
*/
defaults.put("queue.download.bandwidth.bytes", String.valueOf(-1));
/**
* While downloading, update the icon of the downloaded file as a progress indicator
*/
defaults.put("queue.download.updateIcon", String.valueOf(true));
/**
* Default synchronize action selected in the sync dialog
*/
defaults.put("queue.sync.action.default", SyncTransfer.ACTION_UPLOAD.toString());
defaults.put("queue.prompt.action.default", TransferAction.ACTION_OVERWRITE.toString());
defaults.put("queue.logDrawer.isOpen", String.valueOf(false));
defaults.put("queue.logDrawer.size.height", String.valueOf(200));
defaults.put("ftp.transfermode", com.enterprisedt.net.ftp.FTPTransferType.BINARY.toString());
/**
* Line seperator to use for ASCII transfers
*/
defaults.put("ftp.line.separator", "unix");
/**
* Send LIST -a
*/
defaults.put("ftp.sendExtendedListCommand", String.valueOf(true));
defaults.put("ftp.sendStatListCommand", String.valueOf(true));
/**
* Fallback to active or passive mode respectively
*/
defaults.put("ftp.connectmode.fallback", String.valueOf(true));
/**
* Protect the data channel by default
*/
defaults.put("ftp.tls.datachannel", "P"); //C
/**
* Still open connection if securing data channel fails
*/
defaults.put("ftp.tls.datachannel.failOnError", String.valueOf(false));
/**
* Do not accept certificates that can't be found in the Keychain
*/
defaults.put("ftp.tls.acceptAnyCertificate", String.valueOf(false));
/**
* If the parser should not trim whitespace from filenames
*/
defaults.put("ftp.parser.whitespaceAware", String.valueOf(true));
/**
* Default bucket location
*/
defaults.put("s3.location", "US");
/**
* Validaty for public S3 URLs
*/
defaults.put("s3.url.expire.seconds", String.valueOf(24 * 60 * 60)); //expiry time for public URL
/**
* Generate publicy accessible URLs when copying URLs in S3 browser
*/
defaults.put("s3.url.public", String.valueOf(false));
defaults.put("s3.tls.acceptAnyCertificate", String.valueOf(false));
// defaults.put("s3.crypto.algorithm", "PBEWithMD5AndDES");
defaults.put("webdav.followRedirects", String.valueOf(true));
defaults.put("webdav.tls.acceptAnyCertificate", String.valueOf(false));
/**
* Maximum concurrent connections to the same host
* Unlimited by default
*/
defaults.put("connection.host.max", String.valueOf(-1));
/**
* Default login name
*/
defaults.put("connection.login.name", System.getProperty("user.name"));
defaults.put("connection.login.anon.name", "anonymous");
defaults.put("connection.login.anon.pass", "[email protected]");
/**
* Search for passphrases in Keychain
*/
defaults.put("connection.login.useKeychain", String.valueOf(true));
defaults.put("connection.login.addKeychain", String.valueOf(true));
defaults.put("connection.port.default", String.valueOf(21));
defaults.put("connection.protocol.default", "ftp");
defaults.put("connection.timeout.seconds", String.valueOf(30));
/**
* Retry to connect after a I/O failure automatically
*/
defaults.put("connection.retry", String.valueOf(1));
defaults.put("connection.retry.delay", String.valueOf(10));
defaults.put("connection.hostname.default", "localhost");
/**
* Try to resolve the hostname when entered in connection dialog
*/
defaults.put("connection.hostname.check", String.valueOf(true)); //Check hostname reachability using NSNetworkDiagnostics
defaults.put("connection.hostname.idn", String.valueOf(true)); //Convert hostnames to Punycode
/**
* Normalize path names
*/
defaults.put("path.normalize", String.valueOf(true));
defaults.put("path.normalize.unicode", String.valueOf(false));
/**
* Use the SFTP subsystem or a SCP channel for file transfers over SSH
*/
defaults.put("ssh.transfer", Protocol.SFTP.getIdentifier()); // Session.SCP
/**
* Location of the openssh known_hosts file
*/
defaults.put("ssh.knownhosts", "~/.ssh/known_hosts");
defaults.put("ssh.CSEncryption", "blowfish-cbc"); //client -> server encryption cipher
defaults.put("ssh.SCEncryption", "blowfish-cbc"); //server -> client encryption cipher
defaults.put("ssh.CSAuthentication", "hmac-md5"); //client -> server message authentication
defaults.put("ssh.SCAuthentication", "hmac-md5"); //server -> client message authentication
defaults.put("ssh.publickey", "ssh-rsa");
defaults.put("ssh.compression", "none"); //zlib
defaults.put("archive.default", "tar.gz");
/**
* Archiver
*/
defaults.put("archive.command.create.tar", "tar -cvpPf {0}.tar {0}");
defaults.put("archive.command.create.tar.gz", "tar -czvpPf {0}.tar.gz {0}");
defaults.put("archive.command.create.tar.bz2", "tar -cjvpPf {0}.tar.bz2 {0}");
defaults.put("archive.command.create.zip", "zip -rv {0}.zip {0}");
defaults.put("archive.command.create.gz", "gzip -rv {0}");
defaults.put("archive.command.create.bz2", "bzip2 -zvk {0}");
/**
* Unarchiver
*/
defaults.put("archive.command.expand.tar", "tar -xvpPf {0} -C {1}");
defaults.put("archive.command.expand.tar.gz", "tar -xzvpPf {0} -C {1}");
defaults.put("archive.command.expand.tar.bz2", "tar -xjvpPf {0} -C {1}");
defaults.put("archive.command.expand.zip", "unzip -n {0} -d {1}");
defaults.put("archive.command.expand.gz", "gzip -dv {0}");
defaults.put("archive.command.expand.bz2", "bzip2 -dvk {0}");
defaults.put("update.check", String.valueOf(true));
final int DAY = 60*60*24;
defaults.put("update.check.interval", String.valueOf(DAY)); // periodic update check in seconds
}
|
diff --git a/src/com/winvector/anneal/RunAnneal.java b/src/com/winvector/anneal/RunAnneal.java
index fcc1897..67c6610 100644
--- a/src/com/winvector/anneal/RunAnneal.java
+++ b/src/com/winvector/anneal/RunAnneal.java
@@ -1,143 +1,158 @@
package com.winvector.anneal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public final class RunAnneal<T extends Comparable<T>> {
private final Population<T> shared;
public RunAnneal(final Population<T> shared) {
this.shared = shared;
}
private class AnnealJob1 implements Runnable {
public final int id;
public final int psize;
public final Random rand;
public AnnealJob1(final int id, final int psize, final Random rand) {
this.id = id;
this.psize = psize;
this.rand = rand;
}
private void swap(final Population<T> p) {
synchronized(shared) {
//System.out.println("Runnable " + id + " mixing into main population " + new Date());
for(int oi=0;oi<psize;++oi) {
if(rand.nextBoolean()) {
final int ti = rand.nextInt(shared.population.size());
final T or = p.population.get(oi);
final double os = p.pscore[oi];
p.population.set(oi,shared.population.get(ti));
p.pscore[oi] = shared.pscore[ti];
shared.population.set(ti,or);
shared.pscore[ti] = os;
}
}
}
}
protected double score(final T mi) {
return shared.pv.scoreExample(mi);
}
protected int nInserts(final double score) {
final int nInserts = Math.max((int)Math.floor(10.0*score),1);
return nInserts;
}
@Override
public void run() {
final Population<T> p;
synchronized(shared) {
System.out.println("anneal Runnable " + id + " start " + new Date());
p = new Population<T>(rand,shared,psize);
}
T donor = p.population.get(rand.nextInt(psize));
for(int step=0;step<10*psize;++step) {
final Set<T> mutations = shared.pv.mutations(donor,rand);
final T d2 = p.population.get(rand.nextInt(psize));
final Set<T> children = shared.pv.breed(donor,d2,rand);
mutations.addAll(children);
+ mutations.add(donor);
boolean record = false;
+ T bestC = null;
+ double bestCscore = 0.0;
final ArrayList<T> goodC = new ArrayList<T>(mutations.size());
for(final T mi: mutations) {
final double scorem = score(mi);
if(scorem>0.0) {
+ if((null==bestC)||(scorem>bestCscore)) {
+ bestC = mi;
+ bestCscore = scorem;
+ }
goodC.add(mi);
if(p.show(mi,scorem)) {
record = true;
donor = mi;
synchronized(shared) {
if(shared.show(mi,scorem)) {
System.out.println("new record: " + p.bestScore + "\t" + p.best + "\t" + new Date());
}
}
}
final int nInserts = nInserts(scorem);
for(int insi=0;insi<nInserts;++insi) {
final int vi = rand.nextInt(psize);
// number of insertions*worseodds < 1 to ensure progress
if((scorem>p.pscore[vi])||(rand.nextDouble()>0.9)) {
p.population.set(vi,mi);
p.pscore[vi] = scorem;
}
}
}
}
+ if((null!=p.best)&&(p.bestScore>0)) {
+ final int vi = rand.nextInt(psize);
+ p.population.set(vi,p.best);
+ p.pscore[vi] = p.bestScore;
+ }
+ if(null!=bestC) {
+ donor = bestC;
+ }
if(step%1000==0) {
if(goodC.size()>0) {
donor = goodC.get(rand.nextInt(goodC.size()));
} else {
donor = p.population.get(rand.nextInt(psize));
}
}
// mix into shared population
if(record||(step%(psize/2))==0) {
swap(p);
}
}
swap(p);
synchronized(shared) {
System.out.println("anneal Runnable " + id + " finish " + new Date());
}
}
}
private AnnealJob1 newJob(final int id, final int psize, final Random rand) {
return new AnnealJob1(id,psize,rand);
}
public static <T extends Comparable<T>> T runAnneal(final AnnealAdapter<T> pv, final Collection<T> starts, final int nparallel) throws InterruptedException {
System.out.println("start anneal");
final Random rand = new Random(235235);
final Population<T> shared = new Population<T>(pv,new Random(rand.nextLong()),500000,new ArrayList<T>(starts));
final RunAnneal<T> ra = new RunAnneal<T>(shared);
final int njobs = 20;
if(nparallel>1) {
final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(njobs+1);
final ThreadPoolExecutor executor = new ThreadPoolExecutor(nparallel,nparallel,100,TimeUnit.SECONDS,queue);
for(int i=0;i<njobs;++i) {
executor.execute(ra.newJob(i,100000,new Random(rand.nextLong())));
}
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE,TimeUnit.SECONDS);
} else {
for(int i=0;i<njobs;++i) {
ra.newJob(i,100000,new Random(rand.nextLong())).run();
}
}
System.out.println("done anneal1");
return shared.best;
}
}
| false | true | public void run() {
final Population<T> p;
synchronized(shared) {
System.out.println("anneal Runnable " + id + " start " + new Date());
p = new Population<T>(rand,shared,psize);
}
T donor = p.population.get(rand.nextInt(psize));
for(int step=0;step<10*psize;++step) {
final Set<T> mutations = shared.pv.mutations(donor,rand);
final T d2 = p.population.get(rand.nextInt(psize));
final Set<T> children = shared.pv.breed(donor,d2,rand);
mutations.addAll(children);
boolean record = false;
final ArrayList<T> goodC = new ArrayList<T>(mutations.size());
for(final T mi: mutations) {
final double scorem = score(mi);
if(scorem>0.0) {
goodC.add(mi);
if(p.show(mi,scorem)) {
record = true;
donor = mi;
synchronized(shared) {
if(shared.show(mi,scorem)) {
System.out.println("new record: " + p.bestScore + "\t" + p.best + "\t" + new Date());
}
}
}
final int nInserts = nInserts(scorem);
for(int insi=0;insi<nInserts;++insi) {
final int vi = rand.nextInt(psize);
// number of insertions*worseodds < 1 to ensure progress
if((scorem>p.pscore[vi])||(rand.nextDouble()>0.9)) {
p.population.set(vi,mi);
p.pscore[vi] = scorem;
}
}
}
}
if(step%1000==0) {
if(goodC.size()>0) {
donor = goodC.get(rand.nextInt(goodC.size()));
} else {
donor = p.population.get(rand.nextInt(psize));
}
}
// mix into shared population
if(record||(step%(psize/2))==0) {
swap(p);
}
}
swap(p);
synchronized(shared) {
System.out.println("anneal Runnable " + id + " finish " + new Date());
}
}
| public void run() {
final Population<T> p;
synchronized(shared) {
System.out.println("anneal Runnable " + id + " start " + new Date());
p = new Population<T>(rand,shared,psize);
}
T donor = p.population.get(rand.nextInt(psize));
for(int step=0;step<10*psize;++step) {
final Set<T> mutations = shared.pv.mutations(donor,rand);
final T d2 = p.population.get(rand.nextInt(psize));
final Set<T> children = shared.pv.breed(donor,d2,rand);
mutations.addAll(children);
mutations.add(donor);
boolean record = false;
T bestC = null;
double bestCscore = 0.0;
final ArrayList<T> goodC = new ArrayList<T>(mutations.size());
for(final T mi: mutations) {
final double scorem = score(mi);
if(scorem>0.0) {
if((null==bestC)||(scorem>bestCscore)) {
bestC = mi;
bestCscore = scorem;
}
goodC.add(mi);
if(p.show(mi,scorem)) {
record = true;
donor = mi;
synchronized(shared) {
if(shared.show(mi,scorem)) {
System.out.println("new record: " + p.bestScore + "\t" + p.best + "\t" + new Date());
}
}
}
final int nInserts = nInserts(scorem);
for(int insi=0;insi<nInserts;++insi) {
final int vi = rand.nextInt(psize);
// number of insertions*worseodds < 1 to ensure progress
if((scorem>p.pscore[vi])||(rand.nextDouble()>0.9)) {
p.population.set(vi,mi);
p.pscore[vi] = scorem;
}
}
}
}
if((null!=p.best)&&(p.bestScore>0)) {
final int vi = rand.nextInt(psize);
p.population.set(vi,p.best);
p.pscore[vi] = p.bestScore;
}
if(null!=bestC) {
donor = bestC;
}
if(step%1000==0) {
if(goodC.size()>0) {
donor = goodC.get(rand.nextInt(goodC.size()));
} else {
donor = p.population.get(rand.nextInt(psize));
}
}
// mix into shared population
if(record||(step%(psize/2))==0) {
swap(p);
}
}
swap(p);
synchronized(shared) {
System.out.println("anneal Runnable " + id + " finish " + new Date());
}
}
|
diff --git a/eclipse/FML-MockMod/src/cpw/mods/mockmod/MockBlock.java b/eclipse/FML-MockMod/src/cpw/mods/mockmod/MockBlock.java
index b6b98f3e..67ae90c4 100644
--- a/eclipse/FML-MockMod/src/cpw/mods/mockmod/MockBlock.java
+++ b/eclipse/FML-MockMod/src/cpw/mods/mockmod/MockBlock.java
@@ -1,12 +1,12 @@
package cpw.mods.mockmod;
import net.minecraft.src.Block;
import net.minecraft.src.Material;
public class MockBlock extends Block
{
public MockBlock(int id)
{
- super(id,Material.field_1316_v);
+ super(id,Material.field_76259_v);
}
}
| true | true | public MockBlock(int id)
{
super(id,Material.field_1316_v);
}
| public MockBlock(int id)
{
super(id,Material.field_76259_v);
}
|
diff --git a/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java b/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
index 232066c..50c2ef9 100644
--- a/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
+++ b/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
@@ -1,1480 +1,1488 @@
/**
* Copyright (C) 2009-2013 enstratius, Inc.
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.dasein.cloud.cloudstack.compute;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.Tag;
import org.dasein.cloud.cloudstack.CSCloud;
import org.dasein.cloud.cloudstack.CSException;
import org.dasein.cloud.cloudstack.CSMethod;
import org.dasein.cloud.cloudstack.CSServiceProvider;
import org.dasein.cloud.cloudstack.CSTopology;
import org.dasein.cloud.cloudstack.CSVersion;
import org.dasein.cloud.cloudstack.Param;
import org.dasein.cloud.cloudstack.network.Network;
import org.dasein.cloud.cloudstack.network.SecurityGroup;
import org.dasein.cloud.compute.*;
import org.dasein.cloud.network.RawAddress;
import org.dasein.cloud.util.APITrace;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.uom.storage.Gigabyte;
import org.dasein.util.uom.storage.Megabyte;
import org.dasein.util.uom.storage.Storage;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.logicblaze.lingo.util.DefaultTimeoutMap;
public class VirtualMachines extends AbstractVMSupport {
static public final Logger logger = Logger.getLogger(VirtualMachines.class);
static private final String DEPLOY_VIRTUAL_MACHINE = "deployVirtualMachine";
static private final String DESTROY_VIRTUAL_MACHINE = "destroyVirtualMachine";
static private final String GET_VIRTUAL_MACHINE_PASSWORD = "getVMPassword";
static private final String LIST_VIRTUAL_MACHINES = "listVirtualMachines";
static private final String LIST_SERVICE_OFFERINGS = "listServiceOfferings";
static private final String REBOOT_VIRTUAL_MACHINE = "rebootVirtualMachine";
static private final String RESET_VIRTUAL_MACHINE_PASSWORD = "resetPasswordForVirtualMachine";
static private final String RESIZE_VIRTUAL_MACHINE = "scaleVirtualMachine";
static private final String START_VIRTUAL_MACHINE = "startVirtualMachine";
static private final String STOP_VIRTUAL_MACHINE = "stopVirtualMachine";
static private Properties cloudMappings;
static private Map<String,Map<String,String>> customNetworkMappings;
static private Map<String,Map<String,Set<String>>> customServiceMappings;
static private DefaultTimeoutMap productCache = new DefaultTimeoutMap();
private CSCloud provider;
public VirtualMachines(CSCloud provider) {
super(provider);
this.provider = provider;
}
@Override
public VirtualMachine alterVirtualMachine(@Nonnull String vmId, @Nonnull VMScalingOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.alterVM");
try {
String productId = options.getProviderProductId();
if (vmId == null || options.getProviderProductId() == null) {
throw new CloudException("No vmid and/or product id set for this operation");
}
CSMethod method = new CSMethod(provider);
VirtualMachine vm = getVirtualMachine(vmId);
if (vm.getProductId().equals(productId)) {
return vm;
}
boolean restart = false;
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
restart = true;
stop(vmId, true);
}
long timeout = System.currentTimeMillis()+(CalendarWrapper.MINUTE*20L);
while (System.currentTimeMillis() < timeout) {
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
try {
Thread.sleep(15000L);
vm = getVirtualMachine(vmId);
}
catch (InterruptedException ignore) {}
}
else {
break;
}
}
vm = getVirtualMachine(vmId);
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
throw new CloudException("Unable to stop vm for scaling");
}
Document doc = method.get(method.buildUrl(RESIZE_VIRTUAL_MACHINE, new Param("id", vmId), new Param("serviceOfferingId", productId)), RESIZE_VIRTUAL_MACHINE);
NodeList matches = doc.getElementsByTagName("scalevirtualmachineresponse");
String jobId = null;
for( int i=0; i<matches.getLength(); i++ ) {
NodeList attrs = matches.item(i).getChildNodes();
for( int j=0; j<attrs.getLength(); j++ ) {
Node node = attrs.item(j);
if (node != null && node.getNodeName().equalsIgnoreCase("jobid") ) {
jobId = node.getFirstChild().getNodeValue();
}
}
}
if( jobId == null ) {
throw new CloudException("Could not scale server");
}
Document responseDoc = provider.waitForJob(doc, "Scale Server");
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("virtualmachine");
if (nodeList.getLength() > 0) {
Node virtualMachine = nodeList.item(0);
vm = toVirtualMachine(virtualMachine);
if( vm != null ) {
if (restart) {
start(vmId);
}
return vm;
}
}
}
if (restart) {
start(vmId);
}
return getVirtualMachine(vmId);
}
finally {
APITrace.end();
}
}
@Nullable
@Override
public VMScalingCapabilities describeVerticalScalingCapabilities() throws CloudException, InternalException {
return VMScalingCapabilities.getInstance(false,true,Requirement.NONE,Requirement.NONE);
}
@Override
public int getCostFactor(@Nonnull VmState state) throws InternalException, CloudException {
return 100;
}
@Override
public int getMaximumVirtualMachineCount() throws CloudException, InternalException {
return -2;
}
@Override
public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getProduct");
try {
for( Architecture architecture : Architecture.values() ) {
for( VirtualMachineProduct product : listProducts(architecture) ) {
if( product.getProviderProductId().equals(productId) ) {
return product;
}
}
}
if( logger.isDebugEnabled() ) {
logger.debug("Unknown product ID for cloud.com: " + productId);
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) {
return "virtual machine";
}
private String getRootPassword(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.getPassword");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(GET_VIRTUAL_MACHINE_PASSWORD, new Param("id", serverId)), GET_VIRTUAL_MACHINE_PASSWORD);
if (doc != null){
NodeList matches = doc.getElementsByTagName("getvmpasswordresponse");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
NodeList attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node attribute = attributes.item(j);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("password") ) {
NodeList nodes = attribute.getChildNodes();
for( int k=0; k<nodes.getLength(); k++ ) {
Node password = nodes.item(k);
name = password.getNodeName().toLowerCase();
if( password.getChildNodes().getLength() > 0 ) {
value = password.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("encryptedpassword") ) {
return value;
}
}
}
}
}
}
}
logger.warn("Unable to find password for vm with id "+serverId);
return null;
}
catch (CSException e) {
if (e.getHttpCode() == 431) {
logger.warn("No password found for vm "+serverId);
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nullable VirtualMachine getVirtualMachine(@Nonnull String serverId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getVirtualMachine");
try {
CSMethod method = new CSMethod(provider);
try {
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("id", serverId)), LIST_VIRTUAL_MACHINES);
NodeList matches = doc.getElementsByTagName("virtualmachine");
if( matches.getLength() < 1 ) {
return null;
}
for( int i=0; i<matches.getLength(); i++ ) {
VirtualMachine s = toVirtualMachine(matches.item(i));
if( s != null && s.getProviderVirtualMachineId().equals(serverId) ) {
return s;
}
}
}
catch( CloudException e ) {
if( e.getMessage().contains("does not exist") ) {
return null;
}
throw e;
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException {
return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.NONE);
}
@Override
public @Nonnull Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.OPTIONAL;
}
@Override
public @Nonnull Requirement identifyStaticIPRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.identifyVlanRequirement");
try {
if( provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) ) {
return Requirement.NONE;
}
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was set for this request");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new CloudException("No region was set for this request");
}
return (provider.getDataCenterServices().requiresNetwork(regionId) ? Requirement.REQUIRED : Requirement.OPTIONAL);
}
return Requirement.OPTIONAL;
}
finally {
APITrace.end();
}
}
@Override
public boolean isAPITerminationPreventable() throws CloudException, InternalException {
return false;
}
@Override
public boolean isBasicAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.isSubscribed");
try {
CSMethod method = new CSMethod(provider);
try {
method.get(method.buildUrl(CSTopology.LIST_ZONES, new Param("available", "true")), CSTopology.LIST_ZONES);
return true;
}
catch( CSException e ) {
int code = e.getHttpCode();
if( code == HttpServletResponse.SC_FORBIDDEN || code == 401 || code == 531 ) {
return false;
}
throw e;
}
catch( CloudException e ) {
int code = e.getHttpCode();
if( code == HttpServletResponse.SC_FORBIDDEN || code == HttpServletResponse.SC_UNAUTHORIZED ) {
return false;
}
throw e;
}
}
finally {
APITrace.end();
}
}
@Override
public boolean isUserDataSupported() throws CloudException, InternalException {
return true;
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.launch");
try {
String id = withLaunchOptions.getStandardProductId();
VirtualMachineProduct product = getProduct(id);
if( product == null ) {
throw new CloudException("Invalid product ID: " + id);
}
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
return launch22(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName(), withLaunchOptions.getBootstrapKey(), withLaunchOptions.getVlanId(), withLaunchOptions.getFirewallIds(), withLaunchOptions.getUserData());
}
else {
return launch21(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName());
}
}
finally {
APITrace.end();
}
}
@Override
@Deprecated
@SuppressWarnings("deprecation")
public @Nonnull VirtualMachine launch(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nonnull String inZoneId, @Nonnull String name, @Nonnull String description, @Nullable String usingKey, @Nullable String withVlanId, boolean withMonitoring, boolean asSandbox, @Nullable String[] protectedByFirewalls, @Nullable Tag ... tags) throws InternalException, CloudException {
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
StringBuilder userData = new StringBuilder();
if( tags != null && tags.length > 0 ) {
for( Tag tag : tags ) {
userData.append(tag.getKey());
userData.append("=");
userData.append(tag.getValue());
userData.append("\n");
}
}
else {
userData.append("created=Dasein Cloud\n");
}
return launch22(imageId, product, inZoneId, name, usingKey, withVlanId, protectedByFirewalls, userData.toString());
}
else {
return launch21(imageId, product, inZoneId, name);
}
}
private VirtualMachine launch21(String imageId, VirtualMachineProduct product, String inZoneId, String name) throws InternalException, CloudException {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, new Param("zoneId", getContext().getRegionId()), new Param("serviceOfferingId", product.getProviderProductId()), new Param("templateId", imageId), new Param("displayName", name) ), DEPLOY_VIRTUAL_MACHINE));
}
private void load() {
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/cloudMappings.cfg");
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
Properties properties = new Properties();
String line;
while( (line = reader.readLine()) != null ) {
if( line.startsWith("#") ) {
continue;
}
int idx = line.indexOf('=');
if( idx < 0 || line.endsWith("=") ) {
continue;
}
String cloudUrl = line.substring(0, idx);
String cloudId = line.substring(idx+1);
properties.put(cloudUrl, cloudId);
}
cloudMappings = properties;
}
catch( Throwable ignore ) {
// ignore
}
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/customNetworkMappings.cfg");
HashMap<String,Map<String,String>> mapping = new HashMap<String,Map<String,String>>();
Properties properties = new Properties();
properties.load(input);
for( Object key : properties.keySet() ) {
String[] trueKey = ((String)key).split(",");
Map<String,String> current = mapping.get(trueKey[0]);
if( current == null ) {
current = new HashMap<String,String>();
mapping.put(trueKey[0], current);
}
current.put(trueKey[1], (String)properties.get(key));
}
customNetworkMappings = mapping;
}
catch( Throwable ignore ) {
// ignore
}
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/customServiceMappings.cfg");
HashMap<String,Map<String,Set<String>>> mapping = new HashMap<String,Map<String,Set<String>>>();
Properties properties = new Properties();
properties.load(input);
for( Object key : properties.keySet() ) {
String value = (String)properties.get(key);
if( value != null ) {
String[] trueKey = ((String)key).split(",");
Map<String,Set<String>> tmp = mapping.get(trueKey[0]);
if( tmp == null ) {
tmp =new HashMap<String,Set<String>>();
mapping.put(trueKey[0], tmp);
}
TreeSet<String> m = new TreeSet<String>();
String[] offerings = value.split(",");
if( offerings == null || offerings.length < 1 ) {
m.add(value);
}
else {
Collections.addAll(m, offerings);
}
tmp.put(trueKey[1], m);
}
}
customServiceMappings = mapping;
}
catch( Throwable ignore ) {
// ignore
}
}
private @Nonnull VirtualMachine launch22(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nullable String inZoneId, @Nonnull String name, @Nullable String withKeypair, @Nullable String targetVlanId, @Nullable String[] protectedByFirewalls, @Nullable String userData) throws InternalException, CloudException {
ProviderContext ctx = provider.getContext();
List<String> vlans = null;
if( ctx == null ) {
throw new InternalException("No context was provided for this request");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new InternalException("No region is established for this request");
}
String prdId = product.getProviderProductId();
if( customNetworkMappings == null ) {
load();
}
if( customNetworkMappings != null ) {
String cloudId = cloudMappings.getProperty(ctx.getEndpoint());
if( cloudId != null ) {
Map<String,String> map = customNetworkMappings.get(cloudId);
if( map != null ) {
String id = map.get(prdId);
if( id != null ) {
targetVlanId = id;
}
}
}
}
if( targetVlanId != null && targetVlanId.length() < 1 ) {
targetVlanId = null;
}
if( userData == null ) {
userData = "";
}
String securityGroupIds = null;
Param[] params;
if( protectedByFirewalls != null && protectedByFirewalls.length > 0 ) {
StringBuilder str = new StringBuilder();
int idx = 0;
for( String fw : protectedByFirewalls ) {
fw = fw.trim();
if( !fw.equals("") ) {
str.append(fw);
if( (idx++) < protectedByFirewalls.length-1 ) {
str.append(",");
}
}
}
securityGroupIds = str.toString();
}
int count = 4;
if( userData != null && userData.length() > 0 ) {
count++;
}
if( withKeypair != null ) {
count++;
}
if( targetVlanId == null ) {
Network vlan = provider.getNetworkServices().getVlanSupport();
if( vlan != null && vlan.isSubscribed() ) {
if( provider.getDataCenterServices().requiresNetwork(regionId) ) {
vlans = vlan.findFreeNetworks();
}
}
}
else {
vlans = new ArrayList<String>();
vlans.add(targetVlanId);
}
if( vlans != null && vlans.size() > 0 ) {
count++;
}
if( securityGroupIds != null && securityGroupIds.length() > 0 ) {
if( !provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) && !provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) {
securityGroupIds = null;
}
else {
count++;
}
}
else if( provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) {
/*
String sgId = null;
if( withVlanId == null ) {
Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list();
for( Firewall fw : firewalls ) {
if( fw.getName().equalsIgnoreCase("default") && fw.getProviderVlanId() == null ) {
sgId = fw.getProviderFirewallId();
break;
}
}
if( sgId == null ) {
try {
sgId = provider.getNetworkServices().getFirewallSupport().create("default", "Default security group");
}
catch( Throwable t ) {
logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage());
}
}
if( sgId != null ) {
securityGroupIds = sgId;
}
}
else {
Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list();
for( Firewall fw : firewalls ) {
if( (fw.getName().equalsIgnoreCase("default") || fw.getName().equalsIgnoreCase("default-" + withVlanId)) && withVlanId.equals(fw.getProviderVlanId()) ) {
sgId = fw.getProviderFirewallId();
break;
}
}
if( sgId == null ) {
try {
sgId = provider.getNetworkServices().getFirewallSupport().createInVLAN("default-" + withVlanId, "Default " + withVlanId + " security group", withVlanId);
}
catch( Throwable t ) {
logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage());
}
}
}
if( sgId != null ) {
securityGroupIds = sgId;
count++;
}
*/
}
params = new Param[count];
params[0] = new Param("zoneId", getContext().getRegionId());
params[1] = new Param("serviceOfferingId", prdId);
params[2] = new Param("templateId", imageId);
params[3] = new Param("displayName", name);
int i = 4;
if( userData != null && userData.length() > 0 ) {
try {
params[i++] = new Param("userdata", new String(Base64.encodeBase64(userData.getBytes("utf-8")), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
e.printStackTrace();
}
}
if( withKeypair != null ) {
params[i++] = new Param("keypair", withKeypair);
}
if( securityGroupIds != null && securityGroupIds.length() > 0 ) {
params[i++] = new Param("securitygroupids", securityGroupIds);
}
if( vlans != null && vlans.size() > 0 ) {
CloudException lastError = null;
for( String withVlanId : vlans ) {
params[i] = new Param("networkIds", withVlanId);
try {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE));
}
catch( CloudException e ) {
if( e.getMessage().contains("sufficient address capacity") ) {
lastError = e;
continue;
}
throw e;
}
}
if( lastError == null ) {
throw lastError;
}
throw new CloudException("Unable to identify a network into which a VM can be launched");
}
else {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE));
}
}
private @Nonnull VirtualMachine launch(@Nonnull Document doc) throws InternalException, CloudException {
NodeList matches = doc.getElementsByTagName("deployvirtualmachineresponse");
String serverId = null;
String jobId = null;
for( int i=0; i<matches.getLength(); i++ ) {
NodeList attrs = matches.item(i).getChildNodes();
for( int j=0; j<attrs.getLength(); j++ ) {
Node node = attrs.item(j);
if( node != null && (node.getNodeName().equalsIgnoreCase("virtualmachineid") || node.getNodeName().equalsIgnoreCase("id")) ) {
serverId = node.getFirstChild().getNodeValue();
break;
}
else if (node != null && node.getNodeName().equalsIgnoreCase("jobid") ) {
jobId = node.getFirstChild().getNodeValue();
}
}
if( serverId != null ) {
break;
}
}
if( serverId == null && jobId == null ) {
throw new CloudException("Could not launch server");
}
// TODO: very odd logic below; figure out what it thinks it is doing
VirtualMachine vm = null;
// have to wait on jobs as sometimes they fail and we need to bubble error message up
Document responseDoc = provider.waitForJob(doc, "Launch Server");
//parse vm from job completion response to capture vm passwords on initial launch.
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("virtualmachine");
if (nodeList.getLength() > 0) {
Node virtualMachine = nodeList.item(0);
vm = toVirtualMachine(virtualMachine);
if( vm != null ) {
return vm;
}
}
}
if (vm == null){
vm = getVirtualMachine(serverId);
}
if( vm == null ) {
throw new CloudException("No virtual machine provided: " + serverId);
}
return vm;
}
@Override
public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listFirewalls");
try {
SecurityGroup support = provider.getNetworkServices().getFirewallSupport();
if( support == null ) {
return Collections.emptyList();
}
return support.listFirewallsForVM(vmId);
}
finally {
APITrace.end();
}
}
private void setFirewalls(@Nonnull VirtualMachine vm) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.setFirewalls");
try {
SecurityGroup support = provider.getNetworkServices().getFirewallSupport();
if( support == null ) {
return;
}
ArrayList<String> ids = new ArrayList<String>();
Iterable<String> firewalls;
try {
firewalls = support.listFirewallsForVM(vm.getProviderVirtualMachineId());
} catch (Throwable t) {
logger.error("Problem listing firewalls (listSecurityGroups) for '" + vm.getProviderVirtualMachineId() + "': " + t.getMessage());
return;
}
for( String id : firewalls ) {
ids.add(id);
}
vm.setProviderFirewallIds(ids.toArray(new String[ids.size()]));
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listProducts");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was configured for this request");
}
Map<Architecture,Collection<VirtualMachineProduct>> cached;
String endpoint = provider.getContext().getEndpoint();
String accountId = provider.getContext().getAccountNumber();
String regionId = provider.getContext().getRegionId();
productCache.purge();
cached = (HashMap<Architecture, Collection<VirtualMachineProduct>>) productCache.get(endpoint+"_"+accountId+"_"+regionId);
if (cached != null && !cached.isEmpty()) {
if( cached.containsKey(architecture) ) {
Collection<VirtualMachineProduct> products = cached.get(architecture);
if( products != null ) {
return products;
}
}
}
else {
cached = new HashMap<Architecture, Collection<VirtualMachineProduct>>();
productCache.put(endpoint+"_"+accountId+"_"+regionId, cached, CalendarWrapper.HOUR * 4);
}
List<VirtualMachineProduct> products;
Set<String> mapping = null;
if( customServiceMappings == null ) {
load();
}
if( customServiceMappings != null ) {
String cloudId = cloudMappings.getProperty(provider.getContext().getEndpoint());
if( cloudId != null ) {
Map<String,Set<String>> map = customServiceMappings.get(cloudId);
if( map != null ) {
mapping = map.get(provider.getContext().getRegionId());
}
}
}
products = new ArrayList<VirtualMachineProduct>();
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_SERVICE_OFFERINGS, new Param("zoneId", ctx.getRegionId())), LIST_SERVICE_OFFERINGS);
NodeList matches = doc.getElementsByTagName("serviceoffering");
for( int i=0; i<matches.getLength(); i++ ) {
String id = null, name = null;
Node node = matches.item(i);
NodeList attributes;
int memory = 0;
int cpu = 0;
attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node n = attributes.item(j);
String value;
if( n.getChildNodes().getLength() > 0 ) {
value = n.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( n.getNodeName().equals("id") ) {
id = value;
}
else if( n.getNodeName().equals("name") ) {
name = value;
}
else if( n.getNodeName().equals("cpunumber") ) {
cpu = Integer.parseInt(value);
}
else if( n.getNodeName().equals("memory") ) {
memory = Integer.parseInt(value);
}
if( id != null && name != null && cpu > 0 && memory > 0 ) {
break;
}
}
if( id != null ) {
if( mapping == null || mapping.contains(id) ) {
VirtualMachineProduct product;
product = new VirtualMachineProduct();
product.setProviderProductId(id);
product.setName(name + " (" + cpu + " CPU/" + memory + "MB RAM)");
product.setDescription(name + " (" + cpu + " CPU/" + memory + "MB RAM)");
product.setRamSize(new Storage<Megabyte>(memory, Storage.MEGABYTE));
product.setCpuCount(cpu);
product.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
products.add(product);
}
}
}
cached.put(architecture, products);
return products;
}
finally {
APITrace.end();
}
}
private transient Collection<Architecture> architectures;
@Override
public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException {
if( architectures == null ) {
ArrayList<Architecture> a = new ArrayList<Architecture>();
a.add(Architecture.I32);
a.add(Architecture.I64);
architectures = Collections.unmodifiableList(a);
}
return architectures;
}
@Override
public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachineStatus");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES);
ArrayList<ResourceStatus> servers = new ArrayList<ResourceStatus>();
NodeList matches = doc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
ResourceStatus vm = toStatus(node);
if( vm != null ) {
servers.add(vm);
}
}
}
return servers;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachines");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES);
ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>();
NodeList matches = doc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
try {
VirtualMachine vm = toVirtualMachine(node);
if( vm != null ) {
servers.add(vm);
}
} catch (Throwable t) {
logger.error("Problem discovering a virtual machine: " + t.getMessage());
}
}
}
return servers;
}
finally {
APITrace.end();
}
}
private String resetPassword(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.resetPassword");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(RESET_VIRTUAL_MACHINE_PASSWORD, new Param("id", serverId)), RESET_VIRTUAL_MACHINE_PASSWORD);
Document responseDoc = provider.waitForJob(doc, "reset vm password");
if (responseDoc != null){
NodeList matches = responseDoc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
NodeList attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node attribute = attributes.item(j);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("password") ) {
return value;
}
}
}
}
}
logger.warn("Unable to find password for vm with id "+serverId);
return null;
}
finally {
APITrace.end();
}
}
@Override
public void reboot(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.reboot");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(REBOOT_VIRTUAL_MACHINE, new Param("id", serverId)), REBOOT_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public void start(@Nonnull String serverId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.start");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(START_VIRTUAL_MACHINE, new Param("id", serverId)), START_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.stop");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(STOP_VIRTUAL_MACHINE, new Param("id", vmId), new Param("forced", String.valueOf(force))), STOP_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public boolean supportsStartStop(@Nonnull VirtualMachine vm) {
return true;
}
@Override
public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public void terminate(@Nonnull String serverId, @Nullable String explanation) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.terminate");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(DESTROY_VIRTUAL_MACHINE, new Param("id", serverId)), DESTROY_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
private @Nullable ResourceStatus toStatus(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
NodeList attributes = node.getChildNodes();
VmState state = null;
String serverId = null;
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
serverId = value;
}
else if( name.equals("state") ) {
if( value == null ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
}
if( serverId != null && state != null ) {
break;
}
}
if( serverId == null ) {
return null;
}
if( state == null ) {
state = VmState.PENDING;
}
return new ResourceStatus(serverId, state);
}
private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setTags(properties);
- server.setArchitecture(Architecture.I64);
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN)){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
server.setPlatform(image.getPlatform());
}
}
}
+ if (server.getArchitecture() == null) {
+ Templates support = provider.getComputeServices().getImageSupport();
+ if (support != null){
+ MachineImage image =support.getImage(server.getProviderMachineImageId());
+ if (image != null){
+ server.setArchitecture(image.getArchitecture());
+ }
+ }
+ }
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
return server;
}
private Platform guessForWindows(String name){
if (name == null){
return Platform.UNKNOWN;
}
String platform = name.toLowerCase();
if (platform.contains("windows") || platform.contains("win") ){
return Platform.WINDOWS;
}
return Platform.UNKNOWN;
}
}
| false | true | private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setTags(properties);
server.setArchitecture(Architecture.I64);
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN)){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
server.setPlatform(image.getPlatform());
}
}
}
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
return server;
}
| private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setTags(properties);
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN)){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
server.setPlatform(image.getPlatform());
}
}
}
if (server.getArchitecture() == null) {
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
server.setArchitecture(image.getArchitecture());
}
}
}
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
return server;
}
|
diff --git a/src/main/java/util/Config.java b/src/main/java/util/Config.java
index 1354e51..967df79 100644
--- a/src/main/java/util/Config.java
+++ b/src/main/java/util/Config.java
@@ -1,46 +1,46 @@
package util;
import java.util.Properties;
import java.io.InputStream;
public class Config {
public static String get(String key)
{
return getInstance().getConfig(key);
}
private String getConfig(String key)
{
String value = properties.getProperty(key);
if (value == null) {
System.err.println("could not find property '" + key + "'.");
}
return value;
}
private static Config instance = null;
private Properties properties;
private static synchronized Config getInstance()
{
if (instance == null) {
instance = new Config();
}
return instance;
}
private Config() {
properties = new Properties();
try {
- InputStream is = ClassLoader.getSystemResourceAsStream("reversi.properties");
+ InputStream is = this.getClass().getClassLoader().getResourceAsStream("reversi.properties");
if (is == null) {
System.err.println("Could not find reversi.properties in classpath");
} else {
properties.load(is);
}
} catch (java.io.IOException e) {
System.err.println("Failed to load Reversi properties: " + e.getMessage());
}
}
}
| true | true | private Config() {
properties = new Properties();
try {
InputStream is = ClassLoader.getSystemResourceAsStream("reversi.properties");
if (is == null) {
System.err.println("Could not find reversi.properties in classpath");
} else {
properties.load(is);
}
} catch (java.io.IOException e) {
System.err.println("Failed to load Reversi properties: " + e.getMessage());
}
}
| private Config() {
properties = new Properties();
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("reversi.properties");
if (is == null) {
System.err.println("Could not find reversi.properties in classpath");
} else {
properties.load(is);
}
} catch (java.io.IOException e) {
System.err.println("Failed to load Reversi properties: " + e.getMessage());
}
}
|
diff --git a/src/me/sheimi/util/SeqImage.java b/src/me/sheimi/util/SeqImage.java
index e0cb374..e7964cd 100644
--- a/src/me/sheimi/util/SeqImage.java
+++ b/src/me/sheimi/util/SeqImage.java
@@ -1,54 +1,54 @@
/* SeqImage.java - Encode and Decode Image which stored in
* Seq file,
* 10 bytes to store the size + image size
*
* Copyright (C) 2012 Reason Zhang
*/
package me.sheimi.util;
import java.util.Arrays;
import java.io.*;
public class SeqImage {
private byte[] image;
private byte[] encoded;
public static final int SIZE_LEN = 10;
public static final String SIZE_FORMATER = "%10d";
public SeqImage(byte[] image) {
this.image = image;
}
public SeqImage(InputStream is, int size) throws IOException {
image = new byte[size];
is.read(image);
}
public int getSize() {
return image.length;
}
public byte[] getImage() {
return image;
}
public byte[] encode() {
if (encoded == null) {
byte[] size = String.format(SIZE_FORMATER, image.length).getBytes();
byte[] encoded = new byte[SIZE_LEN + image.length];
System.arraycopy(size, 0, encoded, 0, size.length);
- System.arraycopy(image, 0, encoded, size.length, encoded.length);
+ System.arraycopy(image, 0, encoded, size.length, image.length);
}
return encoded;
}
public static SeqImage decode(byte[] src) {
byte[] len = Arrays.copyOfRange(src, 0, SIZE_LEN);
int size = Integer.parseInt(new String(len));
byte[] image = Arrays.copyOfRange(src, SIZE_LEN, SIZE_LEN + size);
return new SeqImage(image);
}
}
| true | true | public byte[] encode() {
if (encoded == null) {
byte[] size = String.format(SIZE_FORMATER, image.length).getBytes();
byte[] encoded = new byte[SIZE_LEN + image.length];
System.arraycopy(size, 0, encoded, 0, size.length);
System.arraycopy(image, 0, encoded, size.length, encoded.length);
}
return encoded;
}
| public byte[] encode() {
if (encoded == null) {
byte[] size = String.format(SIZE_FORMATER, image.length).getBytes();
byte[] encoded = new byte[SIZE_LEN + image.length];
System.arraycopy(size, 0, encoded, 0, size.length);
System.arraycopy(image, 0, encoded, size.length, image.length);
}
return encoded;
}
|
diff --git a/test/regression/src/org/jacorb/test/bugs/bugjac486/BugJac486Test.java b/test/regression/src/org/jacorb/test/bugs/bugjac486/BugJac486Test.java
index 6256dd50f..2fec82477 100644
--- a/test/regression/src/org/jacorb/test/bugs/bugjac486/BugJac486Test.java
+++ b/test/regression/src/org/jacorb/test/bugs/bugjac486/BugJac486Test.java
@@ -1,111 +1,111 @@
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2012 Gerald Brose / The JacORB Team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.jacorb.test.bugs.bugjac486;
import java.util.Properties;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.jacorb.orb.iiop.IIOPProfile;
import org.jacorb.test.BasicServer;
import org.jacorb.test.BasicServerHelper;
import org.jacorb.test.common.ClientServerSetup;
import org.jacorb.test.common.ClientServerTestCase;
import org.jacorb.test.common.CommonSetup;
import org.jacorb.test.common.TestUtils;
import org.jacorb.test.orb.BasicServerImpl;
/**
* @author Alphonse Bendt
*/
public class BugJac486Test extends ClientServerTestCase
{
private static final String objectKey = "/BugJac486Test/BugJac486POA/BugJac486ID";
private static final String sslPort = "48120";
public BugJac486Test(String name, ClientServerSetup setup)
{
super(name, setup);
}
public void testSSLIOPCorbalocRequiresGIOP12_1() throws Exception
{
try
{
IIOPProfile profile = new IIOPProfile("corbaloc:ssliop:localhost:" + sslPort + objectKey);
profile.configure(((org.jacorb.orb.ORB)setup.getClientOrb()).getConfiguration());
fail();
}
catch(IllegalArgumentException e)
{
}
}
public void testAccessSecureAcceptorWithoutSSLShouldFail() throws Exception
{
try
{
runTest("corbaloc::1.2@localhost:" + sslPort + objectKey);
fail();
}
catch(Exception e)
{
}
}
public void testAccessSSLWithJacorbSpecificExtension() throws Exception
{
runTest("corbaloc:ssliop:1.2@localhost:" + sslPort + objectKey);
}
private void runTest(String corbaLoc)
{
org.omg.CORBA.Object object = setup.getClientOrb().string_to_object(corbaLoc);
BasicServer server = BasicServerHelper.narrow(object);
assertEquals("BugJac486Test", server.bounce_string("BugJac486Test"));
}
public static Test suite()
{
Properties clientProps = new Properties();
Properties serverProps = new Properties();
clientProps.setProperty("jacorb.test.ssl", "true");
serverProps.setProperty("jacorb.test.ssl", "true");
serverProps.setProperty("jacorb.test.corbaloc.enable", "true");
serverProps.setProperty("jacorb.test.corbaloc.sslport", sslPort);
serverProps.setProperty("jacorb.test.corbaloc.implname", "BugJac486Test");
serverProps.setProperty("jacorb.test.corbaloc.poaname", "BugJac486POA");
serverProps.setProperty("jacorb.test.corbaloc.objectid", "BugJac486ID");
clientProps.setProperty(CommonSetup.JACORB_REGRESSION_DISABLE_IMR, "true");
serverProps.setProperty(CommonSetup.JACORB_REGRESSION_DISABLE_IMR, "true");
- clientProps.setProperty("jacorb.delegate.disconnect_after_systemexception", "false");
+ clientProps.setProperty("jacorb.delegate.disconnect_after_systemexception", "true");
TestSuite suite = new TestSuite(BugJac486Test.class.getName());
ClientServerSetup setup = new ClientServerSetup(suite, BasicServerImpl.class.getName(), clientProps, serverProps);
TestUtils.addToSuite(suite, setup, BugJac486Test.class);
return setup;
}
}
| true | true | public static Test suite()
{
Properties clientProps = new Properties();
Properties serverProps = new Properties();
clientProps.setProperty("jacorb.test.ssl", "true");
serverProps.setProperty("jacorb.test.ssl", "true");
serverProps.setProperty("jacorb.test.corbaloc.enable", "true");
serverProps.setProperty("jacorb.test.corbaloc.sslport", sslPort);
serverProps.setProperty("jacorb.test.corbaloc.implname", "BugJac486Test");
serverProps.setProperty("jacorb.test.corbaloc.poaname", "BugJac486POA");
serverProps.setProperty("jacorb.test.corbaloc.objectid", "BugJac486ID");
clientProps.setProperty(CommonSetup.JACORB_REGRESSION_DISABLE_IMR, "true");
serverProps.setProperty(CommonSetup.JACORB_REGRESSION_DISABLE_IMR, "true");
clientProps.setProperty("jacorb.delegate.disconnect_after_systemexception", "false");
TestSuite suite = new TestSuite(BugJac486Test.class.getName());
ClientServerSetup setup = new ClientServerSetup(suite, BasicServerImpl.class.getName(), clientProps, serverProps);
TestUtils.addToSuite(suite, setup, BugJac486Test.class);
return setup;
}
| public static Test suite()
{
Properties clientProps = new Properties();
Properties serverProps = new Properties();
clientProps.setProperty("jacorb.test.ssl", "true");
serverProps.setProperty("jacorb.test.ssl", "true");
serverProps.setProperty("jacorb.test.corbaloc.enable", "true");
serverProps.setProperty("jacorb.test.corbaloc.sslport", sslPort);
serverProps.setProperty("jacorb.test.corbaloc.implname", "BugJac486Test");
serverProps.setProperty("jacorb.test.corbaloc.poaname", "BugJac486POA");
serverProps.setProperty("jacorb.test.corbaloc.objectid", "BugJac486ID");
clientProps.setProperty(CommonSetup.JACORB_REGRESSION_DISABLE_IMR, "true");
serverProps.setProperty(CommonSetup.JACORB_REGRESSION_DISABLE_IMR, "true");
clientProps.setProperty("jacorb.delegate.disconnect_after_systemexception", "true");
TestSuite suite = new TestSuite(BugJac486Test.class.getName());
ClientServerSetup setup = new ClientServerSetup(suite, BasicServerImpl.class.getName(), clientProps, serverProps);
TestUtils.addToSuite(suite, setup, BugJac486Test.class);
return setup;
}
|
diff --git a/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java b/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java
index 716e70b..77a160b 100644
--- a/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java
+++ b/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java
@@ -1,656 +1,656 @@
package org.makumba.parade.access;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.LogRecord;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.makumba.aether.AetherEvent;
import org.makumba.parade.aether.ActionTypes;
import org.makumba.parade.aether.ObjectTypes;
import org.makumba.parade.init.InitServlet;
import org.makumba.parade.init.RowProperties;
import org.makumba.parade.model.ActionLog;
import org.makumba.parade.model.File;
import org.makumba.parade.model.Log;
import org.makumba.parade.model.User;
import org.makumba.parade.tools.PerThreadPrintStreamLogRecord;
import org.makumba.parade.tools.TriggerFilter;
import org.makumba.parade.view.TickerTapeData;
import org.makumba.parade.view.TickerTapeServlet;
/**
* This servlet makes it possible to log events from various sources into the database. It persists two kinds of logs:
* <ul>
* <li>ActionLogs, generated at each access</li>
* <li>Logs, which are representing one log "line" and link to the ActionLog which led to their generation</li>
* </ul>
*
* TODO improve filtering
*
* @author Manuel Gay
*
*/
public class DatabaseLogServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private Logger logger = Logger.getLogger(DatabaseLogServlet.class);
private RowProperties rp;
private ActionLogDTO lastCommit;
private String lastCommitId;
public void init(ServletConfig conf) {
rp = new RowProperties();
}
public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
// when we start tomcat we are not ready yet to log
// we first need a Hibernate SessionFactory to be initalised
// this happens only after the Initservlet was loaded
req.removeAttribute("org.makumba.parade.servletSuccess");
if (InitServlet.getSessionFactory() == null)
return;
req.setAttribute("org.makumba.parade.servletSuccess", true);
// retrieve the record guy
Object record = req.getAttribute("org.makumba.parade.servletParam");
if (record == null)
return;
// first check if this should be logged at all
if (record instanceof ActionLogDTO) {
if (!shouldLog((ActionLogDTO) record))
return;
}
// open a new session, which we need to perform extraction
Session s = null;
try {
s = InitServlet.getSessionFactory().openSession();
if (record instanceof ActionLogDTO) {
handleActionLog(req, record, s);
} else {
handleLog(req, record, s);
}
// now we pass the event to Aether
if (record instanceof ActionLogDTO && InitServlet.aetherEnabled) {
ActionLogDTO a = (ActionLogDTO) record;
if (!a.getAction().equals(ActionTypes.LOGIN.action())) {
AetherEvent e = buildAetherEventFromLog(a, s);
if (e != null) {
InitServlet.getAether().registerEvent(e);
}
}
}
} finally {
// close the session in any case
s.close();
}
} catch (NullPointerException npe) {
// throw(npe);
StringWriter sw = new StringWriter();
PrintWriter p = new PrintWriter(sw);
npe.printStackTrace(p);
sw.flush();
logger.error("\n***********************************************************************\n"
+ "NPE in database log servlet. please tell developers!\n" + "error message is:\n" + sw.toString()
+ "***********************************************************************");
}
}
private AetherEvent buildAetherEventFromLog(ActionLogDTO log, Session s) {
if (log.getObjectType() == null) {
logger.error("**********************************\n" + "Object type for ActionLog not set: "
+ log.toString());
return null;
}
Double initialLevelCoefficient = 1.0;
String objectURL = log.getObjectType().prefix();
switch (log.getObjectType()) {
case ROW:
objectURL += log.getParadecontext();
break;
case USER:
objectURL += log.getUser();
break;
case FILE:
objectURL += log.getParadecontext() + log.getFile();
Transaction tx = s.beginTransaction();
String rowName = log.getParadecontext() == null ? log.getContext() : log.getParadecontext();
if (rowName == null)
rowName = "";
File f = (File) s
.createQuery(
"select f as file from File f join f.row r where substring(f.path, 1 + length(r.rowpath) + length(r.webappPath) + case when length(r.webappPath) = 0 then 0 else 1 end, length(f.path)) = :path and r.rowname = :rowname")
.setString("path", log.getFile()).setString("rowname", rowName).uniqueResult();
if (f != null) {
initialLevelCoefficient = new Double(Math.abs(f.getPreviousLines() - f.getCurrentLines()) / f.getCurrentLines());
}
tx.commit();
break;
case DIR:
objectURL += log.getParadecontext() + log.getFile();
break;
case CVSFILE:
objectURL += log.getParadecontext() + log.getFile();
break;
}
return new AetherEvent(objectURL, log.getObjectType().toString(), log.getUser(), log.getAction(), log
.getDate(), initialLevelCoefficient);
}
private void handleActionLog(HttpServletRequest req, Object record, Session s) {
ActionLogDTO log = (ActionLogDTO) record;
// filter the log, generate additional information and give some meaning
filterLog(log, s);
// sometimes we just don't log (like for commits)
if (log.getAction().equals("paradeCvsCommit"))
return;
// let's see if we have already someone. if not, we create one
Transaction tx = s.beginTransaction();
ActionLog actionLog = null;
if (log.getId() == null) {
actionLog = new ActionLog();
} else {
actionLog = (ActionLog) s.get(ActionLog.class, log.getId());
}
log.populate(actionLog);
s.saveOrUpdate(actionLog);
tx.commit();
// if we didn't have a brand new actionLog (meaning, a log with some info)
// we add the populated actionLog as an event to the tickertape
// TODO refactor me
if (log.getId() != null) {
String row = (log.getParadecontext() == null || log.getParadecontext().equals("null")) ? ((log.getContext() == null || log
.getContext().equals("null")) ? "parade2" : log.getContext())
: log.getParadecontext();
String actionText = "";
if (log.getAction() != null && !log.getAction().equals("null"))
actionText = "user " + log.getUser() + " in row " + row + " did action: " + log.getAction();
TickerTapeData data = new TickerTapeData(actionText, "", log.getDate().toString());
TickerTapeServlet.addItem(data);
}
// finally we also need to update the ActionLog in the thread
log.setId(actionLog.getId());
TriggerFilter.actionLog.set(log);
}
/**
* Filter that does some "cosmetics" on the log and gives it meaning
*
* @param log
* the original log to be altered
*/
private void filterLog(ActionLogDTO log, Session s) {
String queryString = log.getQueryString();
String uri = log.getUrl();
if (uri == null)
uri = "";
if (queryString == null)
queryString = "";
if (log.getAction() == null)
log.setAction("");
if (log.getParadecontext() == null) {
log.setParadecontext(getParam("context", queryString));
}
if (log.getParadecontext() == null) {
log.setParadecontext(log.getContext());
}
String webapp = "";
// fetch the webapp root in a hackish way
String ctx = log.getParadecontext() == null ? log.getContext() : log.getParadecontext();
if (ctx != null) {
Map<String, String> rowDef = rp.getRowDefinitions().get(ctx);
if (rowDef != null) {
webapp = rowDef.get("webapp");
} else {
logger.warn("Null context for actionLogDTO " + log.toString());
}
}
String actionType = "", op = "", params = "", display = "", path = "", file = "";
if (uri.indexOf("browse.jsp") > -1)
actionType = "browseRow";
if (uri.indexOf("/servlet/browse") > -1)
actionType = "browse";
if (uri.indexOf("File.do") > -1)
actionType = "file";
if (uri.indexOf("File.do") > -1 && queryString.indexOf("browse&") > -1)
actionType = "fileBrowse";
if (uri.indexOf("Cvs.do") > -1)
actionType = "cvs";
if (uri.indexOf("Webapp.do") > -1)
actionType = "webapp";
op = getParam("op", queryString);
params = getParam("params", queryString);
display = getParam("display", queryString);
path = getParam("path", queryString);
file = getParam("file", queryString);
if (op == null)
op = "";
if (params == null)
params = "";
if (display == null)
display = "";
if (path == null)
path = "";
if (file == null)
file = "";
// browse actions
if (actionType.equals("browseRow")) {
log.setAction(ActionTypes.VIEW.action());
log.setObjectType(ObjectTypes.ROW);
}
if (actionType.equals("browse") || actionType.equals("fileBrowse")) {
log.setAction(ActionTypes.VIEW.action());
log.setFile(nicePath(path, "", ""));
log.setObjectType(ObjectTypes.DIR);
}
// view actions
if (uri.endsWith(".jspx")) {
log.setAction(ActionTypes.VIEW.action());
if (webapp.length() > 0) {
log.setFile("/" + webapp + uri.substring(0, uri.length() - 1));
log.setObjectType(ObjectTypes.FILE);
}
}
// execute actions
if (uri.endsWith(".jsp")) {
log.setAction(ActionTypes.EXECUTE.action());
if (webapp.length() > 0) {
- log.setFile("/" + webapp + uri.substring(0, uri.length() - 1));
+ log.setFile("/" + webapp + uri.substring(0, uri.length()));
log.setObjectType(ObjectTypes.FILE);
}
}
// edit (open editor)
if (actionType.equals("file") && op.equals("editFile")) {
log.setAction(ActionTypes.EDIT.action());
log.setFile(nicePath(path, file, webapp));
log.setObjectType(ObjectTypes.FILE);
}
// save
if (actionType.equals("file") && op.equals("saveFile")) {
log.setAction(ActionTypes.SAVE.action());
log.setFile(nicePath(path, file, webapp));
log.setObjectType(ObjectTypes.FILE);
}
// delete
if (actionType.equals("file") && op.equals("deleteFile")) {
log.setAction(ActionTypes.DELETE.action());
log.setFile(nicePath(path, params, webapp));
log.setObjectType(ObjectTypes.FILE);
}
// CVS
if (actionType.equals("cvs")) {
if (op.equals("check")) {
log.setAction(ActionTypes.CVS_CHECK.action());
log.setFile("/" + params);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("update")) {
log.setAction(ActionTypes.CVS_UPDATE_DIR_LOCAL.action());
log.setFile("/" + params);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("rupdate")) {
log.setAction(ActionTypes.CVS_UPDATE_DIR_RECURSIVE.action());
log.setFile("/" + params);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("commit")) {
// this action won't get logged, since we will get another log from the cvs hook
// we just store it in a variable
log.setAction("paradeCvsCommit");
String[] commitParams = getParamValues("params", queryString, null, 0);
log.setFile(nicePath(commitParams[1], "", ""));
log.setObjectType(ObjectTypes.CVSFILE);
// for some weird reason, commit gets logged twice (maybe because of struts?)
// so since we don't want this, we do a check
if (lastCommitId != null && lastCommitId.equals(log.getFile() + log.getQueryString())) {
lastCommitId = null;
// we ignore that log
} else {
lastCommit = log;
}
}
if (op.equals("diff")) {
log.setAction(ActionTypes.CVS_DIFF.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("add") || op.equals("addbin")) {
log.setAction(ActionTypes.CVS_ADD.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("updatefile")) {
log.setAction(ActionTypes.CVS_UPDATE_FILE.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("overridefile")) {
log.setAction(ActionTypes.CVS_OVERRIDE_FILE.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("deletefile")) {
log.setAction(ActionTypes.CVS_DELETE_FILE.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
}
// CVS commit (hook)
if (log.getAction().equals("cvsCommitRepository")) {
log.setAction(ActionTypes.CVS_COMMIT.action());
if (lastCommit != null && lastCommit.getFile() != null) {
// the user commited through parade
// we just check if it's the same file that has been commited through parade so we don't log it twice
// (it will be logged anyway after this)
// and we also add other useful info
if (lastCommit.getFile().equals(log.getFile())) {
lastCommitId = lastCommit.getFile() + lastCommit.getQueryString();
log.setQueryString(lastCommit.getQueryString() + log.getQueryString());
log.setContext(lastCommit.getContext());
log.setParadecontext(lastCommit.getParadecontext());
log.setUser(lastCommit.getUser());
log.setObjectType(ObjectTypes.CVSFILE);
lastCommit = null;
} else {
logger.error("***********************************************************************\n"
+ "Unrecognised parade commit. please tell developers!\n"
+ "***********************************************************************");
}
} else {
// this is an external commit that doesn't come thru parade
// let's try to see if we know the user who did the commit
Transaction tx = s.beginTransaction();
Query q = s.createQuery("from User u where u.cvsuser = ?");
q.setString(0, log.getUser());
List<User> results = q.list();
if (results.size() > 0) {
User u = results.get(0);
if (u != null) {
log.setUser(u.getLogin());
}
}
tx.commit();
}
}
// webapp matters
if (actionType.equals("webapp")) {
log.setObjectType(ObjectTypes.ROW);
if (op.equals("servletContextInstall")) {
log.setAction(ActionTypes.WEBAPP_INSTALL.action());
}
if (op.equals("servletContextRemove")) {
log.setAction(ActionTypes.WEBAPP_UNINSTALL.action());
}
if (op.equals("servletContextReload")) {
log.setAction(ActionTypes.WEBAPP_RELOAD.action());
}
if (op.equals("servletContextRedeploy")) {
log.setAction(ActionTypes.WEBAPP_REDEPLOY.action());
}
if (op.equals("servletContextStop")) {
log.setAction(ActionTypes.WEBAPP_STOP.action());
}
if (op.equals("servletContextStart")) {
log.setAction(ActionTypes.WEBAPP_START.action());
}
}
}
private String nicePath(String path, String file, String webapp) {
try {
// path doesn't end with /
path = path.indexOf("%") > -1 ? URLDecoder.decode(path, "UTF-8") : path;
path = path.startsWith("/") ? "" : "/" + (path.endsWith("/") ? path.substring(0, path.length() - 1) : path);
// file starts with /
file = file.indexOf("%") > -1 ? URLDecoder.decode(file, "UTF-8") : file;
file = file.startsWith("/") ? file : file.length() == 0 ? "" : "/" + file;
// remove webapp path
if (webapp.length() > 0) {
path = path.startsWith("/" + webapp) ? path.substring(("/" + webapp).length()) : path;
file = file.startsWith("/" + webapp) ? file.substring(("/" + webapp).length()) : file;
}
} catch (UnsupportedEncodingException e) {
// shouldn't happen
}
return path + file;
}
private String getParam(String paramName, String queryString) {
int n = queryString.indexOf(paramName + "=");
String param = null;
if (n > -1) {
param = queryString.substring(n + paramName.length() + 1);
if (param.indexOf("&") > -1) {
param = param.substring(0, param.indexOf("&"));
}
}
return param;
}
private String[] getParamValues(String paramName, String queryString, String[] paramValues, int pos) {
if (pos == 0) {
paramValues = new String[5];
}
int n = queryString.indexOf(paramName + "=");
String param = null;
if (n > -1) {
param = queryString.substring(n + paramName.length() + 1);
if (param.indexOf("&") > -1) {
param = param.substring(0, param.indexOf("&"));
}
paramValues[pos] = param;
String qs = queryString.substring(0, n)
+ queryString.substring(n + paramName.length() + 1 + param.length());
pos++;
return getParamValues(paramName, qs, paramValues, pos);
}
return paramValues;
}
/**
* Checks whether this access should be logged or not
*
* @param log
* the DTO containing the log entry
* @return <code>true</code> if this is worth logging, <code>false</code> otherwise
*/
private boolean shouldLog(ActionLogDTO log) {
if (log.getUrl() != null
&& (log.getUrl().endsWith(".ico")
|| log.getUrl().endsWith(".css")
|| log.getUrl().endsWith(".gif")
|| log.getUrl().endsWith(".jpg")
|| log.getUrl().endsWith(".js")
|| log.getUrl().startsWith("/servlet/ticker")
|| log.getUrl().startsWith("/servlet/cvscommit")
|| log.getUrl().startsWith("/servlet/logs")
|| log.getUrl().startsWith("/tipOfTheDay.jsp")
|| log.getUrl().startsWith("/index.jsp")
|| log.getUrl().startsWith("/logout.jsp")
|| log.getUrl().startsWith("/log.jsp")
|| log.getUrl().startsWith("/logs")
|| log.getUrl().startsWith("/userView.jsp")
|| log.getUrl().startsWith("/userEdit.jsp")
|| log.getUrl().startsWith("/showImage.jsp")
|| log.getUrl().startsWith("/todo.jsp")
|| log.getUrl().startsWith("/unauthorized.jsp")
|| log.getUrl().startsWith("/error.jsp")
|| log.getUrl().equals("/")
|| log.getUrl().startsWith("/admin")
|| log.getUrl().startsWith("/Admin.do")
|| log.getUrl().startsWith("/aether")
|| log.getUrl().startsWith("/playground")
|| log.getUrl().startsWith("/logic")
|| log.getUrl().startsWith("/dataDefinitions")
|| (log.getUrl().equals("/servlet/browse") && log.getQueryString().indexOf("display=header") > -1)
|| (log.getUrl().equals("/servlet/browse") && log.getQueryString().indexOf("display=tree") > -1)
|| (log.getUrl().equals("/servlet/browse") && log.getQueryString().indexOf("display=command") > -1)
|| (log.getUrl().equals("File.do") && log.getQueryString().indexOf("display=command&view=new") > -1)
|| log.getUrl().equals("/Command.do") || log.getUrl().startsWith("/scripts/codepress/"))
|| log.getUser() == null || (log.getOrigin() != null && log.getOrigin().equals("tomcat"))) {
return false;
}
return true;
}
private void handleLog(HttpServletRequest req, Object record, Session s) {
// extract useful information from the record
Log log = new Log();
ActionLog actionLog = retrieveActionLog(s);
log.setActionLog(actionLog);
// this is a java.util.logging.LogRecord
if (record instanceof LogRecord) {
LogRecord logrecord = (LogRecord) record;
log.setDate(new Date(logrecord.getMillis()));
log.setLevel(logrecord.getLevel().getName());
log.setMessage(logrecord.getMessage());
log.setOrigin("java.util.Logging");
// log.setThrowable(logrecord.getThrown());
} else if (record instanceof LoggingEvent) {
LoggingEvent logevent = (LoggingEvent) record;
log.setOrigin("log4j");
log.setDate(new Date(logevent.timeStamp));
log.setLevel(logevent.getLevel().toString());
log.setMessage(logevent.getRenderedMessage());
// if(logevent.getThrowableInformation() != null)
// log.setThrowable(logevent.getThrowableInformation().getThrowable());
// else
// log.setThrowable(null);
} else if (record instanceof PerThreadPrintStreamLogRecord) {
PerThreadPrintStreamLogRecord pRecord = (PerThreadPrintStreamLogRecord) record;
log.setDate(pRecord.getDate());
log.setOrigin("stdout");
log.setLevel("INFO");
log.setMessage(pRecord.getMessage());
// log.setThrowable(null);
} else if (record instanceof Object[]) {
Object[] rec = (Object[]) record;
log.setDate((Date) rec[0]);
log.setOrigin("TriggerFilter");
log.setLevel("INFO");
log.setMessage((String) rec[1]);
}
Transaction tx = s.beginTransaction();
// write the guy to the db
s.saveOrUpdate(log);
tx.commit();
}
private ActionLog retrieveActionLog(Session s) {
ActionLogDTO actionLogDTO = TriggerFilter.actionLog.get();
ActionLog actionLog = new ActionLog();
actionLogDTO.populate(actionLog);
// if the actionLog is there but not persisted, we persist it first
if (actionLog.getId() == null) {
Transaction tx = s.beginTransaction();
s.save(actionLog);
tx.commit();
actionLogDTO.setId(actionLog.getId());
TriggerFilter.actionLog.set(actionLogDTO);
} else {
actionLog = (ActionLog) s.get(ActionLog.class, actionLogDTO.getId());
}
return actionLog;
}
}
| true | true | private void filterLog(ActionLogDTO log, Session s) {
String queryString = log.getQueryString();
String uri = log.getUrl();
if (uri == null)
uri = "";
if (queryString == null)
queryString = "";
if (log.getAction() == null)
log.setAction("");
if (log.getParadecontext() == null) {
log.setParadecontext(getParam("context", queryString));
}
if (log.getParadecontext() == null) {
log.setParadecontext(log.getContext());
}
String webapp = "";
// fetch the webapp root in a hackish way
String ctx = log.getParadecontext() == null ? log.getContext() : log.getParadecontext();
if (ctx != null) {
Map<String, String> rowDef = rp.getRowDefinitions().get(ctx);
if (rowDef != null) {
webapp = rowDef.get("webapp");
} else {
logger.warn("Null context for actionLogDTO " + log.toString());
}
}
String actionType = "", op = "", params = "", display = "", path = "", file = "";
if (uri.indexOf("browse.jsp") > -1)
actionType = "browseRow";
if (uri.indexOf("/servlet/browse") > -1)
actionType = "browse";
if (uri.indexOf("File.do") > -1)
actionType = "file";
if (uri.indexOf("File.do") > -1 && queryString.indexOf("browse&") > -1)
actionType = "fileBrowse";
if (uri.indexOf("Cvs.do") > -1)
actionType = "cvs";
if (uri.indexOf("Webapp.do") > -1)
actionType = "webapp";
op = getParam("op", queryString);
params = getParam("params", queryString);
display = getParam("display", queryString);
path = getParam("path", queryString);
file = getParam("file", queryString);
if (op == null)
op = "";
if (params == null)
params = "";
if (display == null)
display = "";
if (path == null)
path = "";
if (file == null)
file = "";
// browse actions
if (actionType.equals("browseRow")) {
log.setAction(ActionTypes.VIEW.action());
log.setObjectType(ObjectTypes.ROW);
}
if (actionType.equals("browse") || actionType.equals("fileBrowse")) {
log.setAction(ActionTypes.VIEW.action());
log.setFile(nicePath(path, "", ""));
log.setObjectType(ObjectTypes.DIR);
}
// view actions
if (uri.endsWith(".jspx")) {
log.setAction(ActionTypes.VIEW.action());
if (webapp.length() > 0) {
log.setFile("/" + webapp + uri.substring(0, uri.length() - 1));
log.setObjectType(ObjectTypes.FILE);
}
}
// execute actions
if (uri.endsWith(".jsp")) {
log.setAction(ActionTypes.EXECUTE.action());
if (webapp.length() > 0) {
log.setFile("/" + webapp + uri.substring(0, uri.length() - 1));
log.setObjectType(ObjectTypes.FILE);
}
}
// edit (open editor)
if (actionType.equals("file") && op.equals("editFile")) {
log.setAction(ActionTypes.EDIT.action());
log.setFile(nicePath(path, file, webapp));
log.setObjectType(ObjectTypes.FILE);
}
// save
if (actionType.equals("file") && op.equals("saveFile")) {
log.setAction(ActionTypes.SAVE.action());
log.setFile(nicePath(path, file, webapp));
log.setObjectType(ObjectTypes.FILE);
}
// delete
if (actionType.equals("file") && op.equals("deleteFile")) {
log.setAction(ActionTypes.DELETE.action());
log.setFile(nicePath(path, params, webapp));
log.setObjectType(ObjectTypes.FILE);
}
// CVS
if (actionType.equals("cvs")) {
if (op.equals("check")) {
log.setAction(ActionTypes.CVS_CHECK.action());
log.setFile("/" + params);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("update")) {
log.setAction(ActionTypes.CVS_UPDATE_DIR_LOCAL.action());
log.setFile("/" + params);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("rupdate")) {
log.setAction(ActionTypes.CVS_UPDATE_DIR_RECURSIVE.action());
log.setFile("/" + params);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("commit")) {
// this action won't get logged, since we will get another log from the cvs hook
// we just store it in a variable
log.setAction("paradeCvsCommit");
String[] commitParams = getParamValues("params", queryString, null, 0);
log.setFile(nicePath(commitParams[1], "", ""));
log.setObjectType(ObjectTypes.CVSFILE);
// for some weird reason, commit gets logged twice (maybe because of struts?)
// so since we don't want this, we do a check
if (lastCommitId != null && lastCommitId.equals(log.getFile() + log.getQueryString())) {
lastCommitId = null;
// we ignore that log
} else {
lastCommit = log;
}
}
if (op.equals("diff")) {
log.setAction(ActionTypes.CVS_DIFF.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("add") || op.equals("addbin")) {
log.setAction(ActionTypes.CVS_ADD.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("updatefile")) {
log.setAction(ActionTypes.CVS_UPDATE_FILE.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("overridefile")) {
log.setAction(ActionTypes.CVS_OVERRIDE_FILE.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("deletefile")) {
log.setAction(ActionTypes.CVS_DELETE_FILE.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
}
// CVS commit (hook)
if (log.getAction().equals("cvsCommitRepository")) {
log.setAction(ActionTypes.CVS_COMMIT.action());
if (lastCommit != null && lastCommit.getFile() != null) {
// the user commited through parade
// we just check if it's the same file that has been commited through parade so we don't log it twice
// (it will be logged anyway after this)
// and we also add other useful info
if (lastCommit.getFile().equals(log.getFile())) {
lastCommitId = lastCommit.getFile() + lastCommit.getQueryString();
log.setQueryString(lastCommit.getQueryString() + log.getQueryString());
log.setContext(lastCommit.getContext());
log.setParadecontext(lastCommit.getParadecontext());
log.setUser(lastCommit.getUser());
log.setObjectType(ObjectTypes.CVSFILE);
lastCommit = null;
} else {
logger.error("***********************************************************************\n"
+ "Unrecognised parade commit. please tell developers!\n"
+ "***********************************************************************");
}
} else {
// this is an external commit that doesn't come thru parade
// let's try to see if we know the user who did the commit
Transaction tx = s.beginTransaction();
Query q = s.createQuery("from User u where u.cvsuser = ?");
q.setString(0, log.getUser());
List<User> results = q.list();
if (results.size() > 0) {
User u = results.get(0);
if (u != null) {
log.setUser(u.getLogin());
}
}
tx.commit();
}
}
// webapp matters
if (actionType.equals("webapp")) {
log.setObjectType(ObjectTypes.ROW);
if (op.equals("servletContextInstall")) {
log.setAction(ActionTypes.WEBAPP_INSTALL.action());
}
if (op.equals("servletContextRemove")) {
log.setAction(ActionTypes.WEBAPP_UNINSTALL.action());
}
if (op.equals("servletContextReload")) {
log.setAction(ActionTypes.WEBAPP_RELOAD.action());
}
if (op.equals("servletContextRedeploy")) {
log.setAction(ActionTypes.WEBAPP_REDEPLOY.action());
}
if (op.equals("servletContextStop")) {
log.setAction(ActionTypes.WEBAPP_STOP.action());
}
if (op.equals("servletContextStart")) {
log.setAction(ActionTypes.WEBAPP_START.action());
}
}
}
| private void filterLog(ActionLogDTO log, Session s) {
String queryString = log.getQueryString();
String uri = log.getUrl();
if (uri == null)
uri = "";
if (queryString == null)
queryString = "";
if (log.getAction() == null)
log.setAction("");
if (log.getParadecontext() == null) {
log.setParadecontext(getParam("context", queryString));
}
if (log.getParadecontext() == null) {
log.setParadecontext(log.getContext());
}
String webapp = "";
// fetch the webapp root in a hackish way
String ctx = log.getParadecontext() == null ? log.getContext() : log.getParadecontext();
if (ctx != null) {
Map<String, String> rowDef = rp.getRowDefinitions().get(ctx);
if (rowDef != null) {
webapp = rowDef.get("webapp");
} else {
logger.warn("Null context for actionLogDTO " + log.toString());
}
}
String actionType = "", op = "", params = "", display = "", path = "", file = "";
if (uri.indexOf("browse.jsp") > -1)
actionType = "browseRow";
if (uri.indexOf("/servlet/browse") > -1)
actionType = "browse";
if (uri.indexOf("File.do") > -1)
actionType = "file";
if (uri.indexOf("File.do") > -1 && queryString.indexOf("browse&") > -1)
actionType = "fileBrowse";
if (uri.indexOf("Cvs.do") > -1)
actionType = "cvs";
if (uri.indexOf("Webapp.do") > -1)
actionType = "webapp";
op = getParam("op", queryString);
params = getParam("params", queryString);
display = getParam("display", queryString);
path = getParam("path", queryString);
file = getParam("file", queryString);
if (op == null)
op = "";
if (params == null)
params = "";
if (display == null)
display = "";
if (path == null)
path = "";
if (file == null)
file = "";
// browse actions
if (actionType.equals("browseRow")) {
log.setAction(ActionTypes.VIEW.action());
log.setObjectType(ObjectTypes.ROW);
}
if (actionType.equals("browse") || actionType.equals("fileBrowse")) {
log.setAction(ActionTypes.VIEW.action());
log.setFile(nicePath(path, "", ""));
log.setObjectType(ObjectTypes.DIR);
}
// view actions
if (uri.endsWith(".jspx")) {
log.setAction(ActionTypes.VIEW.action());
if (webapp.length() > 0) {
log.setFile("/" + webapp + uri.substring(0, uri.length() - 1));
log.setObjectType(ObjectTypes.FILE);
}
}
// execute actions
if (uri.endsWith(".jsp")) {
log.setAction(ActionTypes.EXECUTE.action());
if (webapp.length() > 0) {
log.setFile("/" + webapp + uri.substring(0, uri.length()));
log.setObjectType(ObjectTypes.FILE);
}
}
// edit (open editor)
if (actionType.equals("file") && op.equals("editFile")) {
log.setAction(ActionTypes.EDIT.action());
log.setFile(nicePath(path, file, webapp));
log.setObjectType(ObjectTypes.FILE);
}
// save
if (actionType.equals("file") && op.equals("saveFile")) {
log.setAction(ActionTypes.SAVE.action());
log.setFile(nicePath(path, file, webapp));
log.setObjectType(ObjectTypes.FILE);
}
// delete
if (actionType.equals("file") && op.equals("deleteFile")) {
log.setAction(ActionTypes.DELETE.action());
log.setFile(nicePath(path, params, webapp));
log.setObjectType(ObjectTypes.FILE);
}
// CVS
if (actionType.equals("cvs")) {
if (op.equals("check")) {
log.setAction(ActionTypes.CVS_CHECK.action());
log.setFile("/" + params);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("update")) {
log.setAction(ActionTypes.CVS_UPDATE_DIR_LOCAL.action());
log.setFile("/" + params);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("rupdate")) {
log.setAction(ActionTypes.CVS_UPDATE_DIR_RECURSIVE.action());
log.setFile("/" + params);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("commit")) {
// this action won't get logged, since we will get another log from the cvs hook
// we just store it in a variable
log.setAction("paradeCvsCommit");
String[] commitParams = getParamValues("params", queryString, null, 0);
log.setFile(nicePath(commitParams[1], "", ""));
log.setObjectType(ObjectTypes.CVSFILE);
// for some weird reason, commit gets logged twice (maybe because of struts?)
// so since we don't want this, we do a check
if (lastCommitId != null && lastCommitId.equals(log.getFile() + log.getQueryString())) {
lastCommitId = null;
// we ignore that log
} else {
lastCommit = log;
}
}
if (op.equals("diff")) {
log.setAction(ActionTypes.CVS_DIFF.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("add") || op.equals("addbin")) {
log.setAction(ActionTypes.CVS_ADD.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("updatefile")) {
log.setAction(ActionTypes.CVS_UPDATE_FILE.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("overridefile")) {
log.setAction(ActionTypes.CVS_OVERRIDE_FILE.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
if (op.equals("deletefile")) {
log.setAction(ActionTypes.CVS_DELETE_FILE.action());
log.setFile("/" + file);
log.setObjectType(ObjectTypes.CVSFILE);
}
}
// CVS commit (hook)
if (log.getAction().equals("cvsCommitRepository")) {
log.setAction(ActionTypes.CVS_COMMIT.action());
if (lastCommit != null && lastCommit.getFile() != null) {
// the user commited through parade
// we just check if it's the same file that has been commited through parade so we don't log it twice
// (it will be logged anyway after this)
// and we also add other useful info
if (lastCommit.getFile().equals(log.getFile())) {
lastCommitId = lastCommit.getFile() + lastCommit.getQueryString();
log.setQueryString(lastCommit.getQueryString() + log.getQueryString());
log.setContext(lastCommit.getContext());
log.setParadecontext(lastCommit.getParadecontext());
log.setUser(lastCommit.getUser());
log.setObjectType(ObjectTypes.CVSFILE);
lastCommit = null;
} else {
logger.error("***********************************************************************\n"
+ "Unrecognised parade commit. please tell developers!\n"
+ "***********************************************************************");
}
} else {
// this is an external commit that doesn't come thru parade
// let's try to see if we know the user who did the commit
Transaction tx = s.beginTransaction();
Query q = s.createQuery("from User u where u.cvsuser = ?");
q.setString(0, log.getUser());
List<User> results = q.list();
if (results.size() > 0) {
User u = results.get(0);
if (u != null) {
log.setUser(u.getLogin());
}
}
tx.commit();
}
}
// webapp matters
if (actionType.equals("webapp")) {
log.setObjectType(ObjectTypes.ROW);
if (op.equals("servletContextInstall")) {
log.setAction(ActionTypes.WEBAPP_INSTALL.action());
}
if (op.equals("servletContextRemove")) {
log.setAction(ActionTypes.WEBAPP_UNINSTALL.action());
}
if (op.equals("servletContextReload")) {
log.setAction(ActionTypes.WEBAPP_RELOAD.action());
}
if (op.equals("servletContextRedeploy")) {
log.setAction(ActionTypes.WEBAPP_REDEPLOY.action());
}
if (op.equals("servletContextStop")) {
log.setAction(ActionTypes.WEBAPP_STOP.action());
}
if (op.equals("servletContextStart")) {
log.setAction(ActionTypes.WEBAPP_START.action());
}
}
}
|
diff --git a/search-impl/impl/src/java/org/sakaiproject/search/component/service/impl/SearchIndexBuilderImpl.java b/search-impl/impl/src/java/org/sakaiproject/search/component/service/impl/SearchIndexBuilderImpl.java
index b51a24d4..5ff62beb 100644
--- a/search-impl/impl/src/java/org/sakaiproject/search/component/service/impl/SearchIndexBuilderImpl.java
+++ b/search-impl/impl/src/java/org/sakaiproject/search/component/service/impl/SearchIndexBuilderImpl.java
@@ -1,464 +1,477 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.search.component.service.impl;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.api.ComponentManager;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.event.api.Event;
import org.sakaiproject.event.api.Notification;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.search.api.EntityContentProducer;
import org.sakaiproject.search.api.SearchIndexBuilder;
import org.sakaiproject.search.api.SearchIndexBuilderWorker;
import org.sakaiproject.search.dao.SearchBuilderItemDao;
import org.sakaiproject.search.model.SearchBuilderItem;
import org.sakaiproject.search.model.SearchWriterLock;
/**
* Search index builder is expected to be registered in spring as
* org.sakaiproject.search.api.SearchIndexBuilder as a singleton. It receives
* resources which it adds to its list of pending documents to be indexed. A
* seperate thread then runs thtough the list of entities to be indexed,
* updating the index. Each time the index is updates an event is posted to
* force the Search components that are using the index to reload. Incremental
* updates to the Lucene index require that the searchers reload the index once
* the idex writer has been built.
*
* @author ieb
*/
public class SearchIndexBuilderImpl implements SearchIndexBuilder
{
private static Log log = LogFactory.getLog(SearchIndexBuilderImpl.class);
private SearchBuilderItemDao searchBuilderItemDao = null;
private SearchIndexBuilderWorker searchIndexBuilderWorker = null;
private List producers = new ArrayList();
public void init()
{
ComponentManager cm = org.sakaiproject.component.cover.ComponentManager
.getInstance();
searchIndexBuilderWorker = (SearchIndexBuilderWorker) load(cm,
SearchIndexBuilderWorker.class.getName());
try
{
}
catch (Throwable t)
{
log.error("Failed to init ", t);
}
log.info(this + " completed init()");
}
private Object load(ComponentManager cm, String name)
{
Object o = cm.get(name);
if (o == null)
{
log.error("Cant find Spring component named " + name);
}
return o;
}
/**
* register an entity content producer to provide content to the search
* engine {@inheritDoc}
*/
public void registerEntityContentProducer(EntityContentProducer ecp)
{
log.debug("register " + ecp);
producers.add(ecp);
}
/**
* Add a resource to the indexing queue {@inheritDoc}
*/
public void addResource(Notification notification, Event event)
{
log.debug("Add resource " + notification + "::" + event);
String resourceName = event.getResource();
+ if ( resourceName == null ) {
+ // default if null
+ resourceName = "";
+ }
EntityContentProducer ecp = newEntityContentProducer(event);
Integer action = ecp.getAction(event);
int retries = 5;
while (retries > 0)
{
try
{
SearchBuilderItem sb = searchBuilderItemDao
.findByName(resourceName);
if (sb == null)
{
// new
sb = searchBuilderItemDao.create();
sb.setSearchaction(action);
sb.setName(resourceName);
- sb.setContext(ecp.getSiteId(resourceName));
+ String siteId = ecp.getSiteId(resourceName);
+ if ( siteId == null ) {
+ // default if null should neve happen
+ siteId = "";
+ }
+ sb.setContext(siteId);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
}
else
{
sb.setSearchaction(action);
- sb.setContext(ecp.getSiteId(resourceName));
+ String siteId = ecp.getSiteId(resourceName);
+ if ( siteId == null ) {
+ // default if null, should never happen
+ siteId = "";
+ }
+ sb.setContext(siteId);
sb.setName(resourceName);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
}
searchBuilderItemDao.update(sb);
- sb = searchBuilderItemDao.findByName(resourceName);
log.debug("SEARCHBUILDER: Added Resource " + action + " "
+ sb.getName());
break;
}
catch (Throwable t)
{
log.warn("Retrying to register " + resourceName
+ " with the search engine ", t);
retries--;
}
}
if (retries == 0)
{
log.warn("In trying to register resource " + resourceName
+ " in search engine, I failed after"
+ " 5 attempts, this resource will"
+ " not be indexed untill it is modified");
}
restartBuilder();
}
/**
* refresh the index from the current stored state {@inheritDoc}
*/
public void refreshIndex()
{
SearchBuilderItem sb = searchBuilderItemDao
.findByName(SearchBuilderItem.GLOBAL_MASTER);
if (sb == null)
{
log.debug("Created NEW " + SearchBuilderItem.GLOBAL_MASTER);
sb = searchBuilderItemDao.create();
}
if ((SearchBuilderItem.STATE_COMPLETED.equals(sb.getSearchstate()))
|| (!SearchBuilderItem.ACTION_REBUILD.equals(sb
.getSearchaction())
&& !SearchBuilderItem.STATE_PENDING.equals(sb
.getSearchstate()) && !SearchBuilderItem.STATE_PENDING_2
.equals(sb.getSearchstate())))
{
sb.setSearchaction(SearchBuilderItem.ACTION_REFRESH);
sb.setName(SearchBuilderItem.GLOBAL_MASTER);
sb.setContext(SearchBuilderItem.GLOBAL_CONTEXT);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: REFRESH ALL " + sb.getSearchaction() + " "
+ sb.getName());
restartBuilder();
}
else
{
log.debug("SEARCHBUILDER: REFRESH ALL IN PROGRESS "
+ sb.getSearchaction() + " " + sb.getName());
}
}
public void destroy()
{
searchIndexBuilderWorker.destroy();
}
/*
* List l = searchBuilderItemDao.getAll(); for (Iterator i = l.iterator();
* i.hasNext();) { SearchBuilderItemImpl sbi = (SearchBuilderItemImpl)
* i.next(); sbi.setSearchstate(SearchBuilderItem.STATE_PENDING);
* sbi.setSearchaction(SearchBuilderItem.ACTION_ADD); try { log.info("
* Updating " + sbi.getName()); searchBuilderItemDao.update(sbi); } catch
* (Exception ex) { try { sbi = (SearchBuilderItemImpl) searchBuilderItemDao
* .findByName(sbi.getName()); if (sbi != null) {
* sbi.setSearchstate(SearchBuilderItem.STATE_PENDING);
* sbi.setSearchaction(SearchBuilderItem.ACTION_ADD);
* searchBuilderItemDao.update(sbi); } } catch (Exception e) {
* log.warn("Failed to update on second attempt " + e.getMessage()); } } }
* restartBuilder(); }
*/
/**
* Rebuild the index from the entities own stored state {@inheritDoc}
*/
public void rebuildIndex()
{
try
{
SearchBuilderItem sb = searchBuilderItemDao
.findByName(SearchBuilderItem.GLOBAL_MASTER);
if (sb == null)
{
sb = searchBuilderItemDao.create();
}
sb.setSearchaction(SearchBuilderItem.ACTION_REBUILD);
sb.setName(SearchBuilderItem.GLOBAL_MASTER);
sb.setContext(SearchBuilderItem.GLOBAL_CONTEXT);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: REBUILD ALL " + sb.getSearchaction() + " "
+ sb.getName());
}
catch (Exception ex)
{
log.warn(" rebuild index encountered a problme " + ex.getMessage());
}
restartBuilder();
}
/*
* for (Iterator i = producers.iterator(); i.hasNext();) {
* EntityContentProducer ecp = (EntityContentProducer) i.next(); List
* contentList = ecp.getAllContent(); for (Iterator ci =
* contentList.iterator(); ci.hasNext();) { String resourceName = (String)
* ci.next(); } } }
*/
/**
* This adds and event to the list and if necessary starts a processing
* thread The method is syncronised with removeFromList
*
* @param e
*/
private void restartBuilder()
{
searchIndexBuilderWorker.checkRunning();
}
/**
* Generates a SearchableEntityProducer
*
* @param ref
* @return
* @throws PermissionException
* @throws IdUnusedException
* @throws TypeException
*/
public EntityContentProducer newEntityContentProducer(Reference ref)
{
log.debug(" new entitycontent producer");
for (Iterator i = producers.iterator(); i.hasNext();)
{
EntityContentProducer ecp = (EntityContentProducer) i.next();
if (ecp.matches(ref))
{
return ecp;
}
}
return null;
}
/**
* get hold of an entity content producer using the event
*
* @param event
* @return
*/
public EntityContentProducer newEntityContentProducer(Event event)
{
log.debug(" new entitycontent producer");
for (Iterator i = producers.iterator(); i.hasNext();)
{
EntityContentProducer ecp = (EntityContentProducer) i.next();
if (ecp.matches(event))
{
log.debug(" Matched Entity Content Producer for event " + event
+ " with " + ecp);
return ecp;
}
else
{
log.debug("Skipped ECP " + ecp);
}
}
log.debug("Failed to match any Entity Content Producer for event "
+ event);
return null;
}
/**
* @return Returns the searchBuilderItemDao.
*/
public SearchBuilderItemDao getSearchBuilderItemDao()
{
return searchBuilderItemDao;
}
/**
* @param searchBuilderItemDao
* The searchBuilderItemDao to set.
*/
public void setSearchBuilderItemDao(
SearchBuilderItemDao searchBuilderItemDao)
{
this.searchBuilderItemDao = searchBuilderItemDao;
}
/**
* return true if the queue is empty
*
* @{inheritDoc}
*/
public boolean isBuildQueueEmpty()
{
int n = searchBuilderItemDao.countPending();
log.debug("Queue has " + n);
return (n == 0);
}
/**
* get all the producers registerd, as a clone to avoid concurrent
* modification exceptions
*
* @return
*/
public List getContentProducers()
{
return new ArrayList(producers);
}
public int getPendingDocuments()
{
return searchBuilderItemDao.countPending();
}
/**
* Rebuild the index from the entities own stored state {@inheritDoc}, just
* the supplied siteId
*/
public void rebuildIndex(String currentSiteId)
{
try
{
String siteMaster = MessageFormat.format(
SearchBuilderItem.SITE_MASTER_FORMAT,
new Object[] { currentSiteId });
SearchBuilderItem sb = searchBuilderItemDao.findByName(siteMaster);
if (sb == null)
{
sb = searchBuilderItemDao.create();
}
sb.setSearchaction(SearchBuilderItem.ACTION_REBUILD);
sb.setName(siteMaster);
sb.setContext(currentSiteId);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: REBUILD CONTEXT " + sb.getSearchaction()
+ " " + sb.getName());
}
catch (Exception ex)
{
log.warn(" rebuild index encountered a problme " + ex.getMessage());
}
restartBuilder();
}
/**
* Refresh the index fo the supplied site.
*/
public void refreshIndex(String currentSiteId)
{
String siteMaster = MessageFormat.format(
SearchBuilderItem.SITE_MASTER_FORMAT,
new Object[] { currentSiteId });
SearchBuilderItem sb = searchBuilderItemDao.findByName(siteMaster);
if (sb == null)
{
log.debug("Created NEW " + siteMaster);
sb = searchBuilderItemDao.create();
}
if ((SearchBuilderItem.STATE_COMPLETED.equals(sb.getSearchstate()))
|| (!SearchBuilderItem.ACTION_REBUILD.equals(sb
.getSearchaction())
&& !SearchBuilderItem.STATE_PENDING.equals(sb
.getSearchstate()) && !SearchBuilderItem.STATE_PENDING_2
.equals(sb.getSearchstate())))
{
sb.setSearchaction(SearchBuilderItem.ACTION_REFRESH);
sb.setName(siteMaster);
sb.setContext(currentSiteId);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: REFRESH CONTEXT " + sb.getSearchaction()
+ " " + sb.getName());
restartBuilder();
}
else
{
log.debug("SEARCHBUILDER: REFRESH CONTEXT IN PROGRESS "
+ sb.getSearchaction() + " " + sb.getName());
}
}
public List getAllSearchItems()
{
return searchBuilderItemDao.getAll();
}
public List getGlobalMasterSearchItems()
{
return searchBuilderItemDao.getGlobalMasters();
}
public List getSiteMasterSearchItems()
{
return searchBuilderItemDao.getSiteMasters();
}
public SearchWriterLock getCurrentLock()
{
return searchIndexBuilderWorker.getCurrentLock();
}
public List getNodeStatus()
{
return searchIndexBuilderWorker.getNodeStatus();
}
public boolean removeWorkerLock()
{
return searchIndexBuilderWorker.removeWorkerLock();
}
}
| false | true | public void addResource(Notification notification, Event event)
{
log.debug("Add resource " + notification + "::" + event);
String resourceName = event.getResource();
EntityContentProducer ecp = newEntityContentProducer(event);
Integer action = ecp.getAction(event);
int retries = 5;
while (retries > 0)
{
try
{
SearchBuilderItem sb = searchBuilderItemDao
.findByName(resourceName);
if (sb == null)
{
// new
sb = searchBuilderItemDao.create();
sb.setSearchaction(action);
sb.setName(resourceName);
sb.setContext(ecp.getSiteId(resourceName));
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
}
else
{
sb.setSearchaction(action);
sb.setContext(ecp.getSiteId(resourceName));
sb.setName(resourceName);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
}
searchBuilderItemDao.update(sb);
sb = searchBuilderItemDao.findByName(resourceName);
log.debug("SEARCHBUILDER: Added Resource " + action + " "
+ sb.getName());
break;
}
catch (Throwable t)
{
log.warn("Retrying to register " + resourceName
+ " with the search engine ", t);
retries--;
}
}
if (retries == 0)
{
log.warn("In trying to register resource " + resourceName
+ " in search engine, I failed after"
+ " 5 attempts, this resource will"
+ " not be indexed untill it is modified");
}
restartBuilder();
}
| public void addResource(Notification notification, Event event)
{
log.debug("Add resource " + notification + "::" + event);
String resourceName = event.getResource();
if ( resourceName == null ) {
// default if null
resourceName = "";
}
EntityContentProducer ecp = newEntityContentProducer(event);
Integer action = ecp.getAction(event);
int retries = 5;
while (retries > 0)
{
try
{
SearchBuilderItem sb = searchBuilderItemDao
.findByName(resourceName);
if (sb == null)
{
// new
sb = searchBuilderItemDao.create();
sb.setSearchaction(action);
sb.setName(resourceName);
String siteId = ecp.getSiteId(resourceName);
if ( siteId == null ) {
// default if null should neve happen
siteId = "";
}
sb.setContext(siteId);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
}
else
{
sb.setSearchaction(action);
String siteId = ecp.getSiteId(resourceName);
if ( siteId == null ) {
// default if null, should never happen
siteId = "";
}
sb.setContext(siteId);
sb.setName(resourceName);
sb.setSearchstate(SearchBuilderItem.STATE_PENDING);
}
searchBuilderItemDao.update(sb);
log.debug("SEARCHBUILDER: Added Resource " + action + " "
+ sb.getName());
break;
}
catch (Throwable t)
{
log.warn("Retrying to register " + resourceName
+ " with the search engine ", t);
retries--;
}
}
if (retries == 0)
{
log.warn("In trying to register resource " + resourceName
+ " in search engine, I failed after"
+ " 5 attempts, this resource will"
+ " not be indexed untill it is modified");
}
restartBuilder();
}
|
diff --git a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/normalizer/ChangeFifoArrayAccess.java b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/normalizer/ChangeFifoArrayAccess.java
index 9fea4c0de..f2d3f4ef8 100644
--- a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/normalizer/ChangeFifoArrayAccess.java
+++ b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/tools/normalizer/ChangeFifoArrayAccess.java
@@ -1,107 +1,107 @@
/*
* Copyright (c) 2010, IETR/INSA of Rennes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the IETR/INSA of Rennes nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package net.sf.orcc.tools.normalizer;
import java.util.List;
import net.sf.orcc.df.Actor;
import net.sf.orcc.df.Pattern;
import net.sf.orcc.df.util.DfVisitor;
import net.sf.orcc.ir.Def;
import net.sf.orcc.ir.ExprBinary;
import net.sf.orcc.ir.Expression;
import net.sf.orcc.ir.InstLoad;
import net.sf.orcc.ir.InstStore;
import net.sf.orcc.ir.IrFactory;
import net.sf.orcc.ir.OpBinary;
import net.sf.orcc.ir.Use;
import net.sf.orcc.ir.Var;
import net.sf.orcc.ir.util.AbstractIrVisitor;
/**
* This class defines a transform that changes the load/store on FIFO arrays so
* they use global arrays.
*
* @author Matthieu Wipliez
* @author Jerome Gorin
*
*/
public class ChangeFifoArrayAccess extends DfVisitor<Void> {
private class IrVisitor extends AbstractIrVisitor<Void> {
@Override
public Void caseInstLoad(InstLoad load) {
Use use = load.getSource();
Var var = use.getVariable();
if (var.isLocal() && var.eContainer() instanceof Pattern) {
use.setVariable(actor.getStateVar(var.getName()));
updateIndex(var, load.getIndexes());
}
return null;
}
@Override
public Void caseInstStore(InstStore store) {
Def def = store.getTarget();
Var var = def.getVariable();
if (var.isLocal() && var.eContainer() instanceof Pattern) {
def.setVariable(actor.getStateVar(var.getName()));
updateIndex(var, store.getIndexes());
}
return null;
}
private void updateIndex(Var var, List<Expression> indexes) {
- if (indexes.size() < 2) {
+ if (indexes.size() == 1) {
Var varCount = actor.getStateVar(var.getName() + "_count");
ExprBinary expr = IrFactory.eINSTANCE.createExprBinary(
IrFactory.eINSTANCE.createExprVar(varCount),
OpBinary.PLUS, indexes.get(0),
IrFactory.eINSTANCE.createTypeInt(32));
- indexes.set(0, expr);
+ indexes.add(expr);
} else {
System.err.println("TODO index");
}
}
}
public ChangeFifoArrayAccess() {
irVisitor = new IrVisitor();
}
@Override
public Void caseActor(Actor actor) {
this.actor = actor;
return super.caseActor(actor);
}
}
| false | true | private void updateIndex(Var var, List<Expression> indexes) {
if (indexes.size() < 2) {
Var varCount = actor.getStateVar(var.getName() + "_count");
ExprBinary expr = IrFactory.eINSTANCE.createExprBinary(
IrFactory.eINSTANCE.createExprVar(varCount),
OpBinary.PLUS, indexes.get(0),
IrFactory.eINSTANCE.createTypeInt(32));
indexes.set(0, expr);
} else {
System.err.println("TODO index");
}
}
| private void updateIndex(Var var, List<Expression> indexes) {
if (indexes.size() == 1) {
Var varCount = actor.getStateVar(var.getName() + "_count");
ExprBinary expr = IrFactory.eINSTANCE.createExprBinary(
IrFactory.eINSTANCE.createExprVar(varCount),
OpBinary.PLUS, indexes.get(0),
IrFactory.eINSTANCE.createTypeInt(32));
indexes.add(expr);
} else {
System.err.println("TODO index");
}
}
|
diff --git a/src/com/philiptorchinsky/TimeAppe/MainActivity.java b/src/com/philiptorchinsky/TimeAppe/MainActivity.java
index f506872..27d83af 100644
--- a/src/com/philiptorchinsky/TimeAppe/MainActivity.java
+++ b/src/com/philiptorchinsky/TimeAppe/MainActivity.java
@@ -1,93 +1,93 @@
package com.philiptorchinsky.TimeAppe;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ListActivity {
/**
* Called when the activity is first created.
*/
static public boolean isTest = false;
private DBAdapter dh;
private Adapter notes;
public ArrayList<Item> list = new ArrayList<Item>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dh = new DBAdapter (this);
dh.open();
// dh.destroy();
// dh.close();
//
// dh = new DBAdapter (this);
-// dh.insert("TeamCity training", "inactive", 0,0);
-// dh.insert("Android Study", "inactive", 0,0);
+ dh.insert("TeamCity training", "inactive", 0,0);
+ dh.insert("Android Study", "inactive", 0,0);
// dh.insert("FreelancersFeed", "inactive",0,0);
// GET ROWS
Cursor c = dh.getAll();
- int i = 4;
+ int i = 0;
c.moveToFirst();
if (!c.isAfterLast()) {
do {
String project = c.getString(1);
String status = c.getString(2);
long secondsSpent = c.getLong(3);
long lastactivated = c.getLong(4);
Item newitem = new Item(project, status, secondsSpent, lastactivated);
list.add(newitem);
} while (c.moveToNext());
}
notes = new Adapter (this,list);
setContentView(R.layout.main);
setListAdapter(notes);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Item item = (Item) getListAdapter().getItem(position);
String project = item.getProject();
String status = item.getStatus();
long secondsSpent = item.getSecondsSpent();
long lastActivated = item.getLastactivated();
if (status.equalsIgnoreCase("active")) {
status = "inactive";
item.setStatus(status);
long spentThisTime = System.currentTimeMillis() - lastActivated;
item.setSecondsSpent(secondsSpent + spentThisTime);
list.set((int)id,item);
dh.updateSpentTimeByProject(project,status,secondsSpent + spentThisTime);
// Toast.makeText(this, project + " selected. Now " + (secondsSpent + spentThisTime)/1000.0, Toast.LENGTH_LONG).show();
}
else {
status = "active";
item.setStatus(status);
lastActivated = System.currentTimeMillis();
item.setLastactivated(lastActivated);
list.set((int)id,item);
dh.updateActivatedByProject(project,status,lastActivated);
}
notes.notifyDataSetChanged();
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dh = new DBAdapter (this);
dh.open();
// dh.destroy();
// dh.close();
//
// dh = new DBAdapter (this);
// dh.insert("TeamCity training", "inactive", 0,0);
// dh.insert("Android Study", "inactive", 0,0);
// dh.insert("FreelancersFeed", "inactive",0,0);
// GET ROWS
Cursor c = dh.getAll();
int i = 4;
c.moveToFirst();
if (!c.isAfterLast()) {
do {
String project = c.getString(1);
String status = c.getString(2);
long secondsSpent = c.getLong(3);
long lastactivated = c.getLong(4);
Item newitem = new Item(project, status, secondsSpent, lastactivated);
list.add(newitem);
} while (c.moveToNext());
}
notes = new Adapter (this,list);
setContentView(R.layout.main);
setListAdapter(notes);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dh = new DBAdapter (this);
dh.open();
// dh.destroy();
// dh.close();
//
// dh = new DBAdapter (this);
dh.insert("TeamCity training", "inactive", 0,0);
dh.insert("Android Study", "inactive", 0,0);
// dh.insert("FreelancersFeed", "inactive",0,0);
// GET ROWS
Cursor c = dh.getAll();
int i = 0;
c.moveToFirst();
if (!c.isAfterLast()) {
do {
String project = c.getString(1);
String status = c.getString(2);
long secondsSpent = c.getLong(3);
long lastactivated = c.getLong(4);
Item newitem = new Item(project, status, secondsSpent, lastactivated);
list.add(newitem);
} while (c.moveToNext());
}
notes = new Adapter (this,list);
setContentView(R.layout.main);
setListAdapter(notes);
}
|
diff --git a/common/plugins/eu.esdihumboldt.hale.common.instance/src/eu/esdihumboldt/hale/common/instance/extension/metadata/MetadataInfo.java b/common/plugins/eu.esdihumboldt.hale.common.instance/src/eu/esdihumboldt/hale/common/instance/extension/metadata/MetadataInfo.java
index 638c32114..d86fe8f39 100644
--- a/common/plugins/eu.esdihumboldt.hale.common.instance/src/eu/esdihumboldt/hale/common/instance/extension/metadata/MetadataInfo.java
+++ b/common/plugins/eu.esdihumboldt.hale.common.instance/src/eu/esdihumboldt/hale/common/instance/extension/metadata/MetadataInfo.java
@@ -1,80 +1,85 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2011.
*/
package eu.esdihumboldt.hale.common.instance.extension.metadata;
import org.eclipse.core.runtime.IConfigurationElement;
import de.cs3d.util.eclipse.extension.ExtensionUtil;
import de.cs3d.util.eclipse.extension.simple.IdentifiableExtension.Identifiable;
/**
* Represents a declared Metadata Info
* @author Sebastian Reinhardt
*/
public class MetadataInfo implements Identifiable {
private final String key;
private final String label;
private final String description;
private final Class<? extends MetadataGenerator> generator;
/**
* Create a metadata object from a configuration element.
* @param key the data key
* @param conf the configuration element
*/
@SuppressWarnings("unchecked")
public MetadataInfo(String key, IConfigurationElement conf){
super();
this.key = key;
this.label = conf.getAttribute("label");
this.description = conf.getAttribute("description");
- this.generator = (Class<? extends MetadataGenerator>) ExtensionUtil.loadClass(conf, "generator");
+ if (conf.getAttribute("generator") != null) {
+ this.generator = (Class<? extends MetadataGenerator>) ExtensionUtil.loadClass(conf, "generator");
+ }
+ else {
+ this.generator = null;
+ }
}
/**
* @see de.cs3d.util.eclipse.extension.simple.IdentifiableExtension.Identifiable#getId()
*/
@Override
public String getId() {
return key;
}
/**
* @return the label
*/
public String getLabel() {
return label;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @return the generator class
*/
public Class<? extends MetadataGenerator> getGenerator() {
return generator;
}
}
| true | true | public MetadataInfo(String key, IConfigurationElement conf){
super();
this.key = key;
this.label = conf.getAttribute("label");
this.description = conf.getAttribute("description");
this.generator = (Class<? extends MetadataGenerator>) ExtensionUtil.loadClass(conf, "generator");
}
| public MetadataInfo(String key, IConfigurationElement conf){
super();
this.key = key;
this.label = conf.getAttribute("label");
this.description = conf.getAttribute("description");
if (conf.getAttribute("generator") != null) {
this.generator = (Class<? extends MetadataGenerator>) ExtensionUtil.loadClass(conf, "generator");
}
else {
this.generator = null;
}
}
|
diff --git a/src/org/geometerplus/android/fbreader/library/BookInfoActivity.java b/src/org/geometerplus/android/fbreader/library/BookInfoActivity.java
index 3ca4b4b9..5111d83d 100644
--- a/src/org/geometerplus/android/fbreader/library/BookInfoActivity.java
+++ b/src/org/geometerplus/android/fbreader/library/BookInfoActivity.java
@@ -1,323 +1,325 @@
/*
* Copyright (C) 2010-2012 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.android.fbreader.library;
import java.io.File;
import java.text.DateFormat;
import java.util.*;
import android.app.Activity;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.widget.*;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.filesystem.ZLPhysicalFile;
import org.geometerplus.zlibrary.core.image.ZLImage;
import org.geometerplus.zlibrary.core.image.ZLLoadableImage;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.zlibrary.core.language.ZLLanguageUtil;
import org.geometerplus.zlibrary.ui.android.R;
import org.geometerplus.zlibrary.ui.android.image.ZLAndroidImageData;
import org.geometerplus.zlibrary.ui.android.image.ZLAndroidImageManager;
import org.geometerplus.fbreader.library.*;
import org.geometerplus.fbreader.network.HtmlUtil;
import org.geometerplus.android.fbreader.FBReader;
import org.geometerplus.android.fbreader.preferences.EditBookInfoActivity;
public class BookInfoActivity extends Activity {
private static final boolean ENABLE_EXTENDED_FILE_INFO = false;
public static final String CURRENT_BOOK_PATH_KEY = "CurrentBookPath";
public static final String FROM_READING_MODE_KEY = "fromReadingMode";
private final ZLResource myResource = ZLResource.resource("bookInfo");
private ZLFile myFile;
private int myResult;
private boolean myDontReloadBook;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
Thread.setDefaultUncaughtExceptionHandler(
new org.geometerplus.zlibrary.ui.android.library.UncaughtExceptionHandler(this)
);
final String path = getIntent().getStringExtra(CURRENT_BOOK_PATH_KEY);
myDontReloadBook = getIntent().getBooleanExtra(FROM_READING_MODE_KEY, false);
myFile = ZLFile.createFileByPath(path);
if (SQLiteBooksDatabase.Instance() == null) {
new SQLiteBooksDatabase(this, "LIBRARY");
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.book_info);
myResult = FBReader.RESULT_DO_NOTHING;
setResult(myResult, getIntent());
}
@Override
protected void onStart() {
super.onStart();
final Book book = Book.getByFile(myFile);
if (book != null) {
// we do force language & encoding detection
book.getEncoding();
setupCover(book);
setupBookInfo(book);
setupAnnotation(book);
setupFileInfo(book);
}
setupButton(R.id.book_info_button_open, "openBook", new View.OnClickListener() {
public void onClick(View view) {
if (myDontReloadBook) {
finish();
} else {
startActivity(
new Intent(getApplicationContext(), FBReader.class)
.setAction(Intent.ACTION_VIEW)
.putExtra(FBReader.BOOK_PATH_KEY, myFile.getPath())
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
);
}
}
});
setupButton(R.id.book_info_button_edit, "editInfo", new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(
new Intent(getApplicationContext(), EditBookInfoActivity.class)
.putExtra(CURRENT_BOOK_PATH_KEY, myFile.getPath()),
1
);
}
});
setupButton(R.id.book_info_button_reload, "reloadInfo", new View.OnClickListener() {
public void onClick(View view) {
if (book != null) {
book.reloadInfoFromFile();
setupBookInfo(book);
myDontReloadBook = false;
+ myResult = Math.max(myResult, FBReader.RESULT_RELOAD_BOOK);
+ setResult(myResult);
}
}
});
final View root = findViewById(R.id.book_info_root);
root.invalidate();
root.requestLayout();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final Book book = Book.getByFile(myFile);
if (book != null) {
setupBookInfo(book);
myDontReloadBook = false;
}
myResult = Math.max(myResult, resultCode);
setResult(myResult);
}
private Button findButton(int buttonId) {
return (Button)findViewById(buttonId);
}
private void setupButton(int buttonId, String resourceKey, View.OnClickListener listener) {
final ZLResource buttonResource = ZLResource.resource("dialog").getResource("button");
final Button button = findButton(buttonId);
button.setText(buttonResource.getResource(resourceKey).getValue());
button.setOnClickListener(listener);
}
private void setupInfoPair(int id, String key, CharSequence value) {
setupInfoPair(id, key, value, 0);
}
private void setupInfoPair(int id, String key, CharSequence value, int param) {
final LinearLayout layout = (LinearLayout)findViewById(id);
if (value == null || value.length() == 0) {
layout.setVisibility(View.GONE);
return;
}
layout.setVisibility(View.VISIBLE);
((TextView)layout.findViewById(R.id.book_info_key)).setText(myResource.getResource(key).getValue(param));
((TextView)layout.findViewById(R.id.book_info_value)).setText(value);
}
private void setupCover(Book book) {
final ImageView coverView = (ImageView)findViewById(R.id.book_cover);
final DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
final int maxHeight = metrics.heightPixels * 2 / 3;
final int maxWidth = maxHeight * 2 / 3;
coverView.setVisibility(View.GONE);
coverView.setImageDrawable(null);
final ZLImage image = LibraryUtil.getCover(book);
if (image == null) {
return;
}
if (image instanceof ZLLoadableImage) {
final ZLLoadableImage loadableImage = (ZLLoadableImage)image;
if (!loadableImage.isSynchronized()) {
loadableImage.synchronize();
}
}
final ZLAndroidImageData data =
((ZLAndroidImageManager)ZLAndroidImageManager.Instance()).getImageData(image);
if (data == null) {
return;
}
final Bitmap coverBitmap = data.getBitmap(2 * maxWidth, 2 * maxHeight);
if (coverBitmap == null) {
return;
}
coverView.setVisibility(View.VISIBLE);
coverView.getLayoutParams().width = maxWidth;
coverView.getLayoutParams().height = maxHeight;
coverView.setImageBitmap(coverBitmap);
}
private void setupBookInfo(Book book) {
((TextView)findViewById(R.id.book_info_title)).setText(myResource.getResource("bookInfo").getValue());
setupInfoPair(R.id.book_title, "title", book.getTitle());
final StringBuilder buffer = new StringBuilder();
final List<Author> authors = book.authors();
for (Author a : authors) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append(a.DisplayName);
}
setupInfoPair(R.id.book_authors, "authors", buffer, authors.size());
final SeriesInfo series = book.getSeriesInfo();
setupInfoPair(R.id.book_series, "series", series == null ? null : series.Name);
String seriesIndexString = null;
if (series != null && series.Index != null) {
seriesIndexString = series.Index.toString();
}
setupInfoPair(R.id.book_series_index, "indexInSeries", seriesIndexString);
buffer.delete(0, buffer.length());
final HashSet<String> tagNames = new HashSet<String>();
for (Tag tag : book.tags()) {
if (!tagNames.contains(tag.Name)) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append(tag.Name);
tagNames.add(tag.Name);
}
}
setupInfoPair(R.id.book_tags, "tags", buffer, tagNames.size());
String language = book.getLanguage();
if (!ZLLanguageUtil.languageCodes().contains(language)) {
language = ZLLanguageUtil.OTHER_LANGUAGE_CODE;
}
setupInfoPair(R.id.book_language, "language", ZLLanguageUtil.languageName(language));
}
private void setupAnnotation(Book book) {
final TextView titleView = (TextView)findViewById(R.id.book_info_annotation_title);
final TextView bodyView = (TextView)findViewById(R.id.book_info_annotation_body);
final String annotation = LibraryUtil.getAnnotation(book);
if (annotation == null) {
titleView.setVisibility(View.GONE);
bodyView.setVisibility(View.GONE);
} else {
titleView.setText(myResource.getResource("annotation").getValue());
bodyView.setText(HtmlUtil.getHtmlText(annotation));
bodyView.setMovementMethod(new LinkMovementMethod());
bodyView.setTextColor(ColorStateList.valueOf(bodyView.getTextColors().getDefaultColor()));
}
}
private void setupFileInfo(Book book) {
((TextView)findViewById(R.id.file_info_title)).setText(myResource.getResource("fileInfo").getValue());
setupInfoPair(R.id.file_name, "name", book.File.getPath());
if (ENABLE_EXTENDED_FILE_INFO) {
setupInfoPair(R.id.file_type, "type", book.File.getExtension());
final ZLPhysicalFile physFile = book.File.getPhysicalFile();
final File file = physFile == null ? null : physFile.javaFile();
if (file != null && file.exists() && file.isFile()) {
setupInfoPair(R.id.file_size, "size", formatSize(file.length()));
setupInfoPair(R.id.file_time, "time", formatDate(file.lastModified()));
} else {
setupInfoPair(R.id.file_size, "size", null);
setupInfoPair(R.id.file_time, "time", null);
}
} else {
setupInfoPair(R.id.file_type, "type", null);
setupInfoPair(R.id.file_size, "size", null);
setupInfoPair(R.id.file_time, "time", null);
}
}
private String formatSize(long size) {
if (size <= 0) {
return null;
}
final int kilo = 1024;
if (size < kilo) { // less than 1 kilobyte
return myResource.getResource("sizeInBytes").getValue((int)size).replaceAll("%s", String.valueOf(size));
}
final String value;
if (size < kilo * kilo) { // less than 1 megabyte
value = String.format("%.2f", ((float)size) / kilo);
} else {
value = String.valueOf(size / kilo);
}
return myResource.getResource("sizeInKiloBytes").getValue().replaceAll("%s", value);
}
private String formatDate(long date) {
if (date == 0) {
return null;
}
return DateFormat.getDateTimeInstance().format(new Date(date));
}
}
| true | true | protected void onStart() {
super.onStart();
final Book book = Book.getByFile(myFile);
if (book != null) {
// we do force language & encoding detection
book.getEncoding();
setupCover(book);
setupBookInfo(book);
setupAnnotation(book);
setupFileInfo(book);
}
setupButton(R.id.book_info_button_open, "openBook", new View.OnClickListener() {
public void onClick(View view) {
if (myDontReloadBook) {
finish();
} else {
startActivity(
new Intent(getApplicationContext(), FBReader.class)
.setAction(Intent.ACTION_VIEW)
.putExtra(FBReader.BOOK_PATH_KEY, myFile.getPath())
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
);
}
}
});
setupButton(R.id.book_info_button_edit, "editInfo", new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(
new Intent(getApplicationContext(), EditBookInfoActivity.class)
.putExtra(CURRENT_BOOK_PATH_KEY, myFile.getPath()),
1
);
}
});
setupButton(R.id.book_info_button_reload, "reloadInfo", new View.OnClickListener() {
public void onClick(View view) {
if (book != null) {
book.reloadInfoFromFile();
setupBookInfo(book);
myDontReloadBook = false;
}
}
});
final View root = findViewById(R.id.book_info_root);
root.invalidate();
root.requestLayout();
}
| protected void onStart() {
super.onStart();
final Book book = Book.getByFile(myFile);
if (book != null) {
// we do force language & encoding detection
book.getEncoding();
setupCover(book);
setupBookInfo(book);
setupAnnotation(book);
setupFileInfo(book);
}
setupButton(R.id.book_info_button_open, "openBook", new View.OnClickListener() {
public void onClick(View view) {
if (myDontReloadBook) {
finish();
} else {
startActivity(
new Intent(getApplicationContext(), FBReader.class)
.setAction(Intent.ACTION_VIEW)
.putExtra(FBReader.BOOK_PATH_KEY, myFile.getPath())
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
);
}
}
});
setupButton(R.id.book_info_button_edit, "editInfo", new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(
new Intent(getApplicationContext(), EditBookInfoActivity.class)
.putExtra(CURRENT_BOOK_PATH_KEY, myFile.getPath()),
1
);
}
});
setupButton(R.id.book_info_button_reload, "reloadInfo", new View.OnClickListener() {
public void onClick(View view) {
if (book != null) {
book.reloadInfoFromFile();
setupBookInfo(book);
myDontReloadBook = false;
myResult = Math.max(myResult, FBReader.RESULT_RELOAD_BOOK);
setResult(myResult);
}
}
});
final View root = findViewById(R.id.book_info_root);
root.invalidate();
root.requestLayout();
}
|
diff --git a/src/main/org/jboss/reflect/plugins/InheritableAnnotationHolder.java b/src/main/org/jboss/reflect/plugins/InheritableAnnotationHolder.java
index f388064..453ade8 100644
--- a/src/main/org/jboss/reflect/plugins/InheritableAnnotationHolder.java
+++ b/src/main/org/jboss/reflect/plugins/InheritableAnnotationHolder.java
@@ -1,187 +1,191 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.reflect.plugins;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.jboss.reflect.spi.AnnotatedInfo;
import org.jboss.reflect.spi.AnnotationValue;
import org.jboss.util.JBossObject;
/**
* An annotation holder
*
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @author <a href="mailto:[email protected]">Adrian Brock</a>
*/
public abstract class InheritableAnnotationHolder extends JBossObject implements AnnotatedInfo, Serializable
{
/** serialVersionUID */
private static final long serialVersionUID = 3257290210164289843L;
/** Unknown annotations map */
static final Map UNKNOWN_ANNOTATIONS_MAP = Collections.unmodifiableMap(new HashMap());
/** Unknown annotations */
static final AnnotationValue[] UNKNOWN_ANNOTATIONS = new AnnotationValue[0];
/** Declared annotations Map<String, AnnotationValue> */
protected Map declaredAnnotations = UNKNOWN_ANNOTATIONS_MAP;
/** All annotations Map<String, AnnotationValue> */
protected Map allAnnotations = UNKNOWN_ANNOTATIONS_MAP;
/** All annotations */
protected AnnotationValue[] allAnnotationsArray = UNKNOWN_ANNOTATIONS;
/** Declared annotations */
protected AnnotationValue[] declaredAnnotationsArray = UNKNOWN_ANNOTATIONS;
/** The annotated element */
protected Object annotatedElement;
/** The annotation helper */
protected AnnotationHelper annotationHelper;
/**
* Create a new InheritableAnnotationHolder.
*/
public InheritableAnnotationHolder()
{
}
/**
* Set the annotation helper
*
* @param helper the helper
*/
public void setAnnotationHelper(AnnotationHelper helper)
{
this.annotationHelper = helper;
}
public void setAnnotatedElement(Object annotatedElement)
{
this.annotatedElement = annotatedElement;
}
/**
* Get the declared annotations
*
* @return the declared annotations
*/
public AnnotationValue[] getDeclaredAnnotations()
{
if (declaredAnnotationsArray == UNKNOWN_ANNOTATIONS)
setupAnnotations(annotationHelper.getAnnotations(annotatedElement));
return declaredAnnotationsArray;
}
public AnnotationValue[] getAnnotations()
{
if (allAnnotationsArray == UNKNOWN_ANNOTATIONS)
setupAnnotations(annotationHelper.getAnnotations(annotatedElement));
return allAnnotationsArray;
}
public AnnotationValue getAnnotation(String name)
{
if (allAnnotations == UNKNOWN_ANNOTATIONS_MAP)
setupAnnotations(annotationHelper.getAnnotations(annotatedElement));
return (AnnotationValue) allAnnotations.get(name);
}
public boolean isAnnotationPresent(String name)
{
if (allAnnotations == UNKNOWN_ANNOTATIONS_MAP)
setupAnnotations(annotationHelper.getAnnotations(annotatedElement));
return allAnnotations.containsKey(name);
}
/**
* Set up the annotations
*
* @param annotations the annotations
*/
public void setupAnnotations(AnnotationValue[] annotations)
{
InheritableAnnotationHolder superHolder = getSuperHolder();
+ if (superHolder == null)
+ {
+ return;
+ }
AnnotationValue[] superAllAnnotations = superHolder.getAnnotations();
if (annotations != null && annotations.length > 0)
{
declaredAnnotations = new HashMap();
declaredAnnotationsArray = annotations;
for (int i = 0; i < annotations.length; i++)
declaredAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
allAnnotations = new HashMap();
if (superHolder != null && superAllAnnotations != null && superAllAnnotations.length != 0)
{
for (int i = 0; i < superAllAnnotations.length; i++)
{
AnnotationValue av = superAllAnnotations[i];
if (av.getAnnotationType().isAnnotationPresent("java.lang.annotation.Inherited"));
allAnnotations.put(av.getAnnotationType().getName(), av);
}
}
else
allAnnotationsArray = declaredAnnotationsArray;
for (int i = 0; i < annotations.length; i++)
allAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
allAnnotationsArray = (AnnotationValue[])allAnnotations.values().toArray(new AnnotationValue[allAnnotations.size()]);
}
else
{
if (superHolder != null)
{
allAnnotations = superHolder.getAllAnnotations();
allAnnotationsArray = superAllAnnotations;
}
}
}
/**
* Get all the annotations as a map
*
* @return the map
*/
protected Map getAllAnnotations()
{
if (allAnnotations == UNKNOWN_ANNOTATIONS_MAP)
setupAnnotations(annotationHelper.getAnnotations(annotatedElement));
return allAnnotations;
}
/**
* Get the super holder of annoations
*
* @return the super holder
*/
protected abstract InheritableAnnotationHolder getSuperHolder();
}
| true | true | public void setupAnnotations(AnnotationValue[] annotations)
{
InheritableAnnotationHolder superHolder = getSuperHolder();
AnnotationValue[] superAllAnnotations = superHolder.getAnnotations();
if (annotations != null && annotations.length > 0)
{
declaredAnnotations = new HashMap();
declaredAnnotationsArray = annotations;
for (int i = 0; i < annotations.length; i++)
declaredAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
allAnnotations = new HashMap();
if (superHolder != null && superAllAnnotations != null && superAllAnnotations.length != 0)
{
for (int i = 0; i < superAllAnnotations.length; i++)
{
AnnotationValue av = superAllAnnotations[i];
if (av.getAnnotationType().isAnnotationPresent("java.lang.annotation.Inherited"));
allAnnotations.put(av.getAnnotationType().getName(), av);
}
}
else
allAnnotationsArray = declaredAnnotationsArray;
for (int i = 0; i < annotations.length; i++)
allAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
allAnnotationsArray = (AnnotationValue[])allAnnotations.values().toArray(new AnnotationValue[allAnnotations.size()]);
}
else
{
if (superHolder != null)
{
allAnnotations = superHolder.getAllAnnotations();
allAnnotationsArray = superAllAnnotations;
}
}
}
| public void setupAnnotations(AnnotationValue[] annotations)
{
InheritableAnnotationHolder superHolder = getSuperHolder();
if (superHolder == null)
{
return;
}
AnnotationValue[] superAllAnnotations = superHolder.getAnnotations();
if (annotations != null && annotations.length > 0)
{
declaredAnnotations = new HashMap();
declaredAnnotationsArray = annotations;
for (int i = 0; i < annotations.length; i++)
declaredAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
allAnnotations = new HashMap();
if (superHolder != null && superAllAnnotations != null && superAllAnnotations.length != 0)
{
for (int i = 0; i < superAllAnnotations.length; i++)
{
AnnotationValue av = superAllAnnotations[i];
if (av.getAnnotationType().isAnnotationPresent("java.lang.annotation.Inherited"));
allAnnotations.put(av.getAnnotationType().getName(), av);
}
}
else
allAnnotationsArray = declaredAnnotationsArray;
for (int i = 0; i < annotations.length; i++)
allAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
allAnnotationsArray = (AnnotationValue[])allAnnotations.values().toArray(new AnnotationValue[allAnnotations.size()]);
}
else
{
if (superHolder != null)
{
allAnnotations = superHolder.getAllAnnotations();
allAnnotationsArray = superAllAnnotations;
}
}
}
|
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java
index 29f491d11..9dd0edc4b 100644
--- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java
+++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java
@@ -1,276 +1,278 @@
/*******************************************************************************
* Copyright (c) 2000, 2002 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM - Initial API and implementation
******************************************************************************/
package org.eclipse.core.internal.resources;
import java.util.Hashtable;
import org.eclipse.core.resources.WorkspaceLock;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.internal.utils.*;
//
public class WorkManager implements IManager {
protected int currentOperationId;
// we use a Hashtable for the identifiers to avoid concurrency problems
protected Hashtable identifiers;
protected int nextId;
protected Workspace workspace;
protected WorkspaceLock workspaceLock;
protected Queue operations;
protected Thread currentOperationThread;
class Identifier {
int operationId = OPERATION_EMPTY;
int preparedOperations = 0;
int nestedOperations = 0;
// Indication for running auto build. It is computated based
// on the parameters passed to Workspace.endOperation().
boolean shouldBuild = false;
// Enables or disables a condition based on the shouldBuild field.
boolean avoidAutoBuild = false;
boolean operationCanceled = false;
}
public static final int OPERATION_NONE = -1;
public static final int OPERATION_EMPTY = 0;
public WorkManager(Workspace workspace) {
currentOperationId = OPERATION_NONE;
identifiers = new Hashtable(10);
nextId = 0;
this.workspace = workspace;
operations = new Queue();
}
/**
* Returns null if acquired and a Semaphore object otherwise.
*/
public synchronized Semaphore acquire() {
if (isCurrentOperation())
return null;
if (currentOperationId == OPERATION_NONE && operations.isEmpty()) {
updateCurrentOperation(getOperationId());
return null;
}
return enqueue(new Semaphore(Thread.currentThread()));
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public void avoidAutoBuild() {
getIdentifier(currentOperationThread).avoidAutoBuild = true;
}
/**
* An operation calls this method and it only returns when the operation
* is free to run.
*/
public void checkIn() throws CoreException {
try {
boolean acquired = false;
while (!acquired) {
try {
acquired = getWorkspaceLock().acquire();
+ //above call should block, but sleep just in case it doesn't behave
+ Thread.sleep(50);
} catch (InterruptedException e) {
}
}
} finally {
incrementPreparedOperations();
}
}
/**
* Inform that an operation has finished.
*/
public synchronized void checkOut() throws CoreException {
decrementPreparedOperations();
rebalanceNestedOperations();
// if this is a nested operation, just return
// and do not release the lock
if (getPreparedOperationDepth() > 0)
return;
getWorkspaceLock().release();
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
private void decrementPreparedOperations() {
getIdentifier(currentOperationThread).preparedOperations--;
}
/**
* If there is another semaphore with the same runnable in the
* queue, the other is returned and the new one is not added.
*/
private synchronized Semaphore enqueue(Semaphore newSemaphore) {
Semaphore semaphore = (Semaphore) operations.get(newSemaphore);
if (semaphore == null) {
operations.add(newSemaphore);
return newSemaphore;
}
return semaphore;
}
public synchronized Thread getCurrentOperationThread() {
return currentOperationThread;
}
private Identifier getIdentifier(Thread key) {
Assert.isNotNull(key, "The thread should never be null.");//$NON-NLS-1$
Identifier identifier = (Identifier) identifiers.get(key);
if (identifier == null) {
identifier = getNewIdentifier();
identifiers.put(key, identifier);
}
return identifier;
}
private Identifier getNewIdentifier() {
Identifier identifier = new Identifier();
identifier.operationId = getNextOperationId();
return identifier;
}
private int getNextOperationId() {
return ++nextId;
}
private int getOperationId() {
return getIdentifier(Thread.currentThread()).operationId;
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public int getPreparedOperationDepth() {
return getIdentifier(currentOperationThread).preparedOperations;
}
private WorkspaceLock getWorkspaceLock() throws CoreException {
if (workspaceLock == null)
workspaceLock = workspaceLock = new WorkspaceLock(workspace);
return workspaceLock;
}
/**
* Returns true if the nested operation depth is the same
* as the prepared operation depth, and false otherwise.
*
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
boolean isBalanced() {
Identifier identifier = getIdentifier(currentOperationThread);
return identifier.nestedOperations == identifier.preparedOperations;
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
void incrementNestedOperations() {
getIdentifier(currentOperationThread).nestedOperations++;
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
private void incrementPreparedOperations() {
getIdentifier(currentOperationThread).preparedOperations++;
}
/**
* This method is synchronized with checkIn() and checkOut() that use blocks
* like synchronized (this) { ... }.
*/
public synchronized boolean isCurrentOperation() {
return currentOperationId == getOperationId();
}
public synchronized boolean isNextOperation(Runnable runnable) {
Semaphore next = (Semaphore) operations.peek();
return (next != null) && (next.getRunnable() == runnable);
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public void operationCanceled() {
getIdentifier(currentOperationThread).operationCanceled = true;
}
/**
* Used to make things stable again after an operation has failed between
* a workspace.prepareOperation() and workspace.beginOperation().
*
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public void rebalanceNestedOperations() {
Identifier identifier = getIdentifier(currentOperationThread);
identifier.nestedOperations = identifier.preparedOperations;
}
public synchronized void release() {
resetOperationId();
Semaphore next = (Semaphore) operations.peek();
updateCurrentOperation(OPERATION_NONE);
if (next != null)
next.release();
}
private void resetOperationId() {
// ensure the operation cache on this thread is null
identifiers.remove(currentOperationThread);
}
/**
* This method can only be safely called from inside a workspace operation.
* Should NOT be called from outside a prepareOperation/endOperation block.
*/
public void setBuild(boolean build) {
Identifier identifier = getIdentifier(currentOperationThread);
if (identifier.preparedOperations == identifier.nestedOperations)
identifier.shouldBuild = (identifier.shouldBuild || build);
}
public void setWorkspaceLock(WorkspaceLock lock) {
//if (workspaceLock != null)
//return;
Assert.isNotNull(lock);
workspaceLock = lock;
}
/**
* This method can only be safely called from inside a workspace operation.
* Should NOT be called from outside a prepareOperation/endOperation block.
*/
public boolean shouldBuild() {
Identifier identifier = getIdentifier(currentOperationThread);
if (!identifier.avoidAutoBuild && identifier.shouldBuild) {
if (identifier.operationCanceled)
return Policy.buildOnCancel;
return true;
}
return false;
}
public void shutdown(IProgressMonitor monitor) {
currentOperationId = OPERATION_NONE;
identifiers = null;
nextId = 0;
}
public void startup(IProgressMonitor monitor) {
}
public synchronized void updateCurrentOperation() {
operations.remove();
updateCurrentOperation(getOperationId());
}
private void updateCurrentOperation(int newID) {
currentOperationId = newID;
if (newID == OPERATION_NONE)
currentOperationThread = null;
else
currentOperationThread = Thread.currentThread();
}
public boolean isTreeLocked() {
return workspace.isTreeLocked();
}
}
| true | true | public void checkIn() throws CoreException {
try {
boolean acquired = false;
while (!acquired) {
try {
acquired = getWorkspaceLock().acquire();
} catch (InterruptedException e) {
}
}
} finally {
incrementPreparedOperations();
}
}
| public void checkIn() throws CoreException {
try {
boolean acquired = false;
while (!acquired) {
try {
acquired = getWorkspaceLock().acquire();
//above call should block, but sleep just in case it doesn't behave
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
} finally {
incrementPreparedOperations();
}
}
|
diff --git a/src/main/java/org/apache/commons/digester3/binder/LinkedRuleBuilder.java b/src/main/java/org/apache/commons/digester3/binder/LinkedRuleBuilder.java
index 0ed07195..d915b570 100644
--- a/src/main/java/org/apache/commons/digester3/binder/LinkedRuleBuilder.java
+++ b/src/main/java/org/apache/commons/digester3/binder/LinkedRuleBuilder.java
@@ -1,360 +1,361 @@
package org.apache.commons.digester3.binder;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.digester3.Rule;
/**
* Builder invoked to bind one or more rules to a pattern.
*
* @since 3.0
*/
public final class LinkedRuleBuilder
{
private final RulesBinder mainBinder;
private final FromBinderRuleSet fromBinderRuleSet;
private final ClassLoader classLoader;
private final String keyPattern;
private String namespaceURI;
LinkedRuleBuilder( final RulesBinder mainBinder, final FromBinderRuleSet fromBinderRuleSet,
final ClassLoader classLoader, final String keyPattern )
{
this.mainBinder = mainBinder;
this.fromBinderRuleSet = fromBinderRuleSet;
this.classLoader = classLoader;
this.keyPattern = keyPattern;
}
/**
* Construct rule that automatically sets a property from the body text, taking the property
* name the same as the current element.
*
* @return a new {@link BeanPropertySetterBuilder} instance.
*/
public BeanPropertySetterBuilder setBeanProperty()
{
return addProvider( new BeanPropertySetterBuilder( this.keyPattern,
this.namespaceURI,
this.mainBinder,
this ) );
}
/**
* Calls a method on an object on the stack (normally the top/parent object), passing arguments collected from
* subsequent {@link #callParam(int)} rule or from the body of this element.
*
* @param methodName Method name of the parent object to call
* @return a new {@link CallMethodBuilder} instance.
*/
public CallMethodBuilder callMethod( String methodName )
{
if ( methodName == null || methodName.length() == 0 )
{
mainBinder.addError( "{ forPattern( \"%s\" ).callMethod( String ) } empty 'methodName' not allowed",
keyPattern );
}
return this.addProvider( new CallMethodBuilder( keyPattern, namespaceURI, mainBinder, this, methodName,
classLoader ) );
}
/**
* Saves a parameter for use by a surrounding {@link #callMethod(String)}.
*
* @return a new {@link CallParamBuilder} instance.
*/
public CallParamBuilder callParam()
{
return this.addProvider( new CallParamBuilder( keyPattern, namespaceURI, mainBinder, this ) );
}
/**
* Construct a "call parameter" rule that will save the body text of this element as the parameter value.
*
* @return a new {@link PathCallParamBuilder} instance.
*/
public PathCallParamBuilder callParamPath()
{
return addProvider( new PathCallParamBuilder( keyPattern, namespaceURI, mainBinder, this ) );
}
/**
* Uses an {@link ObjectCreationFactory} to create a new object which it pushes onto the object stack.
*
* When the element is complete, the object will be popped.
*
* @return a new {@link FactoryCreateBuilder} instance.
*/
public FactoryCreateBuilder factoryCreate()
{
return addProvider( new FactoryCreateBuilder( keyPattern, namespaceURI, mainBinder, this, classLoader ) );
}
/**
* Construct an object.
*
* @return a new {@link ObjectCreateBuilder} instance.
*/
public ObjectCreateBuilder createObject()
{
return addProvider( new ObjectCreateBuilder( keyPattern, namespaceURI, mainBinder, this, classLoader ) );
}
/**
* Saves a parameter for use by a surrounding {@link #callMethod(String)}.
*
* @param <T> The parameter type to pass along
* @param paramObj The parameter to pass along
* @return a new {@link ObjectParamBuilder} instance.
*/
public <T> ObjectParamBuilder<T> objectParam( /* @Nullable */T paramObj )
{
return addProvider( new ObjectParamBuilder<T>( keyPattern, namespaceURI, mainBinder, this, paramObj ) );
}
/**
* Sets properties on the object at the top of the stack,
* based on child elements with names matching properties on that object.
*
* @return a new {@link NestedPropertiesBuilder} instance.
*/
public NestedPropertiesBuilder setNestedProperties()
{
// that would be useful when adding rules via automatically generated rules binding (such annotations)
NestedPropertiesBuilder nestedPropertiesBuilder =
fromBinderRuleSet.getProvider( keyPattern, namespaceURI, NestedPropertiesBuilder.class );
if ( nestedPropertiesBuilder != null )
{
return nestedPropertiesBuilder;
}
return addProvider( new NestedPropertiesBuilder( keyPattern, namespaceURI, mainBinder, this ) );
}
/**
* Calls a method on the (top-1) (parent) object, passing the top object (child) as an argument,
* commonly used to establish parent-child relationships.
*
* @param methodName Method name of the parent method to call
* @return a new {@link SetNextBuilder} instance.
*/
public SetNextBuilder setNext( String methodName )
{
if ( methodName == null || methodName.length() == 0 )
{
mainBinder.addError( "{ forPattern( \"%s\" ).setNext( String ) } empty 'methodName' not allowed",
keyPattern );
}
return this.addProvider( new SetNextBuilder( keyPattern, namespaceURI, mainBinder, this, methodName,
classLoader ) );
}
/**
* Sets properties on the object at the top of the stack, based on attributes with corresponding names.
*
* @return a new {@link SetPropertiesBuilder} instance.
*/
public SetPropertiesBuilder setProperties()
{
// that would be useful when adding rules via automatically generated rules binding (such annotations)
SetPropertiesBuilder setPropertiesBuilder =
fromBinderRuleSet.getProvider( keyPattern, namespaceURI, SetPropertiesBuilder.class );
if ( setPropertiesBuilder != null )
{
return setPropertiesBuilder;
}
return addProvider( new SetPropertiesBuilder( keyPattern, namespaceURI, mainBinder, this ) );
}
/**
* Sets an individual property on the object at the top of the stack, based on attributes with specified names.
*
* @param attributePropertyName Name of the attribute that will contain the name of the property to be set
* @return a new {@link SetPropertyBuilder} instance.
*/
public SetPropertyBuilder setProperty( String attributePropertyName )
{
if ( attributePropertyName == null || attributePropertyName.length() == 0 )
{
- mainBinder.addError( "{ forPattern( \"%s\" ).setProperty( String )} empty 'attributePropertyName' not allowed",
- keyPattern );
+ mainBinder
+ .addError( "{ forPattern( \"%s\" ).setProperty( String ) } empty 'attributePropertyName' not allowed",
+ keyPattern );
}
return addProvider( new SetPropertyBuilder( keyPattern,
namespaceURI,
mainBinder,
this,
attributePropertyName ) );
}
/**
* Calls a method on the root object on the stack, passing the top object (child) as an argument.
*
* @param methodName Method name of the parent method to call
* @return a new {@link SetRootBuilder} instance.
*/
public SetRootBuilder setRoot( String methodName )
{
if ( methodName == null || methodName.length() == 0 )
{
mainBinder.addError( "{ forPattern( \"%s\" ).setRoot( String ) } empty 'methodName' not allowed",
keyPattern );
}
return addProvider( new SetRootBuilder( keyPattern, namespaceURI, mainBinder, this, methodName, classLoader ) );
}
/**
* Calls a "set top" method on the top (child) object, passing the (top-1) (parent) object as an argument.
*
* @param methodName Method name of the "set parent" method to call
* @return a new {@link SetTopBuilder} instance.
*/
public SetTopBuilder setTop( String methodName )
{
if ( methodName == null || methodName.length() == 0 )
{
mainBinder.addError( "{ forPattern( \"%s\" ).setTop( String ) } empty 'methodName' not allowed",
keyPattern );
}
return addProvider( new SetTopBuilder( keyPattern, namespaceURI, mainBinder, this, methodName, classLoader ) );
}
/**
* A Digester rule which allows the user to pre-declare a class which is to
* be referenced later at a plugin point by a PluginCreateRule.
*
* NOTE: when using this rule, make sure {@link org.apache.commons.digester3.Digester} instances
* will be created using {@link org.apache.commons.digester3.plugins.PluginRules} rules strategy.
*
* @return a new {@link PluginDeclarationRuleBuilder} instance.
*/
public PluginDeclarationRuleBuilder declarePlugin()
{
return addProvider( new PluginDeclarationRuleBuilder( keyPattern, namespaceURI, mainBinder, this ) );
}
/**
* A Digester rule which allows the user to declare a plugin.
*
* NOTE: when using this rule, make sure {@link org.apache.commons.digester3.Digester} instances
* will be created using {@link org.apache.commons.digester3.plugins.PluginRules} rules strategy.
*
* @return a new {@link PluginDeclarationRuleBuilder} instance.
*/
public PluginCreateRuleBuilder createPlugin()
{
return addProvider( new PluginCreateRuleBuilder( keyPattern, namespaceURI, mainBinder, this ) );
}
/**
* A rule implementation that creates a DOM Node containing the XML at the element that matched the rule.
*
* @return a new {@link NodeCreateRuleProvider} instance.
*/
public NodeCreateRuleProvider createNode()
{
return addProvider( new NodeCreateRuleProvider( keyPattern, namespaceURI, mainBinder, this ) );
}
/**
* Add a custom user rule in the specified pattern.
*
* <b>WARNING</b> keep away from this method as much as you can, since there's the risk
* same input {@link Rule} instance is plugged to more than one Digester;
* use {@link #addRuleCreatedBy(RuleProvider)} instead!!!
*
* @see #addRuleCreatedBy(RuleProvider)
* @see Rule#setDigester(org.apache.commons.digester3.Digester)
* @param <R> The rule type
* @param rule The custom user rule
* @return a new {@link ByRuleBuilder} instance.
*/
public <R extends Rule> ByRuleBuilder<R> addRule( R rule )
{
if ( rule == null )
{
mainBinder.addError( "{ forPattern( \"%s\" ).addRule( R ) } NULL rule not valid", keyPattern );
}
return this.addProvider( new ByRuleBuilder<R>( keyPattern, namespaceURI, mainBinder, this, rule ) );
}
/**
* Add a custom user rule in the specified pattern built by the given provider.
*
* @param <R> The rule type
* @param provider The rule provider
* @return a new {@link ByRuleProviderBuilder} instance.
*/
public <R extends Rule> ByRuleProviderBuilder<R> addRuleCreatedBy( RuleProvider<R> provider )
{
if ( provider == null )
{
mainBinder.addError( "{ forPattern( \"%s\" ).addRuleCreatedBy() } null rule provider not valid",
keyPattern );
}
return addProvider( new ByRuleProviderBuilder<R>( keyPattern, namespaceURI, mainBinder, this, provider ) );
}
/**
* Sets the namespace URI for the current rule pattern.
*
* @param namespaceURI the namespace URI associated to the rule pattern.
* @return this {@link LinkedRuleBuilder} instance
*/
public LinkedRuleBuilder withNamespaceURI( /* @Nullable */String namespaceURI )
{
if ( namespaceURI == null || namespaceURI.length() > 0 )
{
this.namespaceURI = namespaceURI;
}
else
{
// ignore empty namespaces, null is better
this.namespaceURI = null;
}
return this;
}
/**
* Add a provider in the data structure where storing the providers binding.
*
* @param <R> The rule will be created by the given provider
* @param provider The provider has to be stored in the data structure
* @return The provider itself has to be stored in the data structure
*/
private <R extends Rule, RB extends AbstractBackToLinkedRuleBuilder<R>> RB addProvider( RB provider )
{
fromBinderRuleSet.registerProvider( provider );
return provider;
}
}
| true | true | public SetPropertyBuilder setProperty( String attributePropertyName )
{
if ( attributePropertyName == null || attributePropertyName.length() == 0 )
{
mainBinder.addError( "{ forPattern( \"%s\" ).setProperty( String )} empty 'attributePropertyName' not allowed",
keyPattern );
}
return addProvider( new SetPropertyBuilder( keyPattern,
namespaceURI,
mainBinder,
this,
attributePropertyName ) );
}
| public SetPropertyBuilder setProperty( String attributePropertyName )
{
if ( attributePropertyName == null || attributePropertyName.length() == 0 )
{
mainBinder
.addError( "{ forPattern( \"%s\" ).setProperty( String ) } empty 'attributePropertyName' not allowed",
keyPattern );
}
return addProvider( new SetPropertyBuilder( keyPattern,
namespaceURI,
mainBinder,
this,
attributePropertyName ) );
}
|
diff --git a/src/java/fedora/server/utilities/ServerUtility.java b/src/java/fedora/server/utilities/ServerUtility.java
index 981824401..2d24c068c 100644
--- a/src/java/fedora/server/utilities/ServerUtility.java
+++ b/src/java/fedora/server/utilities/ServerUtility.java
@@ -1,183 +1,194 @@
package fedora.server.utilities;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import fedora.common.Constants;
import fedora.common.http.WebClient;
import fedora.server.config.ServerConfiguration;
import fedora.server.config.ServerConfigurationParser;
import fedora.server.errors.GeneralException;
public class ServerUtility {
/** Logger for this class. */
private static final Logger LOG = Logger.getLogger(
ServerUtility.class.getName());
public static final String HTTP = "http";
public static final String HTTPS = "https";
public static final String FEDORA_SERVER_HOST = "fedoraServerHost";
public static final String FEDORA_SERVER_PORT = "fedoraServerPort";
public static final String FEDORA_REDIRECT_PORT = "fedoraRedirectPort";
private static ServerConfiguration CONFIG;
static {
String fedoraHome = Constants.FEDORA_HOME;
if (fedoraHome == null) {
LOG.warn("FEDORA_HOME not set; unable to initialize");
} else {
File fcfgFile = new File(fedoraHome, "server/config/fedora.fcfg");
try {
CONFIG = new ServerConfigurationParser(
new FileInputStream(fcfgFile)).parse();
} catch (IOException e) {
LOG.warn("Unable to read server configuration from "
+ fcfgFile.getPath(), e);
}
}
}
/**
* Tell whether the server is running by pinging it as a client.
*/
public static boolean pingServer(String protocol, String user,
String pass) {
try {
getServerResponse(protocol, user, pass, "/describe");
return true;
} catch (Exception e) {
LOG.debug("Assuming the server isn't running because "
+ "describe request failed", e);
return false;
}
}
/**
* Get the baseURL of the Fedora server from the host and port configured.
*
* It will look like http://localhost:8080/fedora
*/
public static String getBaseURL(String protocol) {
String port;
if (protocol.equals("http")) {
port = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue();
} else if (protocol.equals("https")) {
port = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue();
} else {
throw new RuntimeException("Unrecogonized protocol: " + protocol);
}
return protocol + "://"
+ CONFIG.getParameter(FEDORA_SERVER_HOST).getValue() + ":"
+ port + "/fedora";
}
/**
* Signals for the server to reload its policies.
*/
public static void reloadPolicies(String protocol, String user,
String pass)
throws IOException {
getServerResponse(protocol, user, pass,
"/management/control?action=reloadPolicies");
}
/**
* Hits the given Fedora Server URL and returns the response
* as a String. Throws an IOException if the response code is not 200(OK).
*/
private static String getServerResponse(String protocol, String user,
String pass, String path)
throws IOException {
String url = getBaseURL(protocol) + path;
LOG.info("Getting URL: " + url);
UsernamePasswordCredentials creds =
new UsernamePasswordCredentials(user, pass);
return new WebClient().getResponseAsString(url, true, creds);
}
/**
* Tell whether the given URL appears to be referring to somewhere
* within the Fedora webapp.
*/
public static boolean isURLFedoraServer(String url) {
String fedoraServerHost = CONFIG.getParameter(FEDORA_SERVER_HOST).getValue();
String fedoraServerPort = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue();
String fedoraServerRedirectPort = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue();
// Check for URLs that are callbacks to the Fedora server
if (url.startsWith("http://"+fedoraServerHost+":"+fedoraServerPort+"/fedora/") ||
url.startsWith("http://"+fedoraServerHost+"/fedora/") ||
url.startsWith("https://"+fedoraServerHost+":"+fedoraServerRedirectPort+"/fedora/") ||
- url.startsWith("https://"+fedoraServerHost+"/fedora/") ) {
+ url.startsWith("https://"+fedoraServerHost+"/fedora/")
+ // This is an ugly hack to fix backend security bug when authentication enabled
+ // for api-a. The getDS target is intentionally unsecure to allow backend services
+ // that cannot handle authentication or ssl a callback channel. If not excluded
+ // here, it can result in the incorrect assignment of fedoraRole=fedoraInternalCall-1
+ // elsewhere in the code to be associated with the getDS target. Additional
+ // refactoring is needed to eliminate the need for this hack.
+ &&
+ !(url.startsWith("http://"+fedoraServerHost+":"+fedoraServerPort+"/fedora/getDS?") ||
+ url.startsWith("http://"+fedoraServerHost+"/fedora/getDS?") ||
+ url.startsWith("https://"+fedoraServerHost+":"+fedoraServerRedirectPort+"/fedora/getDS?") ||
+ url.startsWith("https://"+fedoraServerHost+"/fedora/getDS?")) ) {
LOG.debug("URL was Fedora-to-Fedora callback: "+url);
return true;
} else {
LOG.debug("URL was Non-Fedora callback: "+url);
return false;
}
}
/**
* Initializes logging to use Log4J and to send WARN messages to STDOUT for
* command-line use.
*/
private static void initLogging() {
// send all log4j output to STDOUT and configure levels
Properties props = new Properties();
props.setProperty("log4j.appender.STDOUT",
"org.apache.log4j.ConsoleAppender");
props.setProperty("log4j.appender.STDOUT.layout",
"org.apache.log4j.PatternLayout");
props.setProperty("log4j.appender.STDOUT.layout.ConversionPattern",
"%p: %m%n");
props.setProperty("log4j.rootLogger", "WARN, STDOUT");
PropertyConfigurator.configure(props);
// tell commons-logging to use Log4J
final String pfx = "org.apache.commons.logging.";
System.setProperty(pfx + "LogFactory", pfx + "impl.Log4jFactory");
System.setProperty(pfx + "Log", pfx + "impl.Log4JLogger");
}
/**
* Command-line entry point to reload policies.
*
* Takes 3 args: protocol user pass
*/
public static void main(String[] args) {
initLogging();
if (args.length == 3) {
try {
reloadPolicies(args[0], args[1], args[2]);
System.out.println("SUCCESS: Policies have been reloaded");
System.exit(0);
} catch (Throwable th) {
th.printStackTrace();
System.err.println("ERROR: Reloading policies failed; see above");
System.exit(1);
}
} else {
System.err.println("ERROR: Three arguments required: "
+ "http|https username password");
System.exit(1);
}
}
}
| true | true | public static boolean isURLFedoraServer(String url) {
String fedoraServerHost = CONFIG.getParameter(FEDORA_SERVER_HOST).getValue();
String fedoraServerPort = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue();
String fedoraServerRedirectPort = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue();
// Check for URLs that are callbacks to the Fedora server
if (url.startsWith("http://"+fedoraServerHost+":"+fedoraServerPort+"/fedora/") ||
url.startsWith("http://"+fedoraServerHost+"/fedora/") ||
url.startsWith("https://"+fedoraServerHost+":"+fedoraServerRedirectPort+"/fedora/") ||
url.startsWith("https://"+fedoraServerHost+"/fedora/") ) {
LOG.debug("URL was Fedora-to-Fedora callback: "+url);
return true;
} else {
LOG.debug("URL was Non-Fedora callback: "+url);
return false;
}
}
| public static boolean isURLFedoraServer(String url) {
String fedoraServerHost = CONFIG.getParameter(FEDORA_SERVER_HOST).getValue();
String fedoraServerPort = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue();
String fedoraServerRedirectPort = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue();
// Check for URLs that are callbacks to the Fedora server
if (url.startsWith("http://"+fedoraServerHost+":"+fedoraServerPort+"/fedora/") ||
url.startsWith("http://"+fedoraServerHost+"/fedora/") ||
url.startsWith("https://"+fedoraServerHost+":"+fedoraServerRedirectPort+"/fedora/") ||
url.startsWith("https://"+fedoraServerHost+"/fedora/")
// This is an ugly hack to fix backend security bug when authentication enabled
// for api-a. The getDS target is intentionally unsecure to allow backend services
// that cannot handle authentication or ssl a callback channel. If not excluded
// here, it can result in the incorrect assignment of fedoraRole=fedoraInternalCall-1
// elsewhere in the code to be associated with the getDS target. Additional
// refactoring is needed to eliminate the need for this hack.
&&
!(url.startsWith("http://"+fedoraServerHost+":"+fedoraServerPort+"/fedora/getDS?") ||
url.startsWith("http://"+fedoraServerHost+"/fedora/getDS?") ||
url.startsWith("https://"+fedoraServerHost+":"+fedoraServerRedirectPort+"/fedora/getDS?") ||
url.startsWith("https://"+fedoraServerHost+"/fedora/getDS?")) ) {
LOG.debug("URL was Fedora-to-Fedora callback: "+url);
return true;
} else {
LOG.debug("URL was Non-Fedora callback: "+url);
return false;
}
}
|
diff --git a/hale/eu.esdihumboldt.hale.gmlwriter/src/eu/esdihumboldt/hale/gmlwriter/impl/internal/geometry/writers/AbstractGeometryWriter.java b/hale/eu.esdihumboldt.hale.gmlwriter/src/eu/esdihumboldt/hale/gmlwriter/impl/internal/geometry/writers/AbstractGeometryWriter.java
index 2fb932ed0..e0758c49f 100644
--- a/hale/eu.esdihumboldt.hale.gmlwriter/src/eu/esdihumboldt/hale/gmlwriter/impl/internal/geometry/writers/AbstractGeometryWriter.java
+++ b/hale/eu.esdihumboldt.hale.gmlwriter/src/eu/esdihumboldt/hale/gmlwriter/impl/internal/geometry/writers/AbstractGeometryWriter.java
@@ -1,480 +1,481 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2010.
*/
package eu.esdihumboldt.hale.gmlwriter.impl.internal.geometry.writers;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.geotools.feature.NameImpl;
import org.opengis.feature.type.Name;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import de.cs3d.util.logging.ALogger;
import de.cs3d.util.logging.ALoggerFactory;
import eu.esdihumboldt.hale.gmlwriter.impl.internal.GmlWriterUtil;
import eu.esdihumboldt.hale.gmlwriter.impl.internal.StreamGmlWriter;
import eu.esdihumboldt.hale.gmlwriter.impl.internal.geometry.DefinitionPath;
import eu.esdihumboldt.hale.gmlwriter.impl.internal.geometry.GeometryWriter;
import eu.esdihumboldt.hale.gmlwriter.impl.internal.geometry.PathElement;
import eu.esdihumboldt.hale.schemaprovider.model.AttributeDefinition;
import eu.esdihumboldt.hale.schemaprovider.model.TypeDefinition;
/**
* Abstract geometry writer implementation
*
* @author Simon Templer
* @partner 01 / Fraunhofer Institute for Computer Graphics Research
* @version $Id$
* @param <T> the geometry type
*/
public abstract class AbstractGeometryWriter<T extends Geometry> implements GeometryWriter<T> {
/**
* Represents a descent in the document, must be used to end elements
* started with
*/
public static class Descent {
private final XMLStreamWriter writer;
private final DefinitionPath path;
/**
* Constructor
*
* @param writer the XMl stream writer
* @param path the descent path
*/
private Descent(XMLStreamWriter writer, DefinitionPath path) {
super();
this.path = path;
this.writer = writer;
}
/**
* @return the path
*/
public DefinitionPath getPath() {
return path;
}
/**
* Close the descent
*
* @throws XMLStreamException if an error occurs closing the elements
*/
public void close() throws XMLStreamException {
if (path.isEmpty()) {
return;
}
for (int i = 0; i < path.getSteps().size(); i++) {
writer.writeEndElement();
}
}
}
private static final ALogger log = ALoggerFactory.getLogger(AbstractGeometryWriter.class);
private final Class<T> geometryType;
private final Set<Name> compatibleTypes = new HashSet<Name>();
private final Set<Pattern> basePatterns = new HashSet<Pattern>();
private final Set<Pattern> verifyPatterns = new HashSet<Pattern>();
/**
* The attribute type names supported for writing coordinates with
* {@link #writeCoordinates(XMLStreamWriter, Coordinate[], TypeDefinition, String)} or
* {@link #descendAndWriteCoordinates(XMLStreamWriter, Pattern, Coordinate[], TypeDefinition, String)}.
*
* Use for validating end-points.
*/
private final static Set<String> SUPPORTED_COORDINATES_TYPES = Collections.unmodifiableSet(
new HashSet<String>(Arrays.asList("DirectPositionType",
"DirectPositionListType", "CoordinatesType")));
/**
* Constructor
*
* @param geometryType the geometry type
*/
public AbstractGeometryWriter(Class<T> geometryType) {
super();
this.geometryType = geometryType;
}
/**
* @see GeometryWriter#getCompatibleTypes()
*/
@Override
public Set<Name> getCompatibleTypes() {
return Collections.unmodifiableSet(compatibleTypes);
}
/**
* Add a compatible type. A <code>null</code> namespace references the GML
* namespace.
*
* @param typeName the type name
*/
public void addCompatibleType(Name typeName) {
compatibleTypes.add(typeName);
}
/**
* @see GeometryWriter#getGeometryType()
*/
@Override
public Class<T> getGeometryType() {
return geometryType;
}
/**
* Add a base pattern. When matching the path the pattern path is appended
* to the base path.
*
* @param pattern the pattern string
* @see Pattern#parse(String)
*/
public void addBasePattern(String pattern) {
Pattern p = Pattern.parse(pattern);
if (p.isValid()) {
basePatterns.add(p);
}
else {
log.warn("Ignoring invalid pattern: " + pattern);
}
}
/**
* Add a verification pattern. If a match for a base pattern is found the
* verification patterns will be used to verify the structure. For a path to
* be accepted, all verification patterns must match and the resulting
* end-points of the verification patterns must be valid.
* @see #verifyEndPoint(TypeDefinition)
*
* @param pattern the pattern string
* @see Pattern#parse(String)
*/
public void addVerificationPattern(String pattern) {
Pattern p = Pattern.parse(pattern);
if (p.isValid()) {
verifyPatterns.add(p);
}
else {
log.warn("Ignoring invalid pattern: " + pattern);
}
}
/**
* Add a verification pattern. If a match for a base pattern is found the
* verification patterns will be used to verify the structure. For a path to
* be accepted, all verification patterns must match and the resulting
* end-points of the verification patterns must be valid.
* @see #verifyEndPoint(TypeDefinition)
*
* @param pattern the pattern
* @see Pattern#parse(String)
*/
public void addVerificationPattern(Pattern pattern) {
if (pattern.isValid()) {
verifyPatterns.add(pattern);
}
else {
log.warn("Ignoring invalid pattern: " + pattern);
}
}
/**
* Verify the verification end point. After reaching the end-point of a
* verification pattern this method is called with the {@link TypeDefinition}
* of the end-point to assure the needed structure is present (e.g. a
* DirectPositionListType element). If no verification pattern is present
* the end-point of the matched base pattern will be verified.
* The default implementation checks for properties with any of the types
* supported for writing coordinates.
* @see #SUPPORTED_COORDINATES_TYPES
*
* @param endPoint the end-point type definition
*
* @return if the end-point is valid for writing the geometry
*/
protected boolean verifyEndPoint(TypeDefinition endPoint) {
for (AttributeDefinition attribute : endPoint.getAttributes()) {
if (SUPPORTED_COORDINATES_TYPES.contains(attribute.getTypeName().getLocalPart())) {
// a valid property was found
return true;
}
}
return false;
}
/**
* @see GeometryWriter#match(TypeDefinition, DefinitionPath, String)
*/
@Override
public DefinitionPath match(TypeDefinition type, DefinitionPath basePath,
String gmlNs) {
// try to match each base pattern
for (Pattern pattern : basePatterns) {
DefinitionPath path = pattern.match(type, basePath, gmlNs);
if (path != null) {
// verification patterns
if (verifyPatterns != null && !verifyPatterns.isEmpty()) {
for (Pattern verPattern : verifyPatterns) {
DefinitionPath endPoint = verPattern.match(path.getLastType(), new DefinitionPath(path), gmlNs);
if (endPoint != null) {
// verify end-point
boolean ok = verifyEndPoint(endPoint.getLastType());
if (!ok) {
// all end-points must be valid
return null;
}
}
else {
// all verification patterns must match
return null;
}
}
}
else {
// no verify patterns -> check base pattern end-point
boolean ok = verifyEndPoint(path.getLastType());
if (!ok) {
return null;
}
}
/*
* now either all verification patterns matched and the
* end-points were valid, or no verification patterns were
* specified and the base pattern end-point was valid
*/
return path;
}
}
return null;
}
/**
* Write coordinates into a posList or coordinates property
*
* @param writer the XML stream writer
* @param descendPattern the pattern to descend
* @param coordinates the coordinates to write
* @param elementType the type of the encompassing element
* @param gmlNs the GML namespace
* @throws XMLStreamException if an error occurs writing the coordinates
*/
protected static void descendAndWriteCoordinates(XMLStreamWriter writer,
Pattern descendPattern, Coordinate[] coordinates,
TypeDefinition elementType, String gmlNs) throws XMLStreamException {
Descent descent = descend(writer, descendPattern, elementType, gmlNs);
// write geometry
writeCoordinates(writer, coordinates, descent.getPath().getLastType(), gmlNs);
descent.close();
}
/**
* Descend the given pattern
*
* @param writer the XML stream writer
* @param descendPattern the pattern to descend
* @param elementType the type of the encompassing element
* @param gmlNs the GML namespace
* @return the descent that was opened, it must be closed to close the
* opened elements
* @throws XMLStreamException if an error occurs writing the coordinates
*/
protected static Descent descend(XMLStreamWriter writer,
Pattern descendPattern, TypeDefinition elementType,
String gmlNs) throws XMLStreamException {
DefinitionPath path = descendPattern.match(elementType, new DefinitionPath(elementType), gmlNs);
if (path.isEmpty()) {
return new Descent(writer, path);
}
Name name = GmlWriterUtil.getElementName(path.getLastType()); //XXX the element name used may be wrong, is this an issue?
for (PathElement step : path.getSteps()) {
// start elements
name = step.getName();
writer.writeStartElement(name.getNamespaceURI(), name.getLocalPart());
// write eventual required ID
StreamGmlWriter.writeRequiredID(writer, step.getType(), null, false);
}
return new Descent(writer, path);
}
/**
* Write coordinates into a pos, posList or coordinates property
*
* @param writer the XML stream writer
* @param coordinates the coordinates to write
* @param elementType the type of the encompassing element
* @param gmlNs the GML namespace
* @throws XMLStreamException if an error occurs writing the coordinates
*/
protected static void writeCoordinates(XMLStreamWriter writer,
Coordinate[] coordinates, TypeDefinition elementType,
String gmlNs) throws XMLStreamException {
if (coordinates.length > 1) {
if (writeList(writer, coordinates, elementType, gmlNs)) {
return;
}
}
if (writePos(writer, coordinates, elementType, gmlNs)) {
return;
}
if (coordinates.length <= 1) {
if (writeList(writer, coordinates, elementType, gmlNs)) {
return;
}
}
log.error("Unable to write coordinates to element of type " +
elementType.getDisplayName());
}
/**
* Write coordinates into a pos property
*
* @param writer the XML stream writer
* @param coordinates the coordinates to write
* @param elementType the type of the encompassing element
* @param gmlNs the GML namespace
* @return if writing the coordinates was successful
* @throws XMLStreamException if an error occurs writing the coordinates
*/
private static boolean writePos(XMLStreamWriter writer,
Coordinate[] coordinates, TypeDefinition elementType, String gmlNs) throws XMLStreamException {
AttributeDefinition posAttribute = null;
// check for DirectPositionType
for (AttributeDefinition att : elementType.getAttributes()) {
if (att.getTypeName().equals(new NameImpl(gmlNs, "DirectPositionType"))) {
posAttribute = att;
break;
}
}
//TODO support for CoordType
if (posAttribute != null) {
//TODO possibly write repeated positions
writer.writeStartElement(posAttribute.getNamespace(), posAttribute.getName());
// write coordinates separated by spaces
if (coordinates.length > 0) {
Coordinate coordinate = coordinates[0];
writer.writeCharacters(String.valueOf(coordinate.x));
writer.writeCharacters(" ");
writer.writeCharacters(String.valueOf(coordinate.y));
if (!Double.isNaN(coordinate.z)) {
writer.writeCharacters(" ");
writer.writeCharacters(String.valueOf(coordinate.z));
}
}
writer.writeEndElement();
return true;
}
else {
return false;
}
}
/**
* Write coordinates into a posList or coordinates property
*
* @param writer the XML stream writer
* @param coordinates the coordinates to write
* @param elementType the type of the encompassing element
* @param gmlNs the GML namespace
* @return if writing the coordinates was successful
* @throws XMLStreamException if an error occurs writing the coordinates
*/
private static boolean writeList(XMLStreamWriter writer,
Coordinate[] coordinates, TypeDefinition elementType, String gmlNs) throws XMLStreamException {
AttributeDefinition listAttribute = null;
String delimiter = " ";
+ String setDelimiter = " ";
// check for DirectPositionListType
for (AttributeDefinition att : elementType.getAttributes()) {
if (att.getTypeName().equals(new NameImpl(gmlNs, "DirectPositionListType"))) {
listAttribute = att;
break;
}
}
if (listAttribute == null) {
// check for CoordinatesType
for (AttributeDefinition att : elementType.getAttributes()) {
if (att.getTypeName().equals(new NameImpl(gmlNs, "CoordinatesType"))) {
listAttribute = att;
delimiter = ",";
break;
}
}
}
if (listAttribute != null) {
writer.writeStartElement(listAttribute.getNamespace(), listAttribute.getName());
boolean first = true;
// write coordinates separated by spaces
for (Coordinate coordinate : coordinates) {
if (first) {
first = false;
}
else {
- writer.writeCharacters(delimiter);
+ writer.writeCharacters(setDelimiter);
}
writer.writeCharacters(String.valueOf(coordinate.x));
writer.writeCharacters(delimiter);
writer.writeCharacters(String.valueOf(coordinate.y));
if (!Double.isNaN(coordinate.z)) {
writer.writeCharacters(delimiter);
writer.writeCharacters(String.valueOf(coordinate.z));
}
}
writer.writeEndElement();
return true;
}
else {
return false;
}
}
}
| false | true | private static boolean writeList(XMLStreamWriter writer,
Coordinate[] coordinates, TypeDefinition elementType, String gmlNs) throws XMLStreamException {
AttributeDefinition listAttribute = null;
String delimiter = " ";
// check for DirectPositionListType
for (AttributeDefinition att : elementType.getAttributes()) {
if (att.getTypeName().equals(new NameImpl(gmlNs, "DirectPositionListType"))) {
listAttribute = att;
break;
}
}
if (listAttribute == null) {
// check for CoordinatesType
for (AttributeDefinition att : elementType.getAttributes()) {
if (att.getTypeName().equals(new NameImpl(gmlNs, "CoordinatesType"))) {
listAttribute = att;
delimiter = ",";
break;
}
}
}
if (listAttribute != null) {
writer.writeStartElement(listAttribute.getNamespace(), listAttribute.getName());
boolean first = true;
// write coordinates separated by spaces
for (Coordinate coordinate : coordinates) {
if (first) {
first = false;
}
else {
writer.writeCharacters(delimiter);
}
writer.writeCharacters(String.valueOf(coordinate.x));
writer.writeCharacters(delimiter);
writer.writeCharacters(String.valueOf(coordinate.y));
if (!Double.isNaN(coordinate.z)) {
writer.writeCharacters(delimiter);
writer.writeCharacters(String.valueOf(coordinate.z));
}
}
writer.writeEndElement();
return true;
}
else {
return false;
}
}
| private static boolean writeList(XMLStreamWriter writer,
Coordinate[] coordinates, TypeDefinition elementType, String gmlNs) throws XMLStreamException {
AttributeDefinition listAttribute = null;
String delimiter = " ";
String setDelimiter = " ";
// check for DirectPositionListType
for (AttributeDefinition att : elementType.getAttributes()) {
if (att.getTypeName().equals(new NameImpl(gmlNs, "DirectPositionListType"))) {
listAttribute = att;
break;
}
}
if (listAttribute == null) {
// check for CoordinatesType
for (AttributeDefinition att : elementType.getAttributes()) {
if (att.getTypeName().equals(new NameImpl(gmlNs, "CoordinatesType"))) {
listAttribute = att;
delimiter = ",";
break;
}
}
}
if (listAttribute != null) {
writer.writeStartElement(listAttribute.getNamespace(), listAttribute.getName());
boolean first = true;
// write coordinates separated by spaces
for (Coordinate coordinate : coordinates) {
if (first) {
first = false;
}
else {
writer.writeCharacters(setDelimiter);
}
writer.writeCharacters(String.valueOf(coordinate.x));
writer.writeCharacters(delimiter);
writer.writeCharacters(String.valueOf(coordinate.y));
if (!Double.isNaN(coordinate.z)) {
writer.writeCharacters(delimiter);
writer.writeCharacters(String.valueOf(coordinate.z));
}
}
writer.writeEndElement();
return true;
}
else {
return false;
}
}
|
diff --git a/user/src/com/google/gwt/user/client/ui/impl/FocusImplStandard.java b/user/src/com/google/gwt/user/client/ui/impl/FocusImplStandard.java
index 74ca35515..be1d0b4de 100644
--- a/user/src/com/google/gwt/user/client/ui/impl/FocusImplStandard.java
+++ b/user/src/com/google/gwt/user/client/ui/impl/FocusImplStandard.java
@@ -1,95 +1,96 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.client.ui.impl;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.Element;
/**
* Implementation of {@link com.google.gwt.user.client.ui.impl.FocusImpl} that
* uses a hidden input element to serve as a 'proxy' for accesskeys, which are
* only supported on form elements in most browsers.
*/
public class FocusImplStandard extends FocusImpl {
/**
* Single focusHandler shared by all focusable.
*/
static JavaScriptObject focusHandler;
private static native Element createFocusable0(JavaScriptObject focusHandler) /*-{
// Divs are focusable in all browsers, but only IE supports the accessKey
// property on divs. We use the infamous 'hidden input' trick to add an
// accessKey to the focusable div. Note that the input is only used to
// capture focus when the accessKey is pressed. Focus is forwarded to the
// div immediately.
var div = $doc.createElement('div');
div.tabIndex = 0;
var input = $doc.createElement('input');
input.type = 'text';
input.tabIndex = -1;
+ input.setAttribute('role', 'presentation');
var style = input.style;
style.opacity = 0;
style.height = '1px';
style.width = '1px';
style.zIndex = -1;
style.overflow = 'hidden';
style.position = 'absolute';
// Note that we're using isolated lambda methods as the event listeners
// to avoid creating a memory leaks. (Lambdas here would create cycles
// involving the div and input). This also allows us to share a single
// set of handlers among every focusable item.
input.addEventListener('focus', focusHandler, false);
div.appendChild(input);
return div;
}-*/;
@Override
public Element createFocusable() {
return createFocusable0(ensureFocusHandler());
}
@Override
public native void setAccessKey(Element elem, char key) /*-{
elem.firstChild.accessKey = String.fromCharCode(key);
}-*/;
/**
* Use an isolated method call to create the handler to avoid creating memory
* leaks via handler-closures-element.
*/
private native JavaScriptObject createFocusHandler() /*-{
return function(evt) {
// This function is called directly as an event handler, so 'this' is
// set up by the browser to be the input on which the event is fired. We
// call focus() in a timeout or the element may be blurred when this event
// ends.
var div = this.parentNode;
if (div.onfocus) {
$wnd.setTimeout(function() {
div.focus();
}, 0);
}
};
}-*/;
private JavaScriptObject ensureFocusHandler() {
return focusHandler != null ? focusHandler : (focusHandler = createFocusHandler());
}
}
| true | true | private static native Element createFocusable0(JavaScriptObject focusHandler) /*-{
// Divs are focusable in all browsers, but only IE supports the accessKey
// property on divs. We use the infamous 'hidden input' trick to add an
// accessKey to the focusable div. Note that the input is only used to
// capture focus when the accessKey is pressed. Focus is forwarded to the
// div immediately.
var div = $doc.createElement('div');
div.tabIndex = 0;
var input = $doc.createElement('input');
input.type = 'text';
input.tabIndex = -1;
var style = input.style;
style.opacity = 0;
style.height = '1px';
style.width = '1px';
style.zIndex = -1;
style.overflow = 'hidden';
style.position = 'absolute';
// Note that we're using isolated lambda methods as the event listeners
// to avoid creating a memory leaks. (Lambdas here would create cycles
// involving the div and input). This also allows us to share a single
// set of handlers among every focusable item.
input.addEventListener('focus', focusHandler, false);
div.appendChild(input);
return div;
}-*/;
| private static native Element createFocusable0(JavaScriptObject focusHandler) /*-{
// Divs are focusable in all browsers, but only IE supports the accessKey
// property on divs. We use the infamous 'hidden input' trick to add an
// accessKey to the focusable div. Note that the input is only used to
// capture focus when the accessKey is pressed. Focus is forwarded to the
// div immediately.
var div = $doc.createElement('div');
div.tabIndex = 0;
var input = $doc.createElement('input');
input.type = 'text';
input.tabIndex = -1;
input.setAttribute('role', 'presentation');
var style = input.style;
style.opacity = 0;
style.height = '1px';
style.width = '1px';
style.zIndex = -1;
style.overflow = 'hidden';
style.position = 'absolute';
// Note that we're using isolated lambda methods as the event listeners
// to avoid creating a memory leaks. (Lambdas here would create cycles
// involving the div and input). This also allows us to share a single
// set of handlers among every focusable item.
input.addEventListener('focus', focusHandler, false);
div.appendChild(input);
return div;
}-*/;
|
diff --git a/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/ChildContainerProvider.java b/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/ChildContainerProvider.java
index 09daa0b2d..4d94d1eda 100644
--- a/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/ChildContainerProvider.java
+++ b/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/ChildContainerProvider.java
@@ -1,140 +1,140 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.fabric.service;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.karaf.admin.management.AdminServiceMBean;
import org.fusesource.fabric.api.Container;
import org.fusesource.fabric.api.ContainerProvider;
import org.fusesource.fabric.api.CreateContainerChildMetadata;
import org.fusesource.fabric.api.CreateContainerChildOptions;
import org.fusesource.fabric.internal.FabricConstants;
public class ChildContainerProvider implements ContainerProvider<CreateContainerChildOptions, CreateContainerChildMetadata> {
final FabricServiceImpl service;
public ChildContainerProvider(FabricServiceImpl service) {
this.service = service;
}
@Override
public Set<CreateContainerChildMetadata> create(final CreateContainerChildOptions options) throws Exception {
final Set<CreateContainerChildMetadata> result = new LinkedHashSet<CreateContainerChildMetadata>();
String parentName = options.getParent();
final Container parent = service.getContainer(parentName);
ContainerTemplate containerTemplate = service.getContainerTemplate(parent);
//Retrieve the credentials from the URI if available.
if (options.getProviderURI() != null && options.getProviderURI().getUserInfo() != null) {
String ui = options.getProviderURI().getUserInfo();
String[] uip = ui != null ? ui.split(":") : null;
if (uip != null) {
containerTemplate.setLogin(uip[0]);
containerTemplate.setPassword(uip[1]);
}
}
containerTemplate.execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
StringBuilder jvmOptsBuilder = new StringBuilder();
jvmOptsBuilder.append("-server -Dcom.sun.management.jmxremote ")
.append(options.getJvmOpts()).append(" ")
.append(options.getZookeeperUrl() != null ? "-Dzookeeper.url=\"" + options.getZookeeperUrl() + "\"" : "");
- if (!options.getJvmOpts().contains("-Xmx")) {
+ if (options.getJvmOpts() == null || !options.getJvmOpts().contains("-Xmx")) {
jvmOptsBuilder.append("-Xmx512m");
}
if (options.isDebugContainer()) {
jvmOptsBuilder.append(" ").append(DEBUG_CONTAINER);
}
if (options.isEnsembleServer()) {
jvmOptsBuilder.append(" ").append(ENSEMBLE_SERVER_CONTAINER);
}
String features = "fabric-agent";
String featuresUrls = "mvn:org.fusesource.fabric/fuse-fabric/" + FabricConstants.FABRIC_VERSION + "/xml/features";
for (int i = 1; i <= options.getNumber(); i++) {
String containerName = options.getName();
if (options.getNumber() > 1) {
containerName += i;
}
CreateContainerChildMetadata metadata = new CreateContainerChildMetadata();
metadata.setCreateOptions(options);
metadata.setContainerName(containerName);
try {
adminService.createInstance(containerName, 0, 0, 0, null, jvmOptsBuilder.toString(), features, featuresUrls);
adminService.startInstance(containerName, null);
} catch (Throwable t) {
metadata.setFailure(t);
}
result.add(metadata);
}
return null;
}
});
return result;
}
@Override
public void start(final Container container) {
getContainerTemplate(container.getParent()).execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
adminService.startInstance(container.getId(), null);
return null;
}
});
}
@Override
public void stop(final Container container) {
getContainerTemplate(container.getParent()).execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
adminService.stopInstance(container.getId());
return null;
}
});
}
@Override
public void destroy(final Container container) {
getContainerTemplate(container.getParent()).execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
try {
if (container.isAlive()) {
adminService.stopInstance(container.getId());
}
} catch (Exception e) {
// Ignore if the container is stopped
if (container.isAlive()) {
throw e;
}
}
adminService.destroyInstance(container.getId());
return null;
}
});
}
protected ContainerTemplate getContainerTemplate(Container container) {
return new ContainerTemplate(container, false, service.getUserName(), service.getPassword());
}
}
| true | true | public Set<CreateContainerChildMetadata> create(final CreateContainerChildOptions options) throws Exception {
final Set<CreateContainerChildMetadata> result = new LinkedHashSet<CreateContainerChildMetadata>();
String parentName = options.getParent();
final Container parent = service.getContainer(parentName);
ContainerTemplate containerTemplate = service.getContainerTemplate(parent);
//Retrieve the credentials from the URI if available.
if (options.getProviderURI() != null && options.getProviderURI().getUserInfo() != null) {
String ui = options.getProviderURI().getUserInfo();
String[] uip = ui != null ? ui.split(":") : null;
if (uip != null) {
containerTemplate.setLogin(uip[0]);
containerTemplate.setPassword(uip[1]);
}
}
containerTemplate.execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
StringBuilder jvmOptsBuilder = new StringBuilder();
jvmOptsBuilder.append("-server -Dcom.sun.management.jmxremote ")
.append(options.getJvmOpts()).append(" ")
.append(options.getZookeeperUrl() != null ? "-Dzookeeper.url=\"" + options.getZookeeperUrl() + "\"" : "");
if (!options.getJvmOpts().contains("-Xmx")) {
jvmOptsBuilder.append("-Xmx512m");
}
if (options.isDebugContainer()) {
jvmOptsBuilder.append(" ").append(DEBUG_CONTAINER);
}
if (options.isEnsembleServer()) {
jvmOptsBuilder.append(" ").append(ENSEMBLE_SERVER_CONTAINER);
}
String features = "fabric-agent";
String featuresUrls = "mvn:org.fusesource.fabric/fuse-fabric/" + FabricConstants.FABRIC_VERSION + "/xml/features";
for (int i = 1; i <= options.getNumber(); i++) {
String containerName = options.getName();
if (options.getNumber() > 1) {
containerName += i;
}
CreateContainerChildMetadata metadata = new CreateContainerChildMetadata();
metadata.setCreateOptions(options);
metadata.setContainerName(containerName);
try {
adminService.createInstance(containerName, 0, 0, 0, null, jvmOptsBuilder.toString(), features, featuresUrls);
adminService.startInstance(containerName, null);
} catch (Throwable t) {
metadata.setFailure(t);
}
result.add(metadata);
}
return null;
}
});
return result;
}
| public Set<CreateContainerChildMetadata> create(final CreateContainerChildOptions options) throws Exception {
final Set<CreateContainerChildMetadata> result = new LinkedHashSet<CreateContainerChildMetadata>();
String parentName = options.getParent();
final Container parent = service.getContainer(parentName);
ContainerTemplate containerTemplate = service.getContainerTemplate(parent);
//Retrieve the credentials from the URI if available.
if (options.getProviderURI() != null && options.getProviderURI().getUserInfo() != null) {
String ui = options.getProviderURI().getUserInfo();
String[] uip = ui != null ? ui.split(":") : null;
if (uip != null) {
containerTemplate.setLogin(uip[0]);
containerTemplate.setPassword(uip[1]);
}
}
containerTemplate.execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
StringBuilder jvmOptsBuilder = new StringBuilder();
jvmOptsBuilder.append("-server -Dcom.sun.management.jmxremote ")
.append(options.getJvmOpts()).append(" ")
.append(options.getZookeeperUrl() != null ? "-Dzookeeper.url=\"" + options.getZookeeperUrl() + "\"" : "");
if (options.getJvmOpts() == null || !options.getJvmOpts().contains("-Xmx")) {
jvmOptsBuilder.append("-Xmx512m");
}
if (options.isDebugContainer()) {
jvmOptsBuilder.append(" ").append(DEBUG_CONTAINER);
}
if (options.isEnsembleServer()) {
jvmOptsBuilder.append(" ").append(ENSEMBLE_SERVER_CONTAINER);
}
String features = "fabric-agent";
String featuresUrls = "mvn:org.fusesource.fabric/fuse-fabric/" + FabricConstants.FABRIC_VERSION + "/xml/features";
for (int i = 1; i <= options.getNumber(); i++) {
String containerName = options.getName();
if (options.getNumber() > 1) {
containerName += i;
}
CreateContainerChildMetadata metadata = new CreateContainerChildMetadata();
metadata.setCreateOptions(options);
metadata.setContainerName(containerName);
try {
adminService.createInstance(containerName, 0, 0, 0, null, jvmOptsBuilder.toString(), features, featuresUrls);
adminService.startInstance(containerName, null);
} catch (Throwable t) {
metadata.setFailure(t);
}
result.add(metadata);
}
return null;
}
});
return result;
}
|
diff --git a/src/de/anycook/graph/filter/AccessOriginFilter.java b/src/de/anycook/graph/filter/AccessOriginFilter.java
index cf00a5e..9fad18c 100644
--- a/src/de/anycook/graph/filter/AccessOriginFilter.java
+++ b/src/de/anycook/graph/filter/AccessOriginFilter.java
@@ -1,61 +1,63 @@
/**
*
*/
package de.anycook.graph.filter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.log4j.Logger;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
/**
* Adds Access-Control-Allow headers to response
* @author Jan Graßegger <[email protected]>
*
*/
public class AccessOriginFilter implements ContainerResponseFilter {
private final Logger logger;
private final static Pattern hostPattern = Pattern.compile("(http://(.*)anycook\\.de).*");
/**
* Default constructor
*/
public AccessOriginFilter() {
logger = Logger.getLogger(getClass());
logger.debug("filter constructor");
}
/* (non-Javadoc)
* @see com.sun.jersey.spi.container.ContainerResponseFilter#filter(com.sun.jersey.spi.container.ContainerRequest, com.sun.jersey.spi.container.ContainerResponse)
*/
@Override
public ContainerResponse filter(ContainerRequest request,
ContainerResponse resp) {
- Matcher hostMatcher = hostPattern.matcher(request.getHeaderValue("Referer"));
+ String referer = request.getHeaderValue("Referer");
+ if(referer == null) return resp;
+ Matcher hostMatcher = hostPattern.matcher(referer);
if(hostMatcher.matches()){
// String refHost = referer.getHost();
//Quelle: http://stackoverflow.com/questions/5406350/access-control-allow-origin-has-no-influence-in-rest-web-service
MultivaluedMap<String, Object> headers =resp.getHttpHeaders();
headers.putSingle("Access-Control-Allow-Origin", hostMatcher.group(1));
headers.putSingle("Access-Control-Allow-Methods",
"POST, PUT,DELETE,GET, OPTIONS");
// if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
headers.putSingle("Access-Control-Allow-Credentials", "true");
}
return resp;
}
}
| true | true | public ContainerResponse filter(ContainerRequest request,
ContainerResponse resp) {
Matcher hostMatcher = hostPattern.matcher(request.getHeaderValue("Referer"));
if(hostMatcher.matches()){
// String refHost = referer.getHost();
//Quelle: http://stackoverflow.com/questions/5406350/access-control-allow-origin-has-no-influence-in-rest-web-service
MultivaluedMap<String, Object> headers =resp.getHttpHeaders();
headers.putSingle("Access-Control-Allow-Origin", hostMatcher.group(1));
headers.putSingle("Access-Control-Allow-Methods",
"POST, PUT,DELETE,GET, OPTIONS");
// if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
headers.putSingle("Access-Control-Allow-Credentials", "true");
}
return resp;
}
| public ContainerResponse filter(ContainerRequest request,
ContainerResponse resp) {
String referer = request.getHeaderValue("Referer");
if(referer == null) return resp;
Matcher hostMatcher = hostPattern.matcher(referer);
if(hostMatcher.matches()){
// String refHost = referer.getHost();
//Quelle: http://stackoverflow.com/questions/5406350/access-control-allow-origin-has-no-influence-in-rest-web-service
MultivaluedMap<String, Object> headers =resp.getHttpHeaders();
headers.putSingle("Access-Control-Allow-Origin", hostMatcher.group(1));
headers.putSingle("Access-Control-Allow-Methods",
"POST, PUT,DELETE,GET, OPTIONS");
// if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
headers.putSingle("Access-Control-Allow-Credentials", "true");
}
return resp;
}
|
diff --git a/org.dawb.common.ui/src/org/dawb/common/ui/plot/trace/TraceUtils.java b/org.dawb.common.ui/src/org/dawb/common/ui/plot/trace/TraceUtils.java
index 3e74167b..baf160cb 100644
--- a/org.dawb.common.ui/src/org/dawb/common/ui/plot/trace/TraceUtils.java
+++ b/org.dawb.common.ui/src/org/dawb/common/ui/plot/trace/TraceUtils.java
@@ -1,82 +1,83 @@
package org.dawb.common.ui.plot.trace;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.dawb.common.ui.plot.IPlottingSystem;
import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset;
/**
* Class containing utility methods for regions to avoid duplication
* @author fcp94556
*
*/
public class TraceUtils {
/**
* Call to get a unique region name
* @param nameStub
* @param system
* @return
*/
public static String getUniqueTrace(final String nameStub, final IPlottingSystem system, final String... usedNames) {
int i = 1;
@SuppressWarnings("unchecked")
final List<String> used = (List<String>) (usedNames!=null ? Arrays.asList(usedNames) : Collections.emptyList());
while(system.getTrace(nameStub+" "+i)!=null || used.contains(nameStub+" "+i)) {
++i;
if (i>10000) break; // something went wrong!
}
return nameStub+" "+i;
}
/**
* Removes a trace of this name if it is already there.
* @param plottingSystem
* @param string
* @return
*/
public static final ILineTrace replaceCreateLineTrace(IPlottingSystem system, String name) {
if (system.getTrace(name)!=null) {
system.removeTrace(system.getTrace(name));
}
return system.createLineTrace(name);
}
/**
* Determine if IImageTrace has custom axes or not.
*/
public static boolean isCustomAxes(IImageTrace trace) {
+ if (trace==null) return false;
List<AbstractDataset> axes = trace.getAxes();
AbstractDataset image = trace.getData();
if (axes==null) return false;
if (axes.isEmpty()) return false;
if (axes.get(0).getDtype()!=AbstractDataset.INT32 || axes.get(1).getDtype()!=AbstractDataset.INT32) {
return true;
}
if (axes.get(0).getSize() == image.getShape()[1] &&
axes.get(1).getSize() == image.getShape()[0]) {
boolean startZero = axes.get(0).getDouble(0)==0d &&
axes.get(1).getDouble(0)==0d;
if (!startZero) return true;
double xEnd = axes.get(0).getDouble(axes.get(0).getSize()-1);
double yEnd = axes.get(1).getDouble(axes.get(1).getSize()-1);
boolean maxSame = xEnd==image.getShape()[1]-1 &&
yEnd==image.getShape()[0]-1;
if (maxSame) return false;
}
return true;
}
}
| true | true | public static boolean isCustomAxes(IImageTrace trace) {
List<AbstractDataset> axes = trace.getAxes();
AbstractDataset image = trace.getData();
if (axes==null) return false;
if (axes.isEmpty()) return false;
if (axes.get(0).getDtype()!=AbstractDataset.INT32 || axes.get(1).getDtype()!=AbstractDataset.INT32) {
return true;
}
if (axes.get(0).getSize() == image.getShape()[1] &&
axes.get(1).getSize() == image.getShape()[0]) {
boolean startZero = axes.get(0).getDouble(0)==0d &&
axes.get(1).getDouble(0)==0d;
if (!startZero) return true;
double xEnd = axes.get(0).getDouble(axes.get(0).getSize()-1);
double yEnd = axes.get(1).getDouble(axes.get(1).getSize()-1);
boolean maxSame = xEnd==image.getShape()[1]-1 &&
yEnd==image.getShape()[0]-1;
if (maxSame) return false;
}
return true;
}
| public static boolean isCustomAxes(IImageTrace trace) {
if (trace==null) return false;
List<AbstractDataset> axes = trace.getAxes();
AbstractDataset image = trace.getData();
if (axes==null) return false;
if (axes.isEmpty()) return false;
if (axes.get(0).getDtype()!=AbstractDataset.INT32 || axes.get(1).getDtype()!=AbstractDataset.INT32) {
return true;
}
if (axes.get(0).getSize() == image.getShape()[1] &&
axes.get(1).getSize() == image.getShape()[0]) {
boolean startZero = axes.get(0).getDouble(0)==0d &&
axes.get(1).getDouble(0)==0d;
if (!startZero) return true;
double xEnd = axes.get(0).getDouble(axes.get(0).getSize()-1);
double yEnd = axes.get(1).getDouble(axes.get(1).getSize()-1);
boolean maxSame = xEnd==image.getShape()[1]-1 &&
yEnd==image.getShape()[0]-1;
if (maxSame) return false;
}
return true;
}
|
diff --git a/NotePad/src/com/example/android/notepad/NoteEditor.java b/NotePad/src/com/example/android/notepad/NoteEditor.java
index 45e6308b..ec452750 100644
--- a/NotePad/src/com/example/android/notepad/NoteEditor.java
+++ b/NotePad/src/com/example/android/notepad/NoteEditor.java
@@ -1,347 +1,349 @@
/*
* Copyright (C) 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.notepad;
import com.example.android.notepad.NotePad.Notes;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
/**
* A generic activity for editing a note in a database. This can be used
* either to simply view a note {@link Intent#ACTION_VIEW}, view and edit a note
* {@link Intent#ACTION_EDIT}, or create a new note {@link Intent#ACTION_INSERT}.
*/
public class NoteEditor extends Activity {
private static final String TAG = "Notes";
/**
* Standard projection for the interesting columns of a normal note.
*/
private static final String[] PROJECTION = new String[] {
Notes._ID, // 0
Notes.NOTE, // 1
};
/** The index of the note column */
private static final int COLUMN_INDEX_NOTE = 1;
// This is our state data that is stored when freezing.
private static final String ORIGINAL_CONTENT = "origContent";
// Identifiers for our menu items.
private static final int REVERT_ID = Menu.FIRST;
private static final int DISCARD_ID = Menu.FIRST + 1;
private static final int DELETE_ID = Menu.FIRST + 2;
// The different distinct states the activity can be run in.
private static final int STATE_EDIT = 0;
private static final int STATE_INSERT = 1;
private int mState;
private boolean mNoteOnly = false;
private Uri mUri;
private Cursor mCursor;
private EditText mText;
private String mOriginalContent;
/**
* A custom EditText that draws lines between each line of text that is displayed.
*/
public static class LinedEditText extends EditText {
private Rect mRect;
private Paint mPaint;
// we need this constructor for LayoutInflater
public LinedEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(0x800000FF);
}
@Override
protected void onDraw(Canvas canvas) {
int count = getLineCount();
Rect r = mRect;
Paint paint = mPaint;
for (int i = 0; i < count; i++) {
int baseline = getLineBounds(i, r);
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
}
super.onDraw(canvas);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
// Do some setup based on the action being performed.
final String action = intent.getAction();
if (Intent.ACTION_EDIT.equals(action) || Intent.ACTION_VIEW.equals(action)) {
// Requested to edit: set that state, and the data being edited.
mState = STATE_EDIT;
mUri = intent.getData();
} else if (Intent.ACTION_INSERT.equals(action)) {
// Requested to insert: set that state, and create a new entry
// in the container.
mState = STATE_INSERT;
mUri = getContentResolver().insert(intent.getData(), null);
+ intent.setAction(Intent.ACTION_EDIT);
+ setIntent(intent);
// If we were unable to create a new note, then just finish
// this activity. A RESULT_CANCELED will be sent back to the
// original activity if they requested a result.
if (mUri == null) {
Log.e(TAG, "Failed to insert new note into " + getIntent().getData());
finish();
return;
}
// The new entry was created, so assume all will end well and
// set the result to be returned.
setResult(RESULT_OK, (new Intent()).setAction(mUri.toString()));
} else {
// Whoops, unknown action! Bail.
Log.e(TAG, "Unknown action, exiting");
finish();
return;
}
// Set the layout for this activity. You can find it in res/layout/note_editor.xml
setContentView(R.layout.note_editor);
// The text view for our note, identified by its ID in the XML file.
mText = (EditText) findViewById(R.id.note);
// Get the note!
mCursor = managedQuery(mUri, PROJECTION, null, null, null);
// If an instance of this activity had previously stopped, we can
// get the original text it started with.
if (savedInstanceState != null) {
mOriginalContent = savedInstanceState.getString(ORIGINAL_CONTENT);
}
}
@Override
protected void onResume() {
super.onResume();
// If we didn't have any trouble retrieving the data, it is now
// time to get at the stuff.
if (mCursor != null) {
// Make sure we are at the one and only row in the cursor.
mCursor.moveToFirst();
// Modify our overall title depending on the mode we are running in.
if (mState == STATE_EDIT) {
setTitle(getText(R.string.title_edit));
} else if (mState == STATE_INSERT) {
setTitle(getText(R.string.title_create));
}
// This is a little tricky: we may be resumed after previously being
// paused/stopped. We want to put the new text in the text view,
// but leave the user where they were (retain the cursor position
// etc). This version of setText does that for us.
String note = mCursor.getString(COLUMN_INDEX_NOTE);
mText.setTextKeepState(note);
// If we hadn't previously retrieved the original text, do so
// now. This allows the user to revert their changes.
if (mOriginalContent == null) {
mOriginalContent = note;
}
} else {
setTitle(getText(R.string.error_title));
mText.setText(getText(R.string.error_message));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// Save away the original text, so we still have it if the activity
// needs to be killed while paused.
outState.putString(ORIGINAL_CONTENT, mOriginalContent);
}
@Override
protected void onPause() {
super.onPause();
// The user is going somewhere else, so make sure their current
// changes are safely saved away in the provider. We don't need
// to do this if only editing.
if (mCursor != null) {
String text = mText.getText().toString();
int length = text.length();
// If this activity is finished, and there is no text, then we
// do something a little special: simply delete the note entry.
// Note that we do this both for editing and inserting... it
// would be reasonable to only do it when inserting.
if (isFinishing() && (length == 0) && !mNoteOnly) {
setResult(RESULT_CANCELED);
deleteNote();
// Get out updates into the provider.
} else {
ContentValues values = new ContentValues();
// This stuff is only done when working with a full-fledged note.
if (!mNoteOnly) {
// Bump the modification time to now.
values.put(Notes.MODIFIED_DATE, System.currentTimeMillis());
// If we are creating a new note, then we want to also create
// an initial title for it.
if (mState == STATE_INSERT) {
String title = text.substring(0, Math.min(30, length));
if (length > 30) {
int lastSpace = title.lastIndexOf(' ');
if (lastSpace > 0) {
title = title.substring(0, lastSpace);
}
}
values.put(Notes.TITLE, title);
}
}
// Write our text back into the provider.
values.put(Notes.NOTE, text);
// Commit all of our changes to persistent storage. When the update completes
// the content provider will notify the cursor of the change, which will
// cause the UI to be updated.
getContentResolver().update(mUri, values, null, null);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Build the menus that are shown when editing.
if (mState == STATE_EDIT) {
menu.add(0, REVERT_ID, 0, R.string.menu_revert)
.setShortcut('0', 'r')
.setIcon(android.R.drawable.ic_menu_revert);
if (!mNoteOnly) {
menu.add(0, DELETE_ID, 0, R.string.menu_delete)
.setShortcut('1', 'd')
.setIcon(android.R.drawable.ic_menu_delete);
}
// Build the menus that are shown when inserting.
} else {
menu.add(0, DISCARD_ID, 0, R.string.menu_discard)
.setShortcut('0', 'd')
.setIcon(android.R.drawable.ic_menu_delete);
}
// If we are working on a full note, then append to the
// menu items for any other activities that can do stuff with it
// as well. This does a query on the system for any activities that
// implement the ALTERNATIVE_ACTION for our data, adding a menu item
// for each one that is found.
if (!mNoteOnly) {
Intent intent = new Intent(null, getIntent().getData());
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
new ComponentName(this, NoteEditor.class), null, intent, 0, null);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle all of the possible menu actions.
switch (item.getItemId()) {
case DELETE_ID:
deleteNote();
finish();
break;
case DISCARD_ID:
cancelNote();
break;
case REVERT_ID:
cancelNote();
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Take care of canceling work on a note. Deletes the note if we
* had created it, otherwise reverts to the original text.
*/
private final void cancelNote() {
if (mCursor != null) {
if (mState == STATE_EDIT) {
// Put the original note text back into the database
mCursor.close();
mCursor = null;
ContentValues values = new ContentValues();
values.put(Notes.NOTE, mOriginalContent);
getContentResolver().update(mUri, values, null, null);
} else if (mState == STATE_INSERT) {
// We inserted an empty note, make sure to delete it
deleteNote();
}
}
setResult(RESULT_CANCELED);
finish();
}
/**
* Take care of deleting a note. Simply deletes the entry.
*/
private final void deleteNote() {
if (mCursor != null) {
mCursor.close();
mCursor = null;
getContentResolver().delete(mUri, null, null);
mText.setText("");
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
// Do some setup based on the action being performed.
final String action = intent.getAction();
if (Intent.ACTION_EDIT.equals(action) || Intent.ACTION_VIEW.equals(action)) {
// Requested to edit: set that state, and the data being edited.
mState = STATE_EDIT;
mUri = intent.getData();
} else if (Intent.ACTION_INSERT.equals(action)) {
// Requested to insert: set that state, and create a new entry
// in the container.
mState = STATE_INSERT;
mUri = getContentResolver().insert(intent.getData(), null);
// If we were unable to create a new note, then just finish
// this activity. A RESULT_CANCELED will be sent back to the
// original activity if they requested a result.
if (mUri == null) {
Log.e(TAG, "Failed to insert new note into " + getIntent().getData());
finish();
return;
}
// The new entry was created, so assume all will end well and
// set the result to be returned.
setResult(RESULT_OK, (new Intent()).setAction(mUri.toString()));
} else {
// Whoops, unknown action! Bail.
Log.e(TAG, "Unknown action, exiting");
finish();
return;
}
// Set the layout for this activity. You can find it in res/layout/note_editor.xml
setContentView(R.layout.note_editor);
// The text view for our note, identified by its ID in the XML file.
mText = (EditText) findViewById(R.id.note);
// Get the note!
mCursor = managedQuery(mUri, PROJECTION, null, null, null);
// If an instance of this activity had previously stopped, we can
// get the original text it started with.
if (savedInstanceState != null) {
mOriginalContent = savedInstanceState.getString(ORIGINAL_CONTENT);
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
// Do some setup based on the action being performed.
final String action = intent.getAction();
if (Intent.ACTION_EDIT.equals(action) || Intent.ACTION_VIEW.equals(action)) {
// Requested to edit: set that state, and the data being edited.
mState = STATE_EDIT;
mUri = intent.getData();
} else if (Intent.ACTION_INSERT.equals(action)) {
// Requested to insert: set that state, and create a new entry
// in the container.
mState = STATE_INSERT;
mUri = getContentResolver().insert(intent.getData(), null);
intent.setAction(Intent.ACTION_EDIT);
setIntent(intent);
// If we were unable to create a new note, then just finish
// this activity. A RESULT_CANCELED will be sent back to the
// original activity if they requested a result.
if (mUri == null) {
Log.e(TAG, "Failed to insert new note into " + getIntent().getData());
finish();
return;
}
// The new entry was created, so assume all will end well and
// set the result to be returned.
setResult(RESULT_OK, (new Intent()).setAction(mUri.toString()));
} else {
// Whoops, unknown action! Bail.
Log.e(TAG, "Unknown action, exiting");
finish();
return;
}
// Set the layout for this activity. You can find it in res/layout/note_editor.xml
setContentView(R.layout.note_editor);
// The text view for our note, identified by its ID in the XML file.
mText = (EditText) findViewById(R.id.note);
// Get the note!
mCursor = managedQuery(mUri, PROJECTION, null, null, null);
// If an instance of this activity had previously stopped, we can
// get the original text it started with.
if (savedInstanceState != null) {
mOriginalContent = savedInstanceState.getString(ORIGINAL_CONTENT);
}
}
|
diff --git a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/GraphBuilderTask.java b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/GraphBuilderTask.java
index 636cf517b..ce2a5ccfc 100644
--- a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/GraphBuilderTask.java
+++ b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/GraphBuilderTask.java
@@ -1,104 +1,107 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.graph_builder;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.opentripplanner.graph_builder.services.GraphBuilder;
import org.opentripplanner.model.GraphBundle;
import org.opentripplanner.routing.contraction.ContractionHierarchySet;
import org.opentripplanner.routing.contraction.ModeAndOptimize;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.impl.ContractionHierarchySerializationLibrary;
import org.opentripplanner.routing.services.GraphService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class GraphBuilderTask implements Runnable {
private static Logger _log = LoggerFactory.getLogger(GraphBuilderTask.class);
private GraphService _graphService;
private List<GraphBuilder> _graphBuilders = new ArrayList<GraphBuilder>();
private GraphBundle _graphBundle;
private boolean _alwaysRebuild = true;
private List<ModeAndOptimize> _modeList;
private double _contractionFactor = 1.0;
@Autowired
public void setGraphService(GraphService graphService) {
_graphService = graphService;
}
public void addGraphBuilder(GraphBuilder loader) {
_graphBuilders.add(loader);
}
public void setGraphBuilders(List<GraphBuilder> graphLoaders) {
_graphBuilders = graphLoaders;
}
public void setGraphBundle(GraphBundle graphBundle) {
_graphBundle = graphBundle;
}
public void setAlwaysRebuild(boolean alwaysRebuild) {
_alwaysRebuild = alwaysRebuild;
}
public void addMode(ModeAndOptimize mo) {
_modeList.add(mo);
}
public void setModes(List<ModeAndOptimize> modeList) {
_modeList = modeList;
}
public void setContractionFactor(double contractionFactor) {
_contractionFactor = contractionFactor;
}
public void run() {
Graph graph = _graphService.getGraph();
+ if (_graphBundle == null) {
+ throw new RuntimeException("graphBuilderTask has no attribute graphBundle.");
+ }
File graphPath = _graphBundle.getGraphPath();
if( graphPath.exists() && ! _alwaysRebuild) {
_log.info("graph already exists and alwaysRebuild=false => skipping graph build");
return;
}
for (GraphBuilder load : _graphBuilders)
load.buildGraph(graph);
ContractionHierarchySet chs = new ContractionHierarchySet(graph, _modeList, _contractionFactor);
chs.build();
try {
ContractionHierarchySerializationLibrary.writeGraph(chs, graphPath);
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
_graphService.refreshGraph();
}
}
| true | true | public void run() {
Graph graph = _graphService.getGraph();
File graphPath = _graphBundle.getGraphPath();
if( graphPath.exists() && ! _alwaysRebuild) {
_log.info("graph already exists and alwaysRebuild=false => skipping graph build");
return;
}
for (GraphBuilder load : _graphBuilders)
load.buildGraph(graph);
ContractionHierarchySet chs = new ContractionHierarchySet(graph, _modeList, _contractionFactor);
chs.build();
try {
ContractionHierarchySerializationLibrary.writeGraph(chs, graphPath);
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
_graphService.refreshGraph();
}
| public void run() {
Graph graph = _graphService.getGraph();
if (_graphBundle == null) {
throw new RuntimeException("graphBuilderTask has no attribute graphBundle.");
}
File graphPath = _graphBundle.getGraphPath();
if( graphPath.exists() && ! _alwaysRebuild) {
_log.info("graph already exists and alwaysRebuild=false => skipping graph build");
return;
}
for (GraphBuilder load : _graphBuilders)
load.buildGraph(graph);
ContractionHierarchySet chs = new ContractionHierarchySet(graph, _modeList, _contractionFactor);
chs.build();
try {
ContractionHierarchySerializationLibrary.writeGraph(chs, graphPath);
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
_graphService.refreshGraph();
}
|
diff --git a/src/web/org/openmrs/web/filter/StartupFilter.java b/src/web/org/openmrs/web/filter/StartupFilter.java
index 08ee4eed..45e73547 100644
--- a/src/web/org/openmrs/web/filter/StartupFilter.java
+++ b/src/web/org/openmrs/web/filter/StartupFilter.java
@@ -1,355 +1,355 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.filter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.directwebremoting.util.JavascriptUtil;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.web.WebConstants;
import org.openmrs.web.filter.initialization.InitializationFilter;
import org.openmrs.web.filter.update.UpdateFilter;
/**
* Abstract class used when a small wizard is needed before Spring, jsp, etc has been started up.
*
* @see UpdateFilter
* @see InitializationFilter
*/
public abstract class StartupFilter implements Filter {
protected final Log log = LogFactory.getLog(getClass());
protected static VelocityEngine velocityEngine = null;
/**
* Set by the {@link #init(FilterConfig)} method so that we have access to the current
* {@link ServletContext}
*/
protected FilterConfig filterConfig = null;
/**
* Records errors that will be displayed to the user
*/
protected List<String> errors = new ArrayList<String>();
/**
* The web.xml file sets this {@link StartupFilter} to be the first filter for all requests.
*
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (skipFilter((HttpServletRequest) request)) {
chain.doFilter(request, response);
} else {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String servletPath = httpRequest.getServletPath();
// for all /images and /initfilter/scripts files, write the path
// (the "/initfilter" part is needed so that the openmrs_static_context-servlet.xml file doesn't
// get instantiated early, before the locale messages are all set up)
if (servletPath.startsWith("/images") || servletPath.startsWith("/initfilter/scripts")) {
- servletPath = servletPath.replaceFirst("/initfilter", ""); // strip out the /initfilter part
+ servletPath = servletPath.replaceFirst("/initfilter", "/WEB-INF/view"); // strip out the /initfilter part
// writes the actual image file path to the response
File file = new File(filterConfig.getServletContext().getRealPath(servletPath));
if (httpRequest.getPathInfo() != null)
file = new File(file, httpRequest.getPathInfo());
try {
InputStream imageFileInputStream = new FileInputStream(file);
OpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream());
imageFileInputStream.close();
}
catch (FileNotFoundException e) {
log.error("Unable to find file: " + file.getAbsolutePath());
}
} else if (servletPath.startsWith("/scripts")) {
log
.error("Calling /scripts during the initializationfilter pages will cause the openmrs_static_context-servlet.xml to initialize too early and cause errors after startup. Use '/initfilter"
+ servletPath + "' instead.");
}
// for anything but /initialsetup
else if (!httpRequest.getServletPath().equals("/" + WebConstants.SETUP_PAGE_URL)) {
// send the user to the setup page
httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME + "/" + WebConstants.SETUP_PAGE_URL);
} else {
if (httpRequest.getMethod().equals("GET")) {
doGet(httpRequest, httpResponse);
} else if (httpRequest.getMethod().equals("POST")) {
// only clear errors before POSTS so that redirects can show errors too.
errors.clear();
doPost(httpRequest, httpResponse);
}
}
// Don't continue down the filter chain otherwise Spring complains
// that it hasn't been set up yet.
// The jsp and servlet filter are also on this chain, so writing to
// the response directly here is the only option
}
}
/**
* Convenience method to set up the velocity context properly
*/
private void initializeVelocity() {
if (velocityEngine == null) {
velocityEngine = new VelocityEngine();
Properties props = new Properties();
props.setProperty(RuntimeConstants.RUNTIME_LOG, "startup_wizard_vel.log");
// props.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
// "org.apache.velocity.runtime.log.CommonsLogLogChute" );
// props.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME,
// "initial_wizard_velocity");
// so the vm pages can import the header/footer
props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
props.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
props.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
try {
velocityEngine.init(props);
}
catch (Exception e) {
log.error("velocity init failed, because: " + e);
}
}
}
/**
* Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests
*
* @param httpRequest
* @param httpResponse
*/
protected abstract void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException;
/**
* Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests
*
* @param httpRequest
* @param httpResponse
* @throws Exception
*/
protected abstract void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException;
/**
* All private attributes on this class are returned to the template via the velocity context
* and reflection
*
* @param templateName the name of the velocity file to render. This name is prepended with
* {@link #getTemplatePrefix()}
* @param referenceMap
* @param writer
*/
protected void renderTemplate(String templateName, Map<String, Object> referenceMap, Writer writer) throws IOException {
VelocityContext velocityContext = new VelocityContext();
if (referenceMap != null) {
for (Map.Entry<String, Object> entry : referenceMap.entrySet()) {
velocityContext.put(entry.getKey(), entry.getValue());
}
}
Object model = getModel();
// put each of the private varibles into the template for convenience
for (Field field : model.getClass().getDeclaredFields()) {
try {
velocityContext.put(field.getName(), field.get(model));
}
catch (IllegalArgumentException e) {
log.error("Error generated while getting field value: " + field.getName(), e);
}
catch (IllegalAccessException e) {
log.error("Error generated while getting field value: " + field.getName(), e);
}
}
String fullTemplatePath = getTemplatePrefix() + templateName;
InputStream templateInputStream = getClass().getClassLoader().getResourceAsStream(fullTemplatePath);
if (templateInputStream == null) {
throw new IOException("Unable to find " + fullTemplatePath);
}
velocityContext.put("errors", errors);
try {
velocityEngine.evaluate(velocityContext, writer, this.getClass().getName(), new InputStreamReader(
templateInputStream));
}
catch (Exception e) {
throw new RuntimeException("Unable to process template: " + fullTemplatePath, e);
}
}
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
initializeVelocity();
}
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
}
/**
* This string is prepended to all templateNames passed to
* {@link #renderTemplate(String, Map, Writer)}
*
* @return string to prepend as the path for the templates
*/
protected String getTemplatePrefix() {
return "org/openmrs/web/filter/";
}
/**
* The model that is used as the backer for all pages in this startup wizard. Should never
* return null.
*
* @return the stored formbacking/model object
*/
protected abstract Object getModel();
/**
* If this returns true, this filter fails early and quickly. All logic is skipped and startup
* and usage continue normally.
*
* @return true if this filter can be skipped
*/
public abstract boolean skipFilter(HttpServletRequest request);
/**
* Convert a map of strings to objects to json
*
* @param map object to convert
* @param sb StringBuffer to append to
*/
private void toJSONString(Map<String, Object> map, StringBuffer sb) {
boolean first = true;
sb.append('{');
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (first)
first = false;
else
sb.append(',');
sb.append('"');
if (entry.getKey() == null)
sb.append("null");
else
sb.append(JavascriptUtil.escapeJavaScript(entry.getKey()));
sb.append('"').append(':');
sb.append(toJSONString(entry.getValue()));
}
sb.append('}');
}
/**
* Convert a list of objects to json
*
* @param list object to convert
* @param sb StringBuffer to append to
*/
private void toJSONString(List<Object> list, StringBuffer sb) {
boolean first = true;
sb.append('[');
for (Object listItem : list) {
if (first)
first = false;
else
sb.append(',');
sb.append(toJSONString(listItem));
}
sb.append(']');
}
/**
* Convert all other objects to json
*
* @param object object to convert
* @param sb StringBuffer to append to
*/
private void toJSONString(Object object, StringBuffer sb) {
if (object == null)
sb.append("null");
else
sb.append('"').append(JavascriptUtil.escapeJavaScript(object.toString())).append('"');
}
/**
* Convenience method to convert the given object to a JSON string.
* Supports Maps, Lists, Strings, Boolean, Double
*
* @param object object to convert to json
* @return JSON string to be eval'd in javascript
*/
protected String toJSONString(Object object) {
StringBuffer sb = new StringBuffer();
if (object instanceof Map)
toJSONString((Map<String, Object>)object, sb);
else if (object instanceof List)
toJSONString((List)object, sb);
else if (object instanceof Boolean)
sb.append(object.toString());
else
toJSONString(object, sb);
return sb.toString();
}
}
| true | true | public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (skipFilter((HttpServletRequest) request)) {
chain.doFilter(request, response);
} else {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String servletPath = httpRequest.getServletPath();
// for all /images and /initfilter/scripts files, write the path
// (the "/initfilter" part is needed so that the openmrs_static_context-servlet.xml file doesn't
// get instantiated early, before the locale messages are all set up)
if (servletPath.startsWith("/images") || servletPath.startsWith("/initfilter/scripts")) {
servletPath = servletPath.replaceFirst("/initfilter", ""); // strip out the /initfilter part
// writes the actual image file path to the response
File file = new File(filterConfig.getServletContext().getRealPath(servletPath));
if (httpRequest.getPathInfo() != null)
file = new File(file, httpRequest.getPathInfo());
try {
InputStream imageFileInputStream = new FileInputStream(file);
OpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream());
imageFileInputStream.close();
}
catch (FileNotFoundException e) {
log.error("Unable to find file: " + file.getAbsolutePath());
}
} else if (servletPath.startsWith("/scripts")) {
log
.error("Calling /scripts during the initializationfilter pages will cause the openmrs_static_context-servlet.xml to initialize too early and cause errors after startup. Use '/initfilter"
+ servletPath + "' instead.");
}
// for anything but /initialsetup
else if (!httpRequest.getServletPath().equals("/" + WebConstants.SETUP_PAGE_URL)) {
// send the user to the setup page
httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME + "/" + WebConstants.SETUP_PAGE_URL);
} else {
if (httpRequest.getMethod().equals("GET")) {
doGet(httpRequest, httpResponse);
} else if (httpRequest.getMethod().equals("POST")) {
// only clear errors before POSTS so that redirects can show errors too.
errors.clear();
doPost(httpRequest, httpResponse);
}
}
// Don't continue down the filter chain otherwise Spring complains
// that it hasn't been set up yet.
// The jsp and servlet filter are also on this chain, so writing to
// the response directly here is the only option
}
}
| public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (skipFilter((HttpServletRequest) request)) {
chain.doFilter(request, response);
} else {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String servletPath = httpRequest.getServletPath();
// for all /images and /initfilter/scripts files, write the path
// (the "/initfilter" part is needed so that the openmrs_static_context-servlet.xml file doesn't
// get instantiated early, before the locale messages are all set up)
if (servletPath.startsWith("/images") || servletPath.startsWith("/initfilter/scripts")) {
servletPath = servletPath.replaceFirst("/initfilter", "/WEB-INF/view"); // strip out the /initfilter part
// writes the actual image file path to the response
File file = new File(filterConfig.getServletContext().getRealPath(servletPath));
if (httpRequest.getPathInfo() != null)
file = new File(file, httpRequest.getPathInfo());
try {
InputStream imageFileInputStream = new FileInputStream(file);
OpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream());
imageFileInputStream.close();
}
catch (FileNotFoundException e) {
log.error("Unable to find file: " + file.getAbsolutePath());
}
} else if (servletPath.startsWith("/scripts")) {
log
.error("Calling /scripts during the initializationfilter pages will cause the openmrs_static_context-servlet.xml to initialize too early and cause errors after startup. Use '/initfilter"
+ servletPath + "' instead.");
}
// for anything but /initialsetup
else if (!httpRequest.getServletPath().equals("/" + WebConstants.SETUP_PAGE_URL)) {
// send the user to the setup page
httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME + "/" + WebConstants.SETUP_PAGE_URL);
} else {
if (httpRequest.getMethod().equals("GET")) {
doGet(httpRequest, httpResponse);
} else if (httpRequest.getMethod().equals("POST")) {
// only clear errors before POSTS so that redirects can show errors too.
errors.clear();
doPost(httpRequest, httpResponse);
}
}
// Don't continue down the filter chain otherwise Spring complains
// that it hasn't been set up yet.
// The jsp and servlet filter are also on this chain, so writing to
// the response directly here is the only option
}
}
|
diff --git a/src/main/java/vazkii/tinkerer/common/network/packet/PacketEnchanterAddEnchant.java b/src/main/java/vazkii/tinkerer/common/network/packet/PacketEnchanterAddEnchant.java
index 0544d14d..daefaa23 100644
--- a/src/main/java/vazkii/tinkerer/common/network/packet/PacketEnchanterAddEnchant.java
+++ b/src/main/java/vazkii/tinkerer/common/network/packet/PacketEnchanterAddEnchant.java
@@ -1,59 +1,59 @@
/**
* This class was created by <Vazkii>. It's distributed as
* part of the ThaumicTinkerer Mod.
*
* ThaumicTinkerer is Open Source and distributed under a
* Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
* (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB)
*
* ThaumicTinkerer is a Derivative Work on Thaumcraft 4.
* Thaumcraft 4 (c) Azanor 2012
* (http://www.minecraftforum.net/topic/1585216-)
*
* File Created @ [16 Sep 2013, 15:45:54 (GMT)]
*/
package vazkii.tinkerer.common.network.packet;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.player.EntityPlayer;
import vazkii.tinkerer.common.block.tile.TileEnchanter;
import vazkii.tinkerer.common.enchantment.core.EnchantmentManager;
import cpw.mods.fml.common.network.PacketDispatcher;
public class PacketEnchanterAddEnchant extends PacketTile<TileEnchanter> {
private static final long serialVersionUID = -2182522429849764376L;
int enchant;
int level;
public PacketEnchanterAddEnchant(TileEnchanter tile, int enchant, int level) {
super(tile);
this.enchant = enchant;
this.level = level;
}
@Override
public void handle() {
if(tile.working)
return;
if(level == -1) {
int index = tile.enchantments.indexOf(enchant);
tile.removeLevel(index);
tile.removeEnchant(index);
} else {
- if(!tile.enchantments.contains(enchant)) {
- if(player instanceof EntityPlayer && EnchantmentManager.canEnchantmentBeUsed(((EntityPlayer) player).username, Enchantment.enchantmentsList[enchant])) {
+ if(!tile.enchantments.contains(enchant)){
+ if(player instanceof EntityPlayer && EnchantmentManager.canApply(tile.getStackInSlot(0), Enchantment.enchantmentsList[enchant], tile.enchantments)&& EnchantmentManager.canEnchantmentBeUsed(((EntityPlayer) player).username, Enchantment.enchantmentsList[enchant])) {
tile.appendEnchant(enchant);
tile.appendLevel(1);
}
} else {
int maxLevel = Enchantment.enchantmentsList[enchant].getMaxLevel();
tile.setLevel(tile.enchantments.indexOf(enchant), Math.max(1, Math.min(maxLevel, level)));
}
}
tile.updateAspectList();
PacketDispatcher.sendPacketToAllPlayers(tile.getDescriptionPacket());
}
}
| true | true | public void handle() {
if(tile.working)
return;
if(level == -1) {
int index = tile.enchantments.indexOf(enchant);
tile.removeLevel(index);
tile.removeEnchant(index);
} else {
if(!tile.enchantments.contains(enchant)) {
if(player instanceof EntityPlayer && EnchantmentManager.canEnchantmentBeUsed(((EntityPlayer) player).username, Enchantment.enchantmentsList[enchant])) {
tile.appendEnchant(enchant);
tile.appendLevel(1);
}
} else {
int maxLevel = Enchantment.enchantmentsList[enchant].getMaxLevel();
tile.setLevel(tile.enchantments.indexOf(enchant), Math.max(1, Math.min(maxLevel, level)));
}
}
tile.updateAspectList();
PacketDispatcher.sendPacketToAllPlayers(tile.getDescriptionPacket());
}
| public void handle() {
if(tile.working)
return;
if(level == -1) {
int index = tile.enchantments.indexOf(enchant);
tile.removeLevel(index);
tile.removeEnchant(index);
} else {
if(!tile.enchantments.contains(enchant)){
if(player instanceof EntityPlayer && EnchantmentManager.canApply(tile.getStackInSlot(0), Enchantment.enchantmentsList[enchant], tile.enchantments)&& EnchantmentManager.canEnchantmentBeUsed(((EntityPlayer) player).username, Enchantment.enchantmentsList[enchant])) {
tile.appendEnchant(enchant);
tile.appendLevel(1);
}
} else {
int maxLevel = Enchantment.enchantmentsList[enchant].getMaxLevel();
tile.setLevel(tile.enchantments.indexOf(enchant), Math.max(1, Math.min(maxLevel, level)));
}
}
tile.updateAspectList();
PacketDispatcher.sendPacketToAllPlayers(tile.getDescriptionPacket());
}
|
diff --git a/src/main/java/bspkrs/armorstatushud/ArmorStatusHUD.java b/src/main/java/bspkrs/armorstatushud/ArmorStatusHUD.java
index 62ce82a..eefa768 100644
--- a/src/main/java/bspkrs/armorstatushud/ArmorStatusHUD.java
+++ b/src/main/java/bspkrs/armorstatushud/ArmorStatusHUD.java
@@ -1,272 +1,274 @@
package bspkrs.armorstatushud;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.config.Configuration;
import org.lwjgl.opengl.GL11;
import bspkrs.client.util.ColorThreshold;
import bspkrs.client.util.HUDUtils;
import bspkrs.util.BSConfiguration;
import bspkrs.util.BSLog;
import bspkrs.util.CommonUtils;
import bspkrs.util.Const;
public class ArmorStatusHUD
{
public static final String VERSION_NUMBER = "v1.16(" + Const.MCVERSION + ")";
private static final String DEFAULT_COLOR_LIST = "100,f; 80,7; 60,e; 40,6; 25,c; 10,4";
public static String alignMode = "bottomleft";
// @BSProp(info="Valid list mode strings are horizontal and vertical")
// public static String listMode = "vertical";
public static boolean enableItemName = false;
public static boolean showItemOverlay = true;
public static String damageColorList = DEFAULT_COLOR_LIST;
public static String damageDisplayType = "value";
public static String damageThresholdType = "percent";
public static boolean showMaxDamage = false;
public static boolean showEquippedItem = true;
public static int xOffset = 2;
public static int yOffset = 2;
public static int yOffsetBottomCenter = 41;
public static boolean applyXOffsetToCenter = false;
public static boolean applyYOffsetToMiddle = false;
public static boolean showInChat = false;
private static RenderItem itemRenderer = new RenderItem();
protected static float zLevel = -110.0F;
private static ScaledResolution scaledResolution;
private static final List<ColorThreshold> colorList = new ArrayList<ColorThreshold>();
private static BSConfiguration config;
public static void loadConfig(File file)
{
String ctgyGen = Configuration.CATEGORY_GENERAL;
if (!CommonUtils.isObfuscatedEnv())
{ // debug settings for deobfuscated execution
// if (file.exists())
// file.delete();
}
config = new BSConfiguration(file);
config.load();
alignMode = config.getString("alignMode", ctgyGen, alignMode,
"Valid alignment strings are topleft, topcenter, topright, middleleft, middlecenter, middleright, bottomleft, bottomcenter, bottomright");
// @BSProp(info="Valid list mode strings are horizontal and vertical")
// public static String listMode = "vertical";
enableItemName = config.getBoolean("enableItemName", ctgyGen, enableItemName,
"Set to true to show item names, false to disable");
showItemOverlay = config.getBoolean("showItemOverlay", ctgyGen, showItemOverlay,
"Set to true to show the standard inventory item overlay (damage bar)");
damageColorList = config.getString("damageColorList", ctgyGen, damageColorList,
"This is a list of percent damage thresholds and text color codes that will be used when item damage is <= the threshold. " +
"Format used: \",\" separates the threshold and the color code, \";\" separates each pair. Valid color values are 0-9, a-f " +
"(color values can be found here: http://www.minecraftwiki.net/wiki/File:Colors.png)");
damageDisplayType = config.getString("damageDisplayType", ctgyGen, damageDisplayType,
"Valid damageDisplayType strings are value, percent, or none");
damageThresholdType = config.getString("damageThresholdType", ctgyGen, damageThresholdType,
"The type of threshold to use when applying the damageColorList thresholds. Valid values are \"percent\" and \"value\".");
showMaxDamage = config.getBoolean("showMaxDamage", ctgyGen, showMaxDamage,
"Set to true to show the max damage when damageDisplayType=value");
showEquippedItem = config.getBoolean("showEquippedItem", ctgyGen, showEquippedItem,
"Set to true to show info for your currently equipped item, false to disable");
xOffset = config.getInt("xOffset", ctgyGen, xOffset, Integer.MIN_VALUE, Integer.MAX_VALUE,
"Horizontal offset from the edge of the screen (when using right alignments the x offset is relative to the right edge of the screen)");
yOffset = config.getInt("yOffset", ctgyGen, yOffset, Integer.MIN_VALUE, Integer.MAX_VALUE,
"Vertical offset from the edge of the screen (when using bottom alignments the y offset is relative to the bottom edge of the screen)");
yOffsetBottomCenter = config.getInt("yOffsetBottomCenter", ctgyGen, yOffsetBottomCenter, Integer.MIN_VALUE, Integer.MAX_VALUE,
"Vertical offset used only for the bottomcenter alignment to avoid the vanilla HUD");
applyXOffsetToCenter = config.getBoolean("applyXOffsetToCenter", ctgyGen, applyXOffsetToCenter,
"Set to true if you want the xOffset value to be applied when using a center alignment");
applyYOffsetToMiddle = config.getBoolean("applyYOffsetToMiddle", ctgyGen, applyYOffsetToMiddle,
"Set to true if you want the yOffset value to be applied when using a middle alignment");
showInChat = config.getBoolean("showInChat", ctgyGen, showInChat,
"Set to true to show info when chat is open, false to disable info when chat is open");
config.save();
try
{
for (String s : damageColorList.split(";"))
{
String[] ct = s.split(",");
colorList.add(new ColorThreshold(Integer.valueOf(ct[0].trim()), ct[1]));
}
}
catch (Throwable e)
{
BSLog.warning("Error encountered parsing damageColorList: " + damageColorList);
BSLog.warning("Reverting to defaultColorList: " + DEFAULT_COLOR_LIST);
for (String s : DEFAULT_COLOR_LIST.split(";"))
{
String[] ct = s.split(",");
colorList.add(new ColorThreshold(Integer.valueOf(ct[0]), ct[1]));
}
}
Collections.sort(colorList);
}
public static boolean onTickInGame(Minecraft mc)
{
if ((mc.inGameHasFocus || mc.currentScreen == null || (mc.currentScreen instanceof GuiChat && showInChat)) && !mc.gameSettings.showDebugInfo && !mc.gameSettings.keyBindPlayerList.func_151470_d())
{
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
scaledResolution = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
displayArmorStatus(mc);
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
return true;
}
private static int getX(int width)
{
if (alignMode.toLowerCase().contains("center"))
return scaledResolution.getScaledWidth() / 2 - width / 2 + (applyXOffsetToCenter ? xOffset : 0);
else if (alignMode.toLowerCase().contains("right"))
return scaledResolution.getScaledWidth() - width - xOffset;
else
return xOffset;
}
private static int getY(int rowCount, int height)
{
if (alignMode.toLowerCase().contains("middle"))
return (scaledResolution.getScaledHeight() / 2) - ((rowCount * height) / 2) + (applyYOffsetToMiddle ? yOffset : 0);
else if (alignMode.equalsIgnoreCase("bottomleft") || alignMode.equalsIgnoreCase("bottomright"))
return scaledResolution.getScaledHeight() - (rowCount * height) - yOffset;
else if (alignMode.equalsIgnoreCase("bottomcenter"))
return scaledResolution.getScaledHeight() - (rowCount * height) - yOffsetBottomCenter;
else
return yOffset;
}
public static boolean playerHasArmorEquipped(EntityPlayer player)
{
return player.inventory.armorItemInSlot(0) != null || player.inventory.armorItemInSlot(1) != null || player.inventory.armorItemInSlot(2) != null || player.inventory.armorItemInSlot(3) != null;
}
public static int countOfDisplayableItems(EntityPlayer player)
{
int i = 0;
i += canDisplayItem(player.inventory.armorItemInSlot(0)) ? 1 : 0;
i += canDisplayItem(player.inventory.armorItemInSlot(1)) ? 1 : 0;
i += canDisplayItem(player.inventory.armorItemInSlot(2)) ? 1 : 0;
i += canDisplayItem(player.inventory.armorItemInSlot(3)) ? 1 : 0;
i += showEquippedItem && canDisplayItem(player.getCurrentEquippedItem()) ? 1 : 0;
return i;
}
public static boolean canDisplayItem(ItemStack item)
{
return item != null;
}
private static void displayArmorStatus(Minecraft mc)
{
if (playerHasArmorEquipped(mc.thePlayer) || (showEquippedItem && canDisplayItem(mc.thePlayer.getCurrentEquippedItem())))
{
int yOffset = enableItemName ? 18 : 16;
int yBase = getY(countOfDisplayableItems(mc.thePlayer), yOffset);
for (int i = 3; i >= -1; i--)
{
ItemStack itemStack = null;
if (i == -1 && showEquippedItem)
itemStack = mc.thePlayer.getCurrentEquippedItem();
else if (i != -1)
itemStack = mc.thePlayer.inventory.armorInventory[i];
else
itemStack = null;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if (canDisplayItem(itemStack))
{
int xBase = 0;
int damage = 1;
int maxDamage = 1;
String itemDamage = "";
if (itemStack.isItemStackDamageable())
{
maxDamage = itemStack.getMaxDamage() + 1;
damage = maxDamage - itemStack.getItemDamageForDisplay();
if (damageDisplayType.equalsIgnoreCase("value"))
itemDamage = "\247" + ColorThreshold.getColorCode(colorList,
(damageThresholdType.equalsIgnoreCase("percent") ? damage * 100 / maxDamage : damage)) + damage +
(showMaxDamage ? "/" + maxDamage : "");
else if (damageDisplayType.equalsIgnoreCase("percent"))
itemDamage = "\247" + ColorThreshold.getColorCode(colorList,
(damageThresholdType.equalsIgnoreCase("percent") ? damage * 100 / maxDamage : damage)) + (damage * 100 / maxDamage) + "%";
}
xBase = getX(18 + 4 + mc.fontRenderer.getStringWidth(HUDUtils.stripCtrl(itemDamage)));
String itemName = "";
if (enableItemName)
{
itemName = itemStack.getDisplayName();
xBase = getX(18 + 4 + mc.fontRenderer.getStringWidth(itemName));
}
GL11.glEnable(32826 /* GL_RESCALE_NORMAL_EXT *//* GL_RESCALE_NORMAL_EXT */);
RenderHelper.enableStandardItemLighting();
RenderHelper.enableGUIStandardItemLighting();
itemRenderer.zLevel = 200.0F;
if (alignMode.toLowerCase().contains("right"))
{
xBase = getX(0);
itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.getTextureManager(), itemStack, xBase - 18, yBase);
if (showItemOverlay)
HUDUtils.renderItemOverlayIntoGUI(mc.fontRenderer, itemStack, xBase - 18, yBase);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(32826 /* GL_RESCALE_NORMAL_EXT *//* GL_RESCALE_NORMAL_EXT */);
+ GL11.glDisable(GL11.GL_BLEND);
int stringWidth = mc.fontRenderer.getStringWidth(HUDUtils.stripCtrl(itemName));
mc.fontRenderer.drawStringWithShadow(itemName + "\247r", xBase - 20 - stringWidth, yBase, 0xffffff);
stringWidth = mc.fontRenderer.getStringWidth(HUDUtils.stripCtrl(itemDamage));
mc.fontRenderer.drawStringWithShadow(itemDamage + "\247r", xBase - 20 - stringWidth, yBase + (enableItemName ? 9 : 4), 0xffffff);
}
else
{
itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.getTextureManager(), itemStack, xBase, yBase);
if (showItemOverlay)
HUDUtils.renderItemOverlayIntoGUI(mc.fontRenderer, itemStack, xBase, yBase);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(32826 /* GL_RESCALE_NORMAL_EXT *//* GL_RESCALE_NORMAL_EXT */);
+ GL11.glDisable(GL11.GL_BLEND);
mc.fontRenderer.drawStringWithShadow(itemName + "\247r", xBase + 20, yBase, 0xffffff);
mc.fontRenderer.drawStringWithShadow(itemDamage + "\247r", xBase + 20, yBase + (enableItemName ? 9 : 4), 0xffffff);
}
yBase += yOffset;
}
}
}
}
}
| false | true | private static void displayArmorStatus(Minecraft mc)
{
if (playerHasArmorEquipped(mc.thePlayer) || (showEquippedItem && canDisplayItem(mc.thePlayer.getCurrentEquippedItem())))
{
int yOffset = enableItemName ? 18 : 16;
int yBase = getY(countOfDisplayableItems(mc.thePlayer), yOffset);
for (int i = 3; i >= -1; i--)
{
ItemStack itemStack = null;
if (i == -1 && showEquippedItem)
itemStack = mc.thePlayer.getCurrentEquippedItem();
else if (i != -1)
itemStack = mc.thePlayer.inventory.armorInventory[i];
else
itemStack = null;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if (canDisplayItem(itemStack))
{
int xBase = 0;
int damage = 1;
int maxDamage = 1;
String itemDamage = "";
if (itemStack.isItemStackDamageable())
{
maxDamage = itemStack.getMaxDamage() + 1;
damage = maxDamage - itemStack.getItemDamageForDisplay();
if (damageDisplayType.equalsIgnoreCase("value"))
itemDamage = "\247" + ColorThreshold.getColorCode(colorList,
(damageThresholdType.equalsIgnoreCase("percent") ? damage * 100 / maxDamage : damage)) + damage +
(showMaxDamage ? "/" + maxDamage : "");
else if (damageDisplayType.equalsIgnoreCase("percent"))
itemDamage = "\247" + ColorThreshold.getColorCode(colorList,
(damageThresholdType.equalsIgnoreCase("percent") ? damage * 100 / maxDamage : damage)) + (damage * 100 / maxDamage) + "%";
}
xBase = getX(18 + 4 + mc.fontRenderer.getStringWidth(HUDUtils.stripCtrl(itemDamage)));
String itemName = "";
if (enableItemName)
{
itemName = itemStack.getDisplayName();
xBase = getX(18 + 4 + mc.fontRenderer.getStringWidth(itemName));
}
GL11.glEnable(32826 /* GL_RESCALE_NORMAL_EXT *//* GL_RESCALE_NORMAL_EXT */);
RenderHelper.enableStandardItemLighting();
RenderHelper.enableGUIStandardItemLighting();
itemRenderer.zLevel = 200.0F;
if (alignMode.toLowerCase().contains("right"))
{
xBase = getX(0);
itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.getTextureManager(), itemStack, xBase - 18, yBase);
if (showItemOverlay)
HUDUtils.renderItemOverlayIntoGUI(mc.fontRenderer, itemStack, xBase - 18, yBase);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(32826 /* GL_RESCALE_NORMAL_EXT *//* GL_RESCALE_NORMAL_EXT */);
int stringWidth = mc.fontRenderer.getStringWidth(HUDUtils.stripCtrl(itemName));
mc.fontRenderer.drawStringWithShadow(itemName + "\247r", xBase - 20 - stringWidth, yBase, 0xffffff);
stringWidth = mc.fontRenderer.getStringWidth(HUDUtils.stripCtrl(itemDamage));
mc.fontRenderer.drawStringWithShadow(itemDamage + "\247r", xBase - 20 - stringWidth, yBase + (enableItemName ? 9 : 4), 0xffffff);
}
else
{
itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.getTextureManager(), itemStack, xBase, yBase);
if (showItemOverlay)
HUDUtils.renderItemOverlayIntoGUI(mc.fontRenderer, itemStack, xBase, yBase);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(32826 /* GL_RESCALE_NORMAL_EXT *//* GL_RESCALE_NORMAL_EXT */);
mc.fontRenderer.drawStringWithShadow(itemName + "\247r", xBase + 20, yBase, 0xffffff);
mc.fontRenderer.drawStringWithShadow(itemDamage + "\247r", xBase + 20, yBase + (enableItemName ? 9 : 4), 0xffffff);
}
yBase += yOffset;
}
}
}
}
| private static void displayArmorStatus(Minecraft mc)
{
if (playerHasArmorEquipped(mc.thePlayer) || (showEquippedItem && canDisplayItem(mc.thePlayer.getCurrentEquippedItem())))
{
int yOffset = enableItemName ? 18 : 16;
int yBase = getY(countOfDisplayableItems(mc.thePlayer), yOffset);
for (int i = 3; i >= -1; i--)
{
ItemStack itemStack = null;
if (i == -1 && showEquippedItem)
itemStack = mc.thePlayer.getCurrentEquippedItem();
else if (i != -1)
itemStack = mc.thePlayer.inventory.armorInventory[i];
else
itemStack = null;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if (canDisplayItem(itemStack))
{
int xBase = 0;
int damage = 1;
int maxDamage = 1;
String itemDamage = "";
if (itemStack.isItemStackDamageable())
{
maxDamage = itemStack.getMaxDamage() + 1;
damage = maxDamage - itemStack.getItemDamageForDisplay();
if (damageDisplayType.equalsIgnoreCase("value"))
itemDamage = "\247" + ColorThreshold.getColorCode(colorList,
(damageThresholdType.equalsIgnoreCase("percent") ? damage * 100 / maxDamage : damage)) + damage +
(showMaxDamage ? "/" + maxDamage : "");
else if (damageDisplayType.equalsIgnoreCase("percent"))
itemDamage = "\247" + ColorThreshold.getColorCode(colorList,
(damageThresholdType.equalsIgnoreCase("percent") ? damage * 100 / maxDamage : damage)) + (damage * 100 / maxDamage) + "%";
}
xBase = getX(18 + 4 + mc.fontRenderer.getStringWidth(HUDUtils.stripCtrl(itemDamage)));
String itemName = "";
if (enableItemName)
{
itemName = itemStack.getDisplayName();
xBase = getX(18 + 4 + mc.fontRenderer.getStringWidth(itemName));
}
GL11.glEnable(32826 /* GL_RESCALE_NORMAL_EXT *//* GL_RESCALE_NORMAL_EXT */);
RenderHelper.enableStandardItemLighting();
RenderHelper.enableGUIStandardItemLighting();
itemRenderer.zLevel = 200.0F;
if (alignMode.toLowerCase().contains("right"))
{
xBase = getX(0);
itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.getTextureManager(), itemStack, xBase - 18, yBase);
if (showItemOverlay)
HUDUtils.renderItemOverlayIntoGUI(mc.fontRenderer, itemStack, xBase - 18, yBase);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(32826 /* GL_RESCALE_NORMAL_EXT *//* GL_RESCALE_NORMAL_EXT */);
GL11.glDisable(GL11.GL_BLEND);
int stringWidth = mc.fontRenderer.getStringWidth(HUDUtils.stripCtrl(itemName));
mc.fontRenderer.drawStringWithShadow(itemName + "\247r", xBase - 20 - stringWidth, yBase, 0xffffff);
stringWidth = mc.fontRenderer.getStringWidth(HUDUtils.stripCtrl(itemDamage));
mc.fontRenderer.drawStringWithShadow(itemDamage + "\247r", xBase - 20 - stringWidth, yBase + (enableItemName ? 9 : 4), 0xffffff);
}
else
{
itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.getTextureManager(), itemStack, xBase, yBase);
if (showItemOverlay)
HUDUtils.renderItemOverlayIntoGUI(mc.fontRenderer, itemStack, xBase, yBase);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(32826 /* GL_RESCALE_NORMAL_EXT *//* GL_RESCALE_NORMAL_EXT */);
GL11.glDisable(GL11.GL_BLEND);
mc.fontRenderer.drawStringWithShadow(itemName + "\247r", xBase + 20, yBase, 0xffffff);
mc.fontRenderer.drawStringWithShadow(itemDamage + "\247r", xBase + 20, yBase + (enableItemName ? 9 : 4), 0xffffff);
}
yBase += yOffset;
}
}
}
}
|
diff --git a/src/main/java/org/spout/vanilla/controller/object/moving/Item.java b/src/main/java/org/spout/vanilla/controller/object/moving/Item.java
index b01a8509..a0f5af68 100644
--- a/src/main/java/org/spout/vanilla/controller/object/moving/Item.java
+++ b/src/main/java/org/spout/vanilla/controller/object/moving/Item.java
@@ -1,151 +1,151 @@
/*
* This file is part of vanilla (http://www.spout.org/).
*
* vanilla is licensed under the SpoutDev License Version 1.
*
* vanilla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* vanilla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.vanilla.controller.object.moving;
import java.util.Arrays;
import java.util.List;
import static org.spout.vanilla.protocol.VanillaNetworkSynchronizer.sendPacket;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import org.spout.api.Spout;
import org.spout.api.entity.Entity;
import org.spout.api.geo.World;
import org.spout.api.inventory.ItemStack;
import org.spout.api.material.Material;
import org.spout.api.math.Vector3;
import org.spout.api.player.Player;
import org.spout.vanilla.configuration.VanillaConfiguration;
import org.spout.vanilla.controller.VanillaControllerTypes;
import org.spout.vanilla.controller.object.Substance;
import org.spout.vanilla.protocol.msg.CollectItemMessage;
/**
* Controller that serves as the base for all items that are not in an inventory (dispersed in the world).
*/
public class Item extends Substance {
private final ItemStack is;
private final int roll;
private int unpickable;
public Item(ItemStack is, Vector3 initial) {
super(VanillaControllerTypes.DROPPED_ITEM);
this.is = is;
this.roll = 1;
unpickable = 10;
setVelocity(initial);
}
@Override
public void onTick(float dt) {
if (unpickable > 0) {
unpickable--;
super.onTick(dt);
return;
}
super.onTick(dt);
- this.move();
+ //move();
World world = getParent().getWorld();
if (world == null) {
return;
}
List<Player> players = Arrays.asList(Spout.getEngine().getOnlinePlayers());
Iterable<Player> onlinePlayers = Iterables.filter(players, isValidPlayer);
double minDistance = -1;
Entity closestPlayer = null;
for (Player plr : onlinePlayers) {
Entity entity = plr.getEntity();
if (entity.getWorld().equals(world)) {
double distance = entity.getPosition().getSquaredDistance(getParent().getPosition());
if (distance < minDistance || minDistance == -1) {
closestPlayer = entity;
minDistance = distance;
}
}
}
double maxDistance = VanillaConfiguration.ITEM_PICKUP_RANGE.getDouble();
if (closestPlayer != null && minDistance <= maxDistance * maxDistance) {
int collected = getParent().getId();
int collector = closestPlayer.getId();
for (Player plr : onlinePlayers) {
if (plr.getEntity().getWorld().equals(world)) {
sendPacket(plr, new CollectItemMessage(collected, collector));
}
}
closestPlayer.getInventory().addItem(is, false);
getParent().kill();
}
}
private final Predicate<Player> isValidPlayer = new Predicate<Player>() {
@Override
public boolean apply(Player p) {
return p != null && p.getEntity() != null && p.getEntity().getWorld() != null;
}
};
/**
* Gets what block the item is.
* @return block of item.
*/
public Material getMaterial() {
return is.getMaterial();
}
/**
* Gets the amount of the block there is in the ItemStack.
* @return amount of items
*/
public int getAmount() {
return is.getAmount();
}
/**
* Gets the data of the item
* @return item data
*/
public short getData() {
return is.getData();
}
/**
* Gets the roll of the item
* @return roll of item.
*/
public int getRoll() {
return roll;
}
}
| true | true | public void onTick(float dt) {
if (unpickable > 0) {
unpickable--;
super.onTick(dt);
return;
}
super.onTick(dt);
this.move();
World world = getParent().getWorld();
if (world == null) {
return;
}
List<Player> players = Arrays.asList(Spout.getEngine().getOnlinePlayers());
Iterable<Player> onlinePlayers = Iterables.filter(players, isValidPlayer);
double minDistance = -1;
Entity closestPlayer = null;
for (Player plr : onlinePlayers) {
Entity entity = plr.getEntity();
if (entity.getWorld().equals(world)) {
double distance = entity.getPosition().getSquaredDistance(getParent().getPosition());
if (distance < minDistance || minDistance == -1) {
closestPlayer = entity;
minDistance = distance;
}
}
}
double maxDistance = VanillaConfiguration.ITEM_PICKUP_RANGE.getDouble();
if (closestPlayer != null && minDistance <= maxDistance * maxDistance) {
int collected = getParent().getId();
int collector = closestPlayer.getId();
for (Player plr : onlinePlayers) {
if (plr.getEntity().getWorld().equals(world)) {
sendPacket(plr, new CollectItemMessage(collected, collector));
}
}
closestPlayer.getInventory().addItem(is, false);
getParent().kill();
}
}
| public void onTick(float dt) {
if (unpickable > 0) {
unpickable--;
super.onTick(dt);
return;
}
super.onTick(dt);
//move();
World world = getParent().getWorld();
if (world == null) {
return;
}
List<Player> players = Arrays.asList(Spout.getEngine().getOnlinePlayers());
Iterable<Player> onlinePlayers = Iterables.filter(players, isValidPlayer);
double minDistance = -1;
Entity closestPlayer = null;
for (Player plr : onlinePlayers) {
Entity entity = plr.getEntity();
if (entity.getWorld().equals(world)) {
double distance = entity.getPosition().getSquaredDistance(getParent().getPosition());
if (distance < minDistance || minDistance == -1) {
closestPlayer = entity;
minDistance = distance;
}
}
}
double maxDistance = VanillaConfiguration.ITEM_PICKUP_RANGE.getDouble();
if (closestPlayer != null && minDistance <= maxDistance * maxDistance) {
int collected = getParent().getId();
int collector = closestPlayer.getId();
for (Player plr : onlinePlayers) {
if (plr.getEntity().getWorld().equals(world)) {
sendPacket(plr, new CollectItemMessage(collected, collector));
}
}
closestPlayer.getInventory().addItem(is, false);
getParent().kill();
}
}
|
diff --git a/src/java/com/idega/block/user/presentation/GroupInfo.java b/src/java/com/idega/block/user/presentation/GroupInfo.java
index 9ae2628..d5f31a1 100644
--- a/src/java/com/idega/block/user/presentation/GroupInfo.java
+++ b/src/java/com/idega/block/user/presentation/GroupInfo.java
@@ -1,297 +1,296 @@
/*
* Created on May 4, 2004
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package com.idega.block.user.presentation;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import com.idega.block.user.business.UserInfoBusiness;
import com.idega.block.user.business.UserInfoBusinessBean;
import com.idega.core.contact.data.Email;
import com.idega.core.contact.data.Phone;
import com.idega.core.contact.data.PhoneType;
import com.idega.core.location.data.Address;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.PresentationObject;
import com.idega.presentation.PresentationObjectContainer;
import com.idega.presentation.Table;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.Text;
import com.idega.user.data.Group;
/**
* Displays info on a group, such as name, address, home page, etc.
*/
public class GroupInfo extends Block {
public static final String IW_BUNDLE_IDENTIFIER = "com.idega.block.user";
public static final String PARAM_NAME_GROUP_ID = "group_id";
private IWResourceBundle _iwrb = null;
public void main(IWContext iwc) {
_iwrb = getResourceBundle(iwc);
_biz = UserInfoBusinessBean.getUserInfoBusiness(iwc);
String groupId = iwc.getParameter(PARAM_NAME_GROUP_ID);
Group group = null;
if(groupId!=null && groupId.length()>0) {
try {
group = _biz.getGroup(iwc, groupId);
} catch (RemoteException e) {
e.printStackTrace();
}
}
if(group == null) {
System.out.println("No group found to display info on");
} else {
add(getGroupInfo(iwc, group));
}
}
private PresentationObject getGroupInfo(IWContext iwc, Group group) {
String phone = "";
String fax = "";
if(_showPhone || _showFax) {
Collection phones = group.getPhones();
if(phones!=null) {
Iterator phoneIter = phones.iterator();
while(phoneIter.hasNext()) {
Phone phoneObj = (Phone) phoneIter.next();
if(phoneObj.getPhoneTypeId() == PhoneType.WORK_PHONE_ID) {
phone = emptyIfNull(phoneObj.getNumber());
- break;
} else if(phoneObj.getPhoneTypeId() == PhoneType.FAX_NUMBER_ID) {
fax = emptyIfNull(phoneObj.getNumber());
}
}
}
}
Table table = new Table();
int row = 1;
if(_showName) {
String name = group.getName();
String nameLabel = _iwrb.getLocalizedString("name", "Name: ");
table.add(nameLabel, 2, row);
table.add(name, 3, row++);
}
if(_showShortName) {
String shortName = emptyIfNull(group.getShortName());
if(_showEmptyFields || (shortName!=null && shortName.length()>0)) {
String shortNameLabel = _iwrb.getLocalizedString("shor_name", "Short name: ");
addTextToTable(table, row++, shortNameLabel, shortName);
}
}
if(_showAddress) {
String address = "";
try {
Address addr = _biz.getGroupAddress(iwc, group);
if(addr!=null) {
address = addr.getStreetAddress() + ", " + addr.getPostalCode().getPostalCode() + " " + addr.getCity();
}
} catch (Exception e) {
e.printStackTrace();
}
if(_showEmptyFields || (address!=null && address.length()>0)) {
String addressLabel = _iwrb.getLocalizedString("address", "Address: ");
addTextToTable(table, row++, addressLabel, address);
}
}
if(_showPhone) {
if(_showEmptyFields || (phone!=null && phone.length()>0)) {
String phoneLabel = _iwrb.getLocalizedString("phone", "Phone: ");
addTextToTable(table, row++, phoneLabel, phone);
}
}
if(_showFax) {
if(_showEmptyFields || (fax!=null && fax.length()>0)) {
String faxLabel = _iwrb.getLocalizedString("fax", "Fax: ");
addTextToTable(table, row++, faxLabel, fax);
}
}
if(_showHomePage) {
String homePageURL = emptyIfNull(group.getHomePageURL());
if(_showEmptyFields || (homePageURL!=null && homePageURL.length()>0)) {
String homePageLabel = _iwrb.getLocalizedString("homepage", "Homepage: ");
Link link = new Link();
link.setText(homePageURL);
link.setURL(homePageURL);
addPOToTable(table, row++, homePageLabel, link);
}
}
if(_showEmails) {
PresentationObject emails = getEmailLinkList(group);
if(_showEmptyFields || (emails!=null)) {
Text emailsLabel = new Text(_iwrb.getLocalizedString("email", "Email: "));
emailsLabel.setStyle(_textLabelStyle);
table.add(emailsLabel, 2, row);
if(emails!=null) {
table.add(emails, 3, row++);
}
}
}
if(_showDescription) {
String description = emptyIfNull(group.getDescription());
if(_showEmptyFields || (description!=null && description.length()>0)) {
String descriptionLabel = _iwrb.getLocalizedString("description", "Description: ");
addTextToTable(table, row++, descriptionLabel, description);
}
}
if(_showExtraInfo) {
String extraInfo = emptyIfNull(group.getExtraInfo());
if(_showEmptyFields || (extraInfo!=null && extraInfo.length()>0)) {
String extraInfoLabel = _iwrb.getLocalizedString("extra_info", "Info: ");
addTextToTable(table, row++, extraInfoLabel, extraInfo);
}
}
return table;
}
/**
* Utility method for adding text to a table
* @param table
* @param row
* @param strLabel
* @param strText
*/
private void addTextToTable(Table table, int row, String strLabel, String strText) {
Text text = new Text(strText);
text.setStyle(_textInfoStyle);
Text label = new Text(strLabel);
label.setStyle(_textLabelStyle);
table.add(label, 2, row);
table.add(text, 3, row);
}
/**
* Utility method for adding a PresentationObject to a table
* @param table
* @param row
* @param strLabel
* @param po
*/
private void addPOToTable(Table table, int row, String strLabel, PresentationObject po) {
Text label = new Text(strLabel);
label.setStyle(_textLabelStyle);
table.add(label, 2, row);
table.add(po, 3, row);
}
private String emptyIfNull(String str) {
return str==null?"":str;
}
/**
* Gets a comma separate list of user's emails, as links
* @param user The user
* @return The user's emails in comma separated list of links
*/
private PresentationObject getEmailLinkList(Group group) {
PresentationObjectContainer container = new PresentationObjectContainer();
//int row = 1;
try {
// @TODO use email list from business bean
Iterator emailIter = group.getEmails().iterator();
if(emailIter==null || !emailIter.hasNext()) {
// no emails for group
System.out.println("No emails for group " + group.getName());
return null;
}
boolean isFirst = true;
while(emailIter.hasNext()) {
if(isFirst) {
isFirst = false;
} else {
container.add(", ");
}
Email email = (Email) emailIter.next();
String address = email.getEmailAddress();
Link link = new Link(address);
link.setURL("mailto:" + address);
link.setSessionId(false);
container.add(link);
}
} catch(Exception e) {
System.out.println("Exception getting emails for group " + group.getName() + ", no emails shown");
e.printStackTrace();
}
return container;
}
public String getBundleIdentifier() {
return IW_BUNDLE_IDENTIFIER;
}
public void setShowName(boolean value) {
_showName = value;
}
public void setShowHomePage(boolean value) {
_showHomePage = value;
}
public void setShowDescription(boolean value) {
_showDescription = value;
}
public void setShowExtraInfo(boolean value) {
_showExtraInfo = value;
}
public void setShowShortName(boolean value) {
_showShortName = value;
}
public void setShowPhone(boolean value) {
_showPhone = value;
}
public void setShowFax(boolean value) {
_showFax = value;
}
public void setShowEmails(boolean value) {
_showEmails = value;
}
public void setShowAddress(boolean value) {
_showAddress = value;
}
public void setTextInfoStyle(String style) {
_textInfoStyle = style;
}
public void setTextLabelStyle(String style) {
_textLabelStyle = style;
}
public void setShowEmptyFields(boolean value) {
_showEmptyFields = value;
}
private boolean _showName = true;
private boolean _showHomePage = false;
private boolean _showDescription = false;
private boolean _showExtraInfo = false;
private boolean _showShortName = false;
private boolean _showPhone = false;
private boolean _showFax = false;
private boolean _showEmails = false;
private boolean _showAddress = false;
private boolean _showEmptyFields = true;
private String _textInfoStyle = "font-family: Arial, Helvetica,sans-serif;font-size: 8pt;color: #000000;";
private String _textLabelStyle = "font-family: Arial, Helvetica,sans-serif;font-weight:bold;font-size: 8pt;color: #000000;";
private UserInfoBusiness _biz = null;
}
| true | true | private PresentationObject getGroupInfo(IWContext iwc, Group group) {
String phone = "";
String fax = "";
if(_showPhone || _showFax) {
Collection phones = group.getPhones();
if(phones!=null) {
Iterator phoneIter = phones.iterator();
while(phoneIter.hasNext()) {
Phone phoneObj = (Phone) phoneIter.next();
if(phoneObj.getPhoneTypeId() == PhoneType.WORK_PHONE_ID) {
phone = emptyIfNull(phoneObj.getNumber());
break;
} else if(phoneObj.getPhoneTypeId() == PhoneType.FAX_NUMBER_ID) {
fax = emptyIfNull(phoneObj.getNumber());
}
}
}
}
Table table = new Table();
int row = 1;
if(_showName) {
String name = group.getName();
String nameLabel = _iwrb.getLocalizedString("name", "Name: ");
table.add(nameLabel, 2, row);
table.add(name, 3, row++);
}
if(_showShortName) {
String shortName = emptyIfNull(group.getShortName());
if(_showEmptyFields || (shortName!=null && shortName.length()>0)) {
String shortNameLabel = _iwrb.getLocalizedString("shor_name", "Short name: ");
addTextToTable(table, row++, shortNameLabel, shortName);
}
}
if(_showAddress) {
String address = "";
try {
Address addr = _biz.getGroupAddress(iwc, group);
if(addr!=null) {
address = addr.getStreetAddress() + ", " + addr.getPostalCode().getPostalCode() + " " + addr.getCity();
}
} catch (Exception e) {
e.printStackTrace();
}
if(_showEmptyFields || (address!=null && address.length()>0)) {
String addressLabel = _iwrb.getLocalizedString("address", "Address: ");
addTextToTable(table, row++, addressLabel, address);
}
}
if(_showPhone) {
if(_showEmptyFields || (phone!=null && phone.length()>0)) {
String phoneLabel = _iwrb.getLocalizedString("phone", "Phone: ");
addTextToTable(table, row++, phoneLabel, phone);
}
}
if(_showFax) {
if(_showEmptyFields || (fax!=null && fax.length()>0)) {
String faxLabel = _iwrb.getLocalizedString("fax", "Fax: ");
addTextToTable(table, row++, faxLabel, fax);
}
}
if(_showHomePage) {
String homePageURL = emptyIfNull(group.getHomePageURL());
if(_showEmptyFields || (homePageURL!=null && homePageURL.length()>0)) {
String homePageLabel = _iwrb.getLocalizedString("homepage", "Homepage: ");
Link link = new Link();
link.setText(homePageURL);
link.setURL(homePageURL);
addPOToTable(table, row++, homePageLabel, link);
}
}
if(_showEmails) {
PresentationObject emails = getEmailLinkList(group);
if(_showEmptyFields || (emails!=null)) {
Text emailsLabel = new Text(_iwrb.getLocalizedString("email", "Email: "));
emailsLabel.setStyle(_textLabelStyle);
table.add(emailsLabel, 2, row);
if(emails!=null) {
table.add(emails, 3, row++);
}
}
}
if(_showDescription) {
String description = emptyIfNull(group.getDescription());
if(_showEmptyFields || (description!=null && description.length()>0)) {
String descriptionLabel = _iwrb.getLocalizedString("description", "Description: ");
addTextToTable(table, row++, descriptionLabel, description);
}
}
if(_showExtraInfo) {
String extraInfo = emptyIfNull(group.getExtraInfo());
if(_showEmptyFields || (extraInfo!=null && extraInfo.length()>0)) {
String extraInfoLabel = _iwrb.getLocalizedString("extra_info", "Info: ");
addTextToTable(table, row++, extraInfoLabel, extraInfo);
}
}
return table;
}
| private PresentationObject getGroupInfo(IWContext iwc, Group group) {
String phone = "";
String fax = "";
if(_showPhone || _showFax) {
Collection phones = group.getPhones();
if(phones!=null) {
Iterator phoneIter = phones.iterator();
while(phoneIter.hasNext()) {
Phone phoneObj = (Phone) phoneIter.next();
if(phoneObj.getPhoneTypeId() == PhoneType.WORK_PHONE_ID) {
phone = emptyIfNull(phoneObj.getNumber());
} else if(phoneObj.getPhoneTypeId() == PhoneType.FAX_NUMBER_ID) {
fax = emptyIfNull(phoneObj.getNumber());
}
}
}
}
Table table = new Table();
int row = 1;
if(_showName) {
String name = group.getName();
String nameLabel = _iwrb.getLocalizedString("name", "Name: ");
table.add(nameLabel, 2, row);
table.add(name, 3, row++);
}
if(_showShortName) {
String shortName = emptyIfNull(group.getShortName());
if(_showEmptyFields || (shortName!=null && shortName.length()>0)) {
String shortNameLabel = _iwrb.getLocalizedString("shor_name", "Short name: ");
addTextToTable(table, row++, shortNameLabel, shortName);
}
}
if(_showAddress) {
String address = "";
try {
Address addr = _biz.getGroupAddress(iwc, group);
if(addr!=null) {
address = addr.getStreetAddress() + ", " + addr.getPostalCode().getPostalCode() + " " + addr.getCity();
}
} catch (Exception e) {
e.printStackTrace();
}
if(_showEmptyFields || (address!=null && address.length()>0)) {
String addressLabel = _iwrb.getLocalizedString("address", "Address: ");
addTextToTable(table, row++, addressLabel, address);
}
}
if(_showPhone) {
if(_showEmptyFields || (phone!=null && phone.length()>0)) {
String phoneLabel = _iwrb.getLocalizedString("phone", "Phone: ");
addTextToTable(table, row++, phoneLabel, phone);
}
}
if(_showFax) {
if(_showEmptyFields || (fax!=null && fax.length()>0)) {
String faxLabel = _iwrb.getLocalizedString("fax", "Fax: ");
addTextToTable(table, row++, faxLabel, fax);
}
}
if(_showHomePage) {
String homePageURL = emptyIfNull(group.getHomePageURL());
if(_showEmptyFields || (homePageURL!=null && homePageURL.length()>0)) {
String homePageLabel = _iwrb.getLocalizedString("homepage", "Homepage: ");
Link link = new Link();
link.setText(homePageURL);
link.setURL(homePageURL);
addPOToTable(table, row++, homePageLabel, link);
}
}
if(_showEmails) {
PresentationObject emails = getEmailLinkList(group);
if(_showEmptyFields || (emails!=null)) {
Text emailsLabel = new Text(_iwrb.getLocalizedString("email", "Email: "));
emailsLabel.setStyle(_textLabelStyle);
table.add(emailsLabel, 2, row);
if(emails!=null) {
table.add(emails, 3, row++);
}
}
}
if(_showDescription) {
String description = emptyIfNull(group.getDescription());
if(_showEmptyFields || (description!=null && description.length()>0)) {
String descriptionLabel = _iwrb.getLocalizedString("description", "Description: ");
addTextToTable(table, row++, descriptionLabel, description);
}
}
if(_showExtraInfo) {
String extraInfo = emptyIfNull(group.getExtraInfo());
if(_showEmptyFields || (extraInfo!=null && extraInfo.length()>0)) {
String extraInfoLabel = _iwrb.getLocalizedString("extra_info", "Info: ");
addTextToTable(table, row++, extraInfoLabel, extraInfo);
}
}
return table;
}
|
diff --git a/src/org/mozilla/javascript/Parser.java b/src/org/mozilla/javascript/Parser.java
index 224b2bcb..28fa5263 100644
--- a/src/org/mozilla/javascript/Parser.java
+++ b/src/org/mozilla/javascript/Parser.java
@@ -1,1557 +1,1556 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Mike Ang
* Mike McCabe
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.io.IOException;
/**
* This class implements the JavaScript parser.
*
* It is based on the C source files jsparse.c and jsparse.h
* in the jsref package.
*
* @see TokenStream
*
* @author Mike McCabe
* @author Brendan Eich
*/
class Parser {
public Parser(IRFactory nf) {
this.nf = nf;
}
private void mustMatchToken(TokenStream ts, int toMatch, String messageId)
throws IOException, JavaScriptException
{
int tt;
if ((tt = ts.getToken()) != toMatch) {
reportError(ts, messageId);
ts.ungetToken(tt); // In case the parser decides to continue
}
}
private void reportError(TokenStream ts, String messageId)
throws JavaScriptException
{
this.ok = false;
ts.reportSyntaxError(messageId, null);
/* Throw an exception to unwind the recursive descent parse.
* We use JavaScriptException here even though it is really
* a different use of the exception than it is usually used
* for.
*/
throw new JavaScriptException(messageId);
}
/*
* Build a parse tree from the given TokenStream.
*
* @param ts the TokenStream to parse
*
* @return an Object representing the parsed
* program. If the parse fails, null will be returned. (The
* parse failure will result in a call to the current Context's
* ErrorReporter.)
*/
public Object parse(TokenStream ts)
throws IOException
{
this.ok = true;
sourceTop = 0;
functionNumber = 0;
int tt; // last token from getToken();
int baseLineno = ts.getLineno(); // line number where source starts
/* so we have something to add nodes to until
* we've collected all the source */
Object tempBlock = nf.createLeaf(TokenStream.BLOCK);
while (true) {
ts.flags |= ts.TSF_REGEXP;
tt = ts.getToken();
ts.flags &= ~ts.TSF_REGEXP;
if (tt <= ts.EOF) {
break;
}
if (tt == ts.FUNCTION) {
try {
nf.addChildToBack(tempBlock, function(ts, false));
} catch (JavaScriptException e) {
this.ok = false;
break;
}
} else {
ts.ungetToken(tt);
nf.addChildToBack(tempBlock, statement(ts));
}
}
if (!this.ok) {
// XXX ts.clearPushback() call here?
return null;
}
Object pn = nf.createScript(tempBlock, ts.getSourceName(),
baseLineno, ts.getLineno(),
sourceToString(0));
return pn;
}
/*
* The C version of this function takes an argument list,
* which doesn't seem to be needed for tree generation...
* it'd only be useful for checking argument hiding, which
* I'm not doing anyway...
*/
private Object parseFunctionBody(TokenStream ts)
throws IOException
{
int oldflags = ts.flags;
ts.flags &= ~(TokenStream.TSF_RETURN_EXPR
| TokenStream.TSF_RETURN_VOID);
ts.flags |= TokenStream.TSF_FUNCTION;
Object pn = nf.createBlock(ts.getLineno());
try {
int tt;
while((tt = ts.peekToken()) > ts.EOF && tt != ts.RC) {
if (tt == TokenStream.FUNCTION) {
ts.getToken();
nf.addChildToBack(pn, function(ts, false));
} else {
nf.addChildToBack(pn, statement(ts));
}
}
} catch (JavaScriptException e) {
this.ok = false;
} finally {
// also in finally block:
// flushNewLines, clearPushback.
ts.flags = oldflags;
}
return pn;
}
private Object function(TokenStream ts, boolean isExpr)
throws IOException, JavaScriptException
{
int baseLineno = ts.getLineno(); // line number where source starts
String name;
Object memberExprNode = null;
if (ts.matchToken(ts.NAME)) {
name = ts.getString();
if (!ts.matchToken(ts.LP)) {
if (Context.getContext().hasFeature
(Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME))
{
// Extension to ECMA: if 'function <name>' does not follow
// by '(', assume <name> starts memberExpr
sourceAddString(ts.NAME, name);
Object memberExprHead = nf.createName(name);
name = null;
memberExprNode = memberExprTail(ts, false, memberExprHead);
}
mustMatchToken(ts, ts.LP, "msg.no.paren.parms");
}
}
else if (ts.matchToken(ts.LP)) {
// Anonymous function
name = null;
}
else {
name = null;
if (Context.getContext().hasFeature
(Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME))
{
// Note that memberExpr can not start with '(' like
// in (1+2).toString, because 'function (' already
// processed as anonymous function
memberExprNode = memberExpr(ts, false);
}
mustMatchToken(ts, ts.LP, "msg.no.paren.parms");
}
if (memberExprNode != null) {
// transform 'function' <memberExpr> to <memberExpr> = function
// even in the decompilated source
sourceAdd((char)ts.ASSIGN);
sourceAdd((char)ts.NOP);
}
// save a reference to the function in the enclosing source.
sourceAdd((char) ts.FUNCTION);
sourceAdd((char)functionNumber);
++functionNumber;
// Save current source top to restore it on exit not to include
// function to parent source
int savedSourceTop = sourceTop;
int savedFunctionNumber = functionNumber;
Object args;
Object body;
String source;
try {
functionNumber = 0;
// FUNCTION as the first token in a Source means it's a function
// definition, and not a reference.
sourceAdd((char) ts.FUNCTION);
if (name != null) { sourceAddString(ts.NAME, name); }
sourceAdd((char) ts.LP);
args = nf.createLeaf(ts.LP);
if (!ts.matchToken(ts.RP)) {
boolean first = true;
do {
if (!first)
sourceAdd((char)ts.COMMA);
first = false;
mustMatchToken(ts, ts.NAME, "msg.no.parm");
String s = ts.getString();
nf.addChildToBack(args, nf.createName(s));
sourceAddString(ts.NAME, s);
} while (ts.matchToken(ts.COMMA));
mustMatchToken(ts, ts.RP, "msg.no.paren.after.parms");
}
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.body");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
body = parseFunctionBody(ts);
mustMatchToken(ts, ts.RC, "msg.no.brace.after.body");
sourceAdd((char)ts.RC);
// skip the last EOL so nested functions work...
// name might be null;
source = sourceToString(savedSourceTop);
}
finally {
sourceTop = savedSourceTop;
functionNumber = savedFunctionNumber;
}
Object pn = nf.createFunction(name, args, body,
ts.getSourceName(),
baseLineno, ts.getLineno(),
source,
isExpr || memberExprNode != null);
if (memberExprNode != null) {
pn = nf.createBinary(ts.ASSIGN, ts.NOP, memberExprNode, pn);
}
// Add EOL but only if function is not part of expression, in which
// case it gets SEMI + EOL from Statement.
if (!isExpr) {
if (memberExprNode != null) {
// Add ';' to make 'function x.f(){}' and 'x.f = function(){}'
// to print the same strings when decompiling
sourceAdd((char)ts.SEMI);
}
sourceAdd((char)ts.EOL);
wellTerminated(ts, ts.FUNCTION);
}
return pn;
}
private Object statements(TokenStream ts)
throws IOException
{
Object pn = nf.createBlock(ts.getLineno());
int tt;
while((tt = ts.peekToken()) > ts.EOF && tt != ts.RC) {
nf.addChildToBack(pn, statement(ts));
}
return pn;
}
private Object condition(TokenStream ts)
throws IOException, JavaScriptException
{
Object pn;
mustMatchToken(ts, ts.LP, "msg.no.paren.cond");
sourceAdd((char)ts.LP);
pn = expr(ts, false);
mustMatchToken(ts, ts.RP, "msg.no.paren.after.cond");
sourceAdd((char)ts.RP);
// there's a check here in jsparse.c that corrects = to ==
return pn;
}
private boolean wellTerminated(TokenStream ts, int lastExprType)
throws IOException, JavaScriptException
{
int tt = ts.peekTokenSameLine();
if (tt == ts.ERROR) {
return false;
}
if (tt != ts.EOF && tt != ts.EOL
&& tt != ts.SEMI && tt != ts.RC)
{
int version = Context.getContext().getLanguageVersion();
if ((tt == ts.FUNCTION || lastExprType == ts.FUNCTION) &&
(version < Context.VERSION_1_2)) {
/*
* Checking against version < 1.2 and version >= 1.0
* in the above line breaks old javascript, so we keep it
* this way for now... XXX warning needed?
*/
return true;
} else {
reportError(ts, "msg.no.semi.stmt");
}
}
return true;
}
// match a NAME; return null if no match.
private String matchLabel(TokenStream ts)
throws IOException, JavaScriptException
{
int lineno = ts.getLineno();
String label = null;
int tt;
tt = ts.peekTokenSameLine();
if (tt == ts.NAME) {
ts.getToken();
label = ts.getString();
}
if (lineno == ts.getLineno())
wellTerminated(ts, ts.ERROR);
return label;
}
private Object statement(TokenStream ts)
throws IOException
{
try {
return statementHelper(ts);
} catch (JavaScriptException e) {
// skip to end of statement
int lineno = ts.getLineno();
int t;
do {
t = ts.getToken();
} while (t != TokenStream.SEMI && t != TokenStream.EOL &&
t != TokenStream.EOF && t != TokenStream.ERROR);
return nf.createExprStatement(nf.createName("error"), lineno);
}
}
/**
* Whether the "catch (e: e instanceof Exception) { ... }" syntax
* is implemented.
*/
private Object statementHelper(TokenStream ts)
throws IOException, JavaScriptException
{
Object pn = null;
// If skipsemi == true, don't add SEMI + EOL to source at the
// end of this statment. For compound statements, IF/FOR etc.
boolean skipsemi = false;
int tt;
int lastExprType = 0; // For wellTerminated. 0 to avoid warning.
tt = ts.getToken();
switch(tt) {
case TokenStream.IF: {
skipsemi = true;
sourceAdd((char)ts.IF);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object ifTrue = statement(ts);
Object ifFalse = null;
if (ts.matchToken(ts.ELSE)) {
sourceAdd((char)ts.RC);
sourceAdd((char)ts.ELSE);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
ifFalse = statement(ts);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createIf(cond, ifTrue, ifFalse, lineno);
break;
}
case TokenStream.SWITCH: {
skipsemi = true;
sourceAdd((char)ts.SWITCH);
pn = nf.createSwitch(ts.getLineno());
Object cur_case = null; // to kill warning
Object case_statements;
mustMatchToken(ts, ts.LP, "msg.no.paren.switch");
sourceAdd((char)ts.LP);
nf.addChildToBack(pn, expr(ts, false));
mustMatchToken(ts, ts.RP, "msg.no.paren.after.switch");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.switch");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
while ((tt = ts.getToken()) != ts.RC && tt != ts.EOF) {
switch(tt) {
case TokenStream.CASE:
sourceAdd((char)ts.CASE);
cur_case = nf.createUnary(ts.CASE, expr(ts, false));
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
break;
case TokenStream.DEFAULT:
cur_case = nf.createLeaf(ts.DEFAULT);
sourceAdd((char)ts.DEFAULT);
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
// XXX check that there isn't more than one default
break;
default:
reportError(ts, "msg.bad.switch");
break;
}
mustMatchToken(ts, ts.COLON, "msg.no.colon.case");
case_statements = nf.createLeaf(TokenStream.BLOCK);
while ((tt = ts.peekToken()) != ts.RC && tt != ts.CASE &&
tt != ts.DEFAULT && tt != ts.EOF)
{
nf.addChildToBack(case_statements, statement(ts));
}
// assert cur_case
nf.addChildToBack(cur_case, case_statements);
nf.addChildToBack(pn, cur_case);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
break;
}
case TokenStream.WHILE: {
skipsemi = true;
sourceAdd((char)ts.WHILE);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWhile(cond, body, lineno);
break;
}
case TokenStream.DO: {
sourceAdd((char)ts.DO);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
int lineno = ts.getLineno();
Object body = statement(ts);
sourceAdd((char)ts.RC);
mustMatchToken(ts, ts.WHILE, "msg.no.while.do");
sourceAdd((char)ts.WHILE);
Object cond = condition(ts);
pn = nf.createDoWhile(body, cond, lineno);
break;
}
case TokenStream.FOR: {
skipsemi = true;
sourceAdd((char)ts.FOR);
int lineno = ts.getLineno();
Object init; // Node init is also foo in 'foo in Object'
Object cond; // Node cond is also object in 'foo in Object'
Object incr = null; // to kill warning
Object body;
mustMatchToken(ts, ts.LP, "msg.no.paren.for");
sourceAdd((char)ts.LP);
tt = ts.peekToken();
if (tt == ts.SEMI) {
init = nf.createLeaf(ts.VOID);
} else {
if (tt == ts.VAR) {
// set init to a var list or initial
ts.getToken(); // throw away the 'var' token
init = variables(ts, true);
}
else {
init = expr(ts, true);
}
}
tt = ts.peekToken();
if (tt == ts.RELOP && ts.getOp() == ts.IN) {
ts.matchToken(ts.RELOP);
sourceAdd((char)ts.IN);
// 'cond' is the object over which we're iterating
cond = expr(ts, false);
} else { // ordinary for loop
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.SEMI) {
// no loop condition
cond = nf.createLeaf(ts.VOID);
} else {
cond = expr(ts, false);
}
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for.cond");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.RP) {
incr = nf.createLeaf(ts.VOID);
} else {
incr = expr(ts, false);
}
}
mustMatchToken(ts, ts.RP, "msg.no.paren.for.ctrl");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
if (incr == null) {
// cond could be null if 'in obj' got eaten by the init node.
pn = nf.createForIn(init, cond, body, lineno);
} else {
pn = nf.createFor(init, cond, incr, body, lineno);
}
break;
}
case TokenStream.TRY: {
int lineno = ts.getLineno();
Object tryblock;
Object catchblocks = null;
Object finallyblock = null;
skipsemi = true;
sourceAdd((char)ts.TRY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
tryblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
catchblocks = nf.createLeaf(TokenStream.BLOCK);
boolean sawDefaultCatch = false;
int peek = ts.peekToken();
if (peek == ts.CATCH) {
while (ts.matchToken(ts.CATCH)) {
if (sawDefaultCatch) {
reportError(ts, "msg.catch.unreachable");
}
sourceAdd((char)ts.CATCH);
mustMatchToken(ts, ts.LP, "msg.no.paren.catch");
sourceAdd((char)ts.LP);
mustMatchToken(ts, ts.NAME, "msg.bad.catchcond");
String varName = ts.getString();
sourceAddString(ts.NAME, varName);
Object catchCond = null;
if (ts.matchToken(ts.IF)) {
sourceAdd((char)ts.IF);
catchCond = expr(ts, false);
} else {
sawDefaultCatch = true;
}
mustMatchToken(ts, ts.RP, "msg.bad.catchcond");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.catchblock");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
nf.addChildToBack(catchblocks,
nf.createCatch(varName, catchCond,
statements(ts),
ts.getLineno()));
mustMatchToken(ts, ts.RC, "msg.no.brace.after.body");
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
} else if (peek != ts.FINALLY) {
mustMatchToken(ts, ts.FINALLY, "msg.try.no.catchfinally");
}
if (ts.matchToken(ts.FINALLY)) {
sourceAdd((char)ts.FINALLY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
finallyblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
pn = nf.createTryCatchFinally(tryblock, catchblocks,
finallyblock, lineno);
break;
}
case TokenStream.THROW: {
int lineno = ts.getLineno();
sourceAdd((char)ts.THROW);
pn = nf.createThrow(expr(ts, false), lineno);
if (lineno == ts.getLineno())
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.BREAK: {
int lineno = ts.getLineno();
sourceAdd((char)ts.BREAK);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createBreak(label, lineno);
break;
}
case TokenStream.CONTINUE: {
int lineno = ts.getLineno();
sourceAdd((char)ts.CONTINUE);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createContinue(label, lineno);
break;
}
case TokenStream.WITH: {
skipsemi = true;
sourceAdd((char)ts.WITH);
int lineno = ts.getLineno();
mustMatchToken(ts, ts.LP, "msg.no.paren.with");
sourceAdd((char)ts.LP);
Object obj = expr(ts, false);
mustMatchToken(ts, ts.RP, "msg.no.paren.after.with");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWith(obj, body, lineno);
break;
}
case TokenStream.VAR: {
int lineno = ts.getLineno();
pn = variables(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.RETURN: {
Object retExpr = null;
- int lineno = 0;
sourceAdd((char)ts.RETURN);
// bail if we're not in a (toplevel) function
if ((ts.flags & ts.TSF_FUNCTION) == 0)
reportError(ts, "msg.bad.return");
/* This is ugly, but we don't want to require a semicolon. */
ts.flags |= ts.TSF_REGEXP;
tt = ts.peekTokenSameLine();
ts.flags &= ~ts.TSF_REGEXP;
+ int lineno = ts.getLineno();
if (tt != ts.EOF && tt != ts.EOL && tt != ts.SEMI && tt != ts.RC) {
- lineno = ts.getLineno();
retExpr = expr(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
ts.flags |= ts.TSF_RETURN_EXPR;
} else {
ts.flags |= ts.TSF_RETURN_VOID;
}
// XXX ASSERT pn
pn = nf.createReturn(retExpr, lineno);
break;
}
case TokenStream.LC:
skipsemi = true;
pn = statements(ts);
mustMatchToken(ts, ts.RC, "msg.no.brace.block");
break;
case TokenStream.ERROR:
// Fall thru, to have a node for error recovery to work on
case TokenStream.EOL:
case TokenStream.SEMI:
pn = nf.createLeaf(ts.VOID);
skipsemi = true;
break;
default: {
lastExprType = tt;
int tokenno = ts.getTokenno();
ts.ungetToken(tt);
int lineno = ts.getLineno();
pn = expr(ts, false);
if (ts.peekToken() == ts.COLON) {
/* check that the last thing the tokenizer returned was a
* NAME and that only one token was consumed.
*/
if (lastExprType != ts.NAME || (ts.getTokenno() != tokenno))
reportError(ts, "msg.bad.label");
ts.getToken(); // eat the COLON
/* in the C source, the label is associated with the
* statement that follows:
* nf.addChildToBack(pn, statement(ts));
*/
String name = ts.getString();
pn = nf.createLabel(name, lineno);
// depend on decompiling lookahead to guess that that
// last name was a label.
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
return pn;
}
if (lastExprType == ts.FUNCTION) {
if (nf.getLeafType(pn) != ts.FUNCTION) {
reportError(ts, "msg.syntax");
}
nf.setFunctionExpressionStatement(pn);
}
pn = nf.createExprStatement(pn, lineno);
/*
* Check explicitly against (multi-line) function
* statement.
* lastExprEndLine is a hack to fix an
* automatic semicolon insertion problem with function
* expressions; the ts.getLineno() == lineno check was
* firing after a function definition even though the
* next statement was on a new line, because
* speculative getToken calls advanced the line number
* even when they didn't succeed.
*/
if (ts.getLineno() == lineno ||
(lastExprType == ts.FUNCTION &&
ts.getLineno() == lastExprEndLine))
{
wellTerminated(ts, lastExprType);
}
break;
}
}
ts.matchToken(ts.SEMI);
if (!skipsemi) {
sourceAdd((char)ts.SEMI);
sourceAdd((char)ts.EOL);
}
return pn;
}
private Object variables(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = nf.createVariables(ts.getLineno());
boolean first = true;
sourceAdd((char)ts.VAR);
for (;;) {
Object name;
Object init;
mustMatchToken(ts, ts.NAME, "msg.bad.var");
String s = ts.getString();
if (!first)
sourceAdd((char)ts.COMMA);
first = false;
sourceAddString(ts.NAME, s);
name = nf.createName(s);
// omitted check for argument hiding
if (ts.matchToken(ts.ASSIGN)) {
if (ts.getOp() != ts.NOP)
reportError(ts, "msg.bad.var.init");
sourceAdd((char)ts.ASSIGN);
sourceAdd((char)ts.NOP);
init = assignExpr(ts, inForInit);
nf.addChildToBack(name, init);
}
nf.addChildToBack(pn, name);
if (!ts.matchToken(ts.COMMA))
break;
}
return pn;
}
private Object expr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = assignExpr(ts, inForInit);
while (ts.matchToken(ts.COMMA)) {
sourceAdd((char)ts.COMMA);
pn = nf.createBinary(ts.COMMA, pn, assignExpr(ts, inForInit));
}
return pn;
}
private Object assignExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = condExpr(ts, inForInit);
if (ts.matchToken(ts.ASSIGN)) {
// omitted: "invalid assignment left-hand side" check.
sourceAdd((char)ts.ASSIGN);
sourceAdd((char)ts.getOp());
pn = nf.createBinary(ts.ASSIGN, ts.getOp(), pn,
assignExpr(ts, inForInit));
}
return pn;
}
private Object condExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object ifTrue;
Object ifFalse;
Object pn = orExpr(ts, inForInit);
if (ts.matchToken(ts.HOOK)) {
sourceAdd((char)ts.HOOK);
ifTrue = assignExpr(ts, false);
mustMatchToken(ts, ts.COLON, "msg.no.colon.cond");
sourceAdd((char)ts.COLON);
ifFalse = assignExpr(ts, inForInit);
return nf.createTernary(pn, ifTrue, ifFalse);
}
return pn;
}
private Object orExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = andExpr(ts, inForInit);
if (ts.matchToken(ts.OR)) {
sourceAdd((char)ts.OR);
pn = nf.createBinary(ts.OR, pn, orExpr(ts, inForInit));
}
return pn;
}
private Object andExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = bitOrExpr(ts, inForInit);
if (ts.matchToken(ts.AND)) {
sourceAdd((char)ts.AND);
pn = nf.createBinary(ts.AND, pn, andExpr(ts, inForInit));
}
return pn;
}
private Object bitOrExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = bitXorExpr(ts, inForInit);
while (ts.matchToken(ts.BITOR)) {
sourceAdd((char)ts.BITOR);
pn = nf.createBinary(ts.BITOR, pn, bitXorExpr(ts, inForInit));
}
return pn;
}
private Object bitXorExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = bitAndExpr(ts, inForInit);
while (ts.matchToken(ts.BITXOR)) {
sourceAdd((char)ts.BITXOR);
pn = nf.createBinary(ts.BITXOR, pn, bitAndExpr(ts, inForInit));
}
return pn;
}
private Object bitAndExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = eqExpr(ts, inForInit);
while (ts.matchToken(ts.BITAND)) {
sourceAdd((char)ts.BITAND);
pn = nf.createBinary(ts.BITAND, pn, eqExpr(ts, inForInit));
}
return pn;
}
private Object eqExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = relExpr(ts, inForInit);
while (ts.matchToken(ts.EQOP)) {
sourceAdd((char)ts.EQOP);
sourceAdd((char)ts.getOp());
pn = nf.createBinary(ts.EQOP, ts.getOp(), pn,
relExpr(ts, inForInit));
}
return pn;
}
private Object relExpr(TokenStream ts, boolean inForInit)
throws IOException, JavaScriptException
{
Object pn = shiftExpr(ts);
while (ts.matchToken(ts.RELOP)) {
int op = ts.getOp();
if (inForInit && op == ts.IN) {
ts.ungetToken(ts.RELOP);
break;
}
sourceAdd((char)ts.RELOP);
sourceAdd((char)op);
pn = nf.createBinary(ts.RELOP, op, pn, shiftExpr(ts));
}
return pn;
}
private Object shiftExpr(TokenStream ts)
throws IOException, JavaScriptException
{
Object pn = addExpr(ts);
while (ts.matchToken(ts.SHOP)) {
sourceAdd((char)ts.SHOP);
sourceAdd((char)ts.getOp());
pn = nf.createBinary(ts.getOp(), pn, addExpr(ts));
}
return pn;
}
private Object addExpr(TokenStream ts)
throws IOException, JavaScriptException
{
int tt;
Object pn = mulExpr(ts);
while ((tt = ts.getToken()) == ts.ADD || tt == ts.SUB) {
sourceAdd((char)tt);
// flushNewLines
pn = nf.createBinary(tt, pn, mulExpr(ts));
}
ts.ungetToken(tt);
return pn;
}
private Object mulExpr(TokenStream ts)
throws IOException, JavaScriptException
{
int tt;
Object pn = unaryExpr(ts);
while ((tt = ts.peekToken()) == ts.MUL ||
tt == ts.DIV ||
tt == ts.MOD) {
tt = ts.getToken();
sourceAdd((char)tt);
pn = nf.createBinary(tt, pn, unaryExpr(ts));
}
return pn;
}
private Object unaryExpr(TokenStream ts)
throws IOException, JavaScriptException
{
int tt;
ts.flags |= ts.TSF_REGEXP;
tt = ts.getToken();
ts.flags &= ~ts.TSF_REGEXP;
switch(tt) {
case TokenStream.UNARYOP:
sourceAdd((char)ts.UNARYOP);
sourceAdd((char)ts.getOp());
return nf.createUnary(ts.UNARYOP, ts.getOp(),
unaryExpr(ts));
case TokenStream.ADD:
case TokenStream.SUB:
sourceAdd((char)ts.UNARYOP);
sourceAdd((char)tt);
return nf.createUnary(ts.UNARYOP, tt, unaryExpr(ts));
case TokenStream.INC:
case TokenStream.DEC:
sourceAdd((char)tt);
return nf.createUnary(tt, ts.PRE, memberExpr(ts, true));
case TokenStream.DELPROP:
sourceAdd((char)ts.DELPROP);
return nf.createUnary(ts.DELPROP, unaryExpr(ts));
case TokenStream.ERROR:
break;
default:
ts.ungetToken(tt);
int lineno = ts.getLineno();
Object pn = memberExpr(ts, true);
/* don't look across a newline boundary for a postfix incop.
* the rhino scanner seems to work differently than the js
* scanner here; in js, it works to have the line number check
* precede the peekToken calls. It'd be better if they had
* similar behavior...
*/
int peeked;
if (((peeked = ts.peekToken()) == ts.INC ||
peeked == ts.DEC) &&
ts.getLineno() == lineno)
{
int pf = ts.getToken();
sourceAdd((char)pf);
return nf.createUnary(pf, ts.POST, pn);
}
return pn;
}
return nf.createName("err"); // Only reached on error. Try to continue.
}
private Object argumentList(TokenStream ts, Object listNode)
throws IOException, JavaScriptException
{
boolean matched;
ts.flags |= ts.TSF_REGEXP;
matched = ts.matchToken(ts.RP);
ts.flags &= ~ts.TSF_REGEXP;
if (!matched) {
boolean first = true;
do {
if (!first)
sourceAdd((char)ts.COMMA);
first = false;
nf.addChildToBack(listNode, assignExpr(ts, false));
} while (ts.matchToken(ts.COMMA));
mustMatchToken(ts, ts.RP, "msg.no.paren.arg");
}
sourceAdd((char)ts.RP);
return listNode;
}
private Object memberExpr(TokenStream ts, boolean allowCallSyntax)
throws IOException, JavaScriptException
{
int tt;
Object pn;
/* Check for new expressions. */
ts.flags |= ts.TSF_REGEXP;
tt = ts.peekToken();
ts.flags &= ~ts.TSF_REGEXP;
if (tt == ts.NEW) {
/* Eat the NEW token. */
ts.getToken();
sourceAdd((char)ts.NEW);
/* Make a NEW node to append to. */
pn = nf.createLeaf(ts.NEW);
nf.addChildToBack(pn, memberExpr(ts, false));
if (ts.matchToken(ts.LP)) {
sourceAdd((char)ts.LP);
/* Add the arguments to pn, if any are supplied. */
pn = argumentList(ts, pn);
}
/* XXX there's a check in the C source against
* "too many constructor arguments" - how many
* do we claim to support?
*/
/* Experimental syntax: allow an object literal to follow a new expression,
* which will mean a kind of anonymous class built with the JavaAdapter.
* the object literal will be passed as an additional argument to the constructor.
*/
tt = ts.peekToken();
if (tt == ts.LC) {
nf.addChildToBack(pn, primaryExpr(ts));
}
} else {
pn = primaryExpr(ts);
}
return memberExprTail(ts, allowCallSyntax, pn);
}
private Object memberExprTail(TokenStream ts, boolean allowCallSyntax,
Object pn)
throws IOException, JavaScriptException
{
lastExprEndLine = ts.getLineno();
int tt;
while ((tt = ts.getToken()) > ts.EOF) {
if (tt == ts.DOT) {
sourceAdd((char)ts.DOT);
mustMatchToken(ts, ts.NAME, "msg.no.name.after.dot");
String s = ts.getString();
sourceAddString(ts.NAME, s);
pn = nf.createBinary(ts.DOT, pn,
nf.createName(ts.getString()));
/* pn = nf.createBinary(ts.DOT, pn, memberExpr(ts))
* is the version in Brendan's IR C version. Not in ECMA...
* does it reflect the 'new' operator syntax he mentioned?
*/
lastExprEndLine = ts.getLineno();
} else if (tt == ts.LB) {
sourceAdd((char)ts.LB);
pn = nf.createBinary(ts.LB, pn, expr(ts, false));
mustMatchToken(ts, ts.RB, "msg.no.bracket.index");
sourceAdd((char)ts.RB);
lastExprEndLine = ts.getLineno();
} else if (allowCallSyntax && tt == ts.LP) {
/* make a call node */
pn = nf.createUnary(ts.CALL, pn);
sourceAdd((char)ts.LP);
/* Add the arguments to pn, if any are supplied. */
pn = argumentList(ts, pn);
lastExprEndLine = ts.getLineno();
} else {
ts.ungetToken(tt);
break;
}
}
return pn;
}
private Object primaryExpr(TokenStream ts)
throws IOException, JavaScriptException
{
int tt;
Object pn;
ts.flags |= ts.TSF_REGEXP;
tt = ts.getToken();
ts.flags &= ~ts.TSF_REGEXP;
switch(tt) {
case TokenStream.FUNCTION:
return function(ts, true);
case TokenStream.LB:
{
sourceAdd((char)ts.LB);
pn = nf.createLeaf(ts.ARRAYLIT);
ts.flags |= ts.TSF_REGEXP;
boolean matched = ts.matchToken(ts.RB);
ts.flags &= ~ts.TSF_REGEXP;
if (!matched) {
boolean first = true;
do {
ts.flags |= ts.TSF_REGEXP;
tt = ts.peekToken();
ts.flags &= ~ts.TSF_REGEXP;
if (!first)
sourceAdd((char)ts.COMMA);
else
first = false;
if (tt == ts.RB) { // to fix [,,,].length behavior...
break;
}
if (tt == ts.COMMA) {
nf.addChildToBack(pn, nf.createLeaf(ts.PRIMARY,
ts.UNDEFINED));
} else {
nf.addChildToBack(pn, assignExpr(ts, false));
}
} while (ts.matchToken(ts.COMMA));
mustMatchToken(ts, ts.RB, "msg.no.bracket.arg");
}
sourceAdd((char)ts.RB);
return nf.createArrayLiteral(pn);
}
case TokenStream.LC: {
pn = nf.createLeaf(ts.OBJLIT);
sourceAdd((char)ts.LC);
if (!ts.matchToken(ts.RC)) {
boolean first = true;
commaloop:
do {
Object property;
if (!first)
sourceAdd((char)ts.COMMA);
else
first = false;
tt = ts.getToken();
switch(tt) {
// map NAMEs to STRINGs in object literal context.
case TokenStream.NAME:
case TokenStream.STRING:
String s = ts.getString();
sourceAddString(ts.NAME, s);
property = nf.createString(ts.getString());
break;
case TokenStream.NUMBER:
double n = ts.getNumber();
sourceAddNumber(n);
property = nf.createNumber(n);
break;
case TokenStream.RC:
// trailing comma is OK.
ts.ungetToken(tt);
break commaloop;
default:
reportError(ts, "msg.bad.prop");
break commaloop;
}
mustMatchToken(ts, ts.COLON, "msg.no.colon.prop");
// OBJLIT is used as ':' in object literal for
// decompilation to solve spacing ambiguity.
sourceAdd((char)ts.OBJLIT);
nf.addChildToBack(pn, property);
nf.addChildToBack(pn, assignExpr(ts, false));
} while (ts.matchToken(ts.COMMA));
mustMatchToken(ts, ts.RC, "msg.no.brace.prop");
}
sourceAdd((char)ts.RC);
return nf.createObjectLiteral(pn);
}
case TokenStream.LP:
/* Brendan's IR-jsparse.c makes a new node tagged with
* TOK_LP here... I'm not sure I understand why. Isn't
* the grouping already implicit in the structure of the
* parse tree? also TOK_LP is already overloaded (I
* think) in the C IR as 'function call.' */
sourceAdd((char)ts.LP);
pn = expr(ts, false);
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.RP, "msg.no.paren");
return pn;
case TokenStream.NAME:
String name = ts.getString();
sourceAddString(ts.NAME, name);
return nf.createName(name);
case TokenStream.NUMBER:
double n = ts.getNumber();
sourceAddNumber(n);
return nf.createNumber(n);
case TokenStream.STRING:
String s = ts.getString();
sourceAddString(ts.STRING, s);
return nf.createString(s);
case TokenStream.OBJECT:
{
String flags = ts.regExpFlags;
ts.regExpFlags = null;
String re = ts.getString();
sourceAddString(ts.OBJECT, '/' + re + '/' + flags);
return nf.createRegExp(re, flags);
}
case TokenStream.PRIMARY:
sourceAdd((char)ts.PRIMARY);
sourceAdd((char)ts.getOp());
return nf.createLeaf(ts.PRIMARY, ts.getOp());
case TokenStream.RESERVED:
reportError(ts, "msg.reserved.id");
break;
case TokenStream.ERROR:
/* the scanner or one of its subroutines reported the error. */
break;
default:
reportError(ts, "msg.syntax");
break;
}
return null; // should never reach here
}
/**
* The following methods save decompilation information about the source.
* Source information is returned from the parser as a String
* associated with function nodes and with the toplevel script. When
* saved in the constant pool of a class, this string will be UTF-8
* encoded, and token values will occupy a single byte.
* Source is saved (mostly) as token numbers. The tokens saved pretty
* much correspond to the token stream of a 'canonical' representation
* of the input program, as directed by the parser. (There were a few
* cases where tokens could have been left out where decompiler could
* easily reconstruct them, but I left them in for clarity). (I also
* looked adding source collection to TokenStream instead, where I
* could have limited the changes to a few lines in getToken... but
* this wouldn't have saved any space in the resulting source
* representation, and would have meant that I'd have to duplicate
* parser logic in the decompiler to disambiguate situations where
* newlines are important.) NativeFunction.decompile expands the
* tokens back into their string representations, using simple
* lookahead to correct spacing and indentation.
* Token types with associated ops (ASSIGN, SHOP, PRIMARY, etc.) are
* saved as two-token pairs. Number tokens are stored inline, as a
* NUMBER token, a character representing the type, and either 1 or 4
* characters representing the bit-encoding of the number. String
* types NAME, STRING and OBJECT are currently stored as a token type,
* followed by a character giving the length of the string (assumed to
* be less than 2^16), followed by the characters of the string
* inlined into the source string. Changing this to some reference to
* to the string in the compiled class' constant pool would probably
* save a lot of space... but would require some method of deriving
* the final constant pool entry from information available at parse
* time.
* Nested functions need a similar mechanism... fortunately the nested
* functions for a given function are generated in source order.
* Nested functions are encoded as FUNCTION followed by a function
* number (encoded as a character), which is enough information to
* find the proper generated NativeFunction instance.
*/
private void sourceAdd(char c) {
if (sourceTop == sourceBuffer.length) {
increaseSourceCapacity(sourceTop + 1);
}
sourceBuffer[sourceTop] = c;
++sourceTop;
}
private void sourceAddString(int type, String str) {
int L = str.length();
// java string length < 2^16?
if (Context.check && L > Character.MAX_VALUE) Context.codeBug();
if (sourceTop + L + 2 > sourceBuffer.length) {
increaseSourceCapacity(sourceTop + L + 2);
}
sourceAdd((char)type);
sourceAdd((char)L);
str.getChars(0, L, sourceBuffer, sourceTop);
sourceTop += L;
}
private void sourceAddNumber(double n) {
sourceAdd((char)TokenStream.NUMBER);
/* encode the number in the source stream.
* Save as NUMBER type (char | char char char char)
* where type is
* 'D' - double, 'S' - short, 'J' - long.
* We need to retain float vs. integer type info to keep the
* behavior of liveconnect type-guessing the same after
* decompilation. (Liveconnect tries to present 1.0 to Java
* as a float/double)
* OPT: This is no longer true. We could compress the format.
* This may not be the most space-efficient encoding;
* the chars created below may take up to 3 bytes in
* constant pool UTF-8 encoding, so a Double could take
* up to 12 bytes.
*/
long lbits = (long)n;
if (lbits != n) {
// if it's floating point, save as a Double bit pattern.
// (12/15/97 our scanner only returns Double for f.p.)
lbits = Double.doubleToLongBits(n);
sourceAdd('D');
sourceAdd((char)(lbits >> 48));
sourceAdd((char)(lbits >> 32));
sourceAdd((char)(lbits >> 16));
sourceAdd((char)lbits);
}
else {
// we can ignore negative values, bc they're already prefixed
// by UNARYOP SUB
if (Context.check && lbits < 0) Context.codeBug();
// will it fit in a char?
// this gives a short encoding for integer values up to 2^16.
if (lbits <= Character.MAX_VALUE) {
sourceAdd('S');
sourceAdd((char)lbits);
}
else { // Integral, but won't fit in a char. Store as a long.
sourceAdd('J');
sourceAdd((char)(lbits >> 48));
sourceAdd((char)(lbits >> 32));
sourceAdd((char)(lbits >> 16));
sourceAdd((char)lbits);
}
}
}
private void increaseSourceCapacity(int minimalCapacity) {
// Call this only when capacity increase is must
if (Context.check && minimalCapacity <= sourceBuffer.length)
Context.codeBug();
int newCapacity = sourceBuffer.length * 2;
if (newCapacity < minimalCapacity) {
newCapacity = minimalCapacity;
}
char[] tmp = new char[newCapacity];
System.arraycopy(sourceBuffer, 0, tmp, 0, sourceTop);
sourceBuffer = tmp;
}
private String sourceToString(int offset) {
if (Context.check && (offset < 0 || sourceTop < offset))
Context.codeBug();
return new String(sourceBuffer, offset, sourceTop - offset);
}
private int lastExprEndLine; // Hack to handle function expr termination.
private IRFactory nf;
private ErrorReporter er;
private boolean ok; // Did the parse encounter an error?
private char[] sourceBuffer = new char[128];
private int sourceTop;
private int functionNumber;
}
| false | true | private Object statementHelper(TokenStream ts)
throws IOException, JavaScriptException
{
Object pn = null;
// If skipsemi == true, don't add SEMI + EOL to source at the
// end of this statment. For compound statements, IF/FOR etc.
boolean skipsemi = false;
int tt;
int lastExprType = 0; // For wellTerminated. 0 to avoid warning.
tt = ts.getToken();
switch(tt) {
case TokenStream.IF: {
skipsemi = true;
sourceAdd((char)ts.IF);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object ifTrue = statement(ts);
Object ifFalse = null;
if (ts.matchToken(ts.ELSE)) {
sourceAdd((char)ts.RC);
sourceAdd((char)ts.ELSE);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
ifFalse = statement(ts);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createIf(cond, ifTrue, ifFalse, lineno);
break;
}
case TokenStream.SWITCH: {
skipsemi = true;
sourceAdd((char)ts.SWITCH);
pn = nf.createSwitch(ts.getLineno());
Object cur_case = null; // to kill warning
Object case_statements;
mustMatchToken(ts, ts.LP, "msg.no.paren.switch");
sourceAdd((char)ts.LP);
nf.addChildToBack(pn, expr(ts, false));
mustMatchToken(ts, ts.RP, "msg.no.paren.after.switch");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.switch");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
while ((tt = ts.getToken()) != ts.RC && tt != ts.EOF) {
switch(tt) {
case TokenStream.CASE:
sourceAdd((char)ts.CASE);
cur_case = nf.createUnary(ts.CASE, expr(ts, false));
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
break;
case TokenStream.DEFAULT:
cur_case = nf.createLeaf(ts.DEFAULT);
sourceAdd((char)ts.DEFAULT);
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
// XXX check that there isn't more than one default
break;
default:
reportError(ts, "msg.bad.switch");
break;
}
mustMatchToken(ts, ts.COLON, "msg.no.colon.case");
case_statements = nf.createLeaf(TokenStream.BLOCK);
while ((tt = ts.peekToken()) != ts.RC && tt != ts.CASE &&
tt != ts.DEFAULT && tt != ts.EOF)
{
nf.addChildToBack(case_statements, statement(ts));
}
// assert cur_case
nf.addChildToBack(cur_case, case_statements);
nf.addChildToBack(pn, cur_case);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
break;
}
case TokenStream.WHILE: {
skipsemi = true;
sourceAdd((char)ts.WHILE);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWhile(cond, body, lineno);
break;
}
case TokenStream.DO: {
sourceAdd((char)ts.DO);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
int lineno = ts.getLineno();
Object body = statement(ts);
sourceAdd((char)ts.RC);
mustMatchToken(ts, ts.WHILE, "msg.no.while.do");
sourceAdd((char)ts.WHILE);
Object cond = condition(ts);
pn = nf.createDoWhile(body, cond, lineno);
break;
}
case TokenStream.FOR: {
skipsemi = true;
sourceAdd((char)ts.FOR);
int lineno = ts.getLineno();
Object init; // Node init is also foo in 'foo in Object'
Object cond; // Node cond is also object in 'foo in Object'
Object incr = null; // to kill warning
Object body;
mustMatchToken(ts, ts.LP, "msg.no.paren.for");
sourceAdd((char)ts.LP);
tt = ts.peekToken();
if (tt == ts.SEMI) {
init = nf.createLeaf(ts.VOID);
} else {
if (tt == ts.VAR) {
// set init to a var list or initial
ts.getToken(); // throw away the 'var' token
init = variables(ts, true);
}
else {
init = expr(ts, true);
}
}
tt = ts.peekToken();
if (tt == ts.RELOP && ts.getOp() == ts.IN) {
ts.matchToken(ts.RELOP);
sourceAdd((char)ts.IN);
// 'cond' is the object over which we're iterating
cond = expr(ts, false);
} else { // ordinary for loop
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.SEMI) {
// no loop condition
cond = nf.createLeaf(ts.VOID);
} else {
cond = expr(ts, false);
}
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for.cond");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.RP) {
incr = nf.createLeaf(ts.VOID);
} else {
incr = expr(ts, false);
}
}
mustMatchToken(ts, ts.RP, "msg.no.paren.for.ctrl");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
if (incr == null) {
// cond could be null if 'in obj' got eaten by the init node.
pn = nf.createForIn(init, cond, body, lineno);
} else {
pn = nf.createFor(init, cond, incr, body, lineno);
}
break;
}
case TokenStream.TRY: {
int lineno = ts.getLineno();
Object tryblock;
Object catchblocks = null;
Object finallyblock = null;
skipsemi = true;
sourceAdd((char)ts.TRY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
tryblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
catchblocks = nf.createLeaf(TokenStream.BLOCK);
boolean sawDefaultCatch = false;
int peek = ts.peekToken();
if (peek == ts.CATCH) {
while (ts.matchToken(ts.CATCH)) {
if (sawDefaultCatch) {
reportError(ts, "msg.catch.unreachable");
}
sourceAdd((char)ts.CATCH);
mustMatchToken(ts, ts.LP, "msg.no.paren.catch");
sourceAdd((char)ts.LP);
mustMatchToken(ts, ts.NAME, "msg.bad.catchcond");
String varName = ts.getString();
sourceAddString(ts.NAME, varName);
Object catchCond = null;
if (ts.matchToken(ts.IF)) {
sourceAdd((char)ts.IF);
catchCond = expr(ts, false);
} else {
sawDefaultCatch = true;
}
mustMatchToken(ts, ts.RP, "msg.bad.catchcond");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.catchblock");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
nf.addChildToBack(catchblocks,
nf.createCatch(varName, catchCond,
statements(ts),
ts.getLineno()));
mustMatchToken(ts, ts.RC, "msg.no.brace.after.body");
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
} else if (peek != ts.FINALLY) {
mustMatchToken(ts, ts.FINALLY, "msg.try.no.catchfinally");
}
if (ts.matchToken(ts.FINALLY)) {
sourceAdd((char)ts.FINALLY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
finallyblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
pn = nf.createTryCatchFinally(tryblock, catchblocks,
finallyblock, lineno);
break;
}
case TokenStream.THROW: {
int lineno = ts.getLineno();
sourceAdd((char)ts.THROW);
pn = nf.createThrow(expr(ts, false), lineno);
if (lineno == ts.getLineno())
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.BREAK: {
int lineno = ts.getLineno();
sourceAdd((char)ts.BREAK);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createBreak(label, lineno);
break;
}
case TokenStream.CONTINUE: {
int lineno = ts.getLineno();
sourceAdd((char)ts.CONTINUE);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createContinue(label, lineno);
break;
}
case TokenStream.WITH: {
skipsemi = true;
sourceAdd((char)ts.WITH);
int lineno = ts.getLineno();
mustMatchToken(ts, ts.LP, "msg.no.paren.with");
sourceAdd((char)ts.LP);
Object obj = expr(ts, false);
mustMatchToken(ts, ts.RP, "msg.no.paren.after.with");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWith(obj, body, lineno);
break;
}
case TokenStream.VAR: {
int lineno = ts.getLineno();
pn = variables(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.RETURN: {
Object retExpr = null;
int lineno = 0;
sourceAdd((char)ts.RETURN);
// bail if we're not in a (toplevel) function
if ((ts.flags & ts.TSF_FUNCTION) == 0)
reportError(ts, "msg.bad.return");
/* This is ugly, but we don't want to require a semicolon. */
ts.flags |= ts.TSF_REGEXP;
tt = ts.peekTokenSameLine();
ts.flags &= ~ts.TSF_REGEXP;
if (tt != ts.EOF && tt != ts.EOL && tt != ts.SEMI && tt != ts.RC) {
lineno = ts.getLineno();
retExpr = expr(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
ts.flags |= ts.TSF_RETURN_EXPR;
} else {
ts.flags |= ts.TSF_RETURN_VOID;
}
// XXX ASSERT pn
pn = nf.createReturn(retExpr, lineno);
break;
}
case TokenStream.LC:
skipsemi = true;
pn = statements(ts);
mustMatchToken(ts, ts.RC, "msg.no.brace.block");
break;
case TokenStream.ERROR:
// Fall thru, to have a node for error recovery to work on
case TokenStream.EOL:
case TokenStream.SEMI:
pn = nf.createLeaf(ts.VOID);
skipsemi = true;
break;
default: {
lastExprType = tt;
int tokenno = ts.getTokenno();
ts.ungetToken(tt);
int lineno = ts.getLineno();
pn = expr(ts, false);
if (ts.peekToken() == ts.COLON) {
/* check that the last thing the tokenizer returned was a
* NAME and that only one token was consumed.
*/
if (lastExprType != ts.NAME || (ts.getTokenno() != tokenno))
reportError(ts, "msg.bad.label");
ts.getToken(); // eat the COLON
/* in the C source, the label is associated with the
* statement that follows:
* nf.addChildToBack(pn, statement(ts));
*/
String name = ts.getString();
pn = nf.createLabel(name, lineno);
// depend on decompiling lookahead to guess that that
// last name was a label.
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
return pn;
}
if (lastExprType == ts.FUNCTION) {
if (nf.getLeafType(pn) != ts.FUNCTION) {
reportError(ts, "msg.syntax");
}
nf.setFunctionExpressionStatement(pn);
}
pn = nf.createExprStatement(pn, lineno);
/*
* Check explicitly against (multi-line) function
* statement.
* lastExprEndLine is a hack to fix an
* automatic semicolon insertion problem with function
* expressions; the ts.getLineno() == lineno check was
* firing after a function definition even though the
* next statement was on a new line, because
* speculative getToken calls advanced the line number
* even when they didn't succeed.
*/
if (ts.getLineno() == lineno ||
(lastExprType == ts.FUNCTION &&
ts.getLineno() == lastExprEndLine))
{
wellTerminated(ts, lastExprType);
}
break;
}
}
ts.matchToken(ts.SEMI);
if (!skipsemi) {
sourceAdd((char)ts.SEMI);
sourceAdd((char)ts.EOL);
}
return pn;
}
| private Object statementHelper(TokenStream ts)
throws IOException, JavaScriptException
{
Object pn = null;
// If skipsemi == true, don't add SEMI + EOL to source at the
// end of this statment. For compound statements, IF/FOR etc.
boolean skipsemi = false;
int tt;
int lastExprType = 0; // For wellTerminated. 0 to avoid warning.
tt = ts.getToken();
switch(tt) {
case TokenStream.IF: {
skipsemi = true;
sourceAdd((char)ts.IF);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object ifTrue = statement(ts);
Object ifFalse = null;
if (ts.matchToken(ts.ELSE)) {
sourceAdd((char)ts.RC);
sourceAdd((char)ts.ELSE);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
ifFalse = statement(ts);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createIf(cond, ifTrue, ifFalse, lineno);
break;
}
case TokenStream.SWITCH: {
skipsemi = true;
sourceAdd((char)ts.SWITCH);
pn = nf.createSwitch(ts.getLineno());
Object cur_case = null; // to kill warning
Object case_statements;
mustMatchToken(ts, ts.LP, "msg.no.paren.switch");
sourceAdd((char)ts.LP);
nf.addChildToBack(pn, expr(ts, false));
mustMatchToken(ts, ts.RP, "msg.no.paren.after.switch");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.switch");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
while ((tt = ts.getToken()) != ts.RC && tt != ts.EOF) {
switch(tt) {
case TokenStream.CASE:
sourceAdd((char)ts.CASE);
cur_case = nf.createUnary(ts.CASE, expr(ts, false));
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
break;
case TokenStream.DEFAULT:
cur_case = nf.createLeaf(ts.DEFAULT);
sourceAdd((char)ts.DEFAULT);
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
// XXX check that there isn't more than one default
break;
default:
reportError(ts, "msg.bad.switch");
break;
}
mustMatchToken(ts, ts.COLON, "msg.no.colon.case");
case_statements = nf.createLeaf(TokenStream.BLOCK);
while ((tt = ts.peekToken()) != ts.RC && tt != ts.CASE &&
tt != ts.DEFAULT && tt != ts.EOF)
{
nf.addChildToBack(case_statements, statement(ts));
}
// assert cur_case
nf.addChildToBack(cur_case, case_statements);
nf.addChildToBack(pn, cur_case);
}
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
break;
}
case TokenStream.WHILE: {
skipsemi = true;
sourceAdd((char)ts.WHILE);
int lineno = ts.getLineno();
Object cond = condition(ts);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWhile(cond, body, lineno);
break;
}
case TokenStream.DO: {
sourceAdd((char)ts.DO);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
int lineno = ts.getLineno();
Object body = statement(ts);
sourceAdd((char)ts.RC);
mustMatchToken(ts, ts.WHILE, "msg.no.while.do");
sourceAdd((char)ts.WHILE);
Object cond = condition(ts);
pn = nf.createDoWhile(body, cond, lineno);
break;
}
case TokenStream.FOR: {
skipsemi = true;
sourceAdd((char)ts.FOR);
int lineno = ts.getLineno();
Object init; // Node init is also foo in 'foo in Object'
Object cond; // Node cond is also object in 'foo in Object'
Object incr = null; // to kill warning
Object body;
mustMatchToken(ts, ts.LP, "msg.no.paren.for");
sourceAdd((char)ts.LP);
tt = ts.peekToken();
if (tt == ts.SEMI) {
init = nf.createLeaf(ts.VOID);
} else {
if (tt == ts.VAR) {
// set init to a var list or initial
ts.getToken(); // throw away the 'var' token
init = variables(ts, true);
}
else {
init = expr(ts, true);
}
}
tt = ts.peekToken();
if (tt == ts.RELOP && ts.getOp() == ts.IN) {
ts.matchToken(ts.RELOP);
sourceAdd((char)ts.IN);
// 'cond' is the object over which we're iterating
cond = expr(ts, false);
} else { // ordinary for loop
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.SEMI) {
// no loop condition
cond = nf.createLeaf(ts.VOID);
} else {
cond = expr(ts, false);
}
mustMatchToken(ts, ts.SEMI, "msg.no.semi.for.cond");
sourceAdd((char)ts.SEMI);
if (ts.peekToken() == ts.RP) {
incr = nf.createLeaf(ts.VOID);
} else {
incr = expr(ts, false);
}
}
mustMatchToken(ts, ts.RP, "msg.no.paren.for.ctrl");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
if (incr == null) {
// cond could be null if 'in obj' got eaten by the init node.
pn = nf.createForIn(init, cond, body, lineno);
} else {
pn = nf.createFor(init, cond, incr, body, lineno);
}
break;
}
case TokenStream.TRY: {
int lineno = ts.getLineno();
Object tryblock;
Object catchblocks = null;
Object finallyblock = null;
skipsemi = true;
sourceAdd((char)ts.TRY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
tryblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
catchblocks = nf.createLeaf(TokenStream.BLOCK);
boolean sawDefaultCatch = false;
int peek = ts.peekToken();
if (peek == ts.CATCH) {
while (ts.matchToken(ts.CATCH)) {
if (sawDefaultCatch) {
reportError(ts, "msg.catch.unreachable");
}
sourceAdd((char)ts.CATCH);
mustMatchToken(ts, ts.LP, "msg.no.paren.catch");
sourceAdd((char)ts.LP);
mustMatchToken(ts, ts.NAME, "msg.bad.catchcond");
String varName = ts.getString();
sourceAddString(ts.NAME, varName);
Object catchCond = null;
if (ts.matchToken(ts.IF)) {
sourceAdd((char)ts.IF);
catchCond = expr(ts, false);
} else {
sawDefaultCatch = true;
}
mustMatchToken(ts, ts.RP, "msg.bad.catchcond");
sourceAdd((char)ts.RP);
mustMatchToken(ts, ts.LC, "msg.no.brace.catchblock");
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
nf.addChildToBack(catchblocks,
nf.createCatch(varName, catchCond,
statements(ts),
ts.getLineno()));
mustMatchToken(ts, ts.RC, "msg.no.brace.after.body");
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
} else if (peek != ts.FINALLY) {
mustMatchToken(ts, ts.FINALLY, "msg.try.no.catchfinally");
}
if (ts.matchToken(ts.FINALLY)) {
sourceAdd((char)ts.FINALLY);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
finallyblock = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
}
pn = nf.createTryCatchFinally(tryblock, catchblocks,
finallyblock, lineno);
break;
}
case TokenStream.THROW: {
int lineno = ts.getLineno();
sourceAdd((char)ts.THROW);
pn = nf.createThrow(expr(ts, false), lineno);
if (lineno == ts.getLineno())
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.BREAK: {
int lineno = ts.getLineno();
sourceAdd((char)ts.BREAK);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createBreak(label, lineno);
break;
}
case TokenStream.CONTINUE: {
int lineno = ts.getLineno();
sourceAdd((char)ts.CONTINUE);
// matchLabel only matches if there is one
String label = matchLabel(ts);
if (label != null) {
sourceAddString(ts.NAME, label);
}
pn = nf.createContinue(label, lineno);
break;
}
case TokenStream.WITH: {
skipsemi = true;
sourceAdd((char)ts.WITH);
int lineno = ts.getLineno();
mustMatchToken(ts, ts.LP, "msg.no.paren.with");
sourceAdd((char)ts.LP);
Object obj = expr(ts, false);
mustMatchToken(ts, ts.RP, "msg.no.paren.after.with");
sourceAdd((char)ts.RP);
sourceAdd((char)ts.LC);
sourceAdd((char)ts.EOL);
Object body = statement(ts);
sourceAdd((char)ts.RC);
sourceAdd((char)ts.EOL);
pn = nf.createWith(obj, body, lineno);
break;
}
case TokenStream.VAR: {
int lineno = ts.getLineno();
pn = variables(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
break;
}
case TokenStream.RETURN: {
Object retExpr = null;
sourceAdd((char)ts.RETURN);
// bail if we're not in a (toplevel) function
if ((ts.flags & ts.TSF_FUNCTION) == 0)
reportError(ts, "msg.bad.return");
/* This is ugly, but we don't want to require a semicolon. */
ts.flags |= ts.TSF_REGEXP;
tt = ts.peekTokenSameLine();
ts.flags &= ~ts.TSF_REGEXP;
int lineno = ts.getLineno();
if (tt != ts.EOF && tt != ts.EOL && tt != ts.SEMI && tt != ts.RC) {
retExpr = expr(ts, false);
if (ts.getLineno() == lineno)
wellTerminated(ts, ts.ERROR);
ts.flags |= ts.TSF_RETURN_EXPR;
} else {
ts.flags |= ts.TSF_RETURN_VOID;
}
// XXX ASSERT pn
pn = nf.createReturn(retExpr, lineno);
break;
}
case TokenStream.LC:
skipsemi = true;
pn = statements(ts);
mustMatchToken(ts, ts.RC, "msg.no.brace.block");
break;
case TokenStream.ERROR:
// Fall thru, to have a node for error recovery to work on
case TokenStream.EOL:
case TokenStream.SEMI:
pn = nf.createLeaf(ts.VOID);
skipsemi = true;
break;
default: {
lastExprType = tt;
int tokenno = ts.getTokenno();
ts.ungetToken(tt);
int lineno = ts.getLineno();
pn = expr(ts, false);
if (ts.peekToken() == ts.COLON) {
/* check that the last thing the tokenizer returned was a
* NAME and that only one token was consumed.
*/
if (lastExprType != ts.NAME || (ts.getTokenno() != tokenno))
reportError(ts, "msg.bad.label");
ts.getToken(); // eat the COLON
/* in the C source, the label is associated with the
* statement that follows:
* nf.addChildToBack(pn, statement(ts));
*/
String name = ts.getString();
pn = nf.createLabel(name, lineno);
// depend on decompiling lookahead to guess that that
// last name was a label.
sourceAdd((char)ts.COLON);
sourceAdd((char)ts.EOL);
return pn;
}
if (lastExprType == ts.FUNCTION) {
if (nf.getLeafType(pn) != ts.FUNCTION) {
reportError(ts, "msg.syntax");
}
nf.setFunctionExpressionStatement(pn);
}
pn = nf.createExprStatement(pn, lineno);
/*
* Check explicitly against (multi-line) function
* statement.
* lastExprEndLine is a hack to fix an
* automatic semicolon insertion problem with function
* expressions; the ts.getLineno() == lineno check was
* firing after a function definition even though the
* next statement was on a new line, because
* speculative getToken calls advanced the line number
* even when they didn't succeed.
*/
if (ts.getLineno() == lineno ||
(lastExprType == ts.FUNCTION &&
ts.getLineno() == lastExprEndLine))
{
wellTerminated(ts, lastExprType);
}
break;
}
}
ts.matchToken(ts.SEMI);
if (!skipsemi) {
sourceAdd((char)ts.SEMI);
sourceAdd((char)ts.EOL);
}
return pn;
}
|
diff --git a/src/server/TourenPlaner.java b/src/server/TourenPlaner.java
index aed822a..2ca5186 100644
--- a/src/server/TourenPlaner.java
+++ b/src/server/TourenPlaner.java
@@ -1,196 +1,190 @@
package server;
import graphrep.GraphRep;
import graphrep.GraphRepDumpReader;
import graphrep.GraphRepTextReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import algorithms.AlgorithmFactory;
import algorithms.GraphAlgorithmFactory;
import algorithms.ShortestPathCHFactory;
import computecore.AlgorithmRegistry;
import computecore.ComputeCore;
import config.ConfigManager;
public class TourenPlaner {
/**
* @param graphName
* Original file name of the graph
* @return The filename of the dumped graph
*/
private static String dumpName(String graphName) {
return graphName + ".dat";
}
private static Map<String, Object> getServerInfo(AlgorithmRegistry reg) {
Map<String, Object> info = new HashMap<String, Object>(4);
info.put("version", new Float(0.1));
info.put(
"servertype",
ConfigManager.getInstance().getEntryBool("private", false) ? "private"
: "public");
info.put("sslport",
ConfigManager.getInstance().getEntryLong("sslport", 8081));
// Enumerate Algorithms
Collection<AlgorithmFactory> algs = reg.getAlgorithms();
Map<String, Object> algInfo;
List<Map<String, Object>> algList = new ArrayList<Map<String, Object>>();
for (AlgorithmFactory alg : algs) {
algInfo = new HashMap<String, Object>(5);
algInfo.put("version", alg.getVersion());
algInfo.put("name", alg.getAlgName());
algInfo.put("urlsuffix", alg.getURLSuffix());
if (alg instanceof GraphAlgorithmFactory) {
algInfo.put("pointconstraints",
((GraphAlgorithmFactory) alg).getPointConstraints());
algInfo.put("constraints",
((GraphAlgorithmFactory) alg).getConstraints());
}
algList.add(algInfo);
}
info.put("algorithms", algList);
return info;
}
/**
* This is the main class of ToureNPlaner. It passes CLI parameters to the
* handler and creates the httpserver
*/
public static void main(String[] args) {
/**
* inits config manager if config file is provided; also prints usage
* information if necessary
*/
CLIHandler handler = new CLIHandler(args);
// if serialize, then ignore whether to read text or dump and read
// text graph since it wouldn't make sense to read a serialized
// graph just to serialize it. Also do this before anything server
// related gets actually started
if (handler.serializegraph()) {
System.out.println("Dumping Graph");
GraphRep graph = null;
String graphfilename = ConfigManager.getInstance().getEntryString(
"graphfilepath",
System.getProperty("user.home") + "/germany-ch.txt");
try {
graph = new GraphRepTextReader()
.createGraphRep(new FileInputStream(graphfilename));
utils.GraphSerializer.serialize(new FileOutputStream(
dumpName(graphfilename)), graph);
System.exit(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// uses defaults if it was not initialized by the CLIHandler
ConfigManager cm = ConfigManager.getInstance();
// Load the Graph
GraphRep graph = null;
String graphfilename = cm.getEntryString("graphfilepath",
System.getProperty("user.home") + "/germany-ch.txt");
try {
if (handler.loadTextGraph()) {
graph = new GraphRepTextReader()
.createGraphRep(new FileInputStream(graphfilename));
} else {
try {
graph = new GraphRepDumpReader()
.createGraphRep(new FileInputStream(graphfilename
+ ".dat"));
} catch (InvalidClassException e) {
// TODO: unify default options?
String textGraphFilename = ConfigManager.getInstance()
.getEntryString(
"graphfilepath",
System.getProperty("user.home")
+ "/germany.txt");
System.err
.println("Dumped Graph version does not match the required version: "
+ e.getMessage());
System.out
.println("Falling back to text reading from file: "
+ textGraphFilename
+ " (path provided by config file) ...");
graph = (new GraphRepTextReader())
.createGraphRep(new FileInputStream(
textGraphFilename));
System.out
.println("Graph successfully read. Now replacing old dumped graph ...");
if ((new File(dumpName(graphfilename))).delete()) {
utils.GraphSerializer.serialize(new FileOutputStream(
dumpName(graphfilename)), graph);
System.out
.println("... success. Now running server ...");
} else {
System.out
.println("... failed. Now running server ...");
}
} catch (IOException e) {
String textGraphFilename = ConfigManager.getInstance()
.getEntryString(
"graphfilepath",
System.getProperty("user.home")
+ "/germany.txt");
System.err.println("Dumped Graph does not exist: "
+ e.getMessage());
System.out
.println("Falling back to text reading from file: "
+ textGraphFilename
+ " (path provided by config file) ...");
graph = (new GraphRepTextReader())
.createGraphRep(new FileInputStream(
textGraphFilename));
System.out
.println("Graph successfully read. Now dumping graph ...");
- if ((new File(dumpName(graphfilename))).delete()) {
- utils.GraphSerializer.serialize(new FileOutputStream(
- dumpName(graphfilename)), graph);
- System.out
- .println("... success. Now running server ...");
- } else {
- System.out
- .println("... failed. Now running server ...");
- }
+ utils.GraphSerializer.serialize(new FileOutputStream(
+ dumpName(graphfilename)), graph);
+ System.out.println("... success. Now running server ...");
}
}
} catch (IOException e) {
e.printStackTrace();
// TODO: server won't calculate graph algorithms without a graph,
// but maybe it will provide some other functionality?
}
if (graph == null) {
System.out
.println("Graph reading FAILED! Only non graph related services will be available!");
}
// Register Algorithms
AlgorithmRegistry reg = new AlgorithmRegistry();
reg.registerAlgorithm(new ShortestPathCHFactory(graph));
// Create our ComputeCore that manages all ComputeThreads
ComputeCore comCore = new ComputeCore(reg, (int) cm.getEntryLong(
"threads", 16), (int) cm.getEntryLong("queuelength", 32));
// Create ServerInfo object
Map<String, Object> serverInfo = getServerInfo(reg);
new HttpServer(cm, reg, serverInfo, comCore);
}
}
| true | true | public static void main(String[] args) {
/**
* inits config manager if config file is provided; also prints usage
* information if necessary
*/
CLIHandler handler = new CLIHandler(args);
// if serialize, then ignore whether to read text or dump and read
// text graph since it wouldn't make sense to read a serialized
// graph just to serialize it. Also do this before anything server
// related gets actually started
if (handler.serializegraph()) {
System.out.println("Dumping Graph");
GraphRep graph = null;
String graphfilename = ConfigManager.getInstance().getEntryString(
"graphfilepath",
System.getProperty("user.home") + "/germany-ch.txt");
try {
graph = new GraphRepTextReader()
.createGraphRep(new FileInputStream(graphfilename));
utils.GraphSerializer.serialize(new FileOutputStream(
dumpName(graphfilename)), graph);
System.exit(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// uses defaults if it was not initialized by the CLIHandler
ConfigManager cm = ConfigManager.getInstance();
// Load the Graph
GraphRep graph = null;
String graphfilename = cm.getEntryString("graphfilepath",
System.getProperty("user.home") + "/germany-ch.txt");
try {
if (handler.loadTextGraph()) {
graph = new GraphRepTextReader()
.createGraphRep(new FileInputStream(graphfilename));
} else {
try {
graph = new GraphRepDumpReader()
.createGraphRep(new FileInputStream(graphfilename
+ ".dat"));
} catch (InvalidClassException e) {
// TODO: unify default options?
String textGraphFilename = ConfigManager.getInstance()
.getEntryString(
"graphfilepath",
System.getProperty("user.home")
+ "/germany.txt");
System.err
.println("Dumped Graph version does not match the required version: "
+ e.getMessage());
System.out
.println("Falling back to text reading from file: "
+ textGraphFilename
+ " (path provided by config file) ...");
graph = (new GraphRepTextReader())
.createGraphRep(new FileInputStream(
textGraphFilename));
System.out
.println("Graph successfully read. Now replacing old dumped graph ...");
if ((new File(dumpName(graphfilename))).delete()) {
utils.GraphSerializer.serialize(new FileOutputStream(
dumpName(graphfilename)), graph);
System.out
.println("... success. Now running server ...");
} else {
System.out
.println("... failed. Now running server ...");
}
} catch (IOException e) {
String textGraphFilename = ConfigManager.getInstance()
.getEntryString(
"graphfilepath",
System.getProperty("user.home")
+ "/germany.txt");
System.err.println("Dumped Graph does not exist: "
+ e.getMessage());
System.out
.println("Falling back to text reading from file: "
+ textGraphFilename
+ " (path provided by config file) ...");
graph = (new GraphRepTextReader())
.createGraphRep(new FileInputStream(
textGraphFilename));
System.out
.println("Graph successfully read. Now dumping graph ...");
if ((new File(dumpName(graphfilename))).delete()) {
utils.GraphSerializer.serialize(new FileOutputStream(
dumpName(graphfilename)), graph);
System.out
.println("... success. Now running server ...");
} else {
System.out
.println("... failed. Now running server ...");
}
}
}
} catch (IOException e) {
e.printStackTrace();
// TODO: server won't calculate graph algorithms without a graph,
// but maybe it will provide some other functionality?
}
if (graph == null) {
System.out
.println("Graph reading FAILED! Only non graph related services will be available!");
}
// Register Algorithms
AlgorithmRegistry reg = new AlgorithmRegistry();
reg.registerAlgorithm(new ShortestPathCHFactory(graph));
// Create our ComputeCore that manages all ComputeThreads
ComputeCore comCore = new ComputeCore(reg, (int) cm.getEntryLong(
"threads", 16), (int) cm.getEntryLong("queuelength", 32));
// Create ServerInfo object
Map<String, Object> serverInfo = getServerInfo(reg);
new HttpServer(cm, reg, serverInfo, comCore);
}
| public static void main(String[] args) {
/**
* inits config manager if config file is provided; also prints usage
* information if necessary
*/
CLIHandler handler = new CLIHandler(args);
// if serialize, then ignore whether to read text or dump and read
// text graph since it wouldn't make sense to read a serialized
// graph just to serialize it. Also do this before anything server
// related gets actually started
if (handler.serializegraph()) {
System.out.println("Dumping Graph");
GraphRep graph = null;
String graphfilename = ConfigManager.getInstance().getEntryString(
"graphfilepath",
System.getProperty("user.home") + "/germany-ch.txt");
try {
graph = new GraphRepTextReader()
.createGraphRep(new FileInputStream(graphfilename));
utils.GraphSerializer.serialize(new FileOutputStream(
dumpName(graphfilename)), graph);
System.exit(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// uses defaults if it was not initialized by the CLIHandler
ConfigManager cm = ConfigManager.getInstance();
// Load the Graph
GraphRep graph = null;
String graphfilename = cm.getEntryString("graphfilepath",
System.getProperty("user.home") + "/germany-ch.txt");
try {
if (handler.loadTextGraph()) {
graph = new GraphRepTextReader()
.createGraphRep(new FileInputStream(graphfilename));
} else {
try {
graph = new GraphRepDumpReader()
.createGraphRep(new FileInputStream(graphfilename
+ ".dat"));
} catch (InvalidClassException e) {
// TODO: unify default options?
String textGraphFilename = ConfigManager.getInstance()
.getEntryString(
"graphfilepath",
System.getProperty("user.home")
+ "/germany.txt");
System.err
.println("Dumped Graph version does not match the required version: "
+ e.getMessage());
System.out
.println("Falling back to text reading from file: "
+ textGraphFilename
+ " (path provided by config file) ...");
graph = (new GraphRepTextReader())
.createGraphRep(new FileInputStream(
textGraphFilename));
System.out
.println("Graph successfully read. Now replacing old dumped graph ...");
if ((new File(dumpName(graphfilename))).delete()) {
utils.GraphSerializer.serialize(new FileOutputStream(
dumpName(graphfilename)), graph);
System.out
.println("... success. Now running server ...");
} else {
System.out
.println("... failed. Now running server ...");
}
} catch (IOException e) {
String textGraphFilename = ConfigManager.getInstance()
.getEntryString(
"graphfilepath",
System.getProperty("user.home")
+ "/germany.txt");
System.err.println("Dumped Graph does not exist: "
+ e.getMessage());
System.out
.println("Falling back to text reading from file: "
+ textGraphFilename
+ " (path provided by config file) ...");
graph = (new GraphRepTextReader())
.createGraphRep(new FileInputStream(
textGraphFilename));
System.out
.println("Graph successfully read. Now dumping graph ...");
utils.GraphSerializer.serialize(new FileOutputStream(
dumpName(graphfilename)), graph);
System.out.println("... success. Now running server ...");
}
}
} catch (IOException e) {
e.printStackTrace();
// TODO: server won't calculate graph algorithms without a graph,
// but maybe it will provide some other functionality?
}
if (graph == null) {
System.out
.println("Graph reading FAILED! Only non graph related services will be available!");
}
// Register Algorithms
AlgorithmRegistry reg = new AlgorithmRegistry();
reg.registerAlgorithm(new ShortestPathCHFactory(graph));
// Create our ComputeCore that manages all ComputeThreads
ComputeCore comCore = new ComputeCore(reg, (int) cm.getEntryLong(
"threads", 16), (int) cm.getEntryLong("queuelength", 32));
// Create ServerInfo object
Map<String, Object> serverInfo = getServerInfo(reg);
new HttpServer(cm, reg, serverInfo, comCore);
}
|
diff --git a/datastore/src/test/java/org/jboss/test/capedwarf/datastore/test/AllocateIdsTestCase.java b/datastore/src/test/java/org/jboss/test/capedwarf/datastore/test/AllocateIdsTestCase.java
index 42311d13..ff07bbd1 100644
--- a/datastore/src/test/java/org/jboss/test/capedwarf/datastore/test/AllocateIdsTestCase.java
+++ b/datastore/src/test/java/org/jboss/test/capedwarf/datastore/test/AllocateIdsTestCase.java
@@ -1,76 +1,77 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.capedwarf.datastore.test;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyRange;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author <a href="mailto:[email protected]">Ales Justin</a>
*/
@RunWith(Arquillian.class)
public class AllocateIdsTestCase extends AbstractTest {
@Test
public void testAllocateId() throws Exception {
long initialValue = getInitialValue("SomeKind");
KeyRange keys = service.allocateIds("SomeKind", 10L);
Assert.assertNotNull(keys);
Key start = keys.getStart();
Assert.assertNotNull(start);
Assert.assertEquals(1 + initialValue, start.getId());
Key end = keys.getEnd();
Assert.assertNotNull(end);
Assert.assertEquals(10 + initialValue, end.getId());
}
@Test
public void testCheckKeyRange() throws Exception {
long initialValue = getInitialValue("OtherKind");
KeyRange kr1 = new KeyRange(null, "OtherKind", 1 + initialValue, 5 + initialValue);
DatastoreService.KeyRangeState state1 = service.allocateIdRange(kr1);
Assert.assertNotNull(state1);
- Assert.assertSame(DatastoreService.KeyRangeState.CONTENTION, state1);
+ // imo, it could be either -- depending on the impl
+ Assert.assertTrue(DatastoreService.KeyRangeState.CONTENTION == state1 || DatastoreService.KeyRangeState.EMPTY == state1);
KeyRange kr2 = service.allocateIds("OtherKind", 6);
Assert.assertNotNull(kr2);
KeyRange kr3 = new KeyRange(null, "OtherKind", 2 + initialValue, 5 + initialValue);
DatastoreService.KeyRangeState state2 = service.allocateIdRange(kr3);
Assert.assertNotNull(state2);
Assert.assertSame(DatastoreService.KeyRangeState.COLLISION, state2);
}
private long getInitialValue(String kind) {
return service.allocateIds(kind, 1L).getStart().getId();
}
}
| true | true | public void testCheckKeyRange() throws Exception {
long initialValue = getInitialValue("OtherKind");
KeyRange kr1 = new KeyRange(null, "OtherKind", 1 + initialValue, 5 + initialValue);
DatastoreService.KeyRangeState state1 = service.allocateIdRange(kr1);
Assert.assertNotNull(state1);
Assert.assertSame(DatastoreService.KeyRangeState.CONTENTION, state1);
KeyRange kr2 = service.allocateIds("OtherKind", 6);
Assert.assertNotNull(kr2);
KeyRange kr3 = new KeyRange(null, "OtherKind", 2 + initialValue, 5 + initialValue);
DatastoreService.KeyRangeState state2 = service.allocateIdRange(kr3);
Assert.assertNotNull(state2);
Assert.assertSame(DatastoreService.KeyRangeState.COLLISION, state2);
}
| public void testCheckKeyRange() throws Exception {
long initialValue = getInitialValue("OtherKind");
KeyRange kr1 = new KeyRange(null, "OtherKind", 1 + initialValue, 5 + initialValue);
DatastoreService.KeyRangeState state1 = service.allocateIdRange(kr1);
Assert.assertNotNull(state1);
// imo, it could be either -- depending on the impl
Assert.assertTrue(DatastoreService.KeyRangeState.CONTENTION == state1 || DatastoreService.KeyRangeState.EMPTY == state1);
KeyRange kr2 = service.allocateIds("OtherKind", 6);
Assert.assertNotNull(kr2);
KeyRange kr3 = new KeyRange(null, "OtherKind", 2 + initialValue, 5 + initialValue);
DatastoreService.KeyRangeState state2 = service.allocateIdRange(kr3);
Assert.assertNotNull(state2);
Assert.assertSame(DatastoreService.KeyRangeState.COLLISION, state2);
}
|
diff --git a/src/se/chalmers/tda367/std/core/BuildController.java b/src/se/chalmers/tda367/std/core/BuildController.java
index 699bbab..1048396 100644
--- a/src/se/chalmers/tda367/std/core/BuildController.java
+++ b/src/se/chalmers/tda367/std/core/BuildController.java
@@ -1,105 +1,105 @@
package se.chalmers.tda367.std.core;
import se.chalmers.tda367.std.core.tiles.BuildableTile;
import se.chalmers.tda367.std.core.tiles.towers.ITower;
import se.chalmers.tda367.std.utilities.Position;
/**
* The class that contains the game logic for build phase of the game.
* @author Johan Andersson
* @modified
* @date Apr 22, 2012
*/
public class BuildController {
private static final double SELL_MODIFER = 0.75;
private GameBoard board;
private Player player;
public BuildController(GameBoard board, Player player){
this.board = board;
this.player = player;
}
/** Builds a tower on the board.
*
* @param tower - Tower to be built.
* @param pos - Position to build upon.
* @return - True if tower was build otherwise false
*/
public boolean buildTower(ITower tower, Position pos){
if(isBuildableSpot(pos) && playerCanAffordTower(tower)){
board.placeTile(tower, pos);
return true;
} else {
return false;
}
}
/** Tells if a spot is buildable.
*
* @param pos - Position to test buildability on.
* @return - True if position is buildable on board.
*/
public boolean isBuildableSpot(Position pos) {
return board.canBuildAt(pos);
}
/** Tells if a player can afford a tower.
*
* @param tower - Tower to test affordability on.
* @return - True if player can afford upgrade.
*/
public boolean playerCanAffordTower(ITower tower) {
return player.getMoney() >= tower.getBaseCost();
}
/** Upgrades a tower if possible.
*
* @param tower - Tower to be upgraded.
* @return - True if tower was upgraded.
*/
public boolean upgradeTower(ITower tower){
if(playerCanAffordUpgrade(tower)){
tower.upgrade();
return true;
} else {
return false;
}
}
/** Tells if a player can afford to upgrade a tower.
*
* @param tower - Tower considered to upgrade.
* @return - True if player can afford upgrade.
*/
public boolean playerCanAffordUpgrade(ITower tower) {
return player.getMoney() >= tower.getUpgradeCost();
}
/** Sells a tower if possible.
*
* @param tower - Tower to be sold.
* @param pos - Position on which the tower is built.
* @return - True if tower is sold.
*/
public boolean sellTower(ITower tower, Position pos){
if(isTowerAt(tower,pos)){
- player.setMoney(player.getMoney() + (int)(tower.getTotalValue() * SELL_MODIFER+0.5));
+ player.setMoney(player.getMoney() + (int)(tower.getTotalValue() * SELL_MODIFER + 0.5));
board.placeTile(new BuildableTile(null), pos);
return true;
} else {
return false;
}
}
private boolean isTowerAt(ITower tower, Position pos) {
return tower == board.getTileAt(pos);
//TODO Does it work?
}
}
| true | true | public boolean sellTower(ITower tower, Position pos){
if(isTowerAt(tower,pos)){
player.setMoney(player.getMoney() + (int)(tower.getTotalValue() * SELL_MODIFER+0.5));
board.placeTile(new BuildableTile(null), pos);
return true;
} else {
return false;
}
}
| public boolean sellTower(ITower tower, Position pos){
if(isTowerAt(tower,pos)){
player.setMoney(player.getMoney() + (int)(tower.getTotalValue() * SELL_MODIFER + 0.5));
board.placeTile(new BuildableTile(null), pos);
return true;
} else {
return false;
}
}
|
diff --git a/src/main/java/org/ops4j/pax/runner/FileUtils.java b/src/main/java/org/ops4j/pax/runner/FileUtils.java
index eebe7990..1af1f4a7 100644
--- a/src/main/java/org/ops4j/pax/runner/FileUtils.java
+++ b/src/main/java/org/ops4j/pax/runner/FileUtils.java
@@ -1,90 +1,97 @@
/*
* Copyright 2006 Niclas Hedhman.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ops4j.pax.runner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class FileUtils
{
static Writer openPropertyFile( File file )
throws IOException
{
FileOutputStream fos = new FileOutputStream( file );
OutputStreamWriter oos = new OutputStreamWriter( fos, "ISO-8859-1" );
BufferedWriter out = new BufferedWriter( oos );
return out;
}
static void writeProperty( Writer out, String key, String value )
throws IOException
{
out.write( key );
out.write( '=' );
out.write( value );
out.write( "\n\n" );
}
static public String getTextContent( File textUtf8File )
throws IOException
{
FileInputStream fis = new FileInputStream( textUtf8File );
InputStreamReader isr = new InputStreamReader( fis );
BufferedReader br = new BufferedReader( isr );
StringBuffer buf = new StringBuffer( 1000 );
- char[] ch = new char[1000];
- int length = 0;
- while( length != -1 )
+ try
{
- length = br.read( ch );
- if( length > 0 )
+ char[] ch = new char[1000];
+ int length = 0;
+ while( length != -1 )
{
- buf.append( ch, 0, length );
+ length = br.read( ch );
+ if( length > 0 )
+ {
+ buf.append( ch, 0, length );
+ }
}
}
+ finally
+ {
+ br.close();
+ }
String result = buf.toString();
buf.setLength( 0 );
return result;
}
public static void writeTextContent( File md5File, String text )
throws IOException
{
FileOutputStream fos = new FileOutputStream( md5File );
try
{
OutputStreamWriter osw = new OutputStreamWriter( fos );
BufferedWriter bw = new BufferedWriter( osw );
bw.write( text );
bw.flush();
bw.close();
} finally
{
fos.close();
}
}
}
| false | true | static public String getTextContent( File textUtf8File )
throws IOException
{
FileInputStream fis = new FileInputStream( textUtf8File );
InputStreamReader isr = new InputStreamReader( fis );
BufferedReader br = new BufferedReader( isr );
StringBuffer buf = new StringBuffer( 1000 );
char[] ch = new char[1000];
int length = 0;
while( length != -1 )
{
length = br.read( ch );
if( length > 0 )
{
buf.append( ch, 0, length );
}
}
String result = buf.toString();
buf.setLength( 0 );
return result;
}
| static public String getTextContent( File textUtf8File )
throws IOException
{
FileInputStream fis = new FileInputStream( textUtf8File );
InputStreamReader isr = new InputStreamReader( fis );
BufferedReader br = new BufferedReader( isr );
StringBuffer buf = new StringBuffer( 1000 );
try
{
char[] ch = new char[1000];
int length = 0;
while( length != -1 )
{
length = br.read( ch );
if( length > 0 )
{
buf.append( ch, 0, length );
}
}
}
finally
{
br.close();
}
String result = buf.toString();
buf.setLength( 0 );
return result;
}
|
diff --git a/caatja-gwt-demos/src/main/java/com/katspow/caatjagwtdemos/client/welcome/hypernumber/core/GameScene.java b/caatja-gwt-demos/src/main/java/com/katspow/caatjagwtdemos/client/welcome/hypernumber/core/GameScene.java
index 2e8bc84..57feecf 100644
--- a/caatja-gwt-demos/src/main/java/com/katspow/caatjagwtdemos/client/welcome/hypernumber/core/GameScene.java
+++ b/caatja-gwt-demos/src/main/java/com/katspow/caatjagwtdemos/client/welcome/hypernumber/core/GameScene.java
@@ -1,783 +1,783 @@
package com.katspow.caatjagwtdemos.client.welcome.hypernumber.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.katspow.caatja.behavior.AlphaBehavior;
import com.katspow.caatja.behavior.BaseBehavior;
import com.katspow.caatja.behavior.BehaviorListener;
import com.katspow.caatja.behavior.ContainerBehavior;
import com.katspow.caatja.behavior.Interpolator;
import com.katspow.caatja.behavior.PathBehavior;
import com.katspow.caatja.behavior.RotateBehavior;
import com.katspow.caatja.behavior.ScaleBehavior;
import com.katspow.caatja.behavior.SetForTimeReturnValue;
import com.katspow.caatja.core.canvas.CaatjaGradient;
import com.katspow.caatja.core.canvas.CaatjaImage;
import com.katspow.caatja.event.CAATMouseEvent;
import com.katspow.caatja.foundation.Director;
import com.katspow.caatja.foundation.Scene;
import com.katspow.caatja.foundation.actor.Actor;
import com.katspow.caatja.foundation.actor.ActorContainer;
import com.katspow.caatja.foundation.actor.Button;
import com.katspow.caatja.foundation.actor.ImageActor;
import com.katspow.caatja.foundation.image.CompoundImage;
import com.katspow.caatja.foundation.timer.Callback;
import com.katspow.caatja.foundation.timer.TimerTask;
import com.katspow.caatja.foundation.ui.ShapeActor;
import com.katspow.caatja.foundation.ui.TextActor;
import com.katspow.caatja.pathutil.CurvePath;
import com.katspow.caatja.pathutil.LinearPath;
import com.katspow.caatja.pathutil.Path;
import com.katspow.caatjagwtdemos.client.welcome.hypernumber.core.brick.Brick;
import com.katspow.caatjagwtdemos.client.welcome.hypernumber.core.brick.BrickActor;
import com.katspow.caatjagwtdemos.client.welcome.hypernumber.core.context.Context;
import com.katspow.caatjagwtdemos.client.welcome.hypernumber.core.context.ContextListener;
import com.katspow.caatjagwtdemos.client.welcome.hypernumber.startmenu.AnimatedBackground;
public class GameScene implements ContextListener {
public static final int imageBricksW= 9;
public static final int imageBricksH= 7;
int gameRows= 15;
int gameColumns= 20;
int gap = 2;
Context context= null;
public Scene directorScene= null;
SelectionPath selectionPath = null;
ActorContainer bricksContainer = null;
// TODO Check type !!!
ActorContainer fallingBricksContainer= null;
BrickActor[][] brickActors;
CompoundImage bricksImage= null;
CompoundImage buttonImage= null;
TextActor levelActor= null;
Chrono chronoActor= null;
TimerTask timer= null;
TimerTask scrollTimer = null;
ScoreActor scoreActor= null;
ImageActor endGameActor = null;
Director director= null;
int actorInitializationCount= 0; // flag indicating how many actors have finished initializing.
AnimatedBackground backgroundContainer = null;
/**
* Creates the main game Scene.
* @param director a Director instance.
* @throws Exception
*/
public GameScene create (final Director director,int rows,int columns, final Context context) throws Exception {
this.gameRows= rows;
this.gameColumns= columns;
this.director= director;
CaatjaImage image = director.getImage("bricks");
this.bricksImage= new CompoundImage().initialize(
image,
this.imageBricksH,
this.imageBricksW );
CaatjaImage image2 = director.getImage("buttons");
this.buttonImage= new CompoundImage().initialize(
- image2, 6,4 );
+ image2, 7,4 );
// this.context= new Context().
// create( this.gameRows, this.gameColumns, this.imageBricksH ).
// addContextListener(this);
context.addContextListener(this);
this.context = context;
// this.directorScene= director.createScene();
this.directorScene = new Scene() {
@Override
public void activated() {
context.initialize();
}
};
director.addScene(directorScene);
int dw= director.canvas.getCoordinateSpaceWidth();
int dh= director.canvas.getCoordinateSpaceHeight();
////////////////////////animated background
this.backgroundContainer= (AnimatedBackground) new AnimatedBackground().
setBounds(0,0,dw,dh).
setImage(director.getImage("background")).
setOffsetY( -director.getImage("background").getHeight()+2*dh ).
setClip(true);
this.backgroundContainer.setScene(this.directorScene);
this.directorScene.addChild(this.backgroundContainer);
this.context.addContextListener(this.backgroundContainer);
this.brickActors = new BrickActor[gameRows][gameColumns];
////////////////////////Number Bricks
this.bricksContainer= (ActorContainer) new ActorContainer().
setSize(
this.gameColumns*this.getBrickWidth(),
this.gameRows*this.getBrickHeight() );
double bricksCY= (dh-this.bricksContainer.height)/2;
double bricksCX= bricksCY;
this.bricksContainer.setLocation( bricksCX, bricksCY );
this.directorScene.addChild(this.bricksContainer);
int i,j;
for( i=0; i<this.gameRows; i++ ) {
// this.brickActors.push([]);
for( j=0; j<this.gameColumns; j++ ) {
BrickActor brick= (BrickActor) new BrickActor();
brick.initialize( this.bricksImage, this.context.getBrick(i,j) ).
setLocation(-100,-100);
this.brickActors[i][j] = brick;
bricksContainer.addChild(brick);
}
}
/////////////////////// game indicators.
ActorContainer controls= (ActorContainer) new ActorContainer().
setBounds(
this.bricksContainer.x + this.bricksContainer.width + bricksCX,
this.bricksContainer.x,
dw - bricksCX - (this.bricksContainer.x + this.bricksContainer.width) - bricksCX,
this.bricksContainer.height );
this.directorScene.addChild( controls );
/////////////////////// initialize selection path
this.selectionPath= (SelectionPath) new SelectionPath().
setBounds(
this.bricksContainer.x,
this.bricksContainer.y,
this.gameColumns*this.getBrickWidth(),
this.gameRows*this.getBrickHeight());
this.selectionPath.enableEvents(false);
this.directorScene.addChild(this.selectionPath);
this.context.addContextListener(this.selectionPath);
/////////////////////// initialize button
Button restart= (Button) new Button() {
@Override
public void mouseClick(CAATMouseEvent mouseEvent) {
context.timeUp();
}
}.
initialize( this.buttonImage, 20,21,22,23 ).
setLocation(
(controls.width-this.buttonImage.singleWidth)/2,
controls.height - this.buttonImage.singleHeight );
controls.addChild(restart);
///////////////////// Level indicator
CaatjaGradient gradient= director.ctx.createLinearGradient(0,0,0,40);
gradient.addColorStop(0,"#00ff00");
gradient.addColorStop(0.5,"#ffff00");
gradient.addColorStop(1,"#3f3f3f");
this.levelActor= new TextActor().
setFont("40px sans-serif").
setText("");
levelActor.setTextFillStyle( gradient ).
setOutline(true).
calcTextSize(director);
this.levelActor.setLocation((controls.width-this.levelActor.textWidth)/2,5);
controls.addChild(this.levelActor);
///////////////////// Guess Number
GuessNumberActor guess= (GuessNumberActor) new GuessNumberActor().
setBounds((controls.width-80)/2, 50, 80, 30 );
guess.setFont("80px sans-serif").
setText("").
setTextFillStyle("#000000").
setOutline(true).
setOutlineColor("#ffff00");
this.context.addContextListener(guess);
controls.addChild(guess);
///////////////////// chronometer
this.chronoActor= (Chrono) new Chrono().
setBounds( 2, 140, controls.width-4, 20 );
this.context.addContextListener(this.chronoActor);
controls.addChild(this.chronoActor);
///////////////////// score
this.scoreActor= (ScoreActor) new ScoreActor().
setBounds( 2, 180, controls.width-4, 30 );
this.scoreActor.setFont( "40px sans-serif" ).
setTextFillStyle( gradient ).
setOutline( true ).
setOutlineColor( "0x7f7f00" );
controls.addChild( this.scoreActor );
this.context.addContextListener(this.scoreActor);
////////////////////////////////////////////////
this.create_EndGame(director);
return this;
}
private void create_EndGame(final Director director ) throws Exception {
this.endGameActor= (ImageActor) new ImageActor();
endGameActor.setImage(director.getImage("background_op")).
setAlpha( .9 ).
setGlobalAlpha(false);
Button menu= new Button() {
@Override
public void mouseClick(CAATMouseEvent mouseEvent) throws Exception {
Anchor a0 = Actor.Anchor.LEFT;
Anchor a1 = Actor.Anchor.RIGHT;
switch( context.difficulty ) {
case 0:
a0= Actor.Anchor.LEFT;
a1= Actor.Anchor.RIGHT;
break;
case 1:
a0= Actor.Anchor.BOTTOM;
a1= Actor.Anchor.TOP;
break;
case 2:
a0= Actor.Anchor.TOP;
a1= Actor.Anchor.BOTTOM;
break;
}
director.easeInOut(
0,
Scene.Ease.TRANSLATE,
a0,
1,
Scene.Ease.TRANSLATE,
a1,
1000,
false,
new Interpolator().createExponentialInOutInterpolator(3,false),
new Interpolator().createExponentialInOutInterpolator(3,false) );
}
}.
initialize( this.buttonImage, 20,21,22,23 );
Button restart= new Button() {
@Override
public void mouseClick(CAATMouseEvent mouseEvent) {
prepareSceneIn();
context.initialize();
}
}.
initialize( this.buttonImage, 0,1,2,3 );
double x= (this.endGameActor.width - 2*menu.width - 30)/2;
double y= this.endGameActor.height-20-menu.height;
menu.setLocation( x, y );
restart.setLocation( x+menu.width+30, y );
this.endGameActor.addChild(menu);
this.endGameActor.addChild(restart);
this.endGameActor.setFrameTime(-1,0);
this.directorScene.addChild(this.endGameActor);
}
int getBrickWidth () {
return (int) this.bricksImage.singleWidth + this.gap;
}
int getBrickHeight () {
return (int) this.bricksImage.singleHeight + this.gap;
}
public void initializeActors () {
this.selectionPath.initialize();
int i, j;
double radius= Math.max(
this.director.canvas.getCoordinateSpaceWidth(),
this.director.canvas.getCoordinateSpaceHeight() );
double angle= Math.PI*2*Math.random();
double p0= Math.random()*this.director.canvas.getCoordinateSpaceWidth();
double p1= Math.random()*this.director.canvas.getCoordinateSpaceHeight();
double p2= Math.random()*this.director.canvas.getCoordinateSpaceWidth();
double p3= Math.random()*this.director.canvas.getCoordinateSpaceHeight();
for( i=0; i<this.gameRows; i++ ) {
for( j=0; j<this.gameColumns; j++ ) {
BrickActor brickActor= this.brickActors[i][j];
brickActor.setFrameTime( this.directorScene.time, Double.MAX_VALUE ).
setAlpha(1).
enableEvents(true).
resetTransform();
double random= Math.random()*1000;
PathBehavior moveB= (PathBehavior) new PathBehavior().
setFrameTime(this.directorScene.time, 1000+random);
moveB.setPath(
new CurvePath().
setCubic(
radius/2 + Math.cos(angle)*radius,
radius/2 + Math.sin(angle)*radius,
p0, p1, p2, p3,
j*this.bricksImage.singleWidth + j*2,
i*this.bricksImage.singleHeight + i*2)
).
setInterpolator(
new Interpolator().createExponentialInOutInterpolator(3,false) );
ScaleBehavior sb= (ScaleBehavior) new ScaleBehavior().
setFrameTime(this.directorScene.time , 1000+random);
sb.setValues( .1, 1, .1 , 1).
setInterpolator(
new Interpolator().createExponentialInOutInterpolator(3,false) );
brickActor.emptyBehaviorList().
addBehavior(moveB).
addBehavior(sb).
enableEvents(false);
actorCount = 0;
moveB.addListener(new BehaviorListener() {
@Override
public void behaviorExpired(BaseBehavior behaviour, double time, Actor actor) {
actorCount++;
if ( actorCount== gameRows * gameColumns ) {
if ( context.status==context.ST_INITIALIZING ) {
context.setStatus( context.ST_RUNNNING );
}
}
}
public void behaviorApplied(BaseBehavior behavior, double time, double normalizeTime, Actor actor, SetForTimeReturnValue value) {
}
@Override
public void behaviorStarted(BaseBehavior behavior, double time, Actor actor) {
}
});
}
}
this.actorInitializationCount=0;
}
private int actorCount;
private int count;
public void contextEvent (Event event ) {
int i, j;
BrickActor brickActor;
if ( event.source.equals("context")) {
if ( event.event.equals("status")) {
if ( event.params==this.context.ST_INITIALIZING ) {
this.initializeActors();
} else if ( event.params==this.context.ST_RUNNNING) {
for( i=0; i<this.gameRows; i++ ) {
for( j=0; j<this.gameColumns; j++ ) {
brickActor= this.brickActors[i][j];
brickActor.enableEvents(true);
}
}
this.cancelTimer();
this.enableTimer();
} else if ( event.params==this.context.ST_LEVEL_RESULT ) {
this.cancelTimer();
this.context.nextLevel();
} else if ( event.params==this.context.ST_ENDGAME ) {
this.endGame();
}
} else if ( event.event.equals("levelchange")) {
this.levelActor.setText( "Level "+this.context.level );
this.levelActor.calcTextSize( this.director );
this.levelActor.x= (this.levelActor.parent.width-this.levelActor.width)/2;
}
} else if ( event.source.equals("brick")) {
if ( event.event.equals("selection") ) { // des/marcar un elemento.
this.brickSelectionEvent(event);
} else if ( event.event.equals("selectionoverflow")) { // seleccion error.
this.selectionOverflowEvent(event);
} else if ( event.event.equals("selection-cleared")) { // seleccion error.
this.selectionClearedEvent(event);
}
// rebuild selection path
this.selectionPath.setup(
this.context,
this.getBrickWidth(),
this.getBrickHeight() );
}
}
private void brickSelectionEvent(Event event) {
Brick brick= event.brick;
BrickActor brickActor= this.brickActors[brick.row][brick.column];
if ( brick.selected ) {
brickActor.emptyBehaviorList();
ScaleBehavior sb= (ScaleBehavior) new ScaleBehavior().
setValues( 1, .5, 1, .5 ).
setFrameTime( 0, 1000 ).
setPingPong();
AlphaBehavior ab= (AlphaBehavior) new AlphaBehavior().
setValues( 1, .25 ).
setFrameTime( 0, 1000 ).
setPingPong();
ContainerBehavior cb= (ContainerBehavior) new ContainerBehavior().
setFrameTime( 0, 1000 ).
setCycle(true).
setPingPong();
cb.addBehavior( sb ).
addBehavior( ab );
brickActor.addBehavior(cb);
}
else {
brickActor.reset();
}
}
private void selectionOverflowEvent(Event event) {
int i, j;
List<Brick> selectedContextBricks= event.bricks;
for( i=0; i<selectedContextBricks.size(); i++ ) {
this.brickActors[ selectedContextBricks.get(i).row ][ selectedContextBricks.get(i).column ].reset();
}
this.bricksContainer.enableEvents(false);
// get all active actors on board
List<BrickActor> activeActors = new ArrayList<BrickActor>();
for( i=0; i<this.gameRows; i++ ) {
for( j=0; j<this.gameColumns; j++ ) {
BrickActor actor= this.brickActors[i][j];
if ( !actor.brick.removed ) {
activeActors.add(actor);
}
}
}
// define animation callback
count=0;
final int maxCount= activeActors.size();
// for each active actor, play a wrong-path.
for( i=0; i<activeActors.size(); i++ ) {
BrickActor actor= activeActors.get(i);
double signo= Math.random()<.5 ? 1: -1;
Path path = new Path().
beginPath( actor.x, actor.y ).
addLineTo(actor.x + signo*(5+5*Math.random()), actor.y, null ).
addLineTo(actor.x - signo*(10+5*Math.random()), actor.y, null).
closePath();
PathBehavior pathBehavior = (PathBehavior) new PathBehavior().
setFrameTime(this.directorScene.time, 200);
pathBehavior.setPath(path).
addListener(new BehaviorListener() {
@Override
public void behaviorExpired(BaseBehavior behaviour, double time, Actor actor) {
count++;
if ( count==maxCount ) {
bricksContainer.enableEvents(true);
}
}
@Override
public void behaviorApplied(BaseBehavior behavior, double time, double normalizeTime,
Actor actor, SetForTimeReturnValue value) {
}
@Override
public void behaviorStarted(BaseBehavior behavior, double time, Actor actor) {
}
}).
setPingPong() ;
actor.emptyBehaviorList().
addBehavior(pathBehavior);
}
}
private void selectionClearedEvent(Event event) {
List<Brick> selectedContextBricks= event.bricks;
int i, j;
for( i=0; i<selectedContextBricks.size(); i++ ) {
BrickActor actor= this.brickActors[ selectedContextBricks.get(i).row ][ selectedContextBricks.get(i).column ];
double signo= Math.random()<.5 ? 1 : -1;
double offset= 50+Math.random()*30;
double offsetY= 60+Math.random()*30;
actor.parent.setZOrder(actor, Integer.MAX_VALUE);
Path path = (Path) new Path().
beginPath( actor.x, actor.y ).
addQuadricTo(
actor.x+offset*signo, actor.y-300,
actor.x+offset*signo*2, actor.y+this.director.canvas.getCoordinateSpaceHeight()+20, null).
endPath();
PathBehavior pathBehavior = (PathBehavior) new PathBehavior()
.setFrameTime( this.directorScene.time, 800 );
pathBehavior.setPath(path)
.addListener(new BehaviorListener() {
@Override
public void behaviorExpired(BaseBehavior behavior, double time, Actor actor) {
actor.setExpired(true);
}
@Override
public void behaviorApplied(BaseBehavior behavior, double time, double normalizeTime, Actor actor, SetForTimeReturnValue value) throws Exception {
// System.out.println("behavior applied");
List<String> colors= Arrays.asList("#00ff00","#ffff00","#00ffff");
for(int i=0; i<3; i++ ) {
double offset0= Math.random()*10*(Math.random()<.5?1:-1);
double offset1= Math.random()*10*(Math.random()<.5?1:-1);
directorScene.addChild(
new ShapeActor().
setBounds( offset0+actor.x-3, offset1+actor.y-3, 6, 6 ).
setShape( ShapeActor.Shape.CIRCLE).
setFillStyle( colors.get(i%3) ).
setDiscardable(true).
setFrameTime(directorScene.time, 300).
addBehavior(
new AlphaBehavior().
setFrameTime(directorScene.time, 300).
setValues( .6, .1 )
) );
}
}
@Override
public void behaviorStarted(BaseBehavior behavior, double time, Actor actor) {
}
});
actor.enableEvents(false).
emptyBehaviorList().
addBehavior(pathBehavior).
addBehavior(
new RotateBehavior().
setFrameTime( this.directorScene.time, 800 ).
setAngles( 0, (Math.PI + Math.random()*Math.PI*2)*(Math.random()<.5?1:-1) )
).addBehavior(
new AlphaBehavior().
setFrameTime( this.directorScene.time, 800 ).
setValues( 1, .25 )
).setScale( 1.5, 1.5 );
}
this.timer.reset(this.directorScene.time);
}
void showLevelInfo() {
// ActorContainer container= (ActorContainer) new ActorContainer().
//
// setBounds( this.bricksContainer.x, this.bricksContainer.y,
// this.bricksContainer.width, this.bricksContainer.height );
//
// RotateBehavior rb= (RotateBehavior) new RotateBehavior().
// setCycle(true).
// setFrameTime( this.directorScene.time, 3000 );
// rb.setAngles( -Math.PI/8, Math.PI/8 ).
// setInterpolator( new Interpolator().createExponentialInOutInterpolator(3,true) );
// rb.setAnchor( Actor.Anchor.TOP );
//
// CanvasGradient gradient= this.director.ctx.createLinearGradient(0,0,0,90);
// gradient.addColorStop(0,"#00ff00");
// gradient.addColorStop(0.5,"#ffff00");
// gradient.addColorStop(1,"#3f3f3f");
//
// TextActor text= (TextActor) new TextActor().
//
// setFont("90px sans-serif").
// setText("Level "+this.context.level).
// setFillStrokeStyle( gradient ).
// setOutline(true).
// addBehavior( rb );
// text.calcTextSize(this.director);
//
// text.setLocation((container.width-text.textWidth)/2,40);
// container.addChild(text);
//
// this.directorScene.addChild(container);
}
public void prepareSceneIn () {
// setup de actores
this.bricksContainer.enableEvents(true);
// fuera de pantalla
for(int i=0; i<this.gameRows; i++ ) {
for(int j=0; j<this.gameColumns; j++ ) {
this.brickActors[i][j].setLocation(-100,-100);
}
}
this.selectionPath.initialize();
this.chronoActor.tick(0,0);
this.scoreActor.reset();
this.endGameActor.setFrameTime(-1,0);
}
public void endGame () {
// parar y eliminar cronometro.
this.cancelTimer();
// quitar contorl de mouse.
this.bricksContainer.enableEvents(false);
// mostrar endgameactor.
double x= (this.directorScene.width - this.endGameActor.width)/2;
double y= (this.directorScene.height - this.endGameActor.height)/2;
final ImageActor me_endGameActor= this.endGameActor;
LinearPath path = new LinearPath().
setInitialPosition( x, this.directorScene.height ).
setFinalPosition( x, y );
PathBehavior pb = (PathBehavior) new PathBehavior().
setFrameTime( this.directorScene.time, 800 );
pb.setPath(
path);
this.endGameActor.emptyBehaviorList().
setFrameTime(this.directorScene.time, Double.MAX_VALUE).
enableEvents(false).
addBehavior(pb
.
setInterpolator(
new Interpolator().createBounceOutInterpolator(false) ).
addListener(new BehaviorListener() {
@Override
public void behaviorExpired(BaseBehavior behavior, double time, Actor actor) {
me_endGameActor.enableEvents(true);
}
@Override
public void behaviorApplied(BaseBehavior behavior, double time, double normalizeTime, Actor actor, SetForTimeReturnValue value) {
}
@Override
public void behaviorStarted(BaseBehavior behavior, double time, Actor actor) {
}
}));
}
public void setDifficulty (int level) {
this.context.difficulty=level;
}
public void cancelTimer (){
if ( this.timer!=null ) {
this.timer.cancel();
}
this.timer= null;
}
public void enableTimer () {
this.timer= this.directorScene.createTimer(
this.directorScene.time,
this.context.turnTime,
new Callback() {
@Override
public void call(double sceneTime, double ttime, TimerTask timerTask) {
context.timeUp();
}
},
new Callback() {
@Override
public void call(double sceneTime, double ttime, TimerTask timerTask) {
chronoActor.tick(ttime, timerTask.duration);
}
},
null);
}
// public void startGame () {
// int iNewSceneIndex= this.director.getSceneIndex(this.directorScene);
// this.director.switchToScene( iNewSceneIndex, 2000, false, true );
// }
}
| true | true | public GameScene create (final Director director,int rows,int columns, final Context context) throws Exception {
this.gameRows= rows;
this.gameColumns= columns;
this.director= director;
CaatjaImage image = director.getImage("bricks");
this.bricksImage= new CompoundImage().initialize(
image,
this.imageBricksH,
this.imageBricksW );
CaatjaImage image2 = director.getImage("buttons");
this.buttonImage= new CompoundImage().initialize(
image2, 6,4 );
// this.context= new Context().
// create( this.gameRows, this.gameColumns, this.imageBricksH ).
// addContextListener(this);
context.addContextListener(this);
this.context = context;
// this.directorScene= director.createScene();
this.directorScene = new Scene() {
@Override
public void activated() {
context.initialize();
}
};
director.addScene(directorScene);
int dw= director.canvas.getCoordinateSpaceWidth();
int dh= director.canvas.getCoordinateSpaceHeight();
////////////////////////animated background
this.backgroundContainer= (AnimatedBackground) new AnimatedBackground().
setBounds(0,0,dw,dh).
setImage(director.getImage("background")).
setOffsetY( -director.getImage("background").getHeight()+2*dh ).
setClip(true);
this.backgroundContainer.setScene(this.directorScene);
this.directorScene.addChild(this.backgroundContainer);
this.context.addContextListener(this.backgroundContainer);
this.brickActors = new BrickActor[gameRows][gameColumns];
////////////////////////Number Bricks
this.bricksContainer= (ActorContainer) new ActorContainer().
setSize(
this.gameColumns*this.getBrickWidth(),
this.gameRows*this.getBrickHeight() );
double bricksCY= (dh-this.bricksContainer.height)/2;
double bricksCX= bricksCY;
this.bricksContainer.setLocation( bricksCX, bricksCY );
this.directorScene.addChild(this.bricksContainer);
int i,j;
for( i=0; i<this.gameRows; i++ ) {
// this.brickActors.push([]);
for( j=0; j<this.gameColumns; j++ ) {
BrickActor brick= (BrickActor) new BrickActor();
brick.initialize( this.bricksImage, this.context.getBrick(i,j) ).
setLocation(-100,-100);
this.brickActors[i][j] = brick;
bricksContainer.addChild(brick);
}
}
/////////////////////// game indicators.
ActorContainer controls= (ActorContainer) new ActorContainer().
setBounds(
this.bricksContainer.x + this.bricksContainer.width + bricksCX,
this.bricksContainer.x,
dw - bricksCX - (this.bricksContainer.x + this.bricksContainer.width) - bricksCX,
this.bricksContainer.height );
this.directorScene.addChild( controls );
/////////////////////// initialize selection path
this.selectionPath= (SelectionPath) new SelectionPath().
setBounds(
this.bricksContainer.x,
this.bricksContainer.y,
this.gameColumns*this.getBrickWidth(),
this.gameRows*this.getBrickHeight());
this.selectionPath.enableEvents(false);
this.directorScene.addChild(this.selectionPath);
this.context.addContextListener(this.selectionPath);
/////////////////////// initialize button
Button restart= (Button) new Button() {
@Override
public void mouseClick(CAATMouseEvent mouseEvent) {
context.timeUp();
}
}.
initialize( this.buttonImage, 20,21,22,23 ).
setLocation(
(controls.width-this.buttonImage.singleWidth)/2,
controls.height - this.buttonImage.singleHeight );
controls.addChild(restart);
///////////////////// Level indicator
CaatjaGradient gradient= director.ctx.createLinearGradient(0,0,0,40);
gradient.addColorStop(0,"#00ff00");
gradient.addColorStop(0.5,"#ffff00");
gradient.addColorStop(1,"#3f3f3f");
this.levelActor= new TextActor().
setFont("40px sans-serif").
setText("");
levelActor.setTextFillStyle( gradient ).
setOutline(true).
calcTextSize(director);
this.levelActor.setLocation((controls.width-this.levelActor.textWidth)/2,5);
controls.addChild(this.levelActor);
///////////////////// Guess Number
GuessNumberActor guess= (GuessNumberActor) new GuessNumberActor().
setBounds((controls.width-80)/2, 50, 80, 30 );
guess.setFont("80px sans-serif").
setText("").
setTextFillStyle("#000000").
setOutline(true).
setOutlineColor("#ffff00");
this.context.addContextListener(guess);
controls.addChild(guess);
///////////////////// chronometer
this.chronoActor= (Chrono) new Chrono().
setBounds( 2, 140, controls.width-4, 20 );
this.context.addContextListener(this.chronoActor);
controls.addChild(this.chronoActor);
///////////////////// score
this.scoreActor= (ScoreActor) new ScoreActor().
setBounds( 2, 180, controls.width-4, 30 );
this.scoreActor.setFont( "40px sans-serif" ).
setTextFillStyle( gradient ).
setOutline( true ).
setOutlineColor( "0x7f7f00" );
controls.addChild( this.scoreActor );
this.context.addContextListener(this.scoreActor);
////////////////////////////////////////////////
this.create_EndGame(director);
return this;
}
| public GameScene create (final Director director,int rows,int columns, final Context context) throws Exception {
this.gameRows= rows;
this.gameColumns= columns;
this.director= director;
CaatjaImage image = director.getImage("bricks");
this.bricksImage= new CompoundImage().initialize(
image,
this.imageBricksH,
this.imageBricksW );
CaatjaImage image2 = director.getImage("buttons");
this.buttonImage= new CompoundImage().initialize(
image2, 7,4 );
// this.context= new Context().
// create( this.gameRows, this.gameColumns, this.imageBricksH ).
// addContextListener(this);
context.addContextListener(this);
this.context = context;
// this.directorScene= director.createScene();
this.directorScene = new Scene() {
@Override
public void activated() {
context.initialize();
}
};
director.addScene(directorScene);
int dw= director.canvas.getCoordinateSpaceWidth();
int dh= director.canvas.getCoordinateSpaceHeight();
////////////////////////animated background
this.backgroundContainer= (AnimatedBackground) new AnimatedBackground().
setBounds(0,0,dw,dh).
setImage(director.getImage("background")).
setOffsetY( -director.getImage("background").getHeight()+2*dh ).
setClip(true);
this.backgroundContainer.setScene(this.directorScene);
this.directorScene.addChild(this.backgroundContainer);
this.context.addContextListener(this.backgroundContainer);
this.brickActors = new BrickActor[gameRows][gameColumns];
////////////////////////Number Bricks
this.bricksContainer= (ActorContainer) new ActorContainer().
setSize(
this.gameColumns*this.getBrickWidth(),
this.gameRows*this.getBrickHeight() );
double bricksCY= (dh-this.bricksContainer.height)/2;
double bricksCX= bricksCY;
this.bricksContainer.setLocation( bricksCX, bricksCY );
this.directorScene.addChild(this.bricksContainer);
int i,j;
for( i=0; i<this.gameRows; i++ ) {
// this.brickActors.push([]);
for( j=0; j<this.gameColumns; j++ ) {
BrickActor brick= (BrickActor) new BrickActor();
brick.initialize( this.bricksImage, this.context.getBrick(i,j) ).
setLocation(-100,-100);
this.brickActors[i][j] = brick;
bricksContainer.addChild(brick);
}
}
/////////////////////// game indicators.
ActorContainer controls= (ActorContainer) new ActorContainer().
setBounds(
this.bricksContainer.x + this.bricksContainer.width + bricksCX,
this.bricksContainer.x,
dw - bricksCX - (this.bricksContainer.x + this.bricksContainer.width) - bricksCX,
this.bricksContainer.height );
this.directorScene.addChild( controls );
/////////////////////// initialize selection path
this.selectionPath= (SelectionPath) new SelectionPath().
setBounds(
this.bricksContainer.x,
this.bricksContainer.y,
this.gameColumns*this.getBrickWidth(),
this.gameRows*this.getBrickHeight());
this.selectionPath.enableEvents(false);
this.directorScene.addChild(this.selectionPath);
this.context.addContextListener(this.selectionPath);
/////////////////////// initialize button
Button restart= (Button) new Button() {
@Override
public void mouseClick(CAATMouseEvent mouseEvent) {
context.timeUp();
}
}.
initialize( this.buttonImage, 20,21,22,23 ).
setLocation(
(controls.width-this.buttonImage.singleWidth)/2,
controls.height - this.buttonImage.singleHeight );
controls.addChild(restart);
///////////////////// Level indicator
CaatjaGradient gradient= director.ctx.createLinearGradient(0,0,0,40);
gradient.addColorStop(0,"#00ff00");
gradient.addColorStop(0.5,"#ffff00");
gradient.addColorStop(1,"#3f3f3f");
this.levelActor= new TextActor().
setFont("40px sans-serif").
setText("");
levelActor.setTextFillStyle( gradient ).
setOutline(true).
calcTextSize(director);
this.levelActor.setLocation((controls.width-this.levelActor.textWidth)/2,5);
controls.addChild(this.levelActor);
///////////////////// Guess Number
GuessNumberActor guess= (GuessNumberActor) new GuessNumberActor().
setBounds((controls.width-80)/2, 50, 80, 30 );
guess.setFont("80px sans-serif").
setText("").
setTextFillStyle("#000000").
setOutline(true).
setOutlineColor("#ffff00");
this.context.addContextListener(guess);
controls.addChild(guess);
///////////////////// chronometer
this.chronoActor= (Chrono) new Chrono().
setBounds( 2, 140, controls.width-4, 20 );
this.context.addContextListener(this.chronoActor);
controls.addChild(this.chronoActor);
///////////////////// score
this.scoreActor= (ScoreActor) new ScoreActor().
setBounds( 2, 180, controls.width-4, 30 );
this.scoreActor.setFont( "40px sans-serif" ).
setTextFillStyle( gradient ).
setOutline( true ).
setOutlineColor( "0x7f7f00" );
controls.addChild( this.scoreActor );
this.context.addContextListener(this.scoreActor);
////////////////////////////////////////////////
this.create_EndGame(director);
return this;
}
|
diff --git a/src/de/aidger/model/inspectors/OverlapContractInspector.java b/src/de/aidger/model/inspectors/OverlapContractInspector.java
index d01f35b6..18a7f4ab 100644
--- a/src/de/aidger/model/inspectors/OverlapContractInspector.java
+++ b/src/de/aidger/model/inspectors/OverlapContractInspector.java
@@ -1,98 +1,98 @@
/*
* This file is part of the aidGer project.
*
* Copyright (C) 2010-2013 The aidGer Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.aidger.model.inspectors;
import static de.aidger.utils.Translation._;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import de.aidger.model.models.Assistant;
import de.aidger.model.models.Contract;
import de.aidger.view.forms.ContractEditorForm.ContractType;
import de.aidger.view.models.UIAssistant;
import siena.SienaException;
/**
* Inspector for overlapped new contracts.
*
* @author aidGer Team
*/
public class OverlapContractInspector extends Inspector {
/**
* The contract to be checked.
*/
Contract contract;
/**
* Creates an overlap contract inspector.
*
* @param contract
* the contract to be checked
*/
public OverlapContractInspector(Contract contract) {
this.contract = contract;
}
/*
* Checks for oberlapped new contracts.
*/
@Override
public void check() {
// do nothing if contract is not new
if (ContractType.valueOf(contract.getType()) != ContractType.newContract) {
return;
}
try {
Assistant assistant = new Assistant((new Assistant())
.getById(contract.getAssistantId()));
List<Contract> contracts = (new Contract()).getContracts(assistant);
for (Contract other : contracts) {
// only handle new contracts and different one
if (ContractType.valueOf(other.getType()) != ContractType.newContract
- || contract.getId().equals(other.getId())) {
+ || (contract.getId() != null && contract.getId().equals(other.getId()))) {
continue;
}
Date s1 = contract.getStartDate();
Date e1 = contract.getEndDate();
Date s2 = other.getStartDate();
Date e2 = other.getEndDate();
if (s2.compareTo(e1) <= 0 && e2.compareTo(s1) >= 0) {
result = MessageFormat
.format(
_("The new contract of {0} overlaps with another one."),
new Object[] { new UIAssistant(assistant)
.toString() });
return;
}
}
} catch (SienaException e) {
}
}
}
| true | true | public void check() {
// do nothing if contract is not new
if (ContractType.valueOf(contract.getType()) != ContractType.newContract) {
return;
}
try {
Assistant assistant = new Assistant((new Assistant())
.getById(contract.getAssistantId()));
List<Contract> contracts = (new Contract()).getContracts(assistant);
for (Contract other : contracts) {
// only handle new contracts and different one
if (ContractType.valueOf(other.getType()) != ContractType.newContract
|| contract.getId().equals(other.getId())) {
continue;
}
Date s1 = contract.getStartDate();
Date e1 = contract.getEndDate();
Date s2 = other.getStartDate();
Date e2 = other.getEndDate();
if (s2.compareTo(e1) <= 0 && e2.compareTo(s1) >= 0) {
result = MessageFormat
.format(
_("The new contract of {0} overlaps with another one."),
new Object[] { new UIAssistant(assistant)
.toString() });
return;
}
}
} catch (SienaException e) {
}
}
| public void check() {
// do nothing if contract is not new
if (ContractType.valueOf(contract.getType()) != ContractType.newContract) {
return;
}
try {
Assistant assistant = new Assistant((new Assistant())
.getById(contract.getAssistantId()));
List<Contract> contracts = (new Contract()).getContracts(assistant);
for (Contract other : contracts) {
// only handle new contracts and different one
if (ContractType.valueOf(other.getType()) != ContractType.newContract
|| (contract.getId() != null && contract.getId().equals(other.getId()))) {
continue;
}
Date s1 = contract.getStartDate();
Date e1 = contract.getEndDate();
Date s2 = other.getStartDate();
Date e2 = other.getEndDate();
if (s2.compareTo(e1) <= 0 && e2.compareTo(s1) >= 0) {
result = MessageFormat
.format(
_("The new contract of {0} overlaps with another one."),
new Object[] { new UIAssistant(assistant)
.toString() });
return;
}
}
} catch (SienaException e) {
}
}
|
diff --git a/trunk/org.mwc.debrief.legacy/src/Debrief/Wrappers/Track/WormInHoleOffset.java b/trunk/org.mwc.debrief.legacy/src/Debrief/Wrappers/Track/WormInHoleOffset.java
index 85c201f30..866cf6c20 100644
--- a/trunk/org.mwc.debrief.legacy/src/Debrief/Wrappers/Track/WormInHoleOffset.java
+++ b/trunk/org.mwc.debrief.legacy/src/Debrief/Wrappers/Track/WormInHoleOffset.java
@@ -1,245 +1,251 @@
package Debrief.Wrappers.Track;
import java.util.Enumeration;
import java.util.Vector;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.SensorContactWrapper;
import Debrief.Wrappers.SensorWrapper;
import Debrief.Wrappers.TrackWrapper;
import MWC.GUI.Editable;
import MWC.GenericData.HiResDate;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldVector;
import MWC.GenericData.WorldDistance.ArrayLength;
import MWC.TacticalData.Fix;
/**
* class to calculate offset position of sensor back from host location by
* travelling back along host track for specified distance
*
* @author ianmayo
*
*/
public class WormInHoleOffset
{
/**
*
* @param track
* @param dtg
* @param arrayOffset
* @return
*/
public static WorldLocation getWormOffsetFor(TrackWrapper track,
HiResDate dtg, WorldDistance arrayOffset)
{
WorldLocation res = null;
double offsetM = - arrayOffset.getValueIn(WorldDistance.METRES);
// double offsetM = Math.abs(arrayOffset.getValueIn(WorldDistance.METRES));
// check we're in period
if (dtg.lessThan(track.getStartDTG()) || dtg.greaterThan(track.getEndDTG()))
return res;
// start off by bracketing the time. work back along the track legs until we
// find the two positions either side
// of the time we're looking for
Enumeration<Editable> enumer = track.getPositions();
Vector<FixWrapper> backTrack = new Vector<FixWrapper>();
FixWrapper nextPoint = null;
while (enumer.hasMoreElements())
{
FixWrapper thisP = (FixWrapper) enumer.nextElement();
- if (thisP.getDateTimeGroup().lessThan(dtg))
+ if(thisP.getDateTimeGroup().equals(dtg))
+ {
+ res = new WorldLocation(thisP.getLocation().add(new WorldVector(thisP.getCourse(),
+ MWC.Algorithms.Conversions.m2Degs(-offsetM), 0d)));
+ return res;
+ }
+ else if (thisP.getDateTimeGroup().lessThan(dtg))
{
backTrack.add(thisP);
}
else
{
// we've passed the point
nextPoint = thisP;
break;
}
}
// right, we have a back track. double-check we have our next point
if (backTrack.size() > 0)
{
// yup, we've bracketed the point. work out where ownship is at this DTG
nextPoint = FixWrapper.interpolateFix(backTrack.lastElement(), nextPoint,
dtg);
for (int i = backTrack.size()-1; i >= 0; i--)
{
FixWrapper thisI = backTrack.elementAt(i);
double thisLen = nextPoint.getLocation().subtract(
thisI.getFixLocation()).getRange();
double thisLenM = MWC.Algorithms.Conversions.Degs2m(thisLen);
// is this less than our stub?
if (thisLenM > offsetM)
{
// so just interpolate along the path
double posDelta = offsetM / thisLenM;
double timeDelta = (nextPoint.getDTG().getMicros() - thisI.getDTG()
.getMicros())
* posDelta;
FixWrapper newMidFix = FixWrapper.interpolateFix(thisI, nextPoint,
new HiResDate(0,
(long) (nextPoint.getDTG().getMicros() - timeDelta)));
res = newMidFix.getLocation();
offsetM = 0;
break;
}
else
{
offsetM -= thisLenM;
nextPoint = thisI;
}
}
}
// do we have any array left to consume?
if (offsetM > 0)
{
// are we on the first data point?
if (nextPoint != null)
{
// yup, just use that one
res = nextPoint.getLocation();
// offset by the array length along the heading
res = new WorldLocation(res.add(new WorldVector(nextPoint.getCourse(),
MWC.Algorithms.Conversions.m2Degs(-offsetM), 0d)));
}
}
return res;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////
// testing for this class
// ////////////////////////////////////////////////////////////////////////////////////////////////
static public final class testMe extends junit.framework.TestCase
{
public void testData() throws InterruptedException
{
TrackWrapper track = getDummyTrack();
assertNotNull("track generated", track);
assertEquals("correct points", 5, track.numFixes());
// get the sensor
SensorWrapper sw = (SensorWrapper) track.getSensors().elements().nextElement();
// find the position of the last fix
SensorContactWrapper scw = (SensorContactWrapper) sw.getNearestTo(sw
.getEndDTG())[0];
assertNotNull("fix found", scw);
outputSensorTrack(sw);
Thread.sleep(100);
outputTrack(track);
Thread.sleep(100);
sw.setWormInHole(true);
outputSensorTrack(sw);
}
private void outputTrack(TrackWrapper track)
{
Enumeration<Editable> numer = track.getPositions();
while (numer.hasMoreElements())
{
FixWrapper thisF = (FixWrapper) numer.nextElement();
System.err.println(MWC.Algorithms.Conversions.Degs2m(thisF
.getLocation().getLong())
+ ", "
+ MWC.Algorithms.Conversions.Degs2m(thisF.getLocation().getLat()));
}
}
private void outputSensorTrack(SensorWrapper sensor)
{
Enumeration<Editable> numer = sensor.elements();
while (numer.hasMoreElements())
{
SensorContactWrapper thisF = (SensorContactWrapper) numer.nextElement();
WorldLocation thisLoc = thisF.getLocation();
System.out.println(MWC.Algorithms.Conversions.Degs2m(thisLoc.getLong())
+ ", " + MWC.Algorithms.Conversions.Degs2m(thisLoc.getLat()));
}
}
private TrackWrapper getDummyTrack()
{
final TrackWrapper tw = new TrackWrapper();
final WorldLocation loc_1 = new WorldLocation(0, 0, 0);
final FixWrapper fw1 = new FixWrapper(new Fix(new HiResDate(100, 0),
loc_1.add(getVector(0, 0)), MWC.Algorithms.Conversions.Degs2Rads(0),
110));
fw1.setLabel("fw1");
final FixWrapper fw2 = new FixWrapper(new Fix(new HiResDate(200, 0),
loc_1.add(getVector(0, 600)), MWC.Algorithms.Conversions
.Degs2Rads(90), 120));
fw2.setLabel("fw2");
final FixWrapper fw3 = new FixWrapper(new Fix(new HiResDate(300, 0),
loc_1.add(getVector(45, 849)), MWC.Algorithms.Conversions
.Degs2Rads(180), 130));
fw3.setLabel("fw3");
final FixWrapper fw4 = new FixWrapper(new Fix(new HiResDate(400, 0),
loc_1.add(getVector(90, 600)), MWC.Algorithms.Conversions
.Degs2Rads(90), 140));
fw4.setLabel("fw4");
final FixWrapper fw5 = new FixWrapper(new Fix(new HiResDate(500, 0),
loc_1.add(getVector(90, 1200)), MWC.Algorithms.Conversions
.Degs2Rads(90), 700));
fw5.setLabel("fw5");
tw.addFix(fw1);
tw.addFix(fw2);
tw.addFix(fw3);
tw.addFix(fw4);
tw.addFix(fw5);
// also give it some sensor data
final SensorWrapper swa = new SensorWrapper("title one");
swa.setSensorOffset(new ArrayLength(-400));
final SensorContactWrapper scwa1 = new SensorContactWrapper("aaa",
new HiResDate(100, 0), null, 0, null, null, null, 0, null);
final SensorContactWrapper scwa2 = new SensorContactWrapper("bbb",
new HiResDate(140, 0), null, 0, null, null, null, 0, null);
final SensorContactWrapper scwa3 = new SensorContactWrapper("ccc",
new HiResDate(280, 0), null, 0, null, null, null, 0, null);
final SensorContactWrapper scwa4 = new SensorContactWrapper("ddd",
new HiResDate(350, 0), null, 0, null, null, null, 0, null);
swa.add(scwa1);
swa.add(scwa2);
swa.add(scwa3);
swa.add(scwa4);
tw.add(swa);
return tw;
}
/**
* @return
*/
private WorldVector getVector(double courseDegs, double distM)
{
return new WorldVector(MWC.Algorithms.Conversions.Degs2Rads(courseDegs),
new WorldDistance(distM, WorldDistance.METRES), null);
}
}
}
| true | true | public static WorldLocation getWormOffsetFor(TrackWrapper track,
HiResDate dtg, WorldDistance arrayOffset)
{
WorldLocation res = null;
double offsetM = - arrayOffset.getValueIn(WorldDistance.METRES);
// double offsetM = Math.abs(arrayOffset.getValueIn(WorldDistance.METRES));
// check we're in period
if (dtg.lessThan(track.getStartDTG()) || dtg.greaterThan(track.getEndDTG()))
return res;
// start off by bracketing the time. work back along the track legs until we
// find the two positions either side
// of the time we're looking for
Enumeration<Editable> enumer = track.getPositions();
Vector<FixWrapper> backTrack = new Vector<FixWrapper>();
FixWrapper nextPoint = null;
while (enumer.hasMoreElements())
{
FixWrapper thisP = (FixWrapper) enumer.nextElement();
if (thisP.getDateTimeGroup().lessThan(dtg))
{
backTrack.add(thisP);
}
else
{
// we've passed the point
nextPoint = thisP;
break;
}
}
// right, we have a back track. double-check we have our next point
if (backTrack.size() > 0)
{
// yup, we've bracketed the point. work out where ownship is at this DTG
nextPoint = FixWrapper.interpolateFix(backTrack.lastElement(), nextPoint,
dtg);
for (int i = backTrack.size()-1; i >= 0; i--)
{
FixWrapper thisI = backTrack.elementAt(i);
double thisLen = nextPoint.getLocation().subtract(
thisI.getFixLocation()).getRange();
double thisLenM = MWC.Algorithms.Conversions.Degs2m(thisLen);
// is this less than our stub?
if (thisLenM > offsetM)
{
// so just interpolate along the path
double posDelta = offsetM / thisLenM;
double timeDelta = (nextPoint.getDTG().getMicros() - thisI.getDTG()
.getMicros())
* posDelta;
FixWrapper newMidFix = FixWrapper.interpolateFix(thisI, nextPoint,
new HiResDate(0,
(long) (nextPoint.getDTG().getMicros() - timeDelta)));
res = newMidFix.getLocation();
offsetM = 0;
break;
}
else
{
offsetM -= thisLenM;
nextPoint = thisI;
}
}
}
// do we have any array left to consume?
if (offsetM > 0)
{
// are we on the first data point?
if (nextPoint != null)
{
// yup, just use that one
res = nextPoint.getLocation();
// offset by the array length along the heading
res = new WorldLocation(res.add(new WorldVector(nextPoint.getCourse(),
MWC.Algorithms.Conversions.m2Degs(-offsetM), 0d)));
}
}
return res;
}
| public static WorldLocation getWormOffsetFor(TrackWrapper track,
HiResDate dtg, WorldDistance arrayOffset)
{
WorldLocation res = null;
double offsetM = - arrayOffset.getValueIn(WorldDistance.METRES);
// double offsetM = Math.abs(arrayOffset.getValueIn(WorldDistance.METRES));
// check we're in period
if (dtg.lessThan(track.getStartDTG()) || dtg.greaterThan(track.getEndDTG()))
return res;
// start off by bracketing the time. work back along the track legs until we
// find the two positions either side
// of the time we're looking for
Enumeration<Editable> enumer = track.getPositions();
Vector<FixWrapper> backTrack = new Vector<FixWrapper>();
FixWrapper nextPoint = null;
while (enumer.hasMoreElements())
{
FixWrapper thisP = (FixWrapper) enumer.nextElement();
if(thisP.getDateTimeGroup().equals(dtg))
{
res = new WorldLocation(thisP.getLocation().add(new WorldVector(thisP.getCourse(),
MWC.Algorithms.Conversions.m2Degs(-offsetM), 0d)));
return res;
}
else if (thisP.getDateTimeGroup().lessThan(dtg))
{
backTrack.add(thisP);
}
else
{
// we've passed the point
nextPoint = thisP;
break;
}
}
// right, we have a back track. double-check we have our next point
if (backTrack.size() > 0)
{
// yup, we've bracketed the point. work out where ownship is at this DTG
nextPoint = FixWrapper.interpolateFix(backTrack.lastElement(), nextPoint,
dtg);
for (int i = backTrack.size()-1; i >= 0; i--)
{
FixWrapper thisI = backTrack.elementAt(i);
double thisLen = nextPoint.getLocation().subtract(
thisI.getFixLocation()).getRange();
double thisLenM = MWC.Algorithms.Conversions.Degs2m(thisLen);
// is this less than our stub?
if (thisLenM > offsetM)
{
// so just interpolate along the path
double posDelta = offsetM / thisLenM;
double timeDelta = (nextPoint.getDTG().getMicros() - thisI.getDTG()
.getMicros())
* posDelta;
FixWrapper newMidFix = FixWrapper.interpolateFix(thisI, nextPoint,
new HiResDate(0,
(long) (nextPoint.getDTG().getMicros() - timeDelta)));
res = newMidFix.getLocation();
offsetM = 0;
break;
}
else
{
offsetM -= thisLenM;
nextPoint = thisI;
}
}
}
// do we have any array left to consume?
if (offsetM > 0)
{
// are we on the first data point?
if (nextPoint != null)
{
// yup, just use that one
res = nextPoint.getLocation();
// offset by the array length along the heading
res = new WorldLocation(res.add(new WorldVector(nextPoint.getCourse(),
MWC.Algorithms.Conversions.m2Degs(-offsetM), 0d)));
}
}
return res;
}
|
diff --git a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java
index 24bf9833..7ca9a210 100644
--- a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java
+++ b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java
@@ -1,142 +1,144 @@
package org.jboss.tools.esb.ui.bot.tests.examples;
import org.jboss.tools.ui.bot.ext.SWTEclipseExt;
import org.jboss.tools.ui.bot.ext.SWTOpenExt;
import org.jboss.tools.ui.bot.ext.SWTTestExt;
import org.jboss.tools.ui.bot.ext.Timing;
import org.jboss.tools.ui.bot.ext.config.Annotations.Require;
import org.jboss.tools.ui.bot.ext.config.Annotations.Server;
import org.jboss.tools.ui.bot.ext.config.Annotations.ServerState;
import org.jboss.tools.ui.bot.ext.config.Annotations.ServerType;
import org.jboss.tools.ui.bot.ext.gen.ActionItem;
import org.jboss.tools.ui.bot.ext.gen.ActionItem.NewObject.ESBESBFile;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTableItem;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.jboss.tools.ui.bot.ext.gen.ActionItem.NewObject.GeneralFolder;
@Require(server=@Server(type=ServerType.SOA,state=ServerState.Running))
public class HelloWorldFileAction extends ESBExampleTest {
public static String inputDir = "inputDir";
public static String outputDir = "outputDir";
public static String errorDir = "errorDir";
public static String projectName = "helloworld_file_action";
public static String clientProjectName = "helloworld_file_action_client";
public static String baseDir = null;
@Override
public String getExampleName() {
return "JBoss ESB HelloWorld File Action Example - ESB";
}
@Override
public String[] getProjectNames() {
return new String[] {"helloworld_file_action","helloworld_file_action_client"};
}
@Override
protected void executeExample() {
/* Create the data directories needed by the quickstart */
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(inputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(outputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(errorDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
/* We need to get the project base dir for the directory definitions in jboss-esb.xml */
SWTBotView theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theProject = bot.tree(0).getTreeItem(projectName).select();
bot.menu("File").menu("Properties").click();
if (System.getProperty("file.separator").equals("/")) {
baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
}
else {
/* Needed to avoid a syntax error with Windows \ dir path characters */
//baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), System.getProperty("file.separator") + System.getProperty("file.separator")) + System.getProperty("file.separator");
+ baseDir = bot.textWithLabel("Location:").getText();
+ System.out.println("DEBUG baseDir = " + bot.textWithLabel("Location:").getText()) ;
baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), "zzz");
}
// if (System.getProperty("file.separator").equals("/")) {
// baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
// }
// else {
// baseDir = bot.textWithLabel("Location:").getText().replaceAll("\\", "\\\\") + System.getProperty("file.separator");
// }
bot.button("OK").click();
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotEditor editor = projectExplorer.openFile(projectName, "esbcontent","META-INF","jboss-esb.xml");
SWTBot theEditor = editor.bot();
theEditor.tree(0).expandNode("jboss-esb.xml", true);
SWTBotTreeItem jbossesbxml = theEditor.tree(0).getTreeItem("jboss-esb.xml");
SWTBotTreeItem providers = jbossesbxml.getNode("Providers");
SWTBotTreeItem FSProvider1 = providers.getNode("FSprovider1");
SWTBotTreeItem helloFileChannel = FSProvider1.getNode("helloFileChannel");
SWTBotTreeItem filter = helloFileChannel.getNode("Filter");
filter.select();
theEditor.text("@INPUTDIR@").setText(baseDir + inputDir);
theEditor.text("@OUTPUTDIR@").setText(baseDir + outputDir);
theEditor.text("@ERRORDIR@").setText(baseDir + errorDir);
editor.save();
bot.sleep(Timing.time30S());
//bot.sleep(30000l);
/* Deploy the quickstart */
super.executeExample();
/* Now, edit the client code */
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theClientProject = bot.tree(0).getTreeItem(clientProjectName).select();
theClientProject.expand();
//bot.sleep(30000l);
editor = projectExplorer.openFile(clientProjectName, "src","org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java");
theEditor = editor.bot();
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
theEditor.styledText().insertText(10, 0, "//");
theEditor.styledText().insertText(11, 0, "\t\tString inputDirectory = \"" + baseDir + "\" + System.getProperty(\"file.separator\") + \"inputDir\";\n");
theEditor.styledText().insertText(12, 0, "//");
theEditor.styledText().insertText(13, 0, "\t\tString fileName = \"MyInput.dat" + "\";\n");
theEditor.styledText().insertText(14, 0, "//");
theEditor.styledText().insertText(15, 0, "\t\tString fileContents = \"Hello World In A File\";\n");
theEditor.styledText().insertText(16, 0, "//");
theEditor.styledText().insertText(17, 0, "\t\tFile x = new File(inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
theEditor.styledText().insertText(23, 0, "//");
theEditor.styledText().insertText(24, 0, "\t\tSystem.out.println(\"Error while writing the file: \" + inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
//bot.sleep(30000l);
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
editor.save();
//bot.sleep(30000l);
String text = executeClientGetServerOutput(getExampleClientProjectName(),"src",
"org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test",
"CreateTestFile.java");
assertFalse ("Test fails due to ESB deployment error: NNNN", text.contains("ERROR [org.apache.juddi.v3.client.transport.wrapper.RequestHandler]"));
assertNotNull("Calling JMS Send message failed, nothing appened to server log",text);
assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Body: Hello World"));
SWTTestExt.servers.removeAllProjectsFromServer();
}
}
| true | true | protected void executeExample() {
/* Create the data directories needed by the quickstart */
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(inputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(outputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(errorDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
/* We need to get the project base dir for the directory definitions in jboss-esb.xml */
SWTBotView theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theProject = bot.tree(0).getTreeItem(projectName).select();
bot.menu("File").menu("Properties").click();
if (System.getProperty("file.separator").equals("/")) {
baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
}
else {
/* Needed to avoid a syntax error with Windows \ dir path characters */
//baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), System.getProperty("file.separator") + System.getProperty("file.separator")) + System.getProperty("file.separator");
baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), "zzz");
}
// if (System.getProperty("file.separator").equals("/")) {
// baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
// }
// else {
// baseDir = bot.textWithLabel("Location:").getText().replaceAll("\\", "\\\\") + System.getProperty("file.separator");
// }
bot.button("OK").click();
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotEditor editor = projectExplorer.openFile(projectName, "esbcontent","META-INF","jboss-esb.xml");
SWTBot theEditor = editor.bot();
theEditor.tree(0).expandNode("jboss-esb.xml", true);
SWTBotTreeItem jbossesbxml = theEditor.tree(0).getTreeItem("jboss-esb.xml");
SWTBotTreeItem providers = jbossesbxml.getNode("Providers");
SWTBotTreeItem FSProvider1 = providers.getNode("FSprovider1");
SWTBotTreeItem helloFileChannel = FSProvider1.getNode("helloFileChannel");
SWTBotTreeItem filter = helloFileChannel.getNode("Filter");
filter.select();
theEditor.text("@INPUTDIR@").setText(baseDir + inputDir);
theEditor.text("@OUTPUTDIR@").setText(baseDir + outputDir);
theEditor.text("@ERRORDIR@").setText(baseDir + errorDir);
editor.save();
bot.sleep(Timing.time30S());
//bot.sleep(30000l);
/* Deploy the quickstart */
super.executeExample();
/* Now, edit the client code */
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theClientProject = bot.tree(0).getTreeItem(clientProjectName).select();
theClientProject.expand();
//bot.sleep(30000l);
editor = projectExplorer.openFile(clientProjectName, "src","org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java");
theEditor = editor.bot();
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
theEditor.styledText().insertText(10, 0, "//");
theEditor.styledText().insertText(11, 0, "\t\tString inputDirectory = \"" + baseDir + "\" + System.getProperty(\"file.separator\") + \"inputDir\";\n");
theEditor.styledText().insertText(12, 0, "//");
theEditor.styledText().insertText(13, 0, "\t\tString fileName = \"MyInput.dat" + "\";\n");
theEditor.styledText().insertText(14, 0, "//");
theEditor.styledText().insertText(15, 0, "\t\tString fileContents = \"Hello World In A File\";\n");
theEditor.styledText().insertText(16, 0, "//");
theEditor.styledText().insertText(17, 0, "\t\tFile x = new File(inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
theEditor.styledText().insertText(23, 0, "//");
theEditor.styledText().insertText(24, 0, "\t\tSystem.out.println(\"Error while writing the file: \" + inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
//bot.sleep(30000l);
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
editor.save();
//bot.sleep(30000l);
String text = executeClientGetServerOutput(getExampleClientProjectName(),"src",
"org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test",
"CreateTestFile.java");
assertFalse ("Test fails due to ESB deployment error: NNNN", text.contains("ERROR [org.apache.juddi.v3.client.transport.wrapper.RequestHandler]"));
assertNotNull("Calling JMS Send message failed, nothing appened to server log",text);
assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Body: Hello World"));
SWTTestExt.servers.removeAllProjectsFromServer();
}
| protected void executeExample() {
/* Create the data directories needed by the quickstart */
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(inputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(outputDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
bot.menu("File").menu("New").menu("Folder").click();
bot.tree(0).getTreeItem(projectName).select();
bot.text(1).setText(errorDir);
bot.button("&Finish").click();
bot.sleep(Timing.time3S());
/* We need to get the project base dir for the directory definitions in jboss-esb.xml */
SWTBotView theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theProject = bot.tree(0).getTreeItem(projectName).select();
bot.menu("File").menu("Properties").click();
if (System.getProperty("file.separator").equals("/")) {
baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
}
else {
/* Needed to avoid a syntax error with Windows \ dir path characters */
//baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), System.getProperty("file.separator") + System.getProperty("file.separator")) + System.getProperty("file.separator");
baseDir = bot.textWithLabel("Location:").getText();
System.out.println("DEBUG baseDir = " + bot.textWithLabel("Location:").getText()) ;
baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), "zzz");
}
// if (System.getProperty("file.separator").equals("/")) {
// baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator");
// }
// else {
// baseDir = bot.textWithLabel("Location:").getText().replaceAll("\\", "\\\\") + System.getProperty("file.separator");
// }
bot.button("OK").click();
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotEditor editor = projectExplorer.openFile(projectName, "esbcontent","META-INF","jboss-esb.xml");
SWTBot theEditor = editor.bot();
theEditor.tree(0).expandNode("jboss-esb.xml", true);
SWTBotTreeItem jbossesbxml = theEditor.tree(0).getTreeItem("jboss-esb.xml");
SWTBotTreeItem providers = jbossesbxml.getNode("Providers");
SWTBotTreeItem FSProvider1 = providers.getNode("FSprovider1");
SWTBotTreeItem helloFileChannel = FSProvider1.getNode("helloFileChannel");
SWTBotTreeItem filter = helloFileChannel.getNode("Filter");
filter.select();
theEditor.text("@INPUTDIR@").setText(baseDir + inputDir);
theEditor.text("@OUTPUTDIR@").setText(baseDir + outputDir);
theEditor.text("@ERRORDIR@").setText(baseDir + errorDir);
editor.save();
bot.sleep(Timing.time30S());
//bot.sleep(30000l);
/* Deploy the quickstart */
super.executeExample();
/* Now, edit the client code */
theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL);
SWTBotTreeItem theClientProject = bot.tree(0).getTreeItem(clientProjectName).select();
theClientProject.expand();
//bot.sleep(30000l);
editor = projectExplorer.openFile(clientProjectName, "src","org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java");
theEditor = editor.bot();
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
theEditor.styledText().insertText(10, 0, "//");
theEditor.styledText().insertText(11, 0, "\t\tString inputDirectory = \"" + baseDir + "\" + System.getProperty(\"file.separator\") + \"inputDir\";\n");
theEditor.styledText().insertText(12, 0, "//");
theEditor.styledText().insertText(13, 0, "\t\tString fileName = \"MyInput.dat" + "\";\n");
theEditor.styledText().insertText(14, 0, "//");
theEditor.styledText().insertText(15, 0, "\t\tString fileContents = \"Hello World In A File\";\n");
theEditor.styledText().insertText(16, 0, "//");
theEditor.styledText().insertText(17, 0, "\t\tFile x = new File(inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
theEditor.styledText().insertText(23, 0, "//");
theEditor.styledText().insertText(24, 0, "\t\tSystem.out.println(\"Error while writing the file: \" + inputDirectory + System.getProperty(\"file.separator\") + fileName);\n");
//bot.sleep(30000l);
//System.out.println ("DEBUG " + theEditor.styledText().getText() );
editor.save();
//bot.sleep(30000l);
String text = executeClientGetServerOutput(getExampleClientProjectName(),"src",
"org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test",
"CreateTestFile.java");
assertFalse ("Test fails due to ESB deployment error: NNNN", text.contains("ERROR [org.apache.juddi.v3.client.transport.wrapper.RequestHandler]"));
assertNotNull("Calling JMS Send message failed, nothing appened to server log",text);
assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Body: Hello World"));
SWTTestExt.servers.removeAllProjectsFromServer();
}
|
diff --git a/src/edu/mit/mobile/android/content/dbhelper/SearchDBHelper.java b/src/edu/mit/mobile/android/content/dbhelper/SearchDBHelper.java
index b554c9b..7a9137f 100644
--- a/src/edu/mit/mobile/android/content/dbhelper/SearchDBHelper.java
+++ b/src/edu/mit/mobile/android/content/dbhelper/SearchDBHelper.java
@@ -1,276 +1,280 @@
package edu.mit.mobile.android.content.dbhelper;
import java.util.ArrayList;
import java.util.LinkedList;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Build;
import edu.mit.mobile.android.content.ContentItem;
import edu.mit.mobile.android.content.DBHelper;
import edu.mit.mobile.android.content.GenericDBHelper;
import edu.mit.mobile.android.content.ProviderUtils;
import edu.mit.mobile.android.content.SQLGenerationException;
/**
* <p>
* An implementation of the {@link SearchManager} interface. This handles queries made to the search
* URI, searching one or more tables and one or more columns within that table. Results contain
* appropriate data URIs to link back to the application.
* </p>
*
* <h2>To Use</h2>
*
* <p>
* Create one or more {@link GenericDBHelper}s that you wish to search. For example, a blog post:
* </p>
*
* <code><pre>
* final GenericDBHelper blogPosts = new GenericDBHelper(BlogPost.class);
*
* </pre></code>
* <p>
* ...and comments on those posts:
* </p>
* <code><pre>
*
* final ForeignKeyDBHelper comments = new ForeignKeyDBHelper(BlogPost.class, Comment.class,
* Comment.POST);
* </pre></code>
* <p>
* Add in the search interface:
* </p>
* <code><pre>
* final SearchDBHelper searchHelper = new SearchDBHelper();
* </pre></code>
* <p>
* And register your helpers with the search helper. The columns specified below indicate which
* columns will be returned (in this case, the title and the body) in the search results and which
* columns will be searched (the body and the title).
* </p>
* <code><pre>
* searchHelper.registerDBHelper(blogPosts, BlogPost.CONTENT_URI, BlogPost.TITLE, BlogPost.BODY,
* BlogPost.BODY, BlogPost.TITLE);
*
* searchHelper.registerDBHelper(comments, Comment.ALL_COMMENTS, Comment.BODY, null, Comment.BODY);
* </pre></code>
* <p>
* Define these as constants to make them easier to use in other contexts
* </p>
* <code><pre>
* public static final String SEARCH_PATH = "search";
* public static final Uri SEARCH = ProviderUtils.toContentUri(AUTHORITY, SEARCH_PATH);
* </pre></code>
* <p>
* This hooks in the search helper at the given path. In this case, the path will be
* <code>content://vnd.android..../search</code>
* </p>
* <code><pre>
* addSearchUri(searchHelper, SEARCH_PATH);
* </pre></code>
*
* @author <a href="mailto:[email protected]">Steve Pomeroy</a>
*
*/
public class SearchDBHelper extends DBHelper {
LinkedList<RegisteredHelper> mRegisteredHelpers = new LinkedList<SearchDBHelper.RegisteredHelper>();
public SearchDBHelper() {
}
/**
* <p>
* Adds a {@link GenericDBHelper} to the list of search helpers that will be queried for this
* search. All the registered DBHelpers will be searched and results will be mixed together.
* </p>
*
* <p>
* The columns to search, provided in {@code searchColumns}, will be queried using a simple
* {@code LIKE "%query%"} substring search. The results are concatenate using {@code UNION ALL}.
* </p>
*
* @param helper
* the helper you wish to search. This must return a valid result for
* {@link GenericDBHelper#getTable()}.
* @param contentUri
* the base URI that will be used when linking back to the item from the search
* results (see {@link SearchManager#SUGGEST_COLUMN_INTENT_DATA}). This can be null
* to disable this feature.
* @param text1Column
* the text column that will be used for {@link SearchManager#SUGGEST_COLUMN_TEXT_1}.
* This is required.
* @param text2Column
* the text column that will be used for {@link SearchManager#SUGGEST_COLUMN_TEXT_2}.
* This is optional and can be null.
* @param searchColumns
* a list of the columns that will be searched for the given keyword.
*/
public void registerDBHelper(GenericDBHelper helper, Uri contentUri, String text1Column,
String text2Column, String... searchColumns) {
mRegisteredHelpers.add(new RegisteredHelper(helper, contentUri, text1Column, text2Column,
searchColumns));
}
private static class RegisteredHelper {
public final GenericDBHelper mHelper;
public final String[] mColumns;
public final String mText2Column;
public final String mText1Column;
public final Uri mContentUri;
public RegisteredHelper(GenericDBHelper helper, Uri contentUri, String text1Column,
String text2Column, String... columns) {
mHelper = helper;
mColumns = columns;
mContentUri = contentUri;
mText1Column = text1Column;
mText2Column = text2Column;
}
}
@Override
public Uri insertDir(SQLiteDatabase db, ContentProvider provider, Uri uri, ContentValues values)
throws SQLException {
throw new UnsupportedOperationException("insert not supported for this helper");
}
@Override
public int updateItem(SQLiteDatabase db, ContentProvider provider, Uri uri,
ContentValues values, String where, String[] whereArgs) {
throw new UnsupportedOperationException("update not supported for this helper");
}
@Override
public int updateDir(SQLiteDatabase db, ContentProvider provider, Uri uri,
ContentValues values, String where, String[] whereArgs) {
throw new UnsupportedOperationException("update not supported for this helper");
}
@Override
public int deleteItem(SQLiteDatabase db, ContentProvider provider, Uri uri, String where,
String[] whereArgs) {
throw new UnsupportedOperationException("delete not supported for this helper");
}
@Override
public int deleteDir(SQLiteDatabase db, ContentProvider provider, Uri uri, String where,
String[] whereArgs) {
throw new UnsupportedOperationException("delete not supported for this helper");
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressWarnings("deprecation")
@Override
public Cursor queryItem(SQLiteDatabase db, Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
final String searchQuery = uri.getLastPathSegment();
final StringBuilder multiSelect = new StringBuilder();
multiSelect.append('(');
final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
boolean addUnion = false;
for (final RegisteredHelper searchReg : mRegisteredHelpers) {
// UNION ALL concatenates the inner queries
if (addUnion) {
multiSelect.append(" UNION ALL ");
}
addUnion = true;
final StringBuilder extSel = new StringBuilder();
// build the selection that matches the search string in the given
int i = 0;
for (final String column : searchReg.mColumns) {
if (i > 0) {
extSel.append(" OR ");
}
extSel.append("\"");
extSel.append(column);
extSel.append("\" LIKE ?1");
i++;
}
final ArrayList<String> extProj = new ArrayList<String>();
final String table = searchReg.mHelper.getTable();
final String tablePrefix = '"' + table + "\".";
extProj.add(tablePrefix + ContentItem._ID + " AS " + ContentItem._ID);
extProj.add(tablePrefix + searchReg.mText1Column + " AS "
+ SearchManager.SUGGEST_COLUMN_TEXT_1);
if (searchReg.mText2Column != null) {
extProj.add(tablePrefix + searchReg.mText2Column + " AS "
+ SearchManager.SUGGEST_COLUMN_TEXT_2);
} else {
// this is needed as sqlite3 crashes otherwise.
extProj.add("'' AS " + SearchManager.SUGGEST_COLUMN_TEXT_2);
}
if (searchReg.mContentUri != null) {
extProj.add("'" + searchReg.mContentUri.toString() + "' AS "
+ SearchManager.SUGGEST_COLUMN_INTENT_DATA);
extProj.add(tablePrefix + ContentItem._ID + " AS "
+ SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
+ } else {
+ // this is needed as sqlite3 crashes otherwise.
+ extProj.add("'' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA);
+ extProj.add("'' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
}
qb.setTables(table);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
multiSelect.append(qb.buildQuery(extProj.toArray(new String[extProj.size()]),
ProviderUtils.addExtraWhere(selection, extSel.toString()), null, null,
sortOrder, null));
} else {
multiSelect.append(qb.buildQuery(extProj.toArray(new String[extProj.size()]),
ProviderUtils.addExtraWhere(selection, extSel.toString()), null, null,
null, sortOrder, null));
}
} // inner selects
multiSelect.append(')');
return db.query(multiSelect.toString(), null, selection,
ProviderUtils.addExtraWhereArgs(selectionArgs, "%" + searchQuery + "%"), null,
null, sortOrder);
}
@Override
public Cursor queryDir(SQLiteDatabase db, Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
throw new UnsupportedOperationException("query dir not supported for this helper");
}
@Override
public String getPath() {
// unused
return null;
}
@Override
public void createTables(SQLiteDatabase db) throws SQLGenerationException {
// unused
}
@Override
public void upgradeTables(SQLiteDatabase db, int oldVersion, int newVersion)
throws SQLGenerationException {
// unused
}
}
| true | true | public Cursor queryItem(SQLiteDatabase db, Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
final String searchQuery = uri.getLastPathSegment();
final StringBuilder multiSelect = new StringBuilder();
multiSelect.append('(');
final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
boolean addUnion = false;
for (final RegisteredHelper searchReg : mRegisteredHelpers) {
// UNION ALL concatenates the inner queries
if (addUnion) {
multiSelect.append(" UNION ALL ");
}
addUnion = true;
final StringBuilder extSel = new StringBuilder();
// build the selection that matches the search string in the given
int i = 0;
for (final String column : searchReg.mColumns) {
if (i > 0) {
extSel.append(" OR ");
}
extSel.append("\"");
extSel.append(column);
extSel.append("\" LIKE ?1");
i++;
}
final ArrayList<String> extProj = new ArrayList<String>();
final String table = searchReg.mHelper.getTable();
final String tablePrefix = '"' + table + "\".";
extProj.add(tablePrefix + ContentItem._ID + " AS " + ContentItem._ID);
extProj.add(tablePrefix + searchReg.mText1Column + " AS "
+ SearchManager.SUGGEST_COLUMN_TEXT_1);
if (searchReg.mText2Column != null) {
extProj.add(tablePrefix + searchReg.mText2Column + " AS "
+ SearchManager.SUGGEST_COLUMN_TEXT_2);
} else {
// this is needed as sqlite3 crashes otherwise.
extProj.add("'' AS " + SearchManager.SUGGEST_COLUMN_TEXT_2);
}
if (searchReg.mContentUri != null) {
extProj.add("'" + searchReg.mContentUri.toString() + "' AS "
+ SearchManager.SUGGEST_COLUMN_INTENT_DATA);
extProj.add(tablePrefix + ContentItem._ID + " AS "
+ SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
}
qb.setTables(table);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
multiSelect.append(qb.buildQuery(extProj.toArray(new String[extProj.size()]),
ProviderUtils.addExtraWhere(selection, extSel.toString()), null, null,
sortOrder, null));
} else {
multiSelect.append(qb.buildQuery(extProj.toArray(new String[extProj.size()]),
ProviderUtils.addExtraWhere(selection, extSel.toString()), null, null,
null, sortOrder, null));
}
} // inner selects
multiSelect.append(')');
return db.query(multiSelect.toString(), null, selection,
ProviderUtils.addExtraWhereArgs(selectionArgs, "%" + searchQuery + "%"), null,
null, sortOrder);
}
| public Cursor queryItem(SQLiteDatabase db, Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
final String searchQuery = uri.getLastPathSegment();
final StringBuilder multiSelect = new StringBuilder();
multiSelect.append('(');
final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
boolean addUnion = false;
for (final RegisteredHelper searchReg : mRegisteredHelpers) {
// UNION ALL concatenates the inner queries
if (addUnion) {
multiSelect.append(" UNION ALL ");
}
addUnion = true;
final StringBuilder extSel = new StringBuilder();
// build the selection that matches the search string in the given
int i = 0;
for (final String column : searchReg.mColumns) {
if (i > 0) {
extSel.append(" OR ");
}
extSel.append("\"");
extSel.append(column);
extSel.append("\" LIKE ?1");
i++;
}
final ArrayList<String> extProj = new ArrayList<String>();
final String table = searchReg.mHelper.getTable();
final String tablePrefix = '"' + table + "\".";
extProj.add(tablePrefix + ContentItem._ID + " AS " + ContentItem._ID);
extProj.add(tablePrefix + searchReg.mText1Column + " AS "
+ SearchManager.SUGGEST_COLUMN_TEXT_1);
if (searchReg.mText2Column != null) {
extProj.add(tablePrefix + searchReg.mText2Column + " AS "
+ SearchManager.SUGGEST_COLUMN_TEXT_2);
} else {
// this is needed as sqlite3 crashes otherwise.
extProj.add("'' AS " + SearchManager.SUGGEST_COLUMN_TEXT_2);
}
if (searchReg.mContentUri != null) {
extProj.add("'" + searchReg.mContentUri.toString() + "' AS "
+ SearchManager.SUGGEST_COLUMN_INTENT_DATA);
extProj.add(tablePrefix + ContentItem._ID + " AS "
+ SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
} else {
// this is needed as sqlite3 crashes otherwise.
extProj.add("'' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA);
extProj.add("'' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
}
qb.setTables(table);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
multiSelect.append(qb.buildQuery(extProj.toArray(new String[extProj.size()]),
ProviderUtils.addExtraWhere(selection, extSel.toString()), null, null,
sortOrder, null));
} else {
multiSelect.append(qb.buildQuery(extProj.toArray(new String[extProj.size()]),
ProviderUtils.addExtraWhere(selection, extSel.toString()), null, null,
null, sortOrder, null));
}
} // inner selects
multiSelect.append(')');
return db.query(multiSelect.toString(), null, selection,
ProviderUtils.addExtraWhereArgs(selectionArgs, "%" + searchQuery + "%"), null,
null, sortOrder);
}
|
diff --git a/clustering-impl/src/main/java/org/clueminer/evolution/WeightsIndividual.java b/clustering-impl/src/main/java/org/clueminer/evolution/WeightsIndividual.java
index d813d4e4c..26441eacd 100644
--- a/clustering-impl/src/main/java/org/clueminer/evolution/WeightsIndividual.java
+++ b/clustering-impl/src/main/java/org/clueminer/evolution/WeightsIndividual.java
@@ -1,157 +1,155 @@
package org.clueminer.evolution;
import org.clueminer.clustering.api.evolution.Individual;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.clueminer.clustering.api.Cluster;
import org.clueminer.clustering.api.Clustering;
import org.clueminer.clustering.api.evolution.Evolution;
import org.clueminer.dataset.api.Dataset;
import org.clueminer.dataset.api.Instance;
import org.clueminer.utils.AlgorithmParameters;
/**
*
* @author Tomas Barton
*/
public class WeightsIndividual extends AbstractIndividual<WeightsIndividual> implements Individual<WeightsIndividual> {
private double fitness = 0;
private static Random rand = new Random();
private double[] weights;
private AlgorithmParameters params;
private Clustering<Cluster> clustering;
public WeightsIndividual(Evolution evolution) {
this.evolution = evolution;
this.algorithm = evolution.getAlgorithm();
init();
}
/**
* Copying constructor
*
* @param parent
*/
public WeightsIndividual(WeightsIndividual parent) {
this.evolution = parent.evolution;
this.algorithm = parent.algorithm;
this.weights = new double[parent.weights.length];
System.arraycopy(parent.weights, 0, weights, 0, parent.weights.length);
this.fitness = parent.fitness;
}
private void init() {
weights = new double[evolution.attributesCount()];
for (int i = 0; i < weights.length; i++) {
weights[i] = rand.nextDouble();
}
countFitness();
}
@Override
public Clustering<Cluster> getClustering() {
return clustering;
}
@Override
public void countFitness() {
clustering = updateCustering();
fitness = evolution.getEvaluator().score(clustering, evolution.getDataset());
}
/**
* Some algorithms (like k-means) have random initialization, so we can't
* reproduce the same results, therefore we have to keep the resulting
* clustering
*
* @return clustering according to current parameters
*/
private Clustering<Cluster> updateCustering() {
Dataset<Instance> data = (Dataset<Instance>) evolution.getDataset().duplicate();
double[] values;
Instance copy;
for (Instance inst : evolution.getDataset()) {
- values = inst.arrayCopy();
+ copy = data.builder().createCopyOf(inst, data);
- for (int i = 0; i < values.length; i++) {
- values[i] = values[i] * weights[i];
+ for (int i = 0; i < inst.size(); i++) {
+ copy.put(i, inst.value(i) * weights[i]);
}
- copy = data.builder().create(values);
- copy.setClassValue(inst.classValue());
data.add(copy);
}
return algorithm.partition(data);
}
@Override
public double getFitness() {
return fitness;
}
/**
* For tests only
*
* @param fitness
*/
protected void setFitness(double fitness) {
this.fitness = fitness;
}
@Override
public void mutate() {
for (int i = 0; i < weights.length; i++) {
if (rand.nextDouble() < evolution.getMutationProbability()) {
weights[i] = rand.nextDouble();
}
}
}
@Override
public List<WeightsIndividual> cross(Individual i) {
List<WeightsIndividual> offsprings = new ArrayList<WeightsIndividual>();
// we'll work with copies
WeightsIndividual thisOne = this.deepCopy();
WeightsIndividual secondOne = ((WeightsIndividual) i).deepCopy();
int cross_id = rand.nextInt(evolution.attributesCount());
System.arraycopy(((WeightsIndividual) i).weights, 0, thisOne.weights, 0, cross_id);
System.arraycopy(((WeightsIndividual) i).weights, cross_id, secondOne.weights, cross_id, evolution.attributesCount() - cross_id);
System.arraycopy(this.weights, 0, secondOne.weights, 0, cross_id);
System.arraycopy(this.weights, cross_id, thisOne.weights, cross_id, evolution.attributesCount() - cross_id);
offsprings.add(thisOne);
offsprings.add(secondOne);
return offsprings;
}
@Override
public WeightsIndividual deepCopy() {
WeightsIndividual newOne = new WeightsIndividual(this);
return newOne;
}
@Override
public boolean isCompatible(Individual other) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public WeightsIndividual duplicate() {
WeightsIndividual duplicate = new WeightsIndividual(evolution);
return duplicate;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[ ");
for (int i = 0; i < weights.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(weights[i]);
}
sb.append("]");
return sb.toString();
}
}
| false | true | private Clustering<Cluster> updateCustering() {
Dataset<Instance> data = (Dataset<Instance>) evolution.getDataset().duplicate();
double[] values;
Instance copy;
for (Instance inst : evolution.getDataset()) {
values = inst.arrayCopy();
for (int i = 0; i < values.length; i++) {
values[i] = values[i] * weights[i];
}
copy = data.builder().create(values);
copy.setClassValue(inst.classValue());
data.add(copy);
}
return algorithm.partition(data);
}
| private Clustering<Cluster> updateCustering() {
Dataset<Instance> data = (Dataset<Instance>) evolution.getDataset().duplicate();
double[] values;
Instance copy;
for (Instance inst : evolution.getDataset()) {
copy = data.builder().createCopyOf(inst, data);
for (int i = 0; i < inst.size(); i++) {
copy.put(i, inst.value(i) * weights[i]);
}
data.add(copy);
}
return algorithm.partition(data);
}
|
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java
index 9715d9c47..d86e48c3d 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/MergeOp.java
@@ -1,1139 +1,1139 @@
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
import static com.google.gerrit.server.git.MergeUtil.getSubmitter;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.base.Objects;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Sets;
import com.google.gerrit.common.ChangeHooks;
import com.google.gerrit.common.data.Capable;
import com.google.gerrit.common.data.SubmitTypeRecord;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.ChangeMessage;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.Project.SubmitType;
import com.google.gerrit.reviewdb.client.RevId;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ChangeUtil;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.AccountCache;
import com.google.gerrit.server.config.AllProjectsName;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.mail.MergeFailSender;
import com.google.gerrit.server.mail.MergedSender;
import com.google.gerrit.server.patch.PatchSetInfoFactory;
import com.google.gerrit.server.patch.PatchSetInfoNotAvailableException;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.project.NoSuchProjectException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.util.RequestScopePropagator;
import com.google.gwtorm.server.AtomicUpdate;
import com.google.gwtorm.server.OrmConcurrencyException;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevSort;
import org.eclipse.jgit.revwalk.RevWalk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Merges changes in submission order into a single branch.
* <p>
* Branches are reduced to the minimum number of heads needed to merge
* everything. This allows commits to be entered into the queue in any order
* (such as ancestors before descendants) and only the most recent commit on any
* line of development will be merged. All unmerged commits along a line of
* development must be in the submission queue in order to merge the tip of that
* line.
* <p>
* Conflicts are handled by discarding the entire line of development and
* marking it as conflicting, even if an earlier commit along that same line can
* be merged cleanly.
*/
public class MergeOp {
public interface Factory {
MergeOp create(Branch.NameKey branch);
}
private static final Logger log = LoggerFactory.getLogger(MergeOp.class);
/** Amount of time to wait between submit and checking for missing deps. */
private static final long DEPENDENCY_DELAY =
MILLISECONDS.convert(15, MINUTES);
private static final long LOCK_FAILURE_RETRY_DELAY =
MILLISECONDS.convert(15, SECONDS);
private static final long DUPLICATE_MESSAGE_INTERVAL =
MILLISECONDS.convert(1, DAYS);
private final GitRepositoryManager repoManager;
private final SchemaFactory<ReviewDb> schemaFactory;
private final ProjectCache projectCache;
private final LabelNormalizer labelNormalizer;
private final GitReferenceUpdated gitRefUpdated;
private final MergedSender.Factory mergedSenderFactory;
private final MergeFailSender.Factory mergeFailSenderFactory;
private final PatchSetInfoFactory patchSetInfoFactory;
private final IdentifiedUser.GenericFactory identifiedUserFactory;
private final ChangeControl.GenericFactory changeControlFactory;
private final MergeQueue mergeQueue;
private final Branch.NameKey destBranch;
private ProjectState destProject;
private final ListMultimap<SubmitType, CodeReviewCommit> toMerge;
private final List<CodeReviewCommit> potentiallyStillSubmittable;
private final Map<Change.Id, CodeReviewCommit> commits;
private ReviewDb db;
private Repository repo;
private RevWalk rw;
private RevFlag canMergeFlag;
private CodeReviewCommit branchTip;
private CodeReviewCommit mergeTip;
private ObjectInserter inserter;
private PersonIdent refLogIdent;
private final ChangeHooks hooks;
private final AccountCache accountCache;
private final TagCache tagCache;
private final SubmitStrategyFactory submitStrategyFactory;
private final SubmoduleOp.Factory subOpFactory;
private final WorkQueue workQueue;
private final RequestScopePropagator requestScopePropagator;
private final AllProjectsName allProjectsName;
@Inject
MergeOp(final GitRepositoryManager grm, final SchemaFactory<ReviewDb> sf,
final ProjectCache pc, final LabelNormalizer fs,
final GitReferenceUpdated gru, final MergedSender.Factory msf,
final MergeFailSender.Factory mfsf,
final PatchSetInfoFactory psif, final IdentifiedUser.GenericFactory iuf,
final ChangeControl.GenericFactory changeControlFactory,
final MergeQueue mergeQueue, @Assisted final Branch.NameKey branch,
final ChangeHooks hooks, final AccountCache accountCache,
final TagCache tagCache,
final SubmitStrategyFactory submitStrategyFactory,
final SubmoduleOp.Factory subOpFactory,
final WorkQueue workQueue,
final RequestScopePropagator requestScopePropagator,
final AllProjectsName allProjectsName) {
repoManager = grm;
schemaFactory = sf;
labelNormalizer = fs;
projectCache = pc;
gitRefUpdated = gru;
mergedSenderFactory = msf;
mergeFailSenderFactory = mfsf;
patchSetInfoFactory = psif;
identifiedUserFactory = iuf;
this.changeControlFactory = changeControlFactory;
this.mergeQueue = mergeQueue;
this.hooks = hooks;
this.accountCache = accountCache;
this.tagCache = tagCache;
this.submitStrategyFactory = submitStrategyFactory;
this.subOpFactory = subOpFactory;
this.workQueue = workQueue;
this.requestScopePropagator = requestScopePropagator;
this.allProjectsName = allProjectsName;
destBranch = branch;
toMerge = ArrayListMultimap.create();
potentiallyStillSubmittable = new ArrayList<CodeReviewCommit>();
commits = new HashMap<Change.Id, CodeReviewCommit>();
}
public void verifyMergeability(Change change) throws NoSuchProjectException {
try {
setDestProject();
openRepository();
final Ref destBranchRef = repo.getRef(destBranch.get());
// Test mergeability of the change if the last merged sha1
// in the branch is different from the last sha1
// the change was tested against.
if ((destBranchRef == null && change.getLastSha1MergeTested() == null)
|| change.getLastSha1MergeTested() == null
|| (destBranchRef != null && !destBranchRef.getObjectId().getName()
.equals(change.getLastSha1MergeTested().get()))) {
openSchema();
openBranch();
validateChangeList(Collections.singletonList(change));
if (!toMerge.isEmpty()) {
final Entry<SubmitType, CodeReviewCommit> e =
toMerge.entries().iterator().next();
final boolean isMergeable =
createStrategy(e.getKey()).dryRun(branchTip, e.getValue());
// update sha1 tested merge.
if (destBranchRef != null) {
change.setLastSha1MergeTested(new RevId(destBranchRef
.getObjectId().getName()));
} else {
change.setLastSha1MergeTested(new RevId(""));
}
change.setMergeable(isMergeable);
db.changes().update(Collections.singleton(change));
} else {
log.error("Test merge attempt for change: " + change.getId()
+ " failed");
}
}
} catch (MergeException e) {
log.error("Test merge attempt for change: " + change.getId()
+ " failed", e);
} catch (OrmException e) {
log.error("Test merge attempt for change: " + change.getId()
+ " failed: Not able to query the database", e);
} catch (IOException e) {
log.error("Test merge attempt for change: " + change.getId()
+ " failed", e);
} finally {
if (repo != null) {
repo.close();
}
if (db != null) {
db.close();
}
}
}
private void setDestProject() throws MergeException {
destProject = projectCache.get(destBranch.getParentKey());
if (destProject == null) {
throw new MergeException("No such project: " + destBranch.getParentKey());
}
}
private void openSchema() throws OrmException {
if (db == null) {
db = schemaFactory.open();
}
}
public void merge() throws MergeException, NoSuchProjectException {
setDestProject();
try {
openSchema();
openRepository();
openBranch();
final ListMultimap<SubmitType, Change> toSubmit =
validateChangeList(db.changes().submitted(destBranch).toList());
final ListMultimap<SubmitType, CodeReviewCommit> toMergeNextTurn =
ArrayListMultimap.create();
final List<CodeReviewCommit> potentiallyStillSubmittableOnNextRun =
new ArrayList<CodeReviewCommit>();
while (!toMerge.isEmpty()) {
toMergeNextTurn.clear();
final Set<SubmitType> submitTypes =
new HashSet<Project.SubmitType>(toMerge.keySet());
for (final SubmitType submitType : submitTypes) {
final RefUpdate branchUpdate = openBranch();
final SubmitStrategy strategy = createStrategy(submitType);
preMerge(strategy, toMerge.get(submitType));
updateBranch(strategy, branchUpdate);
updateChangeStatus(toSubmit.get(submitType));
updateSubscriptions(toSubmit.get(submitType));
for (final Iterator<CodeReviewCommit> it =
potentiallyStillSubmittable.iterator(); it.hasNext();) {
final CodeReviewCommit commit = it.next();
if (containsMissingCommits(toMerge, commit)
|| containsMissingCommits(toMergeNextTurn, commit)) {
// change has missing dependencies, but all commits which are
// missing are still attempted to be merged with another submit
// strategy, retry to merge this commit in the next turn
it.remove();
commit.statusCode = null;
commit.missing = null;
toMergeNextTurn.put(submitType, commit);
}
}
potentiallyStillSubmittableOnNextRun.addAll(potentiallyStillSubmittable);
potentiallyStillSubmittable.clear();
}
toMerge.clear();
toMerge.putAll(toMergeNextTurn);
}
for (final CodeReviewCommit commit : potentiallyStillSubmittableOnNextRun) {
final Capable capable = isSubmitStillPossible(commit);
if (capable != Capable.OK) {
sendMergeFail(commit.change,
message(commit.change, capable.getMessage()), false);
}
}
} catch (OrmException e) {
throw new MergeException("Cannot query the database", e);
} finally {
if (inserter != null) {
inserter.release();
}
if (rw != null) {
rw.release();
}
if (repo != null) {
repo.close();
}
if (db != null) {
db.close();
}
}
}
private boolean containsMissingCommits(
final ListMultimap<SubmitType, CodeReviewCommit> map,
final CodeReviewCommit commit) {
if (!isSubmitForMissingCommitsStillPossible(commit)) {
return false;
}
for (final CodeReviewCommit missingCommit : commit.missing) {
if (!map.containsValue(missingCommit)) {
return false;
}
}
return true;
}
private boolean isSubmitForMissingCommitsStillPossible(final CodeReviewCommit commit) {
if (commit.missing == null || commit.missing.isEmpty()) {
return false;
}
for (CodeReviewCommit missingCommit : commit.missing) {
loadChangeInfo(missingCommit);
if (missingCommit.patchsetId == null) {
// The commit doesn't have a patch set, so it cannot be
// submitted to the branch.
//
return false;
}
if (!missingCommit.change.currentPatchSetId().equals(
missingCommit.patchsetId)) {
// If the missing commit is not the current patch set,
// the change must be rebased to use the proper parent.
//
return false;
}
}
return true;
}
private void preMerge(final SubmitStrategy strategy,
final List<CodeReviewCommit> toMerge) throws MergeException {
mergeTip = strategy.run(branchTip, toMerge);
refLogIdent = strategy.getRefLogIdent();
commits.putAll(strategy.getNewCommits());
}
private SubmitStrategy createStrategy(final SubmitType submitType)
throws MergeException, NoSuchProjectException {
return submitStrategyFactory.create(submitType, db, repo, rw, inserter,
canMergeFlag, getAlreadyAccepted(branchTip), destBranch);
}
private void openRepository() throws MergeException {
final Project.NameKey name = destBranch.getParentKey();
try {
repo = repoManager.openRepository(name);
} catch (RepositoryNotFoundException notGit) {
final String m = "Repository \"" + name.get() + "\" unknown.";
throw new MergeException(m, notGit);
} catch (IOException err) {
final String m = "Error opening repository \"" + name.get() + '"';
throw new MergeException(m, err);
}
rw = new RevWalk(repo) {
@Override
protected RevCommit createCommit(final AnyObjectId id) {
return new CodeReviewCommit(id);
}
};
rw.sort(RevSort.TOPO);
rw.sort(RevSort.COMMIT_TIME_DESC, true);
canMergeFlag = rw.newFlag("CAN_MERGE");
inserter = repo.newObjectInserter();
}
private RefUpdate openBranch() throws MergeException, OrmException {
try {
final RefUpdate branchUpdate = repo.updateRef(destBranch.get());
if (branchUpdate.getOldObjectId() != null) {
branchTip =
(CodeReviewCommit) rw.parseCommit(branchUpdate.getOldObjectId());
} else {
branchTip = null;
}
try {
final Ref destRef = repo.getRef(destBranch.get());
if (destRef != null) {
branchUpdate.setExpectedOldObjectId(destRef.getObjectId());
} else if (repo.getFullBranch().equals(destBranch.get())) {
branchUpdate.setExpectedOldObjectId(ObjectId.zeroId());
} else {
for (final Change c : db.changes().submitted(destBranch).toList()) {
setNew(c, message(c, "Your change could not be merged, "
+ "because the destination branch does not exist anymore."));
}
}
} catch (IOException e) {
throw new MergeException(
"Failed to check existence of destination branch", e);
}
return branchUpdate;
} catch (IOException e) {
throw new MergeException("Cannot open branch", e);
}
}
private Set<RevCommit> getAlreadyAccepted(final CodeReviewCommit branchTip)
throws MergeException {
final Set<RevCommit> alreadyAccepted = new HashSet<RevCommit>();
if (branchTip != null) {
alreadyAccepted.add(branchTip);
}
try {
for (final Ref r : repo.getAllRefs().values()) {
if (r.getName().startsWith(Constants.R_HEADS)
|| r.getName().startsWith(Constants.R_TAGS)) {
try {
alreadyAccepted.add(rw.parseCommit(r.getObjectId()));
} catch (IncorrectObjectTypeException iote) {
// Not a commit? Skip over it.
}
}
}
} catch (IOException e) {
throw new MergeException("Failed to determine already accepted commits.", e);
}
return alreadyAccepted;
}
private ListMultimap<SubmitType, Change> validateChangeList(
final List<Change> submitted) throws MergeException {
final ListMultimap<SubmitType, Change> toSubmit =
ArrayListMultimap.create();
final Set<ObjectId> tips = new HashSet<ObjectId>();
for (final Ref r : repo.getAllRefs().values()) {
tips.add(r.getObjectId());
}
int commitOrder = 0;
for (final Change chg : submitted) {
final Change.Id changeId = chg.getId();
if (chg.currentPatchSetId() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final PatchSet ps;
try {
ps = db.patchSets().get(chg.currentPatchSetId());
} catch (OrmException e) {
throw new MergeException("Cannot query the database", e);
}
if (ps == null || ps.getRevision() == null
|| ps.getRevision().get() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final String idstr = ps.getRevision().get();
final ObjectId id;
try {
id = ObjectId.fromString(idstr);
} catch (IllegalArgumentException iae) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
if (!tips.contains(id)) {
// TODO Technically the proper way to do this test is to use a
// RevWalk on "$id --not --all" and test for an empty set. But
// that is way slower than looking for a ref directly pointing
// at the desired tip. We should always have a ref available.
//
// TODO this is actually an error, the branch is gone but we
// want to merge the issue. We can't safely do that if the
// tip is not reachable.
//
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
final CodeReviewCommit commit;
try {
commit = (CodeReviewCommit) rw.parseCommit(id);
} catch (IOException e) {
log.error("Invalid commit " + id.name() + " on " + chg.getKey(), e);
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
if (GitRepositoryManager.REF_CONFIG.equals(destBranch.get())) {
final Project.NameKey newParent;
try {
ProjectConfig cfg =
new ProjectConfig(destProject.getProject().getNameKey());
cfg.load(repo, commit);
newParent = cfg.getProject().getParent(allProjectsName);
} catch (Exception e) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION));
continue;
}
final Project.NameKey oldParent =
destProject.getProject().getParent(allProjectsName);
if (oldParent == null) {
// update of the 'All-Projects' project
if (newParent != null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_ROOT_PROJECT_CANNOT_HAVE_PARENT));
continue;
}
} else {
if (!oldParent.equals(newParent)) {
final PatchSetApproval psa = getSubmitter(db, ps.getId());
if (psa == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
final IdentifiedUser submitter =
identifiedUserFactory.create(psa.getAccountId());
if (!submitter.getCapabilities().canAdministrateServer()) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
if (projectCache.get(newParent) == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_PARENT_PROJECT_NOT_FOUND));
continue;
}
}
}
}
commit.change = chg;
commit.patchsetId = ps.getId();
commit.originalOrder = commitOrder++;
commits.put(changeId, commit);
if (branchTip != null) {
// If this commit is already merged its a bug in the queuing code
// that we got back here. Just mark it complete and move on. It's
// merged and that is all that mattered to the requestor.
//
try {
if (rw.isMergedInto(commit, branchTip)) {
commit.statusCode = CommitMergeStatus.ALREADY_MERGED;
try {
- setMergedPatchSet(chg.getId(), ps.getId());
+ setMerged(chg, null);
} catch (OrmException e) {
log.error("Cannot mark change " + chg.getId() + " merged", e);
}
continue;
}
} catch (IOException err) {
throw new MergeException("Cannot perform merge base test", err);
}
}
final SubmitType submitType = getSubmitType(chg, ps);
if (submitType == null) {
commits.put(changeId,
CodeReviewCommit.error(CommitMergeStatus.NO_SUBMIT_TYPE));
continue;
}
commit.add(canMergeFlag);
toMerge.put(submitType, commit);
toSubmit.put(submitType, chg);
}
return toSubmit;
}
private SubmitType getSubmitType(final Change change, final PatchSet ps) {
try {
final SubmitTypeRecord r =
changeControlFactory.controlFor(change,
identifiedUserFactory.create(change.getOwner()))
.getSubmitTypeRecord(db, ps);
if (r.status != SubmitTypeRecord.Status.OK) {
log.error("Failed to get submit type for " + change.getKey());
return null;
}
return r.type;
} catch (NoSuchChangeException e) {
log.error("Failed to get submit type for " + change.getKey(), e);
return null;
}
}
private void updateBranch(final SubmitStrategy strategy,
final RefUpdate branchUpdate) throws MergeException {
if ((branchTip == null && mergeTip == null) || branchTip == mergeTip) {
// nothing to do
return;
}
if (mergeTip != null && (branchTip == null || branchTip != mergeTip)) {
if (GitRepositoryManager.REF_CONFIG.equals(branchUpdate.getName())) {
try {
ProjectConfig cfg =
new ProjectConfig(destProject.getProject().getNameKey());
cfg.load(repo, mergeTip);
} catch (Exception e) {
throw new MergeException("Submit would store invalid"
+ " project configuration " + mergeTip.name() + " for "
+ destProject.getProject().getName(), e);
}
}
branchUpdate.setRefLogIdent(refLogIdent);
branchUpdate.setForceUpdate(false);
branchUpdate.setNewObjectId(mergeTip);
branchUpdate.setRefLogMessage("merged", true);
try {
switch (branchUpdate.update(rw)) {
case NEW:
case FAST_FORWARD:
if (branchUpdate.getResult() == RefUpdate.Result.FAST_FORWARD) {
tagCache.updateFastForward(destBranch.getParentKey(),
branchUpdate.getName(),
branchUpdate.getOldObjectId(),
mergeTip);
}
if (GitRepositoryManager.REF_CONFIG.equals(branchUpdate.getName())) {
projectCache.evict(destProject.getProject());
destProject = projectCache.get(destProject.getProject().getNameKey());
repoManager.setProjectDescription(
destProject.getProject().getNameKey(),
destProject.getProject().getDescription());
}
gitRefUpdated.fire(destBranch.getParentKey(), branchUpdate);
Account account = null;
final PatchSetApproval submitter = getSubmitter(db, mergeTip.patchsetId);
if (submitter != null) {
account = accountCache.get(submitter.getAccountId()).getAccount();
}
hooks.doRefUpdatedHook(destBranch, branchUpdate, account);
break;
case LOCK_FAILURE:
String msg;
if (strategy.retryOnLockFailure()) {
mergeQueue.recheckAfter(destBranch, LOCK_FAILURE_RETRY_DELAY,
MILLISECONDS);
msg = "will retry";
} else {
msg = "will not retry";
}
throw new IOException(branchUpdate.getResult().name() + ", " + msg);
default:
throw new IOException(branchUpdate.getResult().name());
}
} catch (IOException e) {
throw new MergeException("Cannot update " + branchUpdate.getName(), e);
}
}
}
private void updateChangeStatus(final List<Change> submitted) {
for (final Change c : submitted) {
final CodeReviewCommit commit = commits.get(c.getId());
final CommitMergeStatus s = commit != null ? commit.statusCode : null;
if (s == null) {
// Shouldn't ever happen, but leave the change alone. We'll pick
// it up on the next pass.
//
continue;
}
final String txt = s.getMessage();
try {
switch (s) {
case CLEAN_MERGE:
setMerged(c, message(c, txt));
break;
case CLEAN_REBASE:
case CLEAN_PICK:
setMerged(c, message(c, txt + " as " + commit.name()));
break;
case ALREADY_MERGED:
setMerged(c, null);
break;
case PATH_CONFLICT:
case MANUAL_RECURSIVE_MERGE:
case CANNOT_CHERRY_PICK_ROOT:
case NOT_FAST_FORWARD:
case INVALID_PROJECT_CONFIGURATION:
case INVALID_PROJECT_CONFIGURATION_PARENT_PROJECT_NOT_FOUND:
case INVALID_PROJECT_CONFIGURATION_ROOT_PROJECT_CANNOT_HAVE_PARENT:
case SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN:
setNew(c, message(c, txt));
break;
case MISSING_DEPENDENCY:
potentiallyStillSubmittable.add(commit);
break;
default:
setNew(c, message(c, "Unspecified merge failure: " + s.name()));
break;
}
} catch (OrmException err) {
log.warn("Error updating change status for " + c.getId(), err);
}
}
}
private void updateSubscriptions(final List<Change> submitted) {
if (mergeTip != null && (branchTip == null || branchTip != mergeTip)) {
SubmoduleOp subOp =
subOpFactory.create(destBranch, mergeTip, rw, repo,
destProject.getProject(), submitted, commits);
try {
subOp.update();
} catch (SubmoduleException e) {
log
.error("The gitLinks were not updated according to the subscriptions "
+ e.getMessage());
}
}
}
private Capable isSubmitStillPossible(final CodeReviewCommit commit) {
final Capable capable;
final Change c = commit.change;
final boolean submitStillPossible = isSubmitForMissingCommitsStillPossible(commit);
final long now = System.currentTimeMillis();
final long waitUntil = c.getLastUpdatedOn().getTime() + DEPENDENCY_DELAY;
if (submitStillPossible && now < waitUntil) {
// If we waited a short while we might still be able to get
// this change submitted. Reschedule an attempt in a bit.
//
mergeQueue.recheckAfter(destBranch, waitUntil - now, MILLISECONDS);
capable = Capable.OK;
} else if (submitStillPossible) {
// It would be possible to submit the change if the missing
// dependencies are also submitted. Perhaps the user just
// forgot to submit those.
//
StringBuilder m = new StringBuilder();
m.append("Change could not be merged because of a missing dependency.");
m.append("\n");
m.append("\n");
m.append("The following changes must also be submitted:\n");
m.append("\n");
for (CodeReviewCommit missingCommit : commit.missing) {
m.append("* ");
m.append(missingCommit.change.getKey().get());
m.append("\n");
}
capable = new Capable(m.toString());
} else {
// It is impossible to submit this change as-is. The author
// needs to rebase it in order to work around the missing
// dependencies.
//
StringBuilder m = new StringBuilder();
m.append("Change cannot be merged due"
+ " to unsatisfiable dependencies.\n");
m.append("\n");
m.append("The following dependency errors were found:\n");
m.append("\n");
for (CodeReviewCommit missingCommit : commit.missing) {
if (missingCommit.patchsetId != null) {
m.append("* Depends on patch set ");
m.append(missingCommit.patchsetId.get());
m.append(" of ");
m.append(missingCommit.change.getKey().abbreviate());
if (missingCommit.patchsetId.get() != missingCommit.change.currentPatchSetId().get()) {
m.append(", however the current patch set is ");
m.append(missingCommit.change.currentPatchSetId().get());
}
m.append(".\n");
} else {
m.append("* Depends on commit ");
m.append(missingCommit.name());
m.append(" which has no change associated with it.\n");
}
}
m.append("\n");
m.append("Please rebase the change and upload a replacement commit.");
capable = new Capable(m.toString());
}
return capable;
}
private void loadChangeInfo(final CodeReviewCommit commit) {
if (commit.patchsetId == null) {
try {
List<PatchSet> matches =
db.patchSets().byRevision(new RevId(commit.name())).toList();
if (matches.size() == 1) {
final PatchSet ps = matches.get(0);
commit.patchsetId = ps.getId();
commit.change = db.changes().get(ps.getId().getParentKey());
}
} catch (OrmException e) {
}
}
}
private ChangeMessage message(final Change c, final String body) {
final String uuid;
try {
uuid = ChangeUtil.messageUUID(db);
} catch (OrmException e) {
return null;
}
final ChangeMessage m =
new ChangeMessage(new ChangeMessage.Key(c.getId(), uuid), null,
c.currentPatchSetId());
m.setMessage(body);
return m;
}
private void setMerged(final Change c, final ChangeMessage msg)
throws OrmException {
try {
db.changes().beginTransaction(c.getId());
// We must pull the patchset out of commits, because the patchset ID is
// modified when using the cherry-pick merge strategy.
CodeReviewCommit commit = commits.get(c.getId());
PatchSet.Id merged = commit.change.currentPatchSetId();
setMergedPatchSet(c.getId(), merged);
PatchSetApproval submitter = saveApprovals(c, merged);
addMergedMessage(submitter, msg);
db.commit();
sendMergedEmail(c, submitter);
if (submitter != null) {
try {
hooks.doChangeMergedHook(c,
accountCache.get(submitter.getAccountId()).getAccount(),
db.patchSets().get(c.currentPatchSetId()), db);
} catch (OrmException ex) {
log.error("Cannot run hook for submitted patch set " + c.getId(), ex);
}
}
} finally {
db.rollback();
}
}
private void setMergedPatchSet(Change.Id changeId, final PatchSet.Id merged)
throws OrmException {
db.changes().atomicUpdate(changeId, new AtomicUpdate<Change>() {
@Override
public Change update(Change c) {
c.setStatus(Change.Status.MERGED);
// It could be possible that the change being merged
// has never had its mergeability tested. So we insure
// merged changes has mergeable field true.
c.setMergeable(true);
if (!merged.equals(c.currentPatchSetId())) {
// Uncool; the patch set changed after we merged it.
// Go back to the patch set that was actually merged.
//
try {
c.setCurrentPatchSet(patchSetInfoFactory.get(db, merged));
} catch (PatchSetInfoNotAvailableException e1) {
log.error("Cannot read merged patch set " + merged, e1);
}
}
ChangeUtil.updated(c);
return c;
}
});
}
private PatchSetApproval saveApprovals(Change c, PatchSet.Id merged)
throws OrmException {
// Flatten out existing approvals for this patch set based upon the current
// permissions. Once the change is closed the approvals are not updated at
// presentation view time, except for zero votes used to indicate a reviewer
// was added. So we need to make sure votes are accurate now. This way if
// permissions get modified in the future, historical records stay accurate.
PatchSetApproval submitter = null;
try {
c.setStatus(Change.Status.MERGED);
List<PatchSetApproval> approvals =
db.patchSetApprovals().byPatchSet(merged).toList();
Set<PatchSetApproval.Key> toDelete =
Sets.newHashSetWithExpectedSize(approvals.size());
for (PatchSetApproval a : approvals) {
if (a.getValue() != 0) {
toDelete.add(a.getKey());
}
}
approvals = labelNormalizer.normalize(c, approvals);
for (PatchSetApproval a : approvals) {
toDelete.remove(a.getKey());
if (a.getValue() > 0 && a.isSubmit()) {
if (submitter == null
|| a.getGranted().compareTo(submitter.getGranted()) > 0) {
submitter = a;
}
}
a.cache(c);
}
db.patchSetApprovals().update(approvals);
db.patchSetApprovals().deleteKeys(toDelete);
} catch (NoSuchChangeException err) {
throw new OrmException(err);
}
return submitter;
}
private void addMergedMessage(PatchSetApproval submitter, ChangeMessage msg)
throws OrmException {
if (msg != null) {
if (submitter != null && msg.getAuthor() == null) {
msg.setAuthor(submitter.getAccountId());
}
db.changeMessages().insert(Collections.singleton(msg));
}
}
private void sendMergedEmail(final Change c, final PatchSetApproval from) {
workQueue.getDefaultQueue()
.submit(requestScopePropagator.wrap(new Runnable() {
@Override
public void run() {
PatchSet patchSet;
try {
ReviewDb reviewDb = schemaFactory.open();
try {
patchSet = reviewDb.patchSets().get(c.currentPatchSetId());
} finally {
reviewDb.close();
}
} catch (Exception e) {
log.error("Cannot send email for submitted patch set " + c.getId(), e);
return;
}
try {
final ChangeControl control = changeControlFactory.controlFor(c,
identifiedUserFactory.create(c.getOwner()));
final MergedSender cm = mergedSenderFactory.create(control);
if (from != null) {
cm.setFrom(from.getAccountId());
}
cm.setPatchSet(patchSet);
cm.send();
} catch (Exception e) {
log.error("Cannot send email for submitted patch set " + c.getId(), e);
}
}
@Override
public String toString() {
return "send-email merged";
}
}));
}
private void setNew(Change c, ChangeMessage msg) {
sendMergeFail(c, msg, true);
}
private boolean isDuplicate(ChangeMessage msg) {
try {
ChangeMessage last = Iterables.getLast(db.changeMessages().byChange(
msg.getPatchSetId().getParentKey()), null);
if (last != null) {
long lastMs = last.getWrittenOn().getTime();
long msgMs = msg.getWrittenOn().getTime();
if (Objects.equal(last.getAuthor(), msg.getAuthor())
&& Objects.equal(last.getMessage(), msg.getMessage())
&& msgMs - lastMs < DUPLICATE_MESSAGE_INTERVAL) {
return true;
}
}
} catch (OrmException err) {
log.warn("Cannot check previous merge failure message", err);
}
return false;
}
private void sendMergeFail(final Change c, final ChangeMessage msg,
final boolean makeNew) {
if (isDuplicate(msg)) {
return;
}
try {
db.changeMessages().insert(Collections.singleton(msg));
} catch (OrmException err) {
log.warn("Cannot record merge failure message", err);
}
if (makeNew) {
try {
db.changes().atomicUpdate(c.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change c) {
if (c.getStatus().isOpen()) {
c.setStatus(Change.Status.NEW);
ChangeUtil.updated(c);
}
return c;
}
});
} catch (OrmConcurrencyException err) {
} catch (OrmException err) {
log.warn("Cannot update change status", err);
}
} else {
try {
ChangeUtil.touch(c, db);
} catch (OrmException err) {
log.warn("Cannot update change timestamp", err);
}
}
PatchSetApproval submitter = null;
try {
submitter = getSubmitter(db, c.currentPatchSetId());
} catch (Exception e) {
log.error("Cannot get submitter", e);
}
final PatchSetApproval from = submitter;
workQueue.getDefaultQueue()
.submit(requestScopePropagator.wrap(new Runnable() {
@Override
public void run() {
PatchSet patchSet;
try {
ReviewDb reviewDb = schemaFactory.open();
try {
patchSet = reviewDb.patchSets().get(c.currentPatchSetId());
} finally {
reviewDb.close();
}
} catch (Exception e) {
log.error("Cannot send email notifications about merge failure", e);
return;
}
try {
final MergeFailSender cm = mergeFailSenderFactory.create(c);
if (from != null) {
cm.setFrom(from.getAccountId());
}
cm.setPatchSet(patchSet);
cm.setChangeMessage(msg);
cm.send();
} catch (Exception e) {
log.error("Cannot send email notifications about merge failure", e);
}
}
@Override
public String toString() {
return "send-email merge-failed";
}
}));
if (submitter != null) {
try {
hooks.doMergeFailedHook(c,
accountCache.get(submitter.getAccountId()).getAccount(),
db.patchSets().get(c.currentPatchSetId()), msg.getMessage(), db);
} catch (OrmException ex) {
log.error("Cannot run hook for merge failed " + c.getId(), ex);
}
}
}
}
| true | true | private ListMultimap<SubmitType, Change> validateChangeList(
final List<Change> submitted) throws MergeException {
final ListMultimap<SubmitType, Change> toSubmit =
ArrayListMultimap.create();
final Set<ObjectId> tips = new HashSet<ObjectId>();
for (final Ref r : repo.getAllRefs().values()) {
tips.add(r.getObjectId());
}
int commitOrder = 0;
for (final Change chg : submitted) {
final Change.Id changeId = chg.getId();
if (chg.currentPatchSetId() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final PatchSet ps;
try {
ps = db.patchSets().get(chg.currentPatchSetId());
} catch (OrmException e) {
throw new MergeException("Cannot query the database", e);
}
if (ps == null || ps.getRevision() == null
|| ps.getRevision().get() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final String idstr = ps.getRevision().get();
final ObjectId id;
try {
id = ObjectId.fromString(idstr);
} catch (IllegalArgumentException iae) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
if (!tips.contains(id)) {
// TODO Technically the proper way to do this test is to use a
// RevWalk on "$id --not --all" and test for an empty set. But
// that is way slower than looking for a ref directly pointing
// at the desired tip. We should always have a ref available.
//
// TODO this is actually an error, the branch is gone but we
// want to merge the issue. We can't safely do that if the
// tip is not reachable.
//
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
final CodeReviewCommit commit;
try {
commit = (CodeReviewCommit) rw.parseCommit(id);
} catch (IOException e) {
log.error("Invalid commit " + id.name() + " on " + chg.getKey(), e);
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
if (GitRepositoryManager.REF_CONFIG.equals(destBranch.get())) {
final Project.NameKey newParent;
try {
ProjectConfig cfg =
new ProjectConfig(destProject.getProject().getNameKey());
cfg.load(repo, commit);
newParent = cfg.getProject().getParent(allProjectsName);
} catch (Exception e) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION));
continue;
}
final Project.NameKey oldParent =
destProject.getProject().getParent(allProjectsName);
if (oldParent == null) {
// update of the 'All-Projects' project
if (newParent != null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_ROOT_PROJECT_CANNOT_HAVE_PARENT));
continue;
}
} else {
if (!oldParent.equals(newParent)) {
final PatchSetApproval psa = getSubmitter(db, ps.getId());
if (psa == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
final IdentifiedUser submitter =
identifiedUserFactory.create(psa.getAccountId());
if (!submitter.getCapabilities().canAdministrateServer()) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
if (projectCache.get(newParent) == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_PARENT_PROJECT_NOT_FOUND));
continue;
}
}
}
}
commit.change = chg;
commit.patchsetId = ps.getId();
commit.originalOrder = commitOrder++;
commits.put(changeId, commit);
if (branchTip != null) {
// If this commit is already merged its a bug in the queuing code
// that we got back here. Just mark it complete and move on. It's
// merged and that is all that mattered to the requestor.
//
try {
if (rw.isMergedInto(commit, branchTip)) {
commit.statusCode = CommitMergeStatus.ALREADY_MERGED;
try {
setMergedPatchSet(chg.getId(), ps.getId());
} catch (OrmException e) {
log.error("Cannot mark change " + chg.getId() + " merged", e);
}
continue;
}
} catch (IOException err) {
throw new MergeException("Cannot perform merge base test", err);
}
}
final SubmitType submitType = getSubmitType(chg, ps);
if (submitType == null) {
commits.put(changeId,
CodeReviewCommit.error(CommitMergeStatus.NO_SUBMIT_TYPE));
continue;
}
commit.add(canMergeFlag);
toMerge.put(submitType, commit);
toSubmit.put(submitType, chg);
}
return toSubmit;
}
| private ListMultimap<SubmitType, Change> validateChangeList(
final List<Change> submitted) throws MergeException {
final ListMultimap<SubmitType, Change> toSubmit =
ArrayListMultimap.create();
final Set<ObjectId> tips = new HashSet<ObjectId>();
for (final Ref r : repo.getAllRefs().values()) {
tips.add(r.getObjectId());
}
int commitOrder = 0;
for (final Change chg : submitted) {
final Change.Id changeId = chg.getId();
if (chg.currentPatchSetId() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final PatchSet ps;
try {
ps = db.patchSets().get(chg.currentPatchSetId());
} catch (OrmException e) {
throw new MergeException("Cannot query the database", e);
}
if (ps == null || ps.getRevision() == null
|| ps.getRevision().get() == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
final String idstr = ps.getRevision().get();
final ObjectId id;
try {
id = ObjectId.fromString(idstr);
} catch (IllegalArgumentException iae) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.NO_PATCH_SET));
continue;
}
if (!tips.contains(id)) {
// TODO Technically the proper way to do this test is to use a
// RevWalk on "$id --not --all" and test for an empty set. But
// that is way slower than looking for a ref directly pointing
// at the desired tip. We should always have a ref available.
//
// TODO this is actually an error, the branch is gone but we
// want to merge the issue. We can't safely do that if the
// tip is not reachable.
//
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
final CodeReviewCommit commit;
try {
commit = (CodeReviewCommit) rw.parseCommit(id);
} catch (IOException e) {
log.error("Invalid commit " + id.name() + " on " + chg.getKey(), e);
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.REVISION_GONE));
continue;
}
if (GitRepositoryManager.REF_CONFIG.equals(destBranch.get())) {
final Project.NameKey newParent;
try {
ProjectConfig cfg =
new ProjectConfig(destProject.getProject().getNameKey());
cfg.load(repo, commit);
newParent = cfg.getProject().getParent(allProjectsName);
} catch (Exception e) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION));
continue;
}
final Project.NameKey oldParent =
destProject.getProject().getParent(allProjectsName);
if (oldParent == null) {
// update of the 'All-Projects' project
if (newParent != null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_ROOT_PROJECT_CANNOT_HAVE_PARENT));
continue;
}
} else {
if (!oldParent.equals(newParent)) {
final PatchSetApproval psa = getSubmitter(db, ps.getId());
if (psa == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
final IdentifiedUser submitter =
identifiedUserFactory.create(psa.getAccountId());
if (!submitter.getCapabilities().canAdministrateServer()) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN));
continue;
}
if (projectCache.get(newParent) == null) {
commits.put(changeId, CodeReviewCommit
.error(CommitMergeStatus.INVALID_PROJECT_CONFIGURATION_PARENT_PROJECT_NOT_FOUND));
continue;
}
}
}
}
commit.change = chg;
commit.patchsetId = ps.getId();
commit.originalOrder = commitOrder++;
commits.put(changeId, commit);
if (branchTip != null) {
// If this commit is already merged its a bug in the queuing code
// that we got back here. Just mark it complete and move on. It's
// merged and that is all that mattered to the requestor.
//
try {
if (rw.isMergedInto(commit, branchTip)) {
commit.statusCode = CommitMergeStatus.ALREADY_MERGED;
try {
setMerged(chg, null);
} catch (OrmException e) {
log.error("Cannot mark change " + chg.getId() + " merged", e);
}
continue;
}
} catch (IOException err) {
throw new MergeException("Cannot perform merge base test", err);
}
}
final SubmitType submitType = getSubmitType(chg, ps);
if (submitType == null) {
commits.put(changeId,
CodeReviewCommit.error(CommitMergeStatus.NO_SUBMIT_TYPE));
continue;
}
commit.add(canMergeFlag);
toMerge.put(submitType, commit);
toSubmit.put(submitType, chg);
}
return toSubmit;
}
|
diff --git a/src/com/android/deskclock/timer/TimerFragment.java b/src/com/android/deskclock/timer/TimerFragment.java
index 82a1f930..9d8a297a 100644
--- a/src/com/android/deskclock/timer/TimerFragment.java
+++ b/src/com/android/deskclock/timer/TimerFragment.java
@@ -1,985 +1,988 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.deskclock.timer;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import com.android.deskclock.CircleButtonsLinearLayout;
import com.android.deskclock.DeskClock;
import com.android.deskclock.DeskClock.OnTapListener;
import com.android.deskclock.DeskClockFragment;
import com.android.deskclock.LabelDialogFragment;
import com.android.deskclock.R;
import com.android.deskclock.TimerSetupView;
import com.android.deskclock.Utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
public class TimerFragment extends DeskClockFragment
implements OnClickListener, OnSharedPreferenceChangeListener {
private static final String TAG = "TimerFragment";
private static final String KEY_SETUP_SELECTED = "_setup_selected";
private static final String KEY_ENTRY_STATE = "entry_state";
private Bundle mViewState = null;
private ListView mTimersList;
private View mNewTimerPage;
private View mTimersListPage;
private Button mCancel, mStart;
private View mSeperator;
private ImageButton mAddTimer;
private View mTimerFooter;
private TimerSetupView mTimerSetup;
private TimersListAdapter mAdapter;
private boolean mTicking = false;
private SharedPreferences mPrefs;
private NotificationManager mNotificationManager;
private OnEmptyListListener mOnEmptyListListener;
private View mLastVisibleView = null; // used to decide if to set the view or animate to it.
public TimerFragment() {
}
class ClickAction {
public static final int ACTION_STOP = 1;
public static final int ACTION_PLUS_ONE = 2;
public static final int ACTION_DELETE = 3;
public int mAction;
public TimerObj mTimer;
public ClickAction(int action, TimerObj t) {
mAction = action;
mTimer = t;
}
}
// Container Activity that requests TIMESUP_MODE must implement this interface
public interface OnEmptyListListener {
public void onEmptyList();
public void onListChanged();
}
TimersListAdapter createAdapter(Context context, SharedPreferences prefs) {
if (mOnEmptyListListener == null) {
return new TimersListAdapter(context, prefs);
} else {
return new TimesUpListAdapter(context, prefs);
}
}
class TimersListAdapter extends BaseAdapter {
ArrayList<TimerObj> mTimers = new ArrayList<TimerObj> ();
Context mContext;
SharedPreferences mmPrefs;
public TimersListAdapter(Context context, SharedPreferences prefs) {
mContext = context;
mmPrefs = prefs;
}
@Override
public int getCount() {
return mTimers.size();
}
@Override
public Object getItem(int p) {
return mTimers.get(p);
}
@Override
public long getItemId(int p) {
if (p >= 0 && p < mTimers.size()) {
return mTimers.get(p).mTimerId;
}
return 0;
}
public void deleteTimer(int id) {
for (int i = 0; i < mTimers.size(); i++) {
TimerObj t = mTimers.get(i);
if (t.mTimerId == id) {
if (t.mView != null) {
((TimerListItem) t.mView).stop();
}
t.deleteFromSharedPref(mmPrefs);
mTimers.remove(i);
notifyDataSetChanged();
return;
}
}
}
protected int findTimerPositionById(int id) {
for (int i = 0; i < mTimers.size(); i++) {
TimerObj t = mTimers.get(i);
if (t.mTimerId == id) {
return i;
}
}
return -1;
}
public void removeTimer(TimerObj timerObj) {
int position = findTimerPositionById(timerObj.mTimerId);
if (position >= 0) {
mTimers.remove(position);
notifyDataSetChanged();
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TimerListItem v = new TimerListItem (mContext); // TODO: Need to recycle convertView.
final TimerObj o = (TimerObj)getItem(position);
o.mView = v;
long timeLeft = o.updateTimeLeft(false);
boolean drawRed = o.mState != TimerObj.STATE_RESTART;
v.set(o.mOriginalLength, timeLeft, drawRed);
v.setTime(timeLeft, true);
switch (o.mState) {
case TimerObj.STATE_RUNNING:
v.start();
break;
case TimerObj.STATE_TIMESUP:
v.timesUp();
break;
case TimerObj.STATE_DONE:
v.done();
break;
default:
break;
}
// Timer text serves as a virtual start/stop button.
final CountingTimerView countingTimerView = (CountingTimerView)
v.findViewById(R.id.timer_time_text);
countingTimerView.registerVirtualButtonAction(new Runnable() {
@Override
public void run() {
TimerFragment.this.onClickHelper(
new ClickAction(ClickAction.ACTION_STOP, o));
}
});
ImageButton delete = (ImageButton)v.findViewById(R.id.timer_delete);
delete.setOnClickListener(TimerFragment.this);
delete.setTag(new ClickAction(ClickAction.ACTION_DELETE, o));
ImageButton plusOne = (ImageButton)v. findViewById(R.id.timer_plus_one);
plusOne.setOnClickListener(TimerFragment.this);
plusOne.setTag(new ClickAction(ClickAction.ACTION_PLUS_ONE, o));
TextView stop = (TextView)v. findViewById(R.id.timer_stop);
stop.setTag(new ClickAction(ClickAction.ACTION_STOP, o));
TimerFragment.this.setTimerButtons(o);
v.setBackgroundColor(getResources().getColor(R.color.blackish));
countingTimerView.registerStopTextView(stop);
CircleButtonsLinearLayout circleLayout =
(CircleButtonsLinearLayout)v.findViewById(R.id.timer_circle);
circleLayout.setCircleTimerViewIds(
R.id.timer_time, R.id.timer_plus_one, R.id.timer_delete, R.id.timer_stop,
R.dimen.plusone_reset_button_padding, R.dimen.delete_button_padding,
R.id.timer_label, R.id.timer_label_text);
FrameLayout label = (FrameLayout)v. findViewById(R.id.timer_label);
ImageButton labelIcon = (ImageButton)v. findViewById(R.id.timer_label_icon);
TextView labelText = (TextView)v. findViewById(R.id.timer_label_text);
if (o.mLabel.equals("")) {
labelText.setVisibility(View.GONE);
labelIcon.setVisibility(View.VISIBLE);
} else {
labelText.setText(o.mLabel);
labelText.setVisibility(View.VISIBLE);
labelIcon.setVisibility(View.GONE);
}
if (getActivity() instanceof DeskClock) {
label.setOnTouchListener(new OnTapListener(getActivity(), labelText) {
@Override
protected void processClick(View v) {
onLabelPressed(o);
}
});
} else {
labelIcon.setVisibility(View.INVISIBLE);
}
return v;
}
public void addTimer(TimerObj t) {
mTimers.add(0, t);
sort();
}
public void onSaveInstanceState(Bundle outState) {
TimerObj.putTimersInSharedPrefs(mmPrefs, mTimers);
}
public void onRestoreInstanceState(Bundle outState) {
TimerObj.getTimersFromSharedPrefs(mmPrefs, mTimers);
sort();
}
public void saveGlobalState() {
TimerObj.putTimersInSharedPrefs(mmPrefs, mTimers);
}
public void sort() {
if (getCount() > 0) {
Collections.sort(mTimers, mTimersCompare);
notifyDataSetChanged();
}
}
private final Comparator<TimerObj> mTimersCompare = new Comparator<TimerObj>() {
static final int BUZZING = 0;
static final int IN_USE = 1;
static final int NOT_USED = 2;
protected int getSection(TimerObj timerObj) {
switch (timerObj.mState) {
case TimerObj.STATE_TIMESUP:
return BUZZING;
case TimerObj.STATE_RUNNING:
case TimerObj.STATE_STOPPED:
return IN_USE;
default:
return NOT_USED;
}
}
@Override
public int compare(TimerObj o1, TimerObj o2) {
int section1 = getSection(o1);
int section2 = getSection(o2);
if (section1 != section2) {
return (section1 < section2) ? -1 : 1;
} else if (section1 == BUZZING || section1 == IN_USE) {
return (o1.mTimeLeft < o2.mTimeLeft) ? -1 : 1;
} else {
return (o1.mSetupLength < o2.mSetupLength) ? -1 : 1;
}
}
};
}
class TimesUpListAdapter extends TimersListAdapter {
public TimesUpListAdapter(Context context, SharedPreferences prefs) {
super(context, prefs);
}
@Override
public void onSaveInstanceState(Bundle outState) {
// This adapter has a data subset and never updates entire database
// Individual timers are updated in button handlers.
}
@Override
public void saveGlobalState() {
// This adapter has a data subset and never updates entire database
// Individual timers are updated in button handlers.
}
@Override
public void onRestoreInstanceState(Bundle outState) {
// This adapter loads a subset
TimerObj.getTimersFromSharedPrefs(mmPrefs, mTimers, TimerObj.STATE_TIMESUP);
if (getCount() == 0) {
mOnEmptyListListener.onEmptyList();
} else {
Collections.sort(mTimers, new Comparator<TimerObj>() {
@Override
public int compare(TimerObj o1, TimerObj o2) {
return (o1.mTimeLeft < o2.mTimeLeft) ? -1 : 1;
}
});
}
}
}
private final Runnable mClockTick = new Runnable() {
boolean mVisible = true;
final static int TIME_PERIOD_MS = 1000;
final static int SPLIT = TIME_PERIOD_MS / 2;
@Override
public void run() {
// Setup for blinking
boolean visible = Utils.getTimeNow() % TIME_PERIOD_MS < SPLIT;
boolean toggle = mVisible != visible;
mVisible = visible;
for (int i = 0; i < mAdapter.getCount(); i ++) {
TimerObj t = (TimerObj) mAdapter.getItem(i);
if (t.mState == TimerObj.STATE_RUNNING || t.mState == TimerObj.STATE_TIMESUP) {
long timeLeft = t.updateTimeLeft(false);
if ((TimerListItem)(t.mView) != null) {
((TimerListItem)(t.mView)).setTime(timeLeft, false);
}
}
if (t.mTimeLeft <= 0 && t.mState != TimerObj.STATE_DONE
&& t.mState != TimerObj.STATE_RESTART) {
t.mState = TimerObj.STATE_TIMESUP;
TimerFragment.this.setTimerButtons(t);
if ((TimerListItem)(t.mView) != null) {
((TimerListItem)(t.mView)).timesUp();
}
}
// The blinking
if (toggle && (TimerListItem)(t.mView) != null) {
if (t.mState == TimerObj.STATE_TIMESUP) {
((TimerListItem)(t.mView)).setCircleBlink(mVisible);
}
if (t.mState == TimerObj.STATE_STOPPED) {
((TimerListItem)(t.mView)).setTextBlink(mVisible);
}
}
}
mTimersList.postDelayed(mClockTick, 20);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
// Cache instance data and consume in first call to setupPage()
if (savedInstanceState != null) {
mViewState = savedInstanceState;
}
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.timer_fragment, container, false);
// Handle arguments from parent
Bundle bundle = getArguments();
if (bundle != null && bundle.containsKey(Timers.TIMESUP_MODE)) {
if (bundle.getBoolean(Timers.TIMESUP_MODE, false)) {
try {
mOnEmptyListListener = (OnEmptyListListener) getActivity();
} catch (ClassCastException e) {
Log.wtf(TAG, getActivity().toString() + " must implement OnEmptyListListener");
}
}
}
mTimersList = (ListView)v.findViewById(R.id.timers_list);
// Use light's out if this fragment is within the DeskClock
+ LayoutParams params;
+ float dividerHeight = getResources().getDimension(R.dimen.timer_divider_height);
if (getActivity() instanceof DeskClock) {
- float dividerHeight = getResources().getDimension(R.dimen.timer_divider_height);
View footerView = inflater.inflate(R.layout.blank_footer_view, mTimersList, false);
- LayoutParams params = footerView.getLayoutParams();
+ params = footerView.getLayoutParams();
params.height -= dividerHeight;
footerView.setLayoutParams(params);
footerView.setBackgroundResource(R.color.blackish);
mTimersList.addFooterView(footerView);
- View headerView = inflater.inflate(R.layout.blank_header_view, mTimersList, false);
- params = headerView.getLayoutParams();
- params.height -= dividerHeight;
- headerView.setLayoutParams(params);
- mTimersList.addHeaderView(headerView);
} else {
mTimersList.setBackgroundColor(getResources().getColor(R.color.blackish));
}
+ // Make the top transparent header always visible so that the transition
+ // from the DeskClock app to the alert screen will be more pleasing visually.
+ View headerView = inflater.inflate(R.layout.blank_header_view, mTimersList, false);
+ params = headerView.getLayoutParams();
+ params.height -= dividerHeight;
+ headerView.setLayoutParams(params);
+ mTimersList.addHeaderView(headerView);
mNewTimerPage = v.findViewById(R.id.new_timer_page);
mTimersListPage = v.findViewById(R.id.timers_list_page);
mTimerSetup = (TimerSetupView)v.findViewById(R.id.timer_setup);
mSeperator = v.findViewById(R.id.timer_button_sep);
mCancel = (Button)v.findViewById(R.id.timer_cancel);
mCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mAdapter.getCount() != 0) {
gotoTimersView();
}
}
});
mStart = (Button)v.findViewById(R.id.timer_start);
mStart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// New timer create if timer length is not zero
// Create a new timer object to track the timer and
// switch to the timers view.
int timerLength = mTimerSetup.getTime();
if (timerLength == 0) {
return;
}
TimerObj t = new TimerObj(timerLength * 1000);
t.mState = TimerObj.STATE_RUNNING;
mAdapter.addTimer(t);
updateTimersState(t, Timers.START_TIMER);
gotoTimersView();
mTimersList.setSelection(mAdapter.findTimerPositionById(t.mTimerId));
}
});
mTimerSetup.registerStartButton(mStart);
mAddTimer = (ImageButton)v.findViewById(R.id.timer_add_timer);
mAddTimer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimerSetup.reset();
gotoSetupView();
}
});
mTimerFooter = v.findViewById(R.id.timer_footer);
mTimerFooter.setVisibility(mOnEmptyListListener == null ? View.VISIBLE : View.GONE);
mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
mNotificationManager = (NotificationManager)
getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
return v;
}
@Override
public void onDestroyView() {
mViewState = new Bundle();
saveViewState(mViewState);
super.onDestroyView();
}
@Override
public void onResume() {
if (getActivity() instanceof DeskClock) {
((DeskClock)getActivity()).registerPageChangedListener(this);
}
super.onResume();
mPrefs.registerOnSharedPreferenceChangeListener(this);
mAdapter = createAdapter(getActivity(), mPrefs);
mAdapter.onRestoreInstanceState(null);
if (mPrefs.getBoolean(Timers.FROM_NOTIFICATION, false)) {
// We need to know if this onresume is being called by the user clicking a
// buzzing timer notification. If so, we need to set that timer to have "stopped"
// at the moment the notification was hit.
long now = mPrefs.getLong(Timers.NOTIF_TIME, Utils.getTimeNow());
int timerId = mPrefs.getInt(Timers.NOTIF_ID, -1);
if (timerId != -1) {
TimerObj t = Timers.findTimer(mAdapter.mTimers, timerId);
t.mTimeLeft = t.mOriginalLength - (now - t.mStartTime);
cancelTimerNotification(timerId);
}
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(Timers.FROM_NOTIFICATION, false);
editor.apply();
}
if (mPrefs.getBoolean(Timers.FROM_ALERT, false)) {
// Clear the flag set in the alert because the adapter was just
// created and thusly in sync with the database
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(Timers.FROM_ALERT, false);
editor.apply();
}
mTimersList.setAdapter(mAdapter);
if (mAdapter.getCount() == 0) {
mCancel.setVisibility(View.GONE);
mSeperator.setVisibility(View.GONE);
}
mLastVisibleView = null; // Force a non animation setting of the view
setPage();
}
@Override
public void onPause() {
if (getActivity() instanceof DeskClock) {
((DeskClock)getActivity()).unregisterPageChangedListener(this);
}
super.onPause();
stopClockTicks();
if (mAdapter != null) {
mAdapter.saveGlobalState ();
}
mPrefs.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onPageChanged(int page) {
if (page == DeskClock.TIMER_TAB_INDEX && mAdapter != null) {
mAdapter.sort();
}
}
@Override
public void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
if (mAdapter != null) {
mAdapter.onSaveInstanceState (outState);
}
if (mNewTimerPage != null) {
saveViewState(outState);
} else if (mViewState != null) {
outState.putAll(mViewState);
}
}
private void saveViewState(Bundle outState) {
outState.putBoolean(KEY_SETUP_SELECTED, mNewTimerPage.getVisibility() == View.VISIBLE);
mTimerSetup.saveEntryState(outState, KEY_ENTRY_STATE);
}
public void setPage() {
boolean switchToSetupView;
if (mViewState != null) {
switchToSetupView = mViewState.getBoolean(KEY_SETUP_SELECTED, false);
mTimerSetup.restoreEntryState(mViewState, KEY_ENTRY_STATE);
mViewState = null;
} else {
switchToSetupView = mAdapter.getCount() == 0;
}
if (switchToSetupView) {
gotoSetupView();
} else {
gotoTimersView();
}
}
public void stopAllTimesUpTimers() {
boolean notifyChange = false;
// To avoid race conditions where a timer was dismissed and it is still in the timers list
// and can be picked again, create a temporary list of timers to be removed first and
// then removed them one by one
LinkedList<TimerObj> timesupTimers = new LinkedList<TimerObj>();
for (int i = 0; i < mAdapter.getCount(); i ++) {
TimerObj timerObj = (TimerObj) mAdapter.getItem(i);
if (timerObj.mState == TimerObj.STATE_TIMESUP) {
timesupTimers.addFirst(timerObj);
notifyChange = true;
}
}
while (timesupTimers.size() > 0) {
onStopButtonPressed(timesupTimers.remove());
}
if (notifyChange) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(Timers.FROM_ALERT, true);
editor.apply();
}
}
private void gotoSetupView() {
if (mLastVisibleView == null || mLastVisibleView.getId() == R.id.new_timer_page) {
mNewTimerPage.setVisibility(View.VISIBLE);
mNewTimerPage.setScaleX(1f);
mTimersListPage.setVisibility(View.GONE);
} else {
// Animate
ObjectAnimator a = ObjectAnimator.ofFloat(mTimersListPage, View.SCALE_X, 1f, 0f);
a.setInterpolator(new AccelerateInterpolator());
a.setDuration(125);
a.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mTimersListPage.setVisibility(View.GONE);
mNewTimerPage.setScaleX(0);
mNewTimerPage.setVisibility(View.VISIBLE);
ObjectAnimator b = ObjectAnimator.ofFloat(mNewTimerPage, View.SCALE_X, 0f, 1f);
b.setInterpolator(new DecelerateInterpolator());
b.setDuration(225);
b.start();
}
});
a.start();
}
stopClockTicks();
if (mAdapter.getCount() == 0) {
mCancel.setVisibility(View.GONE);
mSeperator.setVisibility(View.GONE);
} else {
mSeperator.setVisibility(View.VISIBLE);
mCancel.setVisibility(View.VISIBLE);
}
mTimerSetup.updateStartButton();
mTimerSetup.updateDeleteButton();
mLastVisibleView = mNewTimerPage;
}
private void gotoTimersView() {
if (mLastVisibleView == null || mLastVisibleView.getId() == R.id.timers_list_page) {
mNewTimerPage.setVisibility(View.GONE);
mTimersListPage.setVisibility(View.VISIBLE);
mTimersListPage.setScaleX(1f);
} else {
// Animate
ObjectAnimator a = ObjectAnimator.ofFloat(mNewTimerPage, View.SCALE_X, 1f, 0f);
a.setInterpolator(new AccelerateInterpolator());
a.setDuration(125);
a.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mNewTimerPage.setVisibility(View.GONE);
mTimersListPage.setScaleX(0);
mTimersListPage.setVisibility(View.VISIBLE);
ObjectAnimator b =
ObjectAnimator.ofFloat(mTimersListPage, View.SCALE_X, 0f, 1f);
b.setInterpolator(new DecelerateInterpolator());
b.setDuration(225);
b.start();
}
});
a.start();
}
startClockTicks();
mLastVisibleView = mTimersListPage;
}
@Override
public void onClick(View v) {
ClickAction tag = (ClickAction) v.getTag();
onClickHelper(tag);
}
private void onClickHelper(ClickAction clickAction) {
switch (clickAction.mAction) {
case ClickAction.ACTION_DELETE:
final TimerObj t = clickAction.mTimer;
if (t.mState == TimerObj.STATE_TIMESUP) {
cancelTimerNotification(t.mTimerId);
}
// Animate deletion, first alpha, then height
ObjectAnimator a = ObjectAnimator.ofFloat(t.mView, View.ALPHA, 1f, 0f);
a.setInterpolator(new AccelerateInterpolator());
a.setDuration(100);
a.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
ObjectAnimator b = ObjectAnimator.ofInt(
t.mView, "animatedHeight", t.mView.getHeight(), 0);
b.setInterpolator(new AccelerateInterpolator());
b.setDuration(200);
b.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mAdapter.deleteTimer(t.mTimerId);
if (mAdapter.getCount() == 0) {
if (mOnEmptyListListener == null) {
mTimerSetup.reset();
gotoSetupView();
} else {
mOnEmptyListListener.onEmptyList();
}
}
// Tell receiver the timer was deleted.
// It will stop all activity related to the
// timer
updateTimersState(t, Timers.DELETE_TIMER);
}
});
b.start();
}
});
a.start();
break;
case ClickAction.ACTION_PLUS_ONE:
onPlusOneButtonPressed(clickAction.mTimer);
setTimerButtons(clickAction.mTimer);
break;
case ClickAction.ACTION_STOP:
onStopButtonPressed(clickAction.mTimer);
setTimerButtons(clickAction.mTimer);
break;
default:
break;
}
}
private void onPlusOneButtonPressed(TimerObj t) {
switch(t.mState) {
case TimerObj.STATE_RUNNING:
t.addTime(60000); //60 seconds in millis
long timeLeft = t.updateTimeLeft(false);
((TimerListItem)(t.mView)).setTime(timeLeft, false);
((TimerListItem)(t.mView)).setLength(timeLeft);
mAdapter.notifyDataSetChanged();
updateTimersState(t, Timers.TIMER_UPDATE);
break;
case TimerObj.STATE_TIMESUP:
// +1 min when the time is up will restart the timer with 1 minute left.
t.mState = TimerObj.STATE_RUNNING;
t.mStartTime = Utils.getTimeNow();
t.mTimeLeft = t. mOriginalLength = 60000;
((TimerListItem)t.mView).setTime(t.mTimeLeft, false);
((TimerListItem)t.mView).set(t.mOriginalLength, t.mTimeLeft, true);
((TimerListItem) t.mView).start();
updateTimersState(t, Timers.TIMER_RESET);
updateTimersState(t, Timers.START_TIMER);
updateTimesUpMode(t);
cancelTimerNotification(t.mTimerId);
break;
case TimerObj.STATE_STOPPED:
case TimerObj.STATE_DONE:
t.mState = TimerObj.STATE_RESTART;
t.mTimeLeft = t. mOriginalLength = t.mSetupLength;
((TimerListItem)t.mView).stop();
((TimerListItem)t.mView).setTime(t.mTimeLeft, false);
((TimerListItem)t.mView).set(t.mOriginalLength, t.mTimeLeft, false);
updateTimersState(t, Timers.TIMER_RESET);
break;
default:
break;
}
}
private void onStopButtonPressed(TimerObj t) {
switch(t.mState) {
case TimerObj.STATE_RUNNING:
// Stop timer and save the remaining time of the timer
t.mState = TimerObj.STATE_STOPPED;
((TimerListItem) t.mView).pause();
t.updateTimeLeft(true);
updateTimersState(t, Timers.TIMER_STOP);
break;
case TimerObj.STATE_STOPPED:
// Reset the remaining time and continue timer
t.mState = TimerObj.STATE_RUNNING;
t.mStartTime = Utils.getTimeNow() - (t.mOriginalLength - t.mTimeLeft);
((TimerListItem) t.mView).start();
updateTimersState(t, Timers.START_TIMER);
break;
case TimerObj.STATE_TIMESUP:
t.mState = TimerObj.STATE_DONE;
// Used in a context where the timer could be off-screen and without a view
if (t.mView != null) {
((TimerListItem) t.mView).done();
}
updateTimersState(t, Timers.TIMER_DONE);
cancelTimerNotification(t.mTimerId);
updateTimesUpMode(t);
break;
case TimerObj.STATE_DONE:
break;
case TimerObj.STATE_RESTART:
t.mState = TimerObj.STATE_RUNNING;
t.mStartTime = Utils.getTimeNow() - (t.mOriginalLength - t.mTimeLeft);
((TimerListItem) t.mView).start();
updateTimersState(t, Timers.START_TIMER);
break;
default:
break;
}
}
private void onLabelPressed(TimerObj t) {
final FragmentTransaction ft = getFragmentManager().beginTransaction();
final Fragment prev = getFragmentManager().findFragmentByTag("label_dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
final LabelDialogFragment newFragment =
LabelDialogFragment.newInstance(t, t.mLabel, getTag());
newFragment.show(ft, "label_dialog");
}
public void setLabel(TimerObj timer, String label) {
((TimerObj) mAdapter.getItem(
mAdapter.findTimerPositionById(timer.mTimerId))).mLabel = label;
if (timer.mState == TimerObj.STATE_TIMESUP) {
// Timer is in timesup mode.
TimerReceiver.showExpiredAlarmNotification(
getActivity().getApplicationContext(), timer);
}
mTimersList.invalidateViews();
}
private void setTimerButtons(TimerObj t) {
Context a = getActivity();
if (a == null || t == null || t.mView == null) {
return;
}
ImageButton plusOne = (ImageButton) t.mView.findViewById(R.id.timer_plus_one);
CountingTimerView countingTimerView = (CountingTimerView)
t.mView.findViewById(R.id.timer_time_text);
TextView stop = (TextView) t.mView.findViewById(R.id.timer_stop);
Resources r = a.getResources();
switch (t.mState) {
case TimerObj.STATE_RUNNING:
plusOne.setVisibility(View.VISIBLE);
plusOne.setContentDescription(r.getString(R.string.timer_plus_one));
plusOne.setImageResource(R.drawable.ic_plusone);
stop.setContentDescription(r.getString(R.string.timer_stop));
stop.setText(R.string.timer_stop);
stop.setTextColor(getResources().getColor(R.color.clock_white));
countingTimerView.setVirtualButtonEnabled(true);
break;
case TimerObj.STATE_STOPPED:
plusOne.setVisibility(View.VISIBLE);
plusOne.setContentDescription(r.getString(R.string.timer_reset));
plusOne.setImageResource(R.drawable.ic_reset);
stop.setContentDescription(r.getString(R.string.timer_start));
stop.setText(R.string.timer_start);
stop.setTextColor(getResources().getColor(R.color.clock_white));
countingTimerView.setVirtualButtonEnabled(true);
break;
case TimerObj.STATE_TIMESUP:
plusOne.setVisibility(View.VISIBLE);
plusOne.setImageResource(R.drawable.ic_plusone);
stop.setContentDescription(r.getString(R.string.timer_stop));
stop.setTextColor(getResources().getColor(R.color.clock_white));
countingTimerView.setVirtualButtonEnabled(true);
break;
case TimerObj.STATE_DONE:
plusOne.setVisibility(View.VISIBLE);
plusOne.setContentDescription(r.getString(R.string.timer_reset));
plusOne.setImageResource(R.drawable.ic_reset);
stop.setVisibility(View.INVISIBLE);
countingTimerView.setVirtualButtonEnabled(false);
break;
case TimerObj.STATE_RESTART:
plusOne.setVisibility(View.INVISIBLE);
stop.setVisibility(View.VISIBLE);
stop.setContentDescription(r.getString(R.string.timer_start));
stop.setText(R.string.timer_start);
stop.setTextColor(getResources().getColor(R.color.clock_white));
countingTimerView.setVirtualButtonEnabled(true);
break;
default:
break;
}
}
private void startClockTicks() {
mTimersList.postDelayed(mClockTick, 20);
mTicking = true;
}
private void stopClockTicks() {
if (mTicking) {
mTimersList.removeCallbacks(mClockTick);
mTicking = false;
}
}
private void updateTimersState(TimerObj t, String action) {
if (!Timers.DELETE_TIMER.equals(action)) {
t.writeToSharedPref(mPrefs);
}
Intent i = new Intent();
i.setAction(action);
i.putExtra(Timers.TIMER_INTENT_EXTRA, t.mTimerId);
getActivity().sendBroadcast(i);
}
private void cancelTimerNotification(int timerId) {
mNotificationManager.cancel(timerId);
}
private void updateTimesUpMode(TimerObj timerObj) {
if (mOnEmptyListListener != null && timerObj.mState != TimerObj.STATE_TIMESUP) {
mAdapter.removeTimer(timerObj);
if (mAdapter.getCount() == 0) {
mOnEmptyListListener.onEmptyList();
} else {
mOnEmptyListListener.onListChanged();
}
}
}
public void restartAdapter() {
mAdapter = createAdapter(getActivity(), mPrefs);
mAdapter.onRestoreInstanceState(null);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (prefs.equals(mPrefs)) {
if ( (key.equals(Timers.FROM_NOTIFICATION) || key.equals(Timers.NOTIF_ID)
|| key.equals(Timers.NOTIF_TIME)) &&
prefs.getBoolean(Timers.FROM_NOTIFICATION, false) ) {
// We need to know if the user has clicked the buzzing timer notification
// while the fragment is still open. If so, this listener will catch that event,
// and allow the timers to be re-instated based on the updated stop time.
// Because this method gets called with every change to the sharedprefs, we ensure
// that we only recalculate the timers if the change was specifically set by the
// user interacting with the notification.
long now = prefs.getLong(Timers.NOTIF_TIME, Utils.getTimeNow());
int timerId = prefs.getInt(Timers.NOTIF_ID, -1);
mAdapter = createAdapter(getActivity(), mPrefs);
mAdapter.onRestoreInstanceState(null);
if (timerId != -1) {
TimerObj t = Timers.findTimer(mAdapter.mTimers, timerId);
t.mTimeLeft = t.mOriginalLength - (now - t.mStartTime);
cancelTimerNotification(timerId);
}
mTimersList.setAdapter(mAdapter);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(Timers.FROM_NOTIFICATION, false);
editor.apply();
}
if (key.equals(Timers.FROM_ALERT) && prefs.getBoolean(Timers.FROM_ALERT, false)) {
// The flag was set in the alert so the adapter needs to re-sync
// with the database
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(Timers.FROM_ALERT, false);
editor.apply();
mAdapter = createAdapter(getActivity(), mPrefs);
mAdapter.onRestoreInstanceState(null);
mTimersList.setAdapter(mAdapter);
}
}
}
}
| false | true | public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.timer_fragment, container, false);
// Handle arguments from parent
Bundle bundle = getArguments();
if (bundle != null && bundle.containsKey(Timers.TIMESUP_MODE)) {
if (bundle.getBoolean(Timers.TIMESUP_MODE, false)) {
try {
mOnEmptyListListener = (OnEmptyListListener) getActivity();
} catch (ClassCastException e) {
Log.wtf(TAG, getActivity().toString() + " must implement OnEmptyListListener");
}
}
}
mTimersList = (ListView)v.findViewById(R.id.timers_list);
// Use light's out if this fragment is within the DeskClock
if (getActivity() instanceof DeskClock) {
float dividerHeight = getResources().getDimension(R.dimen.timer_divider_height);
View footerView = inflater.inflate(R.layout.blank_footer_view, mTimersList, false);
LayoutParams params = footerView.getLayoutParams();
params.height -= dividerHeight;
footerView.setLayoutParams(params);
footerView.setBackgroundResource(R.color.blackish);
mTimersList.addFooterView(footerView);
View headerView = inflater.inflate(R.layout.blank_header_view, mTimersList, false);
params = headerView.getLayoutParams();
params.height -= dividerHeight;
headerView.setLayoutParams(params);
mTimersList.addHeaderView(headerView);
} else {
mTimersList.setBackgroundColor(getResources().getColor(R.color.blackish));
}
mNewTimerPage = v.findViewById(R.id.new_timer_page);
mTimersListPage = v.findViewById(R.id.timers_list_page);
mTimerSetup = (TimerSetupView)v.findViewById(R.id.timer_setup);
mSeperator = v.findViewById(R.id.timer_button_sep);
mCancel = (Button)v.findViewById(R.id.timer_cancel);
mCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mAdapter.getCount() != 0) {
gotoTimersView();
}
}
});
mStart = (Button)v.findViewById(R.id.timer_start);
mStart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// New timer create if timer length is not zero
// Create a new timer object to track the timer and
// switch to the timers view.
int timerLength = mTimerSetup.getTime();
if (timerLength == 0) {
return;
}
TimerObj t = new TimerObj(timerLength * 1000);
t.mState = TimerObj.STATE_RUNNING;
mAdapter.addTimer(t);
updateTimersState(t, Timers.START_TIMER);
gotoTimersView();
mTimersList.setSelection(mAdapter.findTimerPositionById(t.mTimerId));
}
});
mTimerSetup.registerStartButton(mStart);
mAddTimer = (ImageButton)v.findViewById(R.id.timer_add_timer);
mAddTimer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimerSetup.reset();
gotoSetupView();
}
});
mTimerFooter = v.findViewById(R.id.timer_footer);
mTimerFooter.setVisibility(mOnEmptyListListener == null ? View.VISIBLE : View.GONE);
mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
mNotificationManager = (NotificationManager)
getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
return v;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.timer_fragment, container, false);
// Handle arguments from parent
Bundle bundle = getArguments();
if (bundle != null && bundle.containsKey(Timers.TIMESUP_MODE)) {
if (bundle.getBoolean(Timers.TIMESUP_MODE, false)) {
try {
mOnEmptyListListener = (OnEmptyListListener) getActivity();
} catch (ClassCastException e) {
Log.wtf(TAG, getActivity().toString() + " must implement OnEmptyListListener");
}
}
}
mTimersList = (ListView)v.findViewById(R.id.timers_list);
// Use light's out if this fragment is within the DeskClock
LayoutParams params;
float dividerHeight = getResources().getDimension(R.dimen.timer_divider_height);
if (getActivity() instanceof DeskClock) {
View footerView = inflater.inflate(R.layout.blank_footer_view, mTimersList, false);
params = footerView.getLayoutParams();
params.height -= dividerHeight;
footerView.setLayoutParams(params);
footerView.setBackgroundResource(R.color.blackish);
mTimersList.addFooterView(footerView);
} else {
mTimersList.setBackgroundColor(getResources().getColor(R.color.blackish));
}
// Make the top transparent header always visible so that the transition
// from the DeskClock app to the alert screen will be more pleasing visually.
View headerView = inflater.inflate(R.layout.blank_header_view, mTimersList, false);
params = headerView.getLayoutParams();
params.height -= dividerHeight;
headerView.setLayoutParams(params);
mTimersList.addHeaderView(headerView);
mNewTimerPage = v.findViewById(R.id.new_timer_page);
mTimersListPage = v.findViewById(R.id.timers_list_page);
mTimerSetup = (TimerSetupView)v.findViewById(R.id.timer_setup);
mSeperator = v.findViewById(R.id.timer_button_sep);
mCancel = (Button)v.findViewById(R.id.timer_cancel);
mCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mAdapter.getCount() != 0) {
gotoTimersView();
}
}
});
mStart = (Button)v.findViewById(R.id.timer_start);
mStart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// New timer create if timer length is not zero
// Create a new timer object to track the timer and
// switch to the timers view.
int timerLength = mTimerSetup.getTime();
if (timerLength == 0) {
return;
}
TimerObj t = new TimerObj(timerLength * 1000);
t.mState = TimerObj.STATE_RUNNING;
mAdapter.addTimer(t);
updateTimersState(t, Timers.START_TIMER);
gotoTimersView();
mTimersList.setSelection(mAdapter.findTimerPositionById(t.mTimerId));
}
});
mTimerSetup.registerStartButton(mStart);
mAddTimer = (ImageButton)v.findViewById(R.id.timer_add_timer);
mAddTimer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimerSetup.reset();
gotoSetupView();
}
});
mTimerFooter = v.findViewById(R.id.timer_footer);
mTimerFooter.setVisibility(mOnEmptyListListener == null ? View.VISIBLE : View.GONE);
mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
mNotificationManager = (NotificationManager)
getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
return v;
}
|
diff --git a/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/system/exporters/ArbitraryPluginRunner.java b/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/system/exporters/ArbitraryPluginRunner.java
index 0c21ba1a..5c46f482 100644
--- a/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/system/exporters/ArbitraryPluginRunner.java
+++ b/seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/system/exporters/ArbitraryPluginRunner.java
@@ -1,109 +1,109 @@
package com.github.seqware.queryengine.system.exporters;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import com.github.seqware.queryengine.model.Reference;
import com.github.seqware.queryengine.plugins.PluginInterface;
import com.github.seqware.queryengine.plugins.contribs.MutationsToDonorsAggregationPlugin;
import com.github.seqware.queryengine.system.Utility;
import com.github.seqware.queryengine.system.importers.FeatureImporter;
import com.github.seqware.queryengine.system.importers.SOFeatureImporter;
import com.github.seqware.queryengine.util.SGID;
import com.github.seqware.queryengine.factory.SWQEFactory;
public class ArbitraryPluginRunner {
/** Constant <code>OUTPUT_FILE_PARAM='o'</code> */
public static final char OUTPUT_FILE_PARAM = 'o';
/** Constant <code>REFERENCE_ID_PARAM='r'</code> */
public static final char REFERENCE_ID_PARAM = 'r';
/** Constant <code>PLUGIN_CLASS_PARAM='p'</code>*/
public static final char PLUGIN_CLASS_PARAM = 'p';
/** Constant <code>SUCCESS</code>*/
private static final int SUCCESS = 1;
/** Constant <code>FAILIURE</code>*/
private static final int FAILIURE = 1;
private String[] args;
public static void main(String[] args) {
int mainMethod = ArbitraryPluginRunner.runArbitraryPluginRunner(args);
if (mainMethod == FAILIURE) {
System.exit(FeatureImporter.EXIT_CODE_INVALID_FILE);
}
}
public static int runArbitraryPluginRunner(String[] args){
Options options = new Options();
Option option1 = OptionBuilder.withArgName("outputFile").withDescription("(required) output file").hasArgs(1).isRequired().create(OUTPUT_FILE_PARAM);
options.addOption(option1);
Option option2 = OptionBuilder.withArgName("reference").withDescription("(required) the reference ID of the FeatureSet to run plugin on").hasArgs(1).isRequired().create(REFERENCE_ID_PARAM);
options.addOption(option2);
Option option3 = OptionBuilder.withArgName("pluginClass").withDescription("(required) the plugin to be run, full package path").hasArgs(1).isRequired().create(PLUGIN_CLASS_PARAM);
options.addOption(option3);
try{
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
String referenceName = cmd.getOptionValue(REFERENCE_ID_PARAM);
String plugin = cmd.getOptionValue(REFERENCE_ID_PARAM);
String outputFile = cmd.getOptionValue(OUTPUT_FILE_PARAM);
Reference ref = null;
for (Reference r : SWQEFactory.getQueryInterface().getReferences()){
if (referenceName.equals(r.getName())){
ref = r;
break;
}
}
Class<? extends PluginInterface> arbitraryPluginClass;
try {
arbitraryPluginClass = (Class<? extends PluginInterface>) Class.forName(plugin);
long start = new Date().getTime();
System.out.println("Running plugin: " + plugin);
- Utility.dumpFromMapReducePlugin(plugin, ref, null, arbitraryPluginClass, (args.length == 3 ? outputFile : null));
+ Utility.dumpFromMapReducePlugin(plugin, ref, null, arbitraryPluginClass, outputFile);
long stop = new Date().getTime();
float diff = ((stop - start) / 1000) / 60;
System.out.println("Minutes to query: "+diff);
return SUCCESS;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (ref == null){
System.out.println("Reference was not found.");
System.exit(-2);
}
} catch (MissingOptionException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(SOFeatureImporter.class.getSimpleName(), options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
} catch (ParseException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(SOFeatureImporter.class.getSimpleName(), options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
}
return FAILIURE;
}
}
| true | true | public static int runArbitraryPluginRunner(String[] args){
Options options = new Options();
Option option1 = OptionBuilder.withArgName("outputFile").withDescription("(required) output file").hasArgs(1).isRequired().create(OUTPUT_FILE_PARAM);
options.addOption(option1);
Option option2 = OptionBuilder.withArgName("reference").withDescription("(required) the reference ID of the FeatureSet to run plugin on").hasArgs(1).isRequired().create(REFERENCE_ID_PARAM);
options.addOption(option2);
Option option3 = OptionBuilder.withArgName("pluginClass").withDescription("(required) the plugin to be run, full package path").hasArgs(1).isRequired().create(PLUGIN_CLASS_PARAM);
options.addOption(option3);
try{
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
String referenceName = cmd.getOptionValue(REFERENCE_ID_PARAM);
String plugin = cmd.getOptionValue(REFERENCE_ID_PARAM);
String outputFile = cmd.getOptionValue(OUTPUT_FILE_PARAM);
Reference ref = null;
for (Reference r : SWQEFactory.getQueryInterface().getReferences()){
if (referenceName.equals(r.getName())){
ref = r;
break;
}
}
Class<? extends PluginInterface> arbitraryPluginClass;
try {
arbitraryPluginClass = (Class<? extends PluginInterface>) Class.forName(plugin);
long start = new Date().getTime();
System.out.println("Running plugin: " + plugin);
Utility.dumpFromMapReducePlugin(plugin, ref, null, arbitraryPluginClass, (args.length == 3 ? outputFile : null));
long stop = new Date().getTime();
float diff = ((stop - start) / 1000) / 60;
System.out.println("Minutes to query: "+diff);
return SUCCESS;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (ref == null){
System.out.println("Reference was not found.");
System.exit(-2);
}
} catch (MissingOptionException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(SOFeatureImporter.class.getSimpleName(), options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
} catch (ParseException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(SOFeatureImporter.class.getSimpleName(), options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
}
return FAILIURE;
}
| public static int runArbitraryPluginRunner(String[] args){
Options options = new Options();
Option option1 = OptionBuilder.withArgName("outputFile").withDescription("(required) output file").hasArgs(1).isRequired().create(OUTPUT_FILE_PARAM);
options.addOption(option1);
Option option2 = OptionBuilder.withArgName("reference").withDescription("(required) the reference ID of the FeatureSet to run plugin on").hasArgs(1).isRequired().create(REFERENCE_ID_PARAM);
options.addOption(option2);
Option option3 = OptionBuilder.withArgName("pluginClass").withDescription("(required) the plugin to be run, full package path").hasArgs(1).isRequired().create(PLUGIN_CLASS_PARAM);
options.addOption(option3);
try{
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
String referenceName = cmd.getOptionValue(REFERENCE_ID_PARAM);
String plugin = cmd.getOptionValue(REFERENCE_ID_PARAM);
String outputFile = cmd.getOptionValue(OUTPUT_FILE_PARAM);
Reference ref = null;
for (Reference r : SWQEFactory.getQueryInterface().getReferences()){
if (referenceName.equals(r.getName())){
ref = r;
break;
}
}
Class<? extends PluginInterface> arbitraryPluginClass;
try {
arbitraryPluginClass = (Class<? extends PluginInterface>) Class.forName(plugin);
long start = new Date().getTime();
System.out.println("Running plugin: " + plugin);
Utility.dumpFromMapReducePlugin(plugin, ref, null, arbitraryPluginClass, outputFile);
long stop = new Date().getTime();
float diff = ((stop - start) / 1000) / 60;
System.out.println("Minutes to query: "+diff);
return SUCCESS;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (ref == null){
System.out.println("Reference was not found.");
System.exit(-2);
}
} catch (MissingOptionException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(SOFeatureImporter.class.getSimpleName(), options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
} catch (ParseException e) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(SOFeatureImporter.class.getSimpleName(), options);
System.exit(FeatureImporter.EXIT_CODE_INVALID_ARGS);
}
return FAILIURE;
}
|
diff --git a/SoftwareProjectDay/src/edu/se/se441/threads/Clock.java b/SoftwareProjectDay/src/edu/se/se441/threads/Clock.java
index 9383145..3efec92 100644
--- a/SoftwareProjectDay/src/edu/se/se441/threads/Clock.java
+++ b/SoftwareProjectDay/src/edu/se/se441/threads/Clock.java
@@ -1,46 +1,46 @@
package edu.se.se441.threads;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
public class Clock extends Thread{
private CountDownLatch startSignal;
private long startTime; // When the simulation starts.
private ArrayList<Long> timeRegistry;
public Clock(CountDownLatch startSignal){
this.startSignal = startSignal;
timeRegistry = new ArrayList();
}
public void run(){
try {
// Starting all threads at the same time (clock == 0 / "8:00AM").
startSignal.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Set the start time of the simulation.
startTime = System.currentTimeMillis();
- while(this.getTime() > 4800){
+ while(this.getTime() <= 4800){
for(Long t : timeRegistry){
if(t >= this.getTime()){
notifyAll();
}
}
}
}
/**
* @return The time of day in ms (0ms is 8:00AM)
*/
public long getTime(){
return System.currentTimeMillis() - startTime;
}
public void addTimeEvent(long timeOfEvent){
timeRegistry.add(timeOfEvent);
}
}
| true | true | public void run(){
try {
// Starting all threads at the same time (clock == 0 / "8:00AM").
startSignal.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Set the start time of the simulation.
startTime = System.currentTimeMillis();
while(this.getTime() > 4800){
for(Long t : timeRegistry){
if(t >= this.getTime()){
notifyAll();
}
}
}
}
| public void run(){
try {
// Starting all threads at the same time (clock == 0 / "8:00AM").
startSignal.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Set the start time of the simulation.
startTime = System.currentTimeMillis();
while(this.getTime() <= 4800){
for(Long t : timeRegistry){
if(t >= this.getTime()){
notifyAll();
}
}
}
}
|
diff --git a/src/com/sparkedia/valrix/ColorMe/ColorPlayerListener.java b/src/com/sparkedia/valrix/ColorMe/ColorPlayerListener.java
index ee26c2f..b64fa15 100644
--- a/src/com/sparkedia/valrix/ColorMe/ColorPlayerListener.java
+++ b/src/com/sparkedia/valrix/ColorMe/ColorPlayerListener.java
@@ -1,31 +1,31 @@
package com.sparkedia.valrix.ColorMe;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerListener;
public class ColorPlayerListener extends PlayerListener {
protected ColorMe plugin;
public ColorPlayerListener(ColorMe plugin) {
this.plugin = plugin;
}
public void onPlayerChat(PlayerChatEvent event) {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if (ColorMe.colors.keyExists(name)) {
String color = ColorMe.colors.getString(name);
for (int i = 0; i <= 15; i++) {
String col = ChatColor.getByCode(i).name();
if (color.equalsIgnoreCase(col.toLowerCase().replace("_", ""))) {
- player.setDisplayName(ChatColor.valueOf(col)+player.getDisplayName()+ChatColor.WHITE);
+ player.setDisplayName(ChatColor.valueOf(col)+ChatColor.stripColor(player.getDisplayName())+ChatColor.WHITE);
break;
}
}
} else {
player.setDisplayName(ChatColor.stripColor(player.getDisplayName()));
}
}
}
| true | true | public void onPlayerChat(PlayerChatEvent event) {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if (ColorMe.colors.keyExists(name)) {
String color = ColorMe.colors.getString(name);
for (int i = 0; i <= 15; i++) {
String col = ChatColor.getByCode(i).name();
if (color.equalsIgnoreCase(col.toLowerCase().replace("_", ""))) {
player.setDisplayName(ChatColor.valueOf(col)+player.getDisplayName()+ChatColor.WHITE);
break;
}
}
} else {
player.setDisplayName(ChatColor.stripColor(player.getDisplayName()));
}
}
| public void onPlayerChat(PlayerChatEvent event) {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if (ColorMe.colors.keyExists(name)) {
String color = ColorMe.colors.getString(name);
for (int i = 0; i <= 15; i++) {
String col = ChatColor.getByCode(i).name();
if (color.equalsIgnoreCase(col.toLowerCase().replace("_", ""))) {
player.setDisplayName(ChatColor.valueOf(col)+ChatColor.stripColor(player.getDisplayName())+ChatColor.WHITE);
break;
}
}
} else {
player.setDisplayName(ChatColor.stripColor(player.getDisplayName()));
}
}
|
diff --git a/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/AcceleoLibraryOperationVisitor.java b/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/AcceleoLibraryOperationVisitor.java
index 4561ecbd..3934f972 100644
--- a/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/AcceleoLibraryOperationVisitor.java
+++ b/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/AcceleoLibraryOperationVisitor.java
@@ -1,1176 +1,1176 @@
/*******************************************************************************
* Copyright (c) 2008, 2010 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.engine.internal.environment;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.eclipse.acceleo.common.AcceleoServicesRegistry;
import org.eclipse.acceleo.common.IAcceleoConstants;
import org.eclipse.acceleo.common.utils.AcceleoNonStandardLibrary;
import org.eclipse.acceleo.common.utils.AcceleoStandardLibrary;
import org.eclipse.acceleo.engine.AcceleoEngineMessages;
import org.eclipse.acceleo.engine.AcceleoEvaluationException;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EOperation;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.EcoreUtil.ContentTreeIterator;
import org.eclipse.emf.ecore.util.EcoreUtil.CrossReferencer;
import org.eclipse.ocl.util.CollectionUtil;
/**
* The purpose of this Utility class is to allow execution of Standard and non standard Acceleo operations.
*
* @author <a href="mailto:[email protected]">Laurent Goubet</a>
*/
public final class AcceleoLibraryOperationVisitor {
/** This will be used as a place holder so that library operations call can return null. */
private static final Object OPERATION_CALL_FAILED = new Object();
/** This will hold mapping from primitive types names to their Class instance. */
private static final Map<String, Class<?>> PRIMITIVE_TYPES;
/** Holds the prefix we'll use for the temporary context variables created to hold context values. */
private static final String TEMPORARY_CONTEXT_VAR_PREFIX = "context$"; //$NON-NLS-1$
/**
* Maps a source String to its StringTokenizer. Needed for the implementation of the standard operation
* "strtok(String, Integer)" as currently specified.
*/
private static final Map<String, StringTokenizer> TOKENIZERS = new HashMap<String, StringTokenizer>();
/**
* Keeps track of the cross referencer that's been created for this evaluation, if any. This is used and
* will be instantiated by the eInverse() non standard operation.
*/
private static CrossReferencer referencer;
static {
PRIMITIVE_TYPES = new HashMap<String, Class<?>>();
PRIMITIVE_TYPES.put("boolean", boolean.class); //$NON-NLS-1$
PRIMITIVE_TYPES.put("byte", byte.class); //$NON-NLS-1$
PRIMITIVE_TYPES.put("char", char.class); //$NON-NLS-1$
PRIMITIVE_TYPES.put("short", short.class); //$NON-NLS-1$
PRIMITIVE_TYPES.put("int", int.class); //$NON-NLS-1$
PRIMITIVE_TYPES.put("long", long.class); //$NON-NLS-1$
PRIMITIVE_TYPES.put("float", float.class); //$NON-NLS-1$
PRIMITIVE_TYPES.put("double", double.class); //$NON-NLS-1$
}
/** Utility classes don't need to (and shouldn't be) instantiated. */
private AcceleoLibraryOperationVisitor() {
// Hides default constructor
}
/**
* The environment will delegate operation calls to this method if it needs to evaluate non-standard
* Acceleo operations.
*
* @param env
* The environment that calls for this evaluation.
* @param operation
* Operation which is to be evaluated.
* @param source
* Source on which the operations is evaluated.
* @param args
* Arguments of the call.
* @return Result of the operation call.
*/
@SuppressWarnings("unchecked")
public static Object callNonStandardOperation(AcceleoEvaluationEnvironment env, EOperation operation,
Object source, Object... args) {
Object result = OPERATION_CALL_FAILED;
final String operationName = operation.getName();
if (AcceleoNonStandardLibrary.OPERATION_OCLANY_PLUS.equals(operationName)) {
// We'll only be here for two operations : OclAny::+(String) and String::+(OclAny)
assert source instanceof String || args[0] instanceof String;
result = toString(source) + toString(args[0]);
} else if (AcceleoNonStandardLibrary.OPERATION_OCLANY_TOSTRING.equals(operationName)) {
result = toString(source);
} else if (AcceleoNonStandardLibrary.OPERATION_OCLANY_INVOKE.equals(operationName)) {
if (args.length == 3) {
result = invoke(operation.eResource().getURI(), source, args);
}
// fall through : let else fail in UnsupportedOperationException
} else if (AcceleoNonStandardLibrary.OPERATION_OCLANY_CURRENT.equals(operationName)) {
if (args.length == 1) {
result = getContext(env, args);
}
// fall through : let else fail in UnsupportedOperationException
} else if (AcceleoNonStandardLibrary.OPERATION_OCLANY_GETPROPERTY.equals(operationName)) {
if (args.length == 1) {
result = getProperty(env, (String)args[0]);
} else if (args.length == 2 && args[1] instanceof String) {
result = getProperty(env, (String)args[0], (String)args[1]);
} else if (args.length == 2) {
result = getProperty(env, (String)args[0], ((List<Object>)args[1]).toArray());
} else if (args.length == 3) {
result = getProperty(env, (String)args[0], (String)args[1], ((List<Object>)args[2]).toArray());
}
// fall through : let else fail in UnsupportedOperationException
} else if (source instanceof String) {
result = callNonStandardStringOperation(operation, (String)source, args);
} else if (source instanceof EObject) {
result = callNonStandardEObjectOperation(operation, (EObject)source, args);
} else if (source instanceof Collection<?>) {
result = callNonStandardCollectionOperation(operation, (Collection<?>)source, args);
}
if (result != OPERATION_CALL_FAILED) {
return result;
}
// If we're here, the operation is undefined.
throw getExceptionOperationCallFailed(operation, source, args);
}
/**
* The environment will delegate operation calls to this method if it needs to evaluate a standard Acceleo
* operation.
*
* @param env
* The environment that calls for this evaluation.
* @param operation
* Operation which is to be evaluated.
* @param source
* Source on which the operations is evaluated.
* @param args
* Arguments of the call.
* @return Result of the operation call.
*/
public static Object callStandardOperation(AcceleoEvaluationEnvironment env, EOperation operation,
Object source, Object... args) {
Object result = OPERATION_CALL_FAILED;
// Specifications of each standard operation can be found as comments of
// AcceleoStandardLibrary#OPERATION_*.
if (source instanceof String) {
final String sourceValue = (String)source;
if (AcceleoStandardLibrary.OPERATION_STRING_SUBSTITUTE.equals(operation.getName())) {
result = substitute(sourceValue, (String)args[0], (String)args[1], false);
} else if (AcceleoStandardLibrary.OPERATION_STRING_INDEX.equals(operation.getName())) {
// Increment java index value by 1 for OCL
result = sourceValue.indexOf((String)args[0]) + 1;
if (result == Integer.valueOf(0)) {
result = Integer.valueOf(-1);
}
} else if (AcceleoStandardLibrary.OPERATION_STRING_FIRST.equals(operation.getName())) {
int endIndex = ((Integer)args[0]).intValue();
if (endIndex < 0) {
result = env.getInvalidResult();
} else if (endIndex > sourceValue.length()) {
result = sourceValue;
} else {
result = sourceValue.substring(0, endIndex);
}
} else if (AcceleoStandardLibrary.OPERATION_STRING_LAST.equals(operation.getName())) {
int charCount = ((Integer)args[0]).intValue();
if (charCount < 0) {
result = env.getInvalidResult();
} else if (charCount > sourceValue.length()) {
result = sourceValue;
} else {
result = sourceValue.substring(sourceValue.length() - charCount, sourceValue.length());
}
} else if (AcceleoStandardLibrary.OPERATION_STRING_STRSTR.equals(operation.getName())) {
result = sourceValue.contains((String)args[0]);
} else if (AcceleoStandardLibrary.OPERATION_STRING_STRTOK.equals(operation.getName())) {
result = strtok(sourceValue, (String)args[0], (Integer)args[1]);
} else if (AcceleoStandardLibrary.OPERATION_STRING_STRCMP.equals(operation.getName())) {
result = sourceValue.compareTo((String)args[0]);
} else if (AcceleoStandardLibrary.OPERATION_STRING_ISALPHA.equals(operation.getName())) {
result = isAlpha(sourceValue);
} else if (AcceleoStandardLibrary.OPERATION_STRING_ISALPHANUM.equals(operation.getName())) {
result = isAlphanumeric(sourceValue);
} else if (AcceleoStandardLibrary.OPERATION_STRING_TOUPPERFIRST.equals(operation.getName())) {
if (sourceValue.length() == 0) {
result = sourceValue;
} else if (sourceValue.length() == 1) {
result = sourceValue.toUpperCase();
} else {
result = Character.toUpperCase(sourceValue.charAt(0)) + sourceValue.substring(1);
}
} else if (AcceleoStandardLibrary.OPERATION_STRING_TOLOWERFIRST.equals(operation.getName())) {
if (sourceValue.length() == 0) {
result = sourceValue;
} else if (sourceValue.length() == 1) {
result = sourceValue.toLowerCase();
} else {
result = Character.toLowerCase(sourceValue.charAt(0)) + sourceValue.substring(1);
}
}
} else if (source instanceof Integer || source instanceof Long) {
if (AcceleoStandardLibrary.OPERATION_INTEGER_TOSTRING.equals(operation.getName())) {
result = source.toString();
}
} else if (source instanceof Double || source instanceof Float) {
if (AcceleoStandardLibrary.OPERATION_REAL_TOSTRING.equals(operation.getName())) {
result = source.toString();
}
}
if (result != OPERATION_CALL_FAILED) {
return result;
}
// If we're here, the operation is undefined.
throw getExceptionOperationCallFailed(operation, source, args);
}
/**
* Clears all state that could have been memorized by this utility.
*/
public static void dispose() {
TOKENIZERS.clear();
if (referencer != null) {
referencer.clear();
referencer = null;
}
}
/**
* The environment will delegate operation calls to this method if it needs to evaluate non-standard
* EObject operations.
*
* @param operation
* Operation which is to be evaluated.
* @param source
* Source on which the operations is evaluated.
* @param args
* Arguments of the call.
* @return Result of the operation call.
*/
private static Object callNonStandardCollectionOperation(EOperation operation, Collection<?> source,
Object... args) {
Object result = OPERATION_CALL_FAILED;
final String operationName = operation.getName();
if (AcceleoNonStandardLibrary.OPERATION_COLLECTION_SEP.equals(operationName)) {
final Collection<Object> temp = new ArrayList<Object>(source.size() << 1);
final Iterator<?> sourceIterator = source.iterator();
while (sourceIterator.hasNext()) {
temp.add(sourceIterator.next());
if (sourceIterator.hasNext()) {
temp.add(args[0]);
}
}
result = temp;
} else if (AcceleoNonStandardLibrary.OPERATION_COLLECTION_FILTER.equals(operationName)) {
final Collection<Object> temp;
// Determine return type
if (source instanceof ArrayList) {
temp = CollectionUtil.createNewSequence();
} else if (source instanceof LinkedHashSet) {
temp = CollectionUtil.createNewOrderedSet();
} else if (source instanceof Set) {
temp = CollectionUtil.createNewSet();
} else {
temp = CollectionUtil.createNewBag();
}
final Iterator<?> sourceIterator = source.iterator();
while (sourceIterator.hasNext()) {
final Object next = sourceIterator.next();
if (((EClassifier)args[0]).isInstance(next)) {
temp.add(next);
}
}
result = temp;
} else if (AcceleoNonStandardLibrary.OPERATION_COLLECTION_REVERSE.equals(operationName)) {
final List<Object> temp = new ArrayList<Object>(source);
Collections.reverse(temp);
if (source instanceof LinkedHashSet<?>) {
final Set<Object> reversedSet = new LinkedHashSet<Object>(temp);
result = reversedSet;
} else {
result = temp;
}
} else if (AcceleoNonStandardLibrary.OPERATION_COLLECTION_LASTINDEXOF.equals(operationName)) {
final List<Object> temp = new ArrayList<Object>(source);
result = Integer.valueOf(temp.lastIndexOf(args[0]) + 1);
if (result == Integer.valueOf(0)) {
Integer.valueOf(-1);
}
}
return result;
}
/**
* The environment will delegate operation calls to this method if it needs to evaluate non-standard
* EObject operations.
*
* @param operation
* Operation which is to be evaluated.
* @param source
* Source on which the operations is evaluated.
* @param args
* Arguments of the call.
* @return Result of the operation call.
*/
private static Object callNonStandardEObjectOperation(EOperation operation, EObject source,
Object... args) {
Object result = OPERATION_CALL_FAILED;
final String operationName = operation.getName();
if (AcceleoNonStandardLibrary.OPERATION_EOBJECT_EALLCONTENTS.equals(operationName)) {
if (args.length == 0) {
result = eAllContents(source, null);
} else if (args.length == 1 && args[0] instanceof EClassifier) {
result = eAllContents(source, (EClassifier)args[0]);
}
// fall through : let else fail in UnsupportedOperationException
} else if (AcceleoNonStandardLibrary.OPERATION_EOBJECT_ANCESTORS.equals(operationName)) {
if (args.length == 0) {
result = ancestors(source, null);
} else if (args.length == 1 && args[0] instanceof EClassifier) {
result = ancestors(source, (EClassifier)args[0]);
}
// fall through : let else fail in UnsupportedOperationException
} else if (AcceleoNonStandardLibrary.OPERATION_EOBJECT_SIBLINGS.equals(operationName)) {
if (args.length == 0) {
result = siblings(source, null);
} else if (args.length == 1 && args[0] instanceof EClassifier) {
result = siblings(source, (EClassifier)args[0]);
}
// fall through : let else fail in UnsupportedOperationException
} else if (AcceleoNonStandardLibrary.OPERATION_EOBJECT_PRECEDINGSIBLINGS.equals(operationName)) {
if (args.length == 0) {
result = siblings(source, null, true);
} else if (args.length == 1 && args[0] instanceof EClassifier) {
result = siblings(source, (EClassifier)args[0], true);
}
// fall through : let else fail in UnsupportedOperationException
} else if (AcceleoNonStandardLibrary.OPERATION_EOBJECT_FOLLOWINGSIBLINGS.equals(operationName)) {
if (args.length == 0) {
result = siblings(source, null, false);
} else if (args.length == 1 && args[0] instanceof EClassifier) {
result = siblings(source, (EClassifier)args[0], false);
}
// fall through : let else fail in UnsupportedOperationException
} else if (AcceleoNonStandardLibrary.OPERATION_EOBJECT_EINVERSE.equals(operationName)) {
if (args.length == 0) {
result = eInverse(source, null);
} else if (args.length == 1 && args[0] instanceof EClassifier) {
result = eInverse(source, (EClassifier)args[0]);
}
// fall through : let else fail in UnsupportedOperationException
} else if (AcceleoNonStandardLibrary.OPERATION_EOBJECT_EGET.equals(operationName)) {
result = eGet(source, (String)args[0]);
} else if (AcceleoNonStandardLibrary.OPERATION_EOBJECT_ECONTAINER.equals(operationName)) {
result = eContainer(source, (EClassifier)args[0]);
} else if (AcceleoNonStandardLibrary.OPERATION_EOBJECT_ECONTENTS.equals(operationName)) {
result = eContents(source, (EClassifier)args[0]);
}
return result;
}
/**
* The environment will delegate operation calls to this method if it needs to evaluate non-standard
* String operations.
*
* @param operation
* Operation which is to be evaluated.
* @param source
* Source on which the operations is evaluated.
* @param args
* Arguments of the call.
* @return Result of the operation call.
*/
private static Object callNonStandardStringOperation(EOperation operation, String source, Object... args) {
Object result = OPERATION_CALL_FAILED;
final String operationName = operation.getName();
/*
* Note that because of OCL limitations, String::+(OclAny) will be handled before we even arrive here.
* See #callOperation().
*/
if (AcceleoNonStandardLibrary.OPERATION_STRING_SUBSTITUTEALL.equals(operationName)) {
result = substitute(source, (String)args[0], (String)args[1], true);
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_REPLACE.equals(operationName)) {
result = source.replaceFirst((String)args[0], (String)args[1]);
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_REPLACEALL.equals(operationName)) {
result = source.replaceAll((String)args[0], (String)args[1]);
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_ENDSWITH.equals(operationName)) {
result = source.endsWith((String)args[0]);
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_EQUALSIGNORECASE.equals(operationName)) {
result = source.equalsIgnoreCase((String)args[0]);
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_STARTSWITH.equals(operationName)) {
result = source.startsWith((String)args[0]);
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_TRIM.equals(operationName)) {
result = source.trim();
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_TOKENIZE.equals(operationName)) {
result = tokenize(source, (String)args[0]);
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_CONTAINS.equals(operationName)) {
result = source.contains((String)args[0]);
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_MATCHES.equals(operationName)) {
result = source.matches((String)args[0]);
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_LASTINDEX.equals(operationName)) {
// Increment java index value by 1 for OCL
result = source.lastIndexOf((String)args[0]) + 1;
if (result == Integer.valueOf(0)) {
result = Integer.valueOf(-1);
}
} else if (AcceleoNonStandardLibrary.OPERATION_STRING_SUBSTRING.equals(operationName)) {
result = source.substring(((Integer)args[0]).intValue() - 1);
}
return result;
}
/**
* Returns a Sequence containing the full set of <code>source</code>'s ancestors.
*
* @param source
* The EObject we seek the ancestors of.
* @param filter
* Types of the EObjects we seek to retrieve.
* @return Sequence containing the full set of the receiver's ancestors.
*/
private static List<EObject> ancestors(EObject source, EClassifier filter) {
final List<EObject> result = new ArrayList<EObject>();
EObject container = source.eContainer();
while (container != null) {
if (filter == null || filter.isInstance(container)) {
result.add(container);
}
container = container.eContainer();
}
return result;
}
/**
* Iterates over the content of the given EObject and returns the elements of type <code>filter</code>
* from its content tree as a list.
*
* @param source
* The EObject we seek the content tree of.
* @param filter
* Types of the EObjects we seek to retrieve.
* @return The given EObject's whole content tree as a list.
*/
private static List<EObject> eAllContents(EObject source, EClassifier filter) {
final TreeIterator<EObject> contentIterator = source.eAllContents();
final List<EObject> result = new ArrayList<EObject>();
while (contentIterator.hasNext()) {
final EObject next = contentIterator.next();
if (filter == null || filter.isInstance(next)) {
result.add(next);
}
}
return result;
}
/**
* Handles calls to the non standard operation "eContainer". This will retrieve the very first container
* in the hierarchy that is of type <em>filter</em>.
*
* @param source
* The EObject we seek to retrieve a feature value of.
* @param filter
* Types of the container we seek to retrieve.
* @return The first container of type <em>filter</em>.
*/
private static Object eContainer(EObject source, EClassifier filter) {
EObject container = source.eContainer();
while (!filter.isInstance(container)) {
container = container.eContainer();
}
return container;
}
/**
* Iterates over the direct children of the given EObject and returns the elements of type
* <code>filter</code> as a list.
*
* @param source
* The EObject we seek the content of.
* @param filter
* Types of the EObjects we seek to retrieve.
* @return The given EObject's children of type <em>filter</em> as a list.
*/
private static List<EObject> eContents(EObject source, EClassifier filter) {
final Iterator<EObject> contentIterator = source.eContents().iterator();
final List<EObject> result = new ArrayList<EObject>();
while (contentIterator.hasNext()) {
final EObject next = contentIterator.next();
if (filter == null || filter.isInstance(next)) {
result.add(next);
}
}
return result;
}
/**
* Handles calls to the non standard operation "eGet". This will fetch the value of the feature named
* <em>featureName</em> on <em>source</em>.
*
* @param source
* The EObject we seek to retrieve a feature value of.
* @param featureName
* Name of the feature which value we need to retrieve.
* @return Value of the given feature on the given object.
*/
private static Object eGet(EObject source, String featureName) {
Object result = null;
for (EStructuralFeature feature : source.eClass().getEAllStructuralFeatures()) {
if (feature.getName().equals(featureName)) {
result = source.eGet(feature);
}
}
return result;
}
/**
* Returns a Sequence containing the full set of the inverse references on the receiver.
*
* @param target
* The EObject we seek the inverse references of.
* @param filter
* Types of the EObjects we seek to retrieve.
* @return Sequence containing the full set of inverse references.
*/
private static Set<EObject> eInverse(EObject target, EClassifier filter) {
final Set<EObject> result = new LinkedHashSet<EObject>();
if (referencer == null) {
createEInverseCrossreferencer(target);
}
Collection<EStructuralFeature.Setting> settings = referencer.get(target);
if (settings == null) {
return Collections.emptySet();
}
for (EStructuralFeature.Setting setting : settings) {
if (filter == null || filter.isInstance(setting.getEObject())) {
result.add(setting.getEObject());
}
}
return result;
}
/**
* This will create the cross referencer that's to be used by the "eInverse" library. It will attempt to
* create the cross referencer on the target's resourceSet. If it is null, we'll then attempt to create
* the cross referencer on the target's resource. When the resource too is null, we'll create the cross
* referencer on the target's root container.
*
* @param target
* Target of the cross referencing.
*/
private static void createEInverseCrossreferencer(EObject target) {
if (target.eResource() != null && target.eResource().getResourceSet() != null) {
final ResourceSet rs = target.eResource().getResourceSet();
final ContentTreeIterator<Notifier> contentIterator = new ContentTreeIterator<Notifier>(
Collections.singleton(rs)) {
/** Default SUID. */
private static final long serialVersionUID = 1L;
@Override
protected Iterator<Resource> getResourceSetChildren(ResourceSet resourceSet) {
List<Resource> resources = new ArrayList<Resource>();
for (Resource res : resourceSet.getResources()) {
if (!IAcceleoConstants.EMTL_FILE_EXTENSION.equals(res.getURI().fileExtension())) {
resources.add(res);
}
}
resourceSetIterator = new ResourcesIterator(resources);
return resourceSetIterator;
}
};
referencer = new CrossReferencer(rs) {
/** Default SUID. */
private static final long serialVersionUID = 1L;
// static initializer
{
crossReference();
}
@Override
protected TreeIterator<Notifier> newContentsIterator() {
return contentIterator;
}
};
} else if (target.eResource() != null) {
referencer = new CrossReferencer(target.eResource()) {
/** Default SUID. */
private static final long serialVersionUID = 1L;
// static initializer
{
crossReference();
}
};
} else {
referencer = new CrossReferencer(EcoreUtil.getRootContainer(target)) {
/** Default SUID. */
private static final long serialVersionUID = 1L;
// static initializer
{
crossReference();
}
};
}
}
/**
* This will search the first context value corresponding to the given filter or index.
*
* @param env
* The environment that asked for this evaluation.
* @param args
* Arguments of the invocation.
* @return Result of the invocation.
*/
private static Object getContext(AcceleoEvaluationEnvironment env, Object[] args) {
final Object soughtValue;
final List<Object> allIterators = new ArrayList<Object>();
int index = 0;
Object value = env.getValueOf(TEMPORARY_CONTEXT_VAR_PREFIX + index++);
while (value != null) {
allIterators.add(value);
value = env.getValueOf(TEMPORARY_CONTEXT_VAR_PREFIX + index++);
}
if (args[0] instanceof Integer) {
int soughtIndex = ((Integer)args[0]).intValue();
if (soughtIndex > allIterators.size() - 1) {
soughtValue = allIterators.get(0);
} else {
soughtValue = allIterators.get(allIterators.size() - soughtIndex - 1);
}
} else {
final EClassifier filter = (EClassifier)args[0];
for (int i = allIterators.size() - 1; i >= 0; i--) {
if (filter.isInstance(allIterators.get(i))) {
value = allIterators.get(i);
break;
}
}
// "value" is null if there were no iterators of the expected type
soughtValue = value;
}
return soughtValue;
}
/**
* This will be used whenever the environment tried to call a custom EOperation and failed.
*
* @param operation
* Operation which is to be evaluated.
* @param source
* Source on which the operations is evaluated.
* @param args
* Arguments of the call.
* @return The ready-to-throw exception.
*/
private static UnsupportedOperationException getExceptionOperationCallFailed(EOperation operation,
Object source, Object... args) {
final StringBuilder argErrorMsg = new StringBuilder();
for (int i = 0; i < args.length; i++) {
argErrorMsg.append(args[i].getClass().getSimpleName());
if (i < args.length - 1) {
argErrorMsg.append(", "); //$NON-NLS-1$
}
}
final String sourceName;
if (source == null) {
sourceName = "null"; //$NON-NLS-1$
} else {
sourceName = source.getClass().getName();
}
return new UnsupportedOperationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.UndefinedOperation", operation.getName(), argErrorMsg //$NON-NLS-1$
.toString(), sourceName));
}
/**
* This will return the value of the property corresponding to the given key. Precedence rules for the
* properties can be found in the javadoc of
* {@link org.eclipse.acceleo.engine.generation.IAcceleoEngine#addProperties(String)}.
*
* @param env
* The environment that asked for this evaluation.
* @param key
* Key of the property which value is to be returned.
* @return The value of the property corresponding to the given key.
*/
private static String getProperty(AcceleoEvaluationEnvironment env, String key) {
String propertyValue = env.getPropertiesLookup().getProperty(key);
/*
* Pass through MessageFormat so that we're consistent in the handling of special chars such as the
* apostrophe.
*/
if (propertyValue != null) {
propertyValue = MessageFormat.format(propertyValue, new Object[] {});
}
return propertyValue;
}
/**
* This will return the value of the property corresponding to the given key, with parameters substituted
* as needed. Precedence rules for the properties can be found in the javadoc of
* {@link org.eclipse.acceleo.engine.generation.IAcceleoEngine#addProperties(String)}.
*
* @param env
* The environment that asked for this evaluation.
* @param key
* Key of the property which value is to be returned.
* @param arguments
* Substitution for the property parameters.
* @return The value of the property corresponding to the given key.
*/
private static String getProperty(AcceleoEvaluationEnvironment env, String key, Object[] arguments) {
String propertyValue = env.getPropertiesLookup().getProperty(key);
if (propertyValue != null) {
propertyValue = MessageFormat.format(propertyValue, arguments);
}
return propertyValue;
}
/**
* This will return the value of the property corresponding to the given key from the first properties
* holder of the given name. Precedence rules for the properties can be found in the javadoc of
* {@link org.eclipse.acceleo.engine.generation.IAcceleoEngine#addProperties(String)}.
*
* @param env
* The environment that asked for this evaluation.
* @param propertiesFileName
* Name of the properties file in which we seek the given key.
* @param key
* Key of the property which value is to be returned.
* @return The value of the property corresponding to the given key.
*/
private static String getProperty(AcceleoEvaluationEnvironment env, String propertiesFileName, String key) {
String propertyValue = env.getPropertiesLookup().getProperty(propertiesFileName, key);
/*
* Pass through MessageFormat so that we're consistent in the handling of special chars such as the
* apostrophe.
*/
if (propertyValue != null) {
propertyValue = MessageFormat.format(propertyValue, new Object[] {});
}
return propertyValue;
}
/**
* This will return the value of the property corresponding to the given key from the first properties
* holder of the given name, with parameters substituted as needed. Precedence rules for the properties
* can be found in the javadoc of
* {@link org.eclipse.acceleo.engine.generation.IAcceleoEngine#addProperties(String)}.
*
* @param env
* The environment that asked for this evaluation.
* @param propertiesFileName
* Name of the properties file in which we seek the given key.
* @param key
* Key of the property which value is to be returned.
* @param arguments
* Substitution for the property parameters.
* @return The value of the property corresponding to the given key.
*/
private static String getProperty(AcceleoEvaluationEnvironment env, String propertiesFileName,
String key, Object[] arguments) {
String propertyValue = env.getPropertiesLookup().getProperty(propertiesFileName, key);
if (propertyValue != null) {
propertyValue = MessageFormat.format(propertyValue, arguments);
}
return propertyValue;
}
/**
* Handles the invocation of a service.
*
* @param moduleURI
* URI of the module which is currently being evaluated.
* @param source
* Receiver of the invocation. It will be passed as the first argument of the service
* invocation.
* @param args
* Arguments of the invocation. May not contain the receiver, in which case it will be set as
* the first argument.
* @return Result of the invocation.
*/
@SuppressWarnings("unchecked")
private static Object invoke(URI moduleURI, Object source, Object[] args) {
Object result = null;
final Object serviceInstance = AcceleoServicesRegistry.INSTANCE
.addService(moduleURI, (String)args[0]);
if (serviceInstance == null) {
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.ClassNotFound", args[0], moduleURI.lastSegment())); //$NON-NLS-1$
}
final Class<?> serviceClass = serviceInstance.getClass();
final String methodSignature = (String)args[1];
final Method method;
try {
final int openParenthesisIndex = methodSignature.indexOf('(');
if (openParenthesisIndex != -1) {
final String methodName = methodSignature.substring(0, openParenthesisIndex);
final int closeParenthesisIndex = methodSignature.indexOf(')');
if (closeParenthesisIndex - openParenthesisIndex > 1) {
final String parameterTypesString = methodSignature.substring(openParenthesisIndex + 1,
closeParenthesisIndex);
final List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
int nextCommaIndex = parameterTypesString.indexOf(',');
int previousComma = 0;
while (nextCommaIndex != -1) {
final String parameterType = parameterTypesString.substring(previousComma,
nextCommaIndex).trim();
if (PRIMITIVE_TYPES.containsKey(parameterType)) {
parameterTypes.add(PRIMITIVE_TYPES.get(parameterType));
} else if (serviceInstance.getClass().getClassLoader() != null) {
parameterTypes.add(serviceInstance.getClass().getClassLoader().loadClass(
parameterType));
} else {
parameterTypes.add(Class.forName(parameterType));
}
previousComma = nextCommaIndex + 1;
- nextCommaIndex = parameterTypesString.indexOf(nextCommaIndex, ',');
+ nextCommaIndex = parameterTypesString.indexOf(',', previousComma);
}
/*
* The last (or only) parameter type is not followed by a comma and not handled in the
* while
*/
final String parameterType = parameterTypesString.substring(previousComma,
parameterTypesString.length()).trim();
if (PRIMITIVE_TYPES.containsKey(parameterType)) {
parameterTypes.add(PRIMITIVE_TYPES.get(parameterType));
} else if (serviceInstance.getClass().getClassLoader() != null) {
parameterTypes.add(serviceInstance.getClass().getClassLoader().loadClass(
parameterType));
} else {
parameterTypes.add(Class.forName(parameterType));
}
method = serviceClass.getMethod(methodName, parameterTypes
.toArray(new Class[parameterTypes.size()]));
} else {
method = serviceClass.getMethod(methodName);
}
} else {
method = serviceClass.getMethod(methodSignature);
}
// method cannot be null at this point. getMetod has thrown an exception in such cases
assert method != null;
final List<Object> invocationArguments = (List<Object>)args[2];
if (method.getParameterTypes().length == 0) {
if (invocationArguments.size() == 0) {
result = method.invoke(source);
} else {
result = method.invoke(invocationArguments.get(0));
}
} else {
if (method.getParameterTypes().length - invocationArguments.size() == 1) {
invocationArguments.add(0, source);
}
if (method.getParameterTypes().length - invocationArguments.size() == -1) {
final Object swappedSource = invocationArguments.remove(0);
result = method.invoke(swappedSource, invocationArguments
.toArray(new Object[invocationArguments.size()]));
} else {
result = method.invoke(serviceInstance, invocationArguments
.toArray(new Object[invocationArguments.size()]));
}
}
} catch (NoSuchMethodException e) {
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.NoSuchMethod", args[1], args[0]), e); //$NON-NLS-1$
} catch (IllegalArgumentException e) {
throw new AcceleoEvaluationException(e.getMessage(), e);
} catch (IllegalAccessException e) {
/*
* Shouldn't happen. We retrieve methods through Class#getMethod() which only iterates over public
* members.
*/
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.RestrictedMethod", args[1], args[0]), e); //$NON-NLS-1$
} catch (InvocationTargetException e) {
throw new AcceleoEvaluationException(e.getMessage(), e);
} catch (ClassNotFoundException e) {
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.ParameterClassNotFound", args[1], args[0]), e); //$NON-NLS-1$
}
return result;
}
/**
* This will return true if all of the given String's characters are considered letters as per
* {@link Character#isLetter(char)}.
*
* @param s
* The String to consider.
* @return <code>true</code> if the String is composed of letters only, <code>false</code> otherwise.
*/
private static boolean isAlpha(String s) {
final char[] chars = s.toCharArray();
for (final char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
return true;
}
/**
* This will return true if all of the given String's characters are considered letters or digits as per
* {@link Character#isLetterOrDigit(char)}.
*
* @param s
* The String to consider.
* @return <code>true</code> if the String is composed of letters and digits only, <code>false</code>
* otherwise.
*/
private static boolean isAlphanumeric(String s) {
final char[] chars = s.toCharArray();
for (final char c : chars) {
if (!Character.isLetterOrDigit(c)) {
return false;
}
}
return true;
}
/**
* Returns a Sequence containing the full set of <code>source</code>'s siblings.
*
* @param source
* The EObject we seek the siblings of.
* @param filter
* Types of the EObjects we seek to retrieve.
* @return Sequence containing the full set of the receiver's siblings.
*/
private static List<EObject> siblings(EObject source, EClassifier filter) {
final List<EObject> result = new ArrayList<EObject>();
EObject container = source.eContainer();
for (EObject child : getContents(container)) {
if (child != source && (filter == null || filter.isInstance(child))) {
result.add(child);
}
}
return result;
}
/**
* Returns a Sequence containing either all preceding siblings of <code>source</code>, or all of its
* following siblings.
*
* @param source
* The EObject we seek the siblings of.
* @param filter
* Types of the EObjects we seek to retrieve.
* @param preceding
* If <code>true</code>, we'll return the preceding siblings of <em>source</em>. Otherwise,
* this will return its followingSiblings.
* @return Sequence containing the sought set of the receiver's siblings.
*/
private static List<EObject> siblings(EObject source, EClassifier filter, boolean preceding) {
final List<EObject> result = new ArrayList<EObject>();
final EObject container = source.eContainer();
final List<EObject> siblings = getContents(container);
int startIndex = 0;
int endIndex = siblings.size();
if (preceding) {
endIndex = siblings.indexOf(source);
} else {
startIndex = siblings.indexOf(source) + 1;
}
for (int i = startIndex; i < endIndex; i++) {
EObject child = siblings.get(i);
if (filter == null || filter.isInstance(child)) {
result.add(child);
}
}
return result;
}
/**
* Implements the Acceleo Standard library "strtok(String, Integer)" operation. This will make use of the
* StringTokenizer class and cache the result in order to reuse it as needed.
* <p>
* <b>Note</b> that this will <b>not</b> fail if called with <code>flag</code> set to <code>1</code> when
* no tokens remains in the source String. As the behavior in such a case is not specified by the official
* Acceleo specification, we'll return the empty String instead.
* </p>
*
* @param source
* Source String in which tokenization has to take place.
* @param delimiters
* Delimiters around which the <code>source</code> has to be split.
* @param flag
* The value of this influences the token that needs be returned. A value of <code>0</code>
* means the very first token will be returned, a value of <code>1</code> means the returned
* token will be the next (as compared to the last one that's been returned).
* @return The first of all tokens if <code>flag</code> is <code>0</code>, the next token if
* <code>flag</code> is <code>1</code>. Fails in {@link AcceleoEvaluationException} otherwise.
*/
private static String strtok(String source, String delimiters, Integer flag) {
// flag == 0, create a tokenizer, cache it then return its first element.
/*
* flag == 1, create the tokenizer if none exists for this source, retrieve the existing one
* otherwise. Then returns the next token in it.
*/
if (flag.intValue() == 0) {
final StringTokenizer tokenizer = new StringTokenizer(source, delimiters);
TOKENIZERS.put(source, tokenizer);
return tokenizer.nextToken();
} else if (flag.intValue() == 1) {
StringTokenizer tokenizer = TOKENIZERS.get(source);
if (tokenizer == null) {
tokenizer = new StringTokenizer(source, delimiters);
TOKENIZERS.put(source, tokenizer);
}
String token = ""; //$NON-NLS-1$
if (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
}
return token;
}
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.IllegalTokenizerFlag", flag)); //$NON-NLS-1$
}
/**
* Implements the Acceleo standard library's "substitute(String, String)" and non-standard library's
* "substituteAll(String, String)" operation. It will replace either the first or all occurences of a
* given <code>substring</code> in the <code>source</code> by the <code>replacement</code>
* String.<b>Neither <code>substring</code> nor <code>replacement</code> are considered regular
* expressions.</b>
*
* @param source
* Source String in which the substitution has to take place.
* @param substring
* Substring which is to be replaced.
* @param replacement
* String that will be substituted to the sought one.
* @param substituteAll
* Indicates wheter we should substitute all occurences of the substring or only the first.
* @return <code>source</code> with substitution executed, <code>source</code> itself if the substring
* hasn't been found.
*/
private static String substitute(String source, String substring, String replacement,
boolean substituteAll) {
if (substring == null || replacement == null) {
throw new NullPointerException();
}
// substitute replaces Strings, not regexes.
// Surrounding the regex with \Q [...] \E allows just that
final String regex = "\\Q" + substring + "\\E"; //$NON-NLS-1$ //$NON-NLS-2$
// We also need to escape backslashes and dollar signs in the replacement (scary!)
final String replacementValue = replacement.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\$", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"\\\\\\$"); //$NON-NLS-1$
if (substituteAll) {
return source.replaceAll(regex, replacementValue);
}
return source.replaceFirst(regex, replacementValue);
}
/**
* Implements the "tokenize" operation on String type. This will return a sequence containing the tokens
* of the given string (using <code>delim</code> as delimiter).
*
* @param source
* Source String that is to be tokenized.
* @param delim
* The delimiters around which the <code>source</code> is to be split.
* @return A sequence containing the tokens of the given.
*/
private static List<String> tokenize(String source, String delim) {
final StringTokenizer tokenizer = new StringTokenizer(source, delim);
List<String> result = new ArrayList<String>();
while (tokenizer.hasMoreTokens()) {
result.add(tokenizer.nextToken());
}
return result;
}
/**
* Collections need special handling when generated from Acceleo.
*
* @param object
* The object we wish the String representation of.
* @return String representation of the given Object. For Collections, this will be the concatenation of
* all contained Objects' toString.
*/
private static String toString(Object object) {
final StringBuffer buffer = new StringBuffer();
if (object instanceof Collection<?>) {
final Iterator<?> childrenIterator = ((Collection<?>)object).iterator();
while (childrenIterator.hasNext()) {
buffer.append(toString(childrenIterator.next()));
}
} else if (object != null) {
buffer.append(object.toString());
}
// else return empty String
return buffer.toString();
}
/**
* Elements held by a reference with containment=true and derived=true are not returned by
* {@link EObject#eContents()}. This allows us to return the list of all contents from an EObject
* <b>including</b> those references.
*
* @param eObject
* The EObject we seek the content of.
* @return The list of all the content of a given EObject, derived containmnent references included.
*/
private static List<EObject> getContents(EObject eObject) {
final List<EObject> result = new ArrayList<EObject>(eObject.eContents());
for (final EReference reference : eObject.eClass().getEAllReferences()) {
if (reference.isContainment() && reference.isDerived()) {
final Object value = eObject.eGet(reference);
if (value instanceof Collection<?>) {
for (Object newValue : (Collection<?>)value) {
if (!result.contains(newValue) && newValue instanceof EObject) {
result.add((EObject)newValue);
}
}
} else if (!result.contains(value) && value instanceof EObject) {
result.add((EObject)value);
}
}
}
return result;
}
}
| true | true | private static Object invoke(URI moduleURI, Object source, Object[] args) {
Object result = null;
final Object serviceInstance = AcceleoServicesRegistry.INSTANCE
.addService(moduleURI, (String)args[0]);
if (serviceInstance == null) {
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.ClassNotFound", args[0], moduleURI.lastSegment())); //$NON-NLS-1$
}
final Class<?> serviceClass = serviceInstance.getClass();
final String methodSignature = (String)args[1];
final Method method;
try {
final int openParenthesisIndex = methodSignature.indexOf('(');
if (openParenthesisIndex != -1) {
final String methodName = methodSignature.substring(0, openParenthesisIndex);
final int closeParenthesisIndex = methodSignature.indexOf(')');
if (closeParenthesisIndex - openParenthesisIndex > 1) {
final String parameterTypesString = methodSignature.substring(openParenthesisIndex + 1,
closeParenthesisIndex);
final List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
int nextCommaIndex = parameterTypesString.indexOf(',');
int previousComma = 0;
while (nextCommaIndex != -1) {
final String parameterType = parameterTypesString.substring(previousComma,
nextCommaIndex).trim();
if (PRIMITIVE_TYPES.containsKey(parameterType)) {
parameterTypes.add(PRIMITIVE_TYPES.get(parameterType));
} else if (serviceInstance.getClass().getClassLoader() != null) {
parameterTypes.add(serviceInstance.getClass().getClassLoader().loadClass(
parameterType));
} else {
parameterTypes.add(Class.forName(parameterType));
}
previousComma = nextCommaIndex + 1;
nextCommaIndex = parameterTypesString.indexOf(nextCommaIndex, ',');
}
/*
* The last (or only) parameter type is not followed by a comma and not handled in the
* while
*/
final String parameterType = parameterTypesString.substring(previousComma,
parameterTypesString.length()).trim();
if (PRIMITIVE_TYPES.containsKey(parameterType)) {
parameterTypes.add(PRIMITIVE_TYPES.get(parameterType));
} else if (serviceInstance.getClass().getClassLoader() != null) {
parameterTypes.add(serviceInstance.getClass().getClassLoader().loadClass(
parameterType));
} else {
parameterTypes.add(Class.forName(parameterType));
}
method = serviceClass.getMethod(methodName, parameterTypes
.toArray(new Class[parameterTypes.size()]));
} else {
method = serviceClass.getMethod(methodName);
}
} else {
method = serviceClass.getMethod(methodSignature);
}
// method cannot be null at this point. getMetod has thrown an exception in such cases
assert method != null;
final List<Object> invocationArguments = (List<Object>)args[2];
if (method.getParameterTypes().length == 0) {
if (invocationArguments.size() == 0) {
result = method.invoke(source);
} else {
result = method.invoke(invocationArguments.get(0));
}
} else {
if (method.getParameterTypes().length - invocationArguments.size() == 1) {
invocationArguments.add(0, source);
}
if (method.getParameterTypes().length - invocationArguments.size() == -1) {
final Object swappedSource = invocationArguments.remove(0);
result = method.invoke(swappedSource, invocationArguments
.toArray(new Object[invocationArguments.size()]));
} else {
result = method.invoke(serviceInstance, invocationArguments
.toArray(new Object[invocationArguments.size()]));
}
}
} catch (NoSuchMethodException e) {
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.NoSuchMethod", args[1], args[0]), e); //$NON-NLS-1$
} catch (IllegalArgumentException e) {
throw new AcceleoEvaluationException(e.getMessage(), e);
} catch (IllegalAccessException e) {
/*
* Shouldn't happen. We retrieve methods through Class#getMethod() which only iterates over public
* members.
*/
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.RestrictedMethod", args[1], args[0]), e); //$NON-NLS-1$
} catch (InvocationTargetException e) {
throw new AcceleoEvaluationException(e.getMessage(), e);
} catch (ClassNotFoundException e) {
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.ParameterClassNotFound", args[1], args[0]), e); //$NON-NLS-1$
}
return result;
}
| private static Object invoke(URI moduleURI, Object source, Object[] args) {
Object result = null;
final Object serviceInstance = AcceleoServicesRegistry.INSTANCE
.addService(moduleURI, (String)args[0]);
if (serviceInstance == null) {
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.ClassNotFound", args[0], moduleURI.lastSegment())); //$NON-NLS-1$
}
final Class<?> serviceClass = serviceInstance.getClass();
final String methodSignature = (String)args[1];
final Method method;
try {
final int openParenthesisIndex = methodSignature.indexOf('(');
if (openParenthesisIndex != -1) {
final String methodName = methodSignature.substring(0, openParenthesisIndex);
final int closeParenthesisIndex = methodSignature.indexOf(')');
if (closeParenthesisIndex - openParenthesisIndex > 1) {
final String parameterTypesString = methodSignature.substring(openParenthesisIndex + 1,
closeParenthesisIndex);
final List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
int nextCommaIndex = parameterTypesString.indexOf(',');
int previousComma = 0;
while (nextCommaIndex != -1) {
final String parameterType = parameterTypesString.substring(previousComma,
nextCommaIndex).trim();
if (PRIMITIVE_TYPES.containsKey(parameterType)) {
parameterTypes.add(PRIMITIVE_TYPES.get(parameterType));
} else if (serviceInstance.getClass().getClassLoader() != null) {
parameterTypes.add(serviceInstance.getClass().getClassLoader().loadClass(
parameterType));
} else {
parameterTypes.add(Class.forName(parameterType));
}
previousComma = nextCommaIndex + 1;
nextCommaIndex = parameterTypesString.indexOf(',', previousComma);
}
/*
* The last (or only) parameter type is not followed by a comma and not handled in the
* while
*/
final String parameterType = parameterTypesString.substring(previousComma,
parameterTypesString.length()).trim();
if (PRIMITIVE_TYPES.containsKey(parameterType)) {
parameterTypes.add(PRIMITIVE_TYPES.get(parameterType));
} else if (serviceInstance.getClass().getClassLoader() != null) {
parameterTypes.add(serviceInstance.getClass().getClassLoader().loadClass(
parameterType));
} else {
parameterTypes.add(Class.forName(parameterType));
}
method = serviceClass.getMethod(methodName, parameterTypes
.toArray(new Class[parameterTypes.size()]));
} else {
method = serviceClass.getMethod(methodName);
}
} else {
method = serviceClass.getMethod(methodSignature);
}
// method cannot be null at this point. getMetod has thrown an exception in such cases
assert method != null;
final List<Object> invocationArguments = (List<Object>)args[2];
if (method.getParameterTypes().length == 0) {
if (invocationArguments.size() == 0) {
result = method.invoke(source);
} else {
result = method.invoke(invocationArguments.get(0));
}
} else {
if (method.getParameterTypes().length - invocationArguments.size() == 1) {
invocationArguments.add(0, source);
}
if (method.getParameterTypes().length - invocationArguments.size() == -1) {
final Object swappedSource = invocationArguments.remove(0);
result = method.invoke(swappedSource, invocationArguments
.toArray(new Object[invocationArguments.size()]));
} else {
result = method.invoke(serviceInstance, invocationArguments
.toArray(new Object[invocationArguments.size()]));
}
}
} catch (NoSuchMethodException e) {
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.NoSuchMethod", args[1], args[0]), e); //$NON-NLS-1$
} catch (IllegalArgumentException e) {
throw new AcceleoEvaluationException(e.getMessage(), e);
} catch (IllegalAccessException e) {
/*
* Shouldn't happen. We retrieve methods through Class#getMethod() which only iterates over public
* members.
*/
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.RestrictedMethod", args[1], args[0]), e); //$NON-NLS-1$
} catch (InvocationTargetException e) {
throw new AcceleoEvaluationException(e.getMessage(), e);
} catch (ClassNotFoundException e) {
throw new AcceleoEvaluationException(AcceleoEngineMessages.getString(
"AcceleoEvaluationEnvironment.ParameterClassNotFound", args[1], args[0]), e); //$NON-NLS-1$
}
return result;
}
|
diff --git a/src/org/vesalainen/parsers/sql/dsql/DatastoreEngine.java b/src/org/vesalainen/parsers/sql/dsql/DatastoreEngine.java
index b47c139..4448a36 100644
--- a/src/org/vesalainen/parsers/sql/dsql/DatastoreEngine.java
+++ b/src/org/vesalainen/parsers/sql/dsql/DatastoreEngine.java
@@ -1,588 +1,589 @@
/*
* Copyright (C) 2012 Timo Vesalainen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.vesalainen.parsers.sql.dsql;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Index;
import com.google.appengine.api.datastore.Index.IndexState;
import com.google.appengine.api.datastore.Index.Property;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.PropertyProjection;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.TransactionOptions;
import com.google.appengine.api.mail.MailService;
import com.google.appengine.api.mail.MailService.Message;
import com.google.appengine.api.mail.MailServiceFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableSet;
import java.util.Properties;
import java.util.Set;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import org.vesalainen.parsers.sql.ColumnCondition;
import org.vesalainen.parsers.sql.ColumnMetadata;
import org.vesalainen.parsers.sql.ColumnReference;
import org.vesalainen.parsers.sql.FetchResult;
import org.vesalainen.parsers.sql.InsertStatement;
import org.vesalainen.parsers.sql.JoinCondition;
import org.vesalainen.parsers.sql.Relation;
import org.vesalainen.parsers.sql.SQLConverter;
import org.vesalainen.parsers.sql.Table;
import org.vesalainen.parsers.sql.TableContext;
import org.vesalainen.parsers.sql.TableMetadata;
import org.vesalainen.parsers.sql.TruthValue;
import org.vesalainen.parsers.sql.ValueComparisonCondition;
/**
* @author Timo Vesalainen
*/
public class DatastoreEngine implements DSProxyInterface
{
private static final int CHUNKSIZE = 500;
private DatastoreService datastore;
private Statistics statistics;
private SQLConverter converter;
private MailService mailService = MailServiceFactory.getMailService();
private Session session = Session.getDefaultInstance(new Properties(), null);
public DatastoreEngine(DatastoreService datastore)
{
this.datastore = datastore;
if (statistics == null)
{
statistics = new Statistics(datastore);
}
}
public void setConverter(SQLConverter converter)
{
this.converter = converter;
}
@Override
public Collection<Entity> fetch(Table<Entity,Object> table)
{
String kind = table.getName();
TableMetadata kindStats = statistics.getKind(kind);
Query query = new Query(kind);
List<ColumnCondition<Entity, Object>> locals = new ArrayList<>();
for (ColumnCondition<Entity, Object> columnCondition : table.getAndConditions())
{
if (columnCondition instanceof ValueComparisonCondition)
{
ValueComparisonCondition<Entity, Object> ccc = (ValueComparisonCondition) columnCondition;
handleValueComparisonCondition(ccc, query, locals, kindStats);
}
else
{
locals.add(columnCondition);
}
}
checkKeysOnlyAndProjection(query, table, false);
return fetchAndFilter(query, locals);
}
@Override
public Collection<Entity> fetch(TableContext<Entity,Object> tc, boolean update)
{
DSTable<Entity,Object> table = (DSTable) tc.getTable();
String kind = table.getName();
TableMetadata kindStats = statistics.getKind(kind);
Query query = new Query(kind);
DSTable ancestor = table.getAncestor();
if (ancestor != null)
{
TableContext otherCtx = tc.getOther(ancestor);
if (otherCtx.hasData())
{
NavigableSet<Object> columnValues = otherCtx.getColumnValues(Entity.KEY_RESERVED_PROPERTY);
if (columnValues.size() == 1)
{
query.setAncestor((Key)columnValues.first());
}
}
}
List<ColumnCondition<Entity, Object>> locals = new ArrayList<>();
for (ColumnCondition<Entity, Object> columnCondition : table.getAndConditions())
{
if (columnCondition instanceof ParentOfCondition)
{
ParentOfCondition poc = (ParentOfCondition) columnCondition;
handleParentOfCondition(tc, poc, query);
}
else
{
if (columnCondition instanceof ValueComparisonCondition)
{
ValueComparisonCondition<Entity, Object> ccc = (ValueComparisonCondition) columnCondition;
handleValueComparisonCondition(ccc, query, locals, kindStats);
}
else
{
if (columnCondition instanceof JoinCondition)
{
JoinCondition<Entity, Object> jc = (JoinCondition) columnCondition;
boolean cont = handleJoinCondition(jc, tc, query, kindStats);
if (!cont)
{
return new ArrayList<>();
}
}
else
{
locals.add(columnCondition);
}
}
}
}
checkKeysOnlyAndProjection(query, table, update);
return fetchAndFilter(query, locals);
}
private Query.FilterOperator convertRelation(Relation relation)
{
switch (relation)
{
case EQ:
return Query.FilterOperator.EQUAL;
case NE:
return Query.FilterOperator.NOT_EQUAL;
case LE:
return Query.FilterOperator.LESS_THAN_OR_EQUAL;
case LT:
return Query.FilterOperator.LESS_THAN;
case GE:
return Query.FilterOperator.GREATER_THAN_OR_EQUAL;
case GT:
return Query.FilterOperator.GREATER_THAN;
default:
throw new IllegalArgumentException(relation+" not supported");
}
}
@Override
public void update(Collection<Entity> rows)
{
datastore.put(rows);
}
@Override
public void delete(Collection<Entity> rows)
{
List<Key> keys = new ArrayList<>();
for (Entity entity : rows)
{
keys.add(entity.getKey());
}
datastore.delete(keys);
}
@Override
public void insert(InsertStatement insertStatement)
{
Table table = insertStatement.getTable();
String kind = table.getName();
FetchResult<Entity,Object> result = insertStatement.getFetchResult();
for (int row=0;row<result.getRowCount();row++)
{
Entity entity = null;
Key key = (Key) result.getValueAt(row, Entity.KEY_RESERVED_PROPERTY);
if (key != null)
{
if (!key.getKind().equals(kind))
{
insertStatement.throwException(key+" key <> tablename "+kind);
}
entity = new Entity(key);
}
else
{
entity = new Entity(kind);
}
int keyIndex = result.getColumnIndex(Entity.KEY_RESERVED_PROPERTY);
for (int col=0;col<result.getColumnCount();col++)
{
if (col != keyIndex)
{
Object value = result.getValueAt(row, col);
if (value != null)
{
String columnName = result.getColumnName(col);
ColumnMetadata cm = statistics.getProperty(kind, columnName);
if (cm != null && !cm.isIndexed())
{
entity.setUnindexedProperty(columnName, value);
}
else
{
entity.setProperty(columnName, value);
}
}
}
}
datastore.put(entity);
}
}
private void handleParentOfCondition(TableContext<Entity, Object> tc, ParentOfCondition poc, Query query)
{
ColumnReference otherCf = poc.getColumnReference2();
Table otherTab = otherCf.getTable();
TableContext otherCt = tc.getOther(otherTab);
if (otherCt.hasData())
{
NavigableSet<Object> columnValues = otherCt.getColumnValues(Entity.KEY_RESERVED_PROPERTY);
if (columnValues.size() == 1)
{
query.setAncestor((Key)columnValues.first());
}
}
}
private void handleValueComparisonCondition(ValueComparisonCondition<Entity, Object> ccc, Query query, List<ColumnCondition<Entity, Object>> locals, TableMetadata kindStats)
{
String property = ccc.getColumn();
if (kindStats != null)
{
ColumnMetadata propertyStats = kindStats.getColumnMetadata(property);
if (propertyStats != null && propertyStats.isIndexed())
{
query.addFilter(property, convertRelation(ccc.getRelation()), ccc.getValue());
return;
}
}
locals.add(ccc);
}
private boolean handleJoinCondition(JoinCondition<Entity, Object> jc, TableContext tc, Query query, TableMetadata kindStats)
{
String property = jc.getColumn();
if (kindStats != null)
{
ColumnMetadata propertyStats = kindStats.getColumnMetadata(property);
if (Relation.EQ.equals(jc.getRelation()))
{
ColumnReference cf = jc.getColumnReference2();
Table otherTable = cf.getTable();
TableContext otherCtx = tc.getOther(otherTable);
if (otherCtx.hasData())
{
NavigableSet<Object> columnValues = otherCtx.getColumnValues(cf.getColumn());
switch (columnValues.size())
{
case 0:
return false;
case 1:
if (propertyStats != null && propertyStats.isIndexed())
{
query.addFilter(property, Query.FilterOperator.EQUAL, columnValues.first());
}
break;
default:
if (propertyStats != null && propertyStats.isIndexed())
{
query.addFilter(property, Query.FilterOperator.GREATER_THAN_OR_EQUAL, columnValues.first());
query.addFilter(property, Query.FilterOperator.LESS_THAN_OR_EQUAL, columnValues.last());
}
break;
}
}
}
}
return true;
}
private Collection<Entity> fetchAndFilter(Query query, List<ColumnCondition<Entity, Object>> locals)
{
System.err.println(query);
PreparedQuery prepared = datastore.prepare(query);
List<Entity> list = prepared.asList(FetchOptions.Builder.withChunkSize(CHUNKSIZE));
if (!locals.isEmpty())
{
List<Entity> flist = new ArrayList<>();
for (Entity entity : list)
{
boolean ok = true;
for (ColumnCondition cc : locals)
{
if (cc.matches(converter, entity) != TruthValue.TRUE)
{
ok = false;
break;
}
}
if (ok)
{
flist.add(entity);
}
}
System.err.println("filtered from "+list.size()+" to "+flist.size());
return flist;
}
System.err.println("fetched "+list.size());
return list;
}
@Override
public void beginTransaction()
{
datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
}
@Override
public void commitTransaction()
{
datastore.getCurrentTransaction().commit();
}
@Override
public void rollbackTransaction()
{
datastore.getCurrentTransaction().rollback();
}
@Override
public void exit()
{
Transaction currentTransaction = datastore.getCurrentTransaction(null);
if (currentTransaction != null && currentTransaction.isActive())
{
currentTransaction.rollback();
}
}
public Statistics getStatistics()
{
return statistics;
}
@Override
public Key createKey(Key parent, String kind, long id)
{
return KeyFactory.createKey(parent, kind, id);
}
@Override
public Key createKey(Key parent, String kind, String name)
{
return KeyFactory.createKey(parent, kind, name);
}
@Override
public Key createKey(String kind, long id)
{
return KeyFactory.createKey(kind, id);
}
@Override
public Key createKey(String kind, String name)
{
return KeyFactory.createKey(kind, name);
}
@Override
public String createKeyString(Key parent, String kind, long id)
{
return KeyFactory.createKeyString(parent, kind, id);
}
@Override
public String createKeyString(Key parent, String kind, String name)
{
return KeyFactory.createKeyString(parent, kind, name);
}
@Override
public String createKeyString(String kind, long id)
{
return KeyFactory.createKeyString(kind, id);
}
@Override
public String createKeyString(String kind, String name)
{
return KeyFactory.createKeyString(kind, name);
}
@Override
public String keyToString(Key key)
{
return KeyFactory.keyToString(key);
}
@Override
public Key stringToKey(String encoded)
{
return KeyFactory.stringToKey(encoded);
}
private void checkKeysOnlyAndProjection(Query query, Table<Entity, Object> table, boolean update)
{
Set<String> minOutput = new HashSet<>(); // minimum set of output
minOutput.addAll(table.getConditionColumns()); // all columns needed in conditions
+ minOutput.addAll(table.getSortColumns()); // all columns needed in conditions
for (FilterPredicate fp : query.getFilterPredicates())
{
switch (fp.getOperator())
{
case EQUAL:
case IN:
break;
default:
minOutput.remove(fp.getPropertyName()); // minus and-path filtered
break;
}
}
minOutput.addAll(table.getSelectListColumns()); // plus all in select list
if (
minOutput.size() == 1 &&
Entity.KEY_RESERVED_PROPERTY.equals(minOutput.iterator().next())
)
{
query.setKeysOnly();
return;
}
if (!update)
{
// Only indexed properties can be projected.
for (String property : minOutput)
{
ColumnMetadata cm = statistics.getProperty(table.getName(), property);
if (cm == null || !cm.isIndexed())
{
return;
}
}
for (FilterPredicate fp : query.getFilterPredicates())
{
switch (fp.getOperator())
{
case EQUAL:
case IN:
if (minOutput.contains(fp.getPropertyName()))
{
return;
}
}
}
if (minOutput.size() > 1)
{
boolean ok1 = false;
Map<Index, IndexState> indexes = statistics.getIndexes();
for (Entry<Index, IndexState> entry : indexes.entrySet())
{
if (IndexState.SERVING.equals(entry.getValue()))
{
List<Property> properties = entry.getKey().getProperties();
if (minOutput.size() == properties.size())
{
boolean ok2 = true;
for (Property property : properties)
{
if (!minOutput.contains(property.getName()))
{
ok2 = false;
break;
}
}
if (ok2)
{
ok1 = true;
break;
}
}
}
}
if (!ok1)
{
return;
}
}
for (String property : minOutput)
{
query.addProjection(new PropertyProjection(property, null));
}
}
}
@Override
public void send(Message message) throws IOException
{
mailService.send(message);
}
@Override
public Session getSession()
{
return session;
}
@Override
public void send(MimeMessage message) throws IOException
{
try
{
Transport.send(message);
}
catch (MessagingException ex)
{
throw new IOException(ex);
}
}
@Override
public Entity get(Key key) throws EntityNotFoundException
{
return datastore.get(key);
}
@Override
public List<Entity> getAll(String kind)
{
Query query = new Query(kind);
PreparedQuery prepared = datastore.prepare(query);
return prepared.asList(FetchOptions.Builder.withChunkSize(CHUNKSIZE));
}
@Override
public void update(Entity row)
{
datastore.put(row);
}
@Override
public void delete(Entity row)
{
datastore.delete(row.getKey());
}
}
| true | true | private void checkKeysOnlyAndProjection(Query query, Table<Entity, Object> table, boolean update)
{
Set<String> minOutput = new HashSet<>(); // minimum set of output
minOutput.addAll(table.getConditionColumns()); // all columns needed in conditions
for (FilterPredicate fp : query.getFilterPredicates())
{
switch (fp.getOperator())
{
case EQUAL:
case IN:
break;
default:
minOutput.remove(fp.getPropertyName()); // minus and-path filtered
break;
}
}
minOutput.addAll(table.getSelectListColumns()); // plus all in select list
if (
minOutput.size() == 1 &&
Entity.KEY_RESERVED_PROPERTY.equals(minOutput.iterator().next())
)
{
query.setKeysOnly();
return;
}
if (!update)
{
// Only indexed properties can be projected.
for (String property : minOutput)
{
ColumnMetadata cm = statistics.getProperty(table.getName(), property);
if (cm == null || !cm.isIndexed())
{
return;
}
}
for (FilterPredicate fp : query.getFilterPredicates())
{
switch (fp.getOperator())
{
case EQUAL:
case IN:
if (minOutput.contains(fp.getPropertyName()))
{
return;
}
}
}
if (minOutput.size() > 1)
{
boolean ok1 = false;
Map<Index, IndexState> indexes = statistics.getIndexes();
for (Entry<Index, IndexState> entry : indexes.entrySet())
{
if (IndexState.SERVING.equals(entry.getValue()))
{
List<Property> properties = entry.getKey().getProperties();
if (minOutput.size() == properties.size())
{
boolean ok2 = true;
for (Property property : properties)
{
if (!minOutput.contains(property.getName()))
{
ok2 = false;
break;
}
}
if (ok2)
{
ok1 = true;
break;
}
}
}
}
if (!ok1)
{
return;
}
}
for (String property : minOutput)
{
query.addProjection(new PropertyProjection(property, null));
}
}
}
| private void checkKeysOnlyAndProjection(Query query, Table<Entity, Object> table, boolean update)
{
Set<String> minOutput = new HashSet<>(); // minimum set of output
minOutput.addAll(table.getConditionColumns()); // all columns needed in conditions
minOutput.addAll(table.getSortColumns()); // all columns needed in conditions
for (FilterPredicate fp : query.getFilterPredicates())
{
switch (fp.getOperator())
{
case EQUAL:
case IN:
break;
default:
minOutput.remove(fp.getPropertyName()); // minus and-path filtered
break;
}
}
minOutput.addAll(table.getSelectListColumns()); // plus all in select list
if (
minOutput.size() == 1 &&
Entity.KEY_RESERVED_PROPERTY.equals(minOutput.iterator().next())
)
{
query.setKeysOnly();
return;
}
if (!update)
{
// Only indexed properties can be projected.
for (String property : minOutput)
{
ColumnMetadata cm = statistics.getProperty(table.getName(), property);
if (cm == null || !cm.isIndexed())
{
return;
}
}
for (FilterPredicate fp : query.getFilterPredicates())
{
switch (fp.getOperator())
{
case EQUAL:
case IN:
if (minOutput.contains(fp.getPropertyName()))
{
return;
}
}
}
if (minOutput.size() > 1)
{
boolean ok1 = false;
Map<Index, IndexState> indexes = statistics.getIndexes();
for (Entry<Index, IndexState> entry : indexes.entrySet())
{
if (IndexState.SERVING.equals(entry.getValue()))
{
List<Property> properties = entry.getKey().getProperties();
if (minOutput.size() == properties.size())
{
boolean ok2 = true;
for (Property property : properties)
{
if (!minOutput.contains(property.getName()))
{
ok2 = false;
break;
}
}
if (ok2)
{
ok1 = true;
break;
}
}
}
}
if (!ok1)
{
return;
}
}
for (String property : minOutput)
{
query.addProjection(new PropertyProjection(property, null));
}
}
}
|
diff --git a/rvin-mojo/flex-mojo-IT/src/test/java/info/rvin/mojo/flexmojo/test/IT0007Issue0013Test.java b/rvin-mojo/flex-mojo-IT/src/test/java/info/rvin/mojo/flexmojo/test/IT0007Issue0013Test.java
index c7c9373d..1b736409 100644
--- a/rvin-mojo/flex-mojo-IT/src/test/java/info/rvin/mojo/flexmojo/test/IT0007Issue0013Test.java
+++ b/rvin-mojo/flex-mojo-IT/src/test/java/info/rvin/mojo/flexmojo/test/IT0007Issue0013Test.java
@@ -1,31 +1,31 @@
package info.rvin.mojo.flexmojo.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.integrationtests.AbstractMavenIntegrationTestCase;
import org.apache.maven.it.Verifier;
import org.apache.maven.it.util.ResourceExtractor;
public class IT0007Issue0013Test extends AbstractMavenIntegrationTestCase {
public void testWithoutTestFolder() throws Exception {
File testDir = ResourceExtractor.simpleExtractResources(getClass(),
"/issues/issue-0013");
Verifier verifier = new Verifier(testDir.getAbsolutePath(), true);
verifier.deleteArtifact("info.rvin.itest.issues", "issue-0013",
"1.0-SNAPSHOT", "swf");
List<String> cliOptions = new ArrayList<String>();
cliOptions.add("-o");
verifier.setCliOptions(cliOptions );
verifier.executeGoal("install");
verifier.displayStreamBuffers();
- verifier.verifyErrorFreeLog();
+// verifier.verifyErrorFreeLog();
verifier.resetStreams();
File reportDir = new File(testDir, "target/tests-reports");
assertEquals(2, reportDir.listFiles().length);
}
}
| true | true | public void testWithoutTestFolder() throws Exception {
File testDir = ResourceExtractor.simpleExtractResources(getClass(),
"/issues/issue-0013");
Verifier verifier = new Verifier(testDir.getAbsolutePath(), true);
verifier.deleteArtifact("info.rvin.itest.issues", "issue-0013",
"1.0-SNAPSHOT", "swf");
List<String> cliOptions = new ArrayList<String>();
cliOptions.add("-o");
verifier.setCliOptions(cliOptions );
verifier.executeGoal("install");
verifier.displayStreamBuffers();
verifier.verifyErrorFreeLog();
verifier.resetStreams();
File reportDir = new File(testDir, "target/tests-reports");
assertEquals(2, reportDir.listFiles().length);
}
| public void testWithoutTestFolder() throws Exception {
File testDir = ResourceExtractor.simpleExtractResources(getClass(),
"/issues/issue-0013");
Verifier verifier = new Verifier(testDir.getAbsolutePath(), true);
verifier.deleteArtifact("info.rvin.itest.issues", "issue-0013",
"1.0-SNAPSHOT", "swf");
List<String> cliOptions = new ArrayList<String>();
cliOptions.add("-o");
verifier.setCliOptions(cliOptions );
verifier.executeGoal("install");
verifier.displayStreamBuffers();
// verifier.verifyErrorFreeLog();
verifier.resetStreams();
File reportDir = new File(testDir, "target/tests-reports");
assertEquals(2, reportDir.listFiles().length);
}
|
diff --git a/app/models/Game.java b/app/models/Game.java
index 9bd5e7a..628ba18 100644
--- a/app/models/Game.java
+++ b/app/models/Game.java
@@ -1,55 +1,55 @@
package models;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import play.Logger;
public class Game {
private final static String[] CHARS = { "chara0", "chara1", "chara2",
"chara3", "chara4", "chara5", "chara6", "chara7" };
private final static Map<String, Integer[]> POSITIONS = new HashMap<String, Integer[]>();
static{
POSITIONS.put( "chara0", new Integer [] {32,32});
POSITIONS.put( "chara1", new Integer [] {64,32});
POSITIONS.put( "chara2", new Integer [] {32,64});
POSITIONS.put( "chara3", new Integer [] {64,64});
POSITIONS.put( "chara4", new Integer [] {32,48});
POSITIONS.put( "chara5", new Integer [] {48,32});
POSITIONS.put( "chara6", new Integer [] {48,48});
POSITIONS.put( "chara7", new Integer [] {0,0});
}
private Map<String, String> playerMapping = new HashMap<String,String>();
private List<Client> players = new ArrayList<Client>();
private int charCounter = 0;
public Game() {
Logger.info("starting new Game!");
}
public String getNextPlayerFor(String username, String ip) {
if(playerMapping.containsKey(ip)){
return playerMapping.get(ip);
}
if (!playerMapping.containsKey(username) && charCounter < CHARS.length) {
String player = CHARS[charCounter];
Logger.info("Player " + username + " uses Char " + player);
charCounter++;
players.add(new Client(player, username, POSITIONS.get(player)));
- playerMapping.put(ip, username);
+ playerMapping.put(ip, player);
return player;
}
return null;
}
public String getPlayerName(String ip){
return playerMapping.get(ip);
}
public List<Client> getPlayers() {
return players;
}
}
| true | true | public String getNextPlayerFor(String username, String ip) {
if(playerMapping.containsKey(ip)){
return playerMapping.get(ip);
}
if (!playerMapping.containsKey(username) && charCounter < CHARS.length) {
String player = CHARS[charCounter];
Logger.info("Player " + username + " uses Char " + player);
charCounter++;
players.add(new Client(player, username, POSITIONS.get(player)));
playerMapping.put(ip, username);
return player;
}
return null;
}
| public String getNextPlayerFor(String username, String ip) {
if(playerMapping.containsKey(ip)){
return playerMapping.get(ip);
}
if (!playerMapping.containsKey(username) && charCounter < CHARS.length) {
String player = CHARS[charCounter];
Logger.info("Player " + username + " uses Char " + player);
charCounter++;
players.add(new Client(player, username, POSITIONS.get(player)));
playerMapping.put(ip, player);
return player;
}
return null;
}
|
diff --git a/benchmark/src/com/sun/sgs/benchmark/client/ScriptingCommand.java b/benchmark/src/com/sun/sgs/benchmark/client/ScriptingCommand.java
index 5abdf0614..c2e012ccc 100644
--- a/benchmark/src/com/sun/sgs/benchmark/client/ScriptingCommand.java
+++ b/benchmark/src/com/sun/sgs/benchmark/client/ScriptingCommand.java
@@ -1,647 +1,647 @@
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved
*/
package com.sun.sgs.benchmark.client;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.sun.sgs.benchmark.shared.CustomTaskType;
/*
*
*/
public class ScriptingCommand {
/** Constants */
public static final String DELIMITER = "\t";
public static final String EMPTY_STR = "";
public static final int HELP_INDENT_LEN = 20;
public static final String HELP_INDENT_STR;
public static final String NEWLINE = System.getProperty("line.separator");
static {
StringBuilder sb = new StringBuilder();
for (int i=0; i < HELP_INDENT_LEN; i++) sb.append(' ');
HELP_INDENT_STR = sb.toString();
}
/** Member variablees */
private ScriptingCommandType type;
private int count = -1;
private int port = -1;
private long duration = -1;
private long delay = -1;
private long period = -1;
private int size = -1;
private String channelName = null;
private String className = null;
private String hostname = null;
private String objectName = null;
private String tagName = null;
private String topic = null;
private String msg = null;
private String printArg = null;
private String login = null, password = null;
private ScriptingEvent event = null;
private CustomTaskType taskType = null;
private List<String> recips = new LinkedList<String>();
/** Constructors */
/** use parse() to create instances */
private ScriptingCommand(ScriptingCommandType type) {
this.type = type;
}
/** Public Methods */
public String getChannelNameArg() { return channelName; }
public String getClassNameArg() { return className; }
public int getCountArg() { return count; }
public long getDelayArg() { return delay; }
public long getDurationArg() { return duration; }
public ScriptingEvent getEventArg() { return event; }
public static String getHelpString() {
StringBuilder sb = new StringBuilder();
sb.append(" --- Available Commands --- ").append(NEWLINE);
for (ScriptingCommandType type : ScriptingCommandType.values()) {
sb.append(getUsage(type)).append(NEWLINE); /** Just usage info */
}
return sb.toString();
}
public static String getHelpString(String cmdType) {
if (cmdType.equalsIgnoreCase("events")) {
return getEventsHelpString();
} else {
ScriptingCommandType type = ScriptingCommandType.parse(cmdType);
if (type == null) {
return "Unknown help topic. Try 'help' or 'help events'.";
} else {
return getHelpString(type);
}
}
}
public static String getHelpString(ScriptingCommandType type) {
StringBuilder sb = new StringBuilder();
String[] aliases = type.getAliases();
sb.append(getUsage(type)).append(NEWLINE);
sb.append(HELP_INDENT_STR).append("Aliases: ");
for (int i=0; i < aliases.length; i++) {
if (i > 0) sb.append(", ");
sb.append(aliases[i]);
}
return sb.toString();
}
public String getHostnameArg() { return hostname; }
public String getLoginArg() { return login; }
public String getMessageArg() { return msg; }
public String getObjectNameArg() { return objectName; }
public String getPasswordArg() { return password; }
public long getPeriodArg() { return period; }
public int getPortArg() { return port; }
public String getPrintArg() { return printArg; }
public List<String> getRecipientArgs() {
return Collections.unmodifiableList(recips);
}
public int getSizeArg() { return size; }
public String getTagNameArg() { return tagName; }
public CustomTaskType getTaskTypeArg() { return taskType; }
public String getTopicArg() { return topic; }
public ScriptingCommandType getType() { return type; }
public static ScriptingCommand parse(String line)
throws ParseException
{
String[] parts = line.trim().split("\\s+", 2);
ScriptingCommandType type = ScriptingCommandType.parse(parts[0]);
if (type == null) {
throw new ParseException("Unrecognized command: " + parts[0], 0);
}
ScriptingCommand cmd = new ScriptingCommand(type);
String[] args = (parts.length == 2) ? parts[1].split("\\s+") :
new String[] { };
cmd.parseArgs(args);
return cmd;
}
/** Private Methods */
private void parseArgs(String[] args) throws ParseException {
switch (type) {
case CONFIG:
if (args.length <= 2) {
if (args.length >= 1) { /** Optional argument */
hostname = args[0];
}
if (args.length == 2) { /** Optional argument */
try {
port = Integer.valueOf(args[1]);
if (port <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a valid network port: " + args[1], 0);
}
}
return;
}
break;
case CPU:
if (args.length == 1) {
try {
duration = Long.valueOf(args[0]);
if (duration <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[0], 0);
}
return;
}
break;
case CREATE_CHANNEL:
if (args.length == 1) {
channelName = args[0];
return;
}
- return;
+ break;
case DATASTORE_CREATE:
if (args.length >= 2 && args.length <= 3) {
objectName = args[0];
className = args[1];
boolean isArray;
try {
Class<?> clazz = Class.forName(className);
isArray = clazz.isArray();
} catch (ClassNotFoundException e) {
isArray = className.startsWith("["); /** guess */
}
if (isArray) {
/** Note: only single-dimension arrays are supported. */
if (args.length == 3) {
try {
size = Integer.valueOf(args[2]);
if (size < 0) {
size = -1;
throw new NumberFormatException();
}
return;
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[2], 0);
}
}
} else { /** Not an array type */
if (args.length == 2) return;
}
}
break;
case DATASTORE_READ:
if (args.length == 1) {
objectName = args[0];
return;
}
break;
case DATASTORE_WRITE:
if (args.length == 1) {
objectName = args[0];
return;
}
break;
case DISCONNECT:
if (args.length == 0) return; /** No arguments */
break;
case DO_TAG:
if (args.length >= 1 && args.length <= 2) {
tagName = args[0];
count = 1; /** default */
if (args.length == 2) { /** Optional argument */
try {
count = Integer.valueOf(args[1]);
if (count <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[1], 0);
}
}
return;
}
break;
case END_BLOCK:
if (args.length == 0) return; /** No arguments */
break;
case EXIT:
if (args.length == 0) return; /** No arguments */
break;
case HELP:
if (args.length <= 1) {
if (args.length == 1) { /** Optional argument */
topic = args[0];
}
return;
}
break;
case JOIN_CHANNEL:
if (args.length == 1) {
channelName = args[0];
return;
}
return;
case LEAVE_CHANNEL:
if (args.length == 1) {
channelName = args[0];
return;
}
return;
case LOGIN:
if (args.length == 2) {
login = args[0];
password = args[1];
return;
}
break;
case LOGOUT:
if (args.length == 0) return; /** No arguments */
break;
case MALLOC:
if (args.length == 1) {
try {
size = Integer.valueOf(args[0]);
if (size <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[0], 0);
}
return;
}
break;
case ON_EVENT:
if (args.length >= 2 && args.length <= 3) {
event = ScriptingEvent.parse(args[0]);
if (event == null) {
throw new ParseException("Invalid ScriptingEvent alias: " +
args[0], 0);
}
tagName = args[1];
count = 1; /** default */
if (args.length == 3) {
try {
count = Integer.valueOf(args[2]);
if (count <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[1], 0);
}
}
return;
}
break;
case PAUSE:
if (args.length == 1) {
try {
duration = Long.valueOf(args[0]);
if (duration <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[0], 0);
}
return;
}
break;
case PERIODIC_TASK:
if (args.length == 4) {
tagName = args[0];
try {
taskType = Enum.valueOf(CustomTaskType.class, args[1].toUpperCase());
} catch (IllegalArgumentException e) {
throw new ParseException("Invalid " + type + " argument, " +
" not recognized: " + args[1] + ". Should be one of: " +
Arrays.toString(CustomTaskType.values()), 0);
}
try {
delay = Long.valueOf(args[2]);
if (delay < 0) throw new NumberFormatException();
} catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[2], 0);
}
try {
period = Long.valueOf(args[3]);
if (period < 0) throw new NumberFormatException();
} catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[3], 0);
}
return;
}
break;
case PRINT:
/** Accept whole line as argument, including spaces */
if (args.length == 0) break;
printArg = stripQuotes(strJoin(args));
return;
case REQ_RESPONSE:
if (args.length >= 1 && args.length <= 2) {
String sizeArg;
if (args.length == 2) {
channelName = args[0];
sizeArg = args[1];
}
else {
sizeArg = args[0];
}
try {
size = Integer.valueOf(sizeArg);
if (size < 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[0], 0);
}
return;
}
break;
case SEND_CHANNEL:
if (args.length >= 2) {
channelName = args[0];
msg = stripQuotes(strJoin(args, 1));
return;
}
break;
case SEND_DIRECT:
/** Accept whole line as argument, including spaces */
if (args.length == 0) break;
printArg = stripQuotes(strJoin(args));
return;
case START_BLOCK:
if (args.length == 0) return; /** No arguments */
break;
case TAG:
if (args.length == 1) {
tagName = args[0];
return;
}
break;
case WAIT_FOR:
if (args.length == 1) {
event = ScriptingEvent.parse(args[0]);
if (event == null) {
throw new ParseException("Invalid ScriptingEvent alias: " +
args[0], 0);
}
return;
}
break;
default:
throw new IllegalStateException("ScriptingCommand.addProperty()" +
" switch statement fell through without matching any cases. " +
" this=" + this);
}
/**
* If control reaches here, the argument list was invalid (wrong number
* of arguments for this particular ScriptingCommand type.
*/
throw new ParseException("Wrong number of arguments to " + type +
" command (" + args.length + "). try 'help " + type + "'.", 0);
}
private static String stripQuotes(String s) {
s = s.trim().toLowerCase();
if ((s.startsWith("\"") && s.endsWith("\"")) ||
(s.startsWith("'") && s.endsWith("'"))) {
s = s.substring(1, s.length() - 1).trim();
}
return s;
}
private static String getArgList(ScriptingCommandType type) {
switch (type) {
case CONFIG:
return "[hostname [port]]";
case CPU:
return "duration_ms";
case CREATE_CHANNEL:
return "channel (may not contain spaces)";
case DATASTORE_CREATE:
return "object-name class-name - or - " +
"object-name array-class-name size";
case DATASTORE_READ:
return "object-name";
case DATASTORE_WRITE:
return "object-name";
case DISCONNECT:
return "";
case DO_TAG:
return "tagname [repeat-count]";
case END_BLOCK:
return "";
case EXIT:
return "";
case HELP:
return "";
case JOIN_CHANNEL:
return "channel (may not contain spaces)";
case LEAVE_CHANNEL:
return "channel (may not contain spaces)";
case LOGIN:
return "username password";
case LOGOUT:
return "";
case MALLOC:
return "size_bytes";
case ON_EVENT:
return "event tagname [repeat-count]";
case PAUSE:
return "duration_ms";
case PERIODIC_TASK:
return "tag task-type delay_ms period_ms";
case PRINT:
return "message (may contain spaces)";
case REQ_RESPONSE:
return "[channel] size_bytes (channel name may not contain spaces)";
case SEND_CHANNEL:
return "channel message (message may contain spaces, but not channel)";
case SEND_DIRECT:
return "message (may contain spaces)";
case START_BLOCK:
return "";
case TAG:
return "tagname";
case WAIT_FOR:
return "event";
default:
return "Error: unknown command-type: " + type;
}
}
private static String getEventsHelpString() {
StringBuilder sb = new StringBuilder();
sb.append(" --- Available Events (Triggers) --- ").append(NEWLINE);
for (ScriptingEvent evt : ScriptingEvent.values()) {
String[] aliases = evt.getAliases();
String desc = evt.toString();
sb.append(desc);
for (int i=desc.length(); i < HELP_INDENT_LEN; i++) sb.append(" ");
sb.append("Aliases: ");
for (int i=0; i < aliases.length; i++) {
if (i > 0) sb.append(", ");
sb.append(aliases[i]);
}
sb.append(")").append(NEWLINE);
}
return sb.toString();
}
private static String getUsage(ScriptingCommandType type) {
StringBuilder sb = new StringBuilder();
sb.append(type);
while (sb.length() < HELP_INDENT_LEN) sb.append(' ');
sb.append("Usage: ").append(type.getAlias()).append(" ");
/** Arguments */
sb.append(getArgList(type));
return sb.toString();
}
private static String strJoin(String[] strs) {
return strJoin(strs, 0, strs.length);
}
private static String strJoin(String[] strs, int offset) {
return strJoin(strs, offset, strs.length);
}
private static String strJoin(String[] strs, int offset, int length) {
StringBuilder sb = new StringBuilder();
for (int i=offset; i < length; i++) {
sb.append(strs[i]);
sb.append(" ");
}
return sb.toString();
}
}
| true | true | private void parseArgs(String[] args) throws ParseException {
switch (type) {
case CONFIG:
if (args.length <= 2) {
if (args.length >= 1) { /** Optional argument */
hostname = args[0];
}
if (args.length == 2) { /** Optional argument */
try {
port = Integer.valueOf(args[1]);
if (port <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a valid network port: " + args[1], 0);
}
}
return;
}
break;
case CPU:
if (args.length == 1) {
try {
duration = Long.valueOf(args[0]);
if (duration <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[0], 0);
}
return;
}
break;
case CREATE_CHANNEL:
if (args.length == 1) {
channelName = args[0];
return;
}
return;
case DATASTORE_CREATE:
if (args.length >= 2 && args.length <= 3) {
objectName = args[0];
className = args[1];
boolean isArray;
try {
Class<?> clazz = Class.forName(className);
isArray = clazz.isArray();
} catch (ClassNotFoundException e) {
isArray = className.startsWith("["); /** guess */
}
if (isArray) {
/** Note: only single-dimension arrays are supported. */
if (args.length == 3) {
try {
size = Integer.valueOf(args[2]);
if (size < 0) {
size = -1;
throw new NumberFormatException();
}
return;
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[2], 0);
}
}
} else { /** Not an array type */
if (args.length == 2) return;
}
}
break;
case DATASTORE_READ:
if (args.length == 1) {
objectName = args[0];
return;
}
break;
case DATASTORE_WRITE:
if (args.length == 1) {
objectName = args[0];
return;
}
break;
case DISCONNECT:
if (args.length == 0) return; /** No arguments */
break;
case DO_TAG:
if (args.length >= 1 && args.length <= 2) {
tagName = args[0];
count = 1; /** default */
if (args.length == 2) { /** Optional argument */
try {
count = Integer.valueOf(args[1]);
if (count <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[1], 0);
}
}
return;
}
break;
case END_BLOCK:
if (args.length == 0) return; /** No arguments */
break;
case EXIT:
if (args.length == 0) return; /** No arguments */
break;
case HELP:
if (args.length <= 1) {
if (args.length == 1) { /** Optional argument */
topic = args[0];
}
return;
}
break;
case JOIN_CHANNEL:
if (args.length == 1) {
channelName = args[0];
return;
}
return;
case LEAVE_CHANNEL:
if (args.length == 1) {
channelName = args[0];
return;
}
return;
case LOGIN:
if (args.length == 2) {
login = args[0];
password = args[1];
return;
}
break;
case LOGOUT:
if (args.length == 0) return; /** No arguments */
break;
case MALLOC:
if (args.length == 1) {
try {
size = Integer.valueOf(args[0]);
if (size <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[0], 0);
}
return;
}
break;
case ON_EVENT:
if (args.length >= 2 && args.length <= 3) {
event = ScriptingEvent.parse(args[0]);
if (event == null) {
throw new ParseException("Invalid ScriptingEvent alias: " +
args[0], 0);
}
tagName = args[1];
count = 1; /** default */
if (args.length == 3) {
try {
count = Integer.valueOf(args[2]);
if (count <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[1], 0);
}
}
return;
}
break;
case PAUSE:
if (args.length == 1) {
try {
duration = Long.valueOf(args[0]);
if (duration <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[0], 0);
}
return;
}
break;
case PERIODIC_TASK:
if (args.length == 4) {
tagName = args[0];
try {
taskType = Enum.valueOf(CustomTaskType.class, args[1].toUpperCase());
} catch (IllegalArgumentException e) {
throw new ParseException("Invalid " + type + " argument, " +
" not recognized: " + args[1] + ". Should be one of: " +
Arrays.toString(CustomTaskType.values()), 0);
}
try {
delay = Long.valueOf(args[2]);
if (delay < 0) throw new NumberFormatException();
} catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[2], 0);
}
try {
period = Long.valueOf(args[3]);
if (period < 0) throw new NumberFormatException();
} catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[3], 0);
}
return;
}
break;
case PRINT:
/** Accept whole line as argument, including spaces */
if (args.length == 0) break;
printArg = stripQuotes(strJoin(args));
return;
case REQ_RESPONSE:
if (args.length >= 1 && args.length <= 2) {
String sizeArg;
if (args.length == 2) {
channelName = args[0];
sizeArg = args[1];
}
else {
sizeArg = args[0];
}
try {
size = Integer.valueOf(sizeArg);
if (size < 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[0], 0);
}
return;
}
break;
case SEND_CHANNEL:
if (args.length >= 2) {
channelName = args[0];
msg = stripQuotes(strJoin(args, 1));
return;
}
break;
case SEND_DIRECT:
/** Accept whole line as argument, including spaces */
if (args.length == 0) break;
printArg = stripQuotes(strJoin(args));
return;
case START_BLOCK:
if (args.length == 0) return; /** No arguments */
break;
case TAG:
if (args.length == 1) {
tagName = args[0];
return;
}
break;
case WAIT_FOR:
if (args.length == 1) {
event = ScriptingEvent.parse(args[0]);
if (event == null) {
throw new ParseException("Invalid ScriptingEvent alias: " +
args[0], 0);
}
return;
}
break;
default:
throw new IllegalStateException("ScriptingCommand.addProperty()" +
" switch statement fell through without matching any cases. " +
" this=" + this);
}
/**
* If control reaches here, the argument list was invalid (wrong number
* of arguments for this particular ScriptingCommand type.
*/
throw new ParseException("Wrong number of arguments to " + type +
" command (" + args.length + "). try 'help " + type + "'.", 0);
}
| private void parseArgs(String[] args) throws ParseException {
switch (type) {
case CONFIG:
if (args.length <= 2) {
if (args.length >= 1) { /** Optional argument */
hostname = args[0];
}
if (args.length == 2) { /** Optional argument */
try {
port = Integer.valueOf(args[1]);
if (port <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a valid network port: " + args[1], 0);
}
}
return;
}
break;
case CPU:
if (args.length == 1) {
try {
duration = Long.valueOf(args[0]);
if (duration <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[0], 0);
}
return;
}
break;
case CREATE_CHANNEL:
if (args.length == 1) {
channelName = args[0];
return;
}
break;
case DATASTORE_CREATE:
if (args.length >= 2 && args.length <= 3) {
objectName = args[0];
className = args[1];
boolean isArray;
try {
Class<?> clazz = Class.forName(className);
isArray = clazz.isArray();
} catch (ClassNotFoundException e) {
isArray = className.startsWith("["); /** guess */
}
if (isArray) {
/** Note: only single-dimension arrays are supported. */
if (args.length == 3) {
try {
size = Integer.valueOf(args[2]);
if (size < 0) {
size = -1;
throw new NumberFormatException();
}
return;
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[2], 0);
}
}
} else { /** Not an array type */
if (args.length == 2) return;
}
}
break;
case DATASTORE_READ:
if (args.length == 1) {
objectName = args[0];
return;
}
break;
case DATASTORE_WRITE:
if (args.length == 1) {
objectName = args[0];
return;
}
break;
case DISCONNECT:
if (args.length == 0) return; /** No arguments */
break;
case DO_TAG:
if (args.length >= 1 && args.length <= 2) {
tagName = args[0];
count = 1; /** default */
if (args.length == 2) { /** Optional argument */
try {
count = Integer.valueOf(args[1]);
if (count <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[1], 0);
}
}
return;
}
break;
case END_BLOCK:
if (args.length == 0) return; /** No arguments */
break;
case EXIT:
if (args.length == 0) return; /** No arguments */
break;
case HELP:
if (args.length <= 1) {
if (args.length == 1) { /** Optional argument */
topic = args[0];
}
return;
}
break;
case JOIN_CHANNEL:
if (args.length == 1) {
channelName = args[0];
return;
}
return;
case LEAVE_CHANNEL:
if (args.length == 1) {
channelName = args[0];
return;
}
return;
case LOGIN:
if (args.length == 2) {
login = args[0];
password = args[1];
return;
}
break;
case LOGOUT:
if (args.length == 0) return; /** No arguments */
break;
case MALLOC:
if (args.length == 1) {
try {
size = Integer.valueOf(args[0]);
if (size <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[0], 0);
}
return;
}
break;
case ON_EVENT:
if (args.length >= 2 && args.length <= 3) {
event = ScriptingEvent.parse(args[0]);
if (event == null) {
throw new ParseException("Invalid ScriptingEvent alias: " +
args[0], 0);
}
tagName = args[1];
count = 1; /** default */
if (args.length == 3) {
try {
count = Integer.valueOf(args[2]);
if (count <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[1], 0);
}
}
return;
}
break;
case PAUSE:
if (args.length == 1) {
try {
duration = Long.valueOf(args[0]);
if (duration <= 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument," +
" must be a positive integer: " + args[0], 0);
}
return;
}
break;
case PERIODIC_TASK:
if (args.length == 4) {
tagName = args[0];
try {
taskType = Enum.valueOf(CustomTaskType.class, args[1].toUpperCase());
} catch (IllegalArgumentException e) {
throw new ParseException("Invalid " + type + " argument, " +
" not recognized: " + args[1] + ". Should be one of: " +
Arrays.toString(CustomTaskType.values()), 0);
}
try {
delay = Long.valueOf(args[2]);
if (delay < 0) throw new NumberFormatException();
} catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[2], 0);
}
try {
period = Long.valueOf(args[3]);
if (period < 0) throw new NumberFormatException();
} catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[3], 0);
}
return;
}
break;
case PRINT:
/** Accept whole line as argument, including spaces */
if (args.length == 0) break;
printArg = stripQuotes(strJoin(args));
return;
case REQ_RESPONSE:
if (args.length >= 1 && args.length <= 2) {
String sizeArg;
if (args.length == 2) {
channelName = args[0];
sizeArg = args[1];
}
else {
sizeArg = args[0];
}
try {
size = Integer.valueOf(sizeArg);
if (size < 0) throw new NumberFormatException();
}
catch (NumberFormatException e) {
throw new ParseException("Invalid " + type + " argument, " +
" must be a non-negative integer: " + args[0], 0);
}
return;
}
break;
case SEND_CHANNEL:
if (args.length >= 2) {
channelName = args[0];
msg = stripQuotes(strJoin(args, 1));
return;
}
break;
case SEND_DIRECT:
/** Accept whole line as argument, including spaces */
if (args.length == 0) break;
printArg = stripQuotes(strJoin(args));
return;
case START_BLOCK:
if (args.length == 0) return; /** No arguments */
break;
case TAG:
if (args.length == 1) {
tagName = args[0];
return;
}
break;
case WAIT_FOR:
if (args.length == 1) {
event = ScriptingEvent.parse(args[0]);
if (event == null) {
throw new ParseException("Invalid ScriptingEvent alias: " +
args[0], 0);
}
return;
}
break;
default:
throw new IllegalStateException("ScriptingCommand.addProperty()" +
" switch statement fell through without matching any cases. " +
" this=" + this);
}
/**
* If control reaches here, the argument list was invalid (wrong number
* of arguments for this particular ScriptingCommand type.
*/
throw new ParseException("Wrong number of arguments to " + type +
" command (" + args.length + "). try 'help " + type + "'.", 0);
}
|
diff --git a/src/com/wickedspiral/jacss/parser/Parser.java b/src/com/wickedspiral/jacss/parser/Parser.java
index e52cb8b..70523ce 100644
--- a/src/com/wickedspiral/jacss/parser/Parser.java
+++ b/src/com/wickedspiral/jacss/parser/Parser.java
@@ -1,558 +1,558 @@
package com.wickedspiral.jacss.parser;
import com.wickedspiral.jacss.lexer.Token;
import com.wickedspiral.jacss.lexer.TokenListener;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import static com.wickedspiral.jacss.lexer.Token.*;
/**
* @author wasche
* @since 2011.08.04
*/
public class Parser implements TokenListener
{
private static final String MS_ALPHA = "progid:dximagetransform.microsoft.alpha(opacity=";
private static final Collection<String> UNITS = new HashSet<>(
Arrays.asList("px", "em", "pt", "in", "cm", "mm", "pc", "ex", "%"));
private static final Collection<String> KEYWORDS = new HashSet<>(
Arrays.asList("normal", "bold", "italic", "serif", "sans-serif", "fixed"));
private static final Collection<String> BOUNDARY_OPS = new HashSet<>(
Arrays.asList("{", "}", ">", ";", ":", ",")); // or comment
private static final Collection<String> DUAL_ZERO_PROPERTIES = new HashSet<>(
Arrays.asList("background-position", "-webkit-transform-origin", "-moz-transform-origin"));
private static final Collection<String> NONE_PROPERTIES = new HashSet<>();
static
{
NONE_PROPERTIES.add("outline");
for (String property : new String[] {"border", "margin", "padding"})
{
NONE_PROPERTIES.add(property);
for (String edge : new String[]{"top", "left", "bottom", "right"})
{
NONE_PROPERTIES.add(property + "-" + edge);
}
}
}
// buffers
private LinkedList<String> ruleBuffer;
private LinkedList<String> valueBuffer;
private LinkedList<String> rgbBuffer;
private String pending;
// flags
private boolean inRule;
private boolean space;
private boolean charset;
private boolean at;
private boolean ie5mac;
private boolean rgb;
private int checkSpace;
// other state
private String property;
private Token lastToken;
private String lastValue;
private PrintStream out;
private boolean debug;
private boolean keepTailingSemicolons;
private boolean noCollapseZeroes;
private boolean noCollapseNone;
public Parser(OutputStream outputStream, boolean debug, boolean keepTailingSemicolons, boolean noCollapseZeroes,
boolean noCollapseNone)
{
out = new PrintStream(new BufferedOutputStream(outputStream));
ruleBuffer = new LinkedList<>();
valueBuffer = new LinkedList<>();
rgbBuffer = new LinkedList<>();
inRule = false;
space = false;
charset = false;
at = false;
ie5mac = false;
rgb = false;
checkSpace = -1;
this.debug = debug;
this.keepTailingSemicolons = keepTailingSemicolons;
this.noCollapseZeroes = noCollapseZeroes;
this.noCollapseNone = noCollapseNone;
}
// ++ Output functions
private void output(Collection<String> strings)
{
for (String s : strings)
{
output(s);
}
}
private void output(String str)
{
out.print(str);
out.flush();
}
private void dump(String str)
{
ruleBuffer.add(pending);
ruleBuffer.add(str);
output(ruleBuffer);
ruleBuffer.clear();
}
private void write(String str)
{
if (str == null || str.length() == 0) return;
if (str.startsWith("/*!") && ruleBuffer.isEmpty())
{
output(str);
}
if ("}".equals(str))
{
// check for empty rule
if (!ruleBuffer.isEmpty() && !"{".equals(ruleBuffer.getLast()))
{
output(ruleBuffer);
output(str);
}
ruleBuffer.clear();
}
else
{
ruleBuffer.add(str);
}
}
private void buffer(String str)
{
if (str == null || str.length() == 0) return;
if (pending == null)
{
pending = str;
}
else
{
write(pending);
pending = str;
}
}
private void queue(String str)
{
if (str == null || str.length() == 0) return;
if (property != null)
{
valueBuffer.add(str);
}
else
{
buffer(str);
}
}
private void collapseValue()
{
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
String value = sb.toString();
if ("0 0".equals(value) || "0 0 0 0".equals(value) || "0 0 0".equals(value))
{
if (DUAL_ZERO_PROPERTIES.contains(value))
{
buffer("0 0");
}
else
{
buffer("0");
}
}
else if ("none".equals(value) && (NONE_PROPERTIES.contains(property) || "background".equals(property)) && !noCollapseNone)
{
buffer("0");
}
else
{
buffer(value);
}
}
// ++ TokenListener
public void token(Token token, String value)
{
if (debug) System.err.printf("Token: %s, value: %s\n", token, value);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
rgbBuffer.add("0");
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
queue(" ");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
)
{
queue(" ");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
queue(" ");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
pending = null;
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (keepTailingSemicolons)
{
buffer(";");
}
pending = value;
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains(value))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
if ( RBRACE != lastToken )
{
queue(" ");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if (noCollapseZeroes)
{
queue( value );
}
else
{
queue(value.substring(1));
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
- if (MS_ALPHA.equals(value.substring(1, MS_ALPHA.length() + 1).toLowerCase()))
+ if (value.toLowerCase().startsWith(MS_ALPHA, 1))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (!UNITS.contains(value))
{
queue(" ");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && !noCollapseNone)
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
if (value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5))
{
queue(v.substring(0, 1));
queue(v.substring(2, 3));
queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
public void end()
{
write(pending);
if (!ruleBuffer.isEmpty())
{
output(ruleBuffer);
}
}
}
| true | true | public void token(Token token, String value)
{
if (debug) System.err.printf("Token: %s, value: %s\n", token, value);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
rgbBuffer.add("0");
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
queue(" ");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
)
{
queue(" ");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
queue(" ");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
pending = null;
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (keepTailingSemicolons)
{
buffer(";");
}
pending = value;
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains(value))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
if ( RBRACE != lastToken )
{
queue(" ");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if (noCollapseZeroes)
{
queue( value );
}
else
{
queue(value.substring(1));
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
if (MS_ALPHA.equals(value.substring(1, MS_ALPHA.length() + 1).toLowerCase()))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (!UNITS.contains(value))
{
queue(" ");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && !noCollapseNone)
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
if (value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5))
{
queue(v.substring(0, 1));
queue(v.substring(2, 3));
queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
| public void token(Token token, String value)
{
if (debug) System.err.printf("Token: %s, value: %s\n", token, value);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
rgbBuffer.add("0");
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
queue(" ");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
)
{
queue(" ");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
queue(" ");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
pending = null;
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (keepTailingSemicolons)
{
buffer(";");
}
pending = value;
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains(value))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
if ( RBRACE != lastToken )
{
queue(" ");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if (noCollapseZeroes)
{
queue( value );
}
else
{
queue(value.substring(1));
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
if (value.toLowerCase().startsWith(MS_ALPHA, 1))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (!UNITS.contains(value))
{
queue(" ");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && !noCollapseNone)
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
if (value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5))
{
queue(v.substring(0, 1));
queue(v.substring(2, 3));
queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
|
diff --git a/src/org/proofpad/SExpUtils.java b/src/org/proofpad/SExpUtils.java
index fbce89f..043da6b 100755
--- a/src/org/proofpad/SExpUtils.java
+++ b/src/org/proofpad/SExpUtils.java
@@ -1,82 +1,82 @@
package org.proofpad;
import java.util.LinkedList;
import java.util.List;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.Token;
public class SExpUtils {
static enum ExpType {
NORMAL,
FINAL,
UNDOABLE
}
static List<Expression> topLevelExps(RSyntaxDocument doc) {
List<Expression> r = new LinkedList<Expression>();
int parenLevel = 0;
int height = 0;
boolean first = false;
StringBuilder contents = new StringBuilder();
- boolean contentsAdmittable = true;
+ boolean contentsAdmittable = false;
ExpType firstType = ExpType.FINAL;
int charIndex = -1;
Expression prev = null;
int gapHeight = 0;
for (int i = 0; i < doc.getDefaultRootElement().getElementCount(); i++) {
height++;
Token token = doc.getTokenListForLine(i);
while (token != null && token.offset != -1) {
//System.out.println(token);
if (charIndex == -1) {
charIndex = token.offset;
}
if (!token.isComment() && !token.isWhitespace() && !token.isSingleChar('\r')) {
contents.append(token.text, token.textOffset, token.textCount);
if (firstType == ExpType.FINAL && !token.isSingleChar('(')) {
firstType = token.type == Token.RESERVED_WORD_2 ? ExpType.UNDOABLE : ExpType.NORMAL;
if (token.getLexeme().equalsIgnoreCase("defproperty")) {
firstType = ExpType.UNDOABLE;
}
gapHeight = height - 1;
height = 1;
}
contentsAdmittable = true;
} else if (token.isWhitespace()) {
contents.append(token.text, token.textOffset, token.textCount);
}
if (token.isSingleChar('(')) {
parenLevel++;
} else if (token.isSingleChar(')') && parenLevel > 0) {
parenLevel--;
}
boolean nextTokenIsNull = token.getNextToken() == null ||
token.getNextToken().type == Token.NULL;
if (parenLevel == 0 && nextTokenIsNull && contents.length() != 0 && contentsAdmittable) {
if (prev != null) {
prev.nextGapHeight = gapHeight;
}
prev = new Expression(height, contents.toString(), firstType, charIndex,
token.offset + token.textCount, prev);
prev.prevGapHeight = gapHeight;
r.add(prev);
firstType = ExpType.FINAL;
charIndex = -1;
contents = new StringBuilder();
contentsAdmittable = false;
height = 0;
}
if (first) first = false;
token = token.getNextToken();
}
contents.append('\n');
}
r.add(new Expression(height, "", ExpType.FINAL, charIndex, -1, prev));
//for (Expression exp : r) {
// System.out.println(exp.first == null ? "null" : exp.first);
//}
return r;
}
}
| true | true | static List<Expression> topLevelExps(RSyntaxDocument doc) {
List<Expression> r = new LinkedList<Expression>();
int parenLevel = 0;
int height = 0;
boolean first = false;
StringBuilder contents = new StringBuilder();
boolean contentsAdmittable = true;
ExpType firstType = ExpType.FINAL;
int charIndex = -1;
Expression prev = null;
int gapHeight = 0;
for (int i = 0; i < doc.getDefaultRootElement().getElementCount(); i++) {
height++;
Token token = doc.getTokenListForLine(i);
while (token != null && token.offset != -1) {
//System.out.println(token);
if (charIndex == -1) {
charIndex = token.offset;
}
if (!token.isComment() && !token.isWhitespace() && !token.isSingleChar('\r')) {
contents.append(token.text, token.textOffset, token.textCount);
if (firstType == ExpType.FINAL && !token.isSingleChar('(')) {
firstType = token.type == Token.RESERVED_WORD_2 ? ExpType.UNDOABLE : ExpType.NORMAL;
if (token.getLexeme().equalsIgnoreCase("defproperty")) {
firstType = ExpType.UNDOABLE;
}
gapHeight = height - 1;
height = 1;
}
contentsAdmittable = true;
} else if (token.isWhitespace()) {
contents.append(token.text, token.textOffset, token.textCount);
}
if (token.isSingleChar('(')) {
parenLevel++;
} else if (token.isSingleChar(')') && parenLevel > 0) {
parenLevel--;
}
boolean nextTokenIsNull = token.getNextToken() == null ||
token.getNextToken().type == Token.NULL;
if (parenLevel == 0 && nextTokenIsNull && contents.length() != 0 && contentsAdmittable) {
if (prev != null) {
prev.nextGapHeight = gapHeight;
}
prev = new Expression(height, contents.toString(), firstType, charIndex,
token.offset + token.textCount, prev);
prev.prevGapHeight = gapHeight;
r.add(prev);
firstType = ExpType.FINAL;
charIndex = -1;
contents = new StringBuilder();
contentsAdmittable = false;
height = 0;
}
if (first) first = false;
token = token.getNextToken();
}
contents.append('\n');
}
r.add(new Expression(height, "", ExpType.FINAL, charIndex, -1, prev));
//for (Expression exp : r) {
// System.out.println(exp.first == null ? "null" : exp.first);
//}
return r;
}
| static List<Expression> topLevelExps(RSyntaxDocument doc) {
List<Expression> r = new LinkedList<Expression>();
int parenLevel = 0;
int height = 0;
boolean first = false;
StringBuilder contents = new StringBuilder();
boolean contentsAdmittable = false;
ExpType firstType = ExpType.FINAL;
int charIndex = -1;
Expression prev = null;
int gapHeight = 0;
for (int i = 0; i < doc.getDefaultRootElement().getElementCount(); i++) {
height++;
Token token = doc.getTokenListForLine(i);
while (token != null && token.offset != -1) {
//System.out.println(token);
if (charIndex == -1) {
charIndex = token.offset;
}
if (!token.isComment() && !token.isWhitespace() && !token.isSingleChar('\r')) {
contents.append(token.text, token.textOffset, token.textCount);
if (firstType == ExpType.FINAL && !token.isSingleChar('(')) {
firstType = token.type == Token.RESERVED_WORD_2 ? ExpType.UNDOABLE : ExpType.NORMAL;
if (token.getLexeme().equalsIgnoreCase("defproperty")) {
firstType = ExpType.UNDOABLE;
}
gapHeight = height - 1;
height = 1;
}
contentsAdmittable = true;
} else if (token.isWhitespace()) {
contents.append(token.text, token.textOffset, token.textCount);
}
if (token.isSingleChar('(')) {
parenLevel++;
} else if (token.isSingleChar(')') && parenLevel > 0) {
parenLevel--;
}
boolean nextTokenIsNull = token.getNextToken() == null ||
token.getNextToken().type == Token.NULL;
if (parenLevel == 0 && nextTokenIsNull && contents.length() != 0 && contentsAdmittable) {
if (prev != null) {
prev.nextGapHeight = gapHeight;
}
prev = new Expression(height, contents.toString(), firstType, charIndex,
token.offset + token.textCount, prev);
prev.prevGapHeight = gapHeight;
r.add(prev);
firstType = ExpType.FINAL;
charIndex = -1;
contents = new StringBuilder();
contentsAdmittable = false;
height = 0;
}
if (first) first = false;
token = token.getNextToken();
}
contents.append('\n');
}
r.add(new Expression(height, "", ExpType.FINAL, charIndex, -1, prev));
//for (Expression exp : r) {
// System.out.println(exp.first == null ? "null" : exp.first);
//}
return r;
}
|
diff --git a/src/de/tobifleig/lxc/data/FileManager.java b/src/de/tobifleig/lxc/data/FileManager.java
index 5f47338..00e9358 100644
--- a/src/de/tobifleig/lxc/data/FileManager.java
+++ b/src/de/tobifleig/lxc/data/FileManager.java
@@ -1,203 +1,203 @@
/*
* Copyright 2009, 2010, 2011, 2012 Tobias Fleig (tobifleig gmail com)
*
* All rights reserved.
*
* This file is part of LanXchange.
*
* LanXchange is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LanXchange is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LanXchange. If not, see <http://www.gnu.org/licenses/>.
*/
package de.tobifleig.lxc.data;
import de.tobifleig.lxc.net.LXCInstance;
import de.tobifleig.lxc.net.TransFileList;
import java.util.*;
/**
* Manages own & remote LXCFiles
*
* @author Tobias Fleig <tobifleig googlemail com>
*/
public class FileManager {
/**
* Contains all LXCFiles.
*/
private LinkedList<LXCFile> files;
/**
* Stores the latest List of available Files for each instance.
*/
private HashMap<LXCInstance, List<LXCFile>> recentFileLists;
/**
* Creates a new FileManager.
*/
public FileManager() {
files = new LinkedList<LXCFile>();
recentFileLists = new HashMap<LXCInstance, List<LXCFile>>();
}
/**
* Computes incoming TransFileLists.
*
* @param receivedList the received list
* @param sender the origin of this list
*/
public void computeFileList(TransFileList receivedList, LXCInstance sender) {
List<LXCFile> rawList = receivedList.getAll();
- recentFileLists.put(sender, rawList);
+ recentFileLists.put(sender, new ArrayList<LXCFile>(rawList)); // store a copy!
Iterator<LXCFile> iter = files.iterator();
// Remove all files no longer offerd by this instance
while (iter.hasNext()) {
LXCFile file = iter.next();
if (sender.equals(file.getInstance())) {
if (!rawList.contains(file)) {
// no longer offered, remove it, if not download{ing,ed}
if (file.getJobs().isEmpty() && !file.isAvailable()) {
iter.remove();
} else {
// keep, ignore in next step:
rawList.remove(file);
}
} else {
// already known, ignore in next step
rawList.remove(file);
}
}
}
receivedList.setInstance(sender);
receivedList.limitTransVersions();
files.addAll(rawList);
}
/**
* Removes all LXCFiles offered by the given LXCInstance
*
* @param instance the instance which files should be no longer available
*/
public void instanceRemoved(LXCInstance instance) {
recentFileLists.remove(instance);
Iterator<LXCFile> iter = files.iterator();
while (iter.hasNext()) {
LXCFile file = iter.next();
if (file.getInstance().equals(instance)) {
// only delete if not download{ing,ed}
if (file.getJobs().isEmpty() && !file.isAvailable()) {
iter.remove();
}
}
}
}
/**
* Returns the local representation for a LXCFile sent by a remote instance.
* This step is required to upload a file, because only the local representation contains the paths to the source files.
*
* @param remoteRepresentation the remote representation
* @return the local representation, or null if file not available
*/
public LXCFile localRepresentation(LXCFile remoteRepresentation) {
int index = files.indexOf(remoteRepresentation);
if (index != -1) {
return files.get(index);
}
return null;
}
/**
* Creates an up-to-date TransFileList containing all LXCFiles offered by this instance.
*
* @return a TransFileList containing all LXCFiles
*/
public TransFileList getTransFileList() {
ArrayList<LXCFile> offeredFiles = new ArrayList<LXCFile>();
for (LXCFile file : files) {
if (file.isLocal()) {
offeredFiles.add(file);
}
}
return new TransFileList(offeredFiles);
}
/**
* Returns a list of all known Files.
* This list is backed by the internal list, but not modifiable.
*
* @see java.util.Collections
* @return a list of all known files, backed but unmodifiable
*/
public List<LXCFile> getList() {
return Collections.unmodifiableList(files);
}
/**
* Adds a file offered by the local instance.
*
* @param newfile the new file
*/
public void addLocal(LXCFile newfile) {
// do not allow duplicates
for (LXCFile file : files) {
if (file.equals(newfile)) {
return;
}
}
files.add(newfile);
}
/**
* Removes a file offered by the local instance.
*
* @param file a file offered by the local instance
*/
public void removeLocal(LXCFile file) {
files.remove(file);
}
/**
* Returns true, if there are any transfers running.
*
* @return true, if still transferring
*/
public boolean transferRunning() {
for (LXCFile file : files) {
if (!file.getJobs().isEmpty()) {
return true;
}
}
return false;
}
/**
* Resets a available file.
* Resetting a file reverts the "downloaded"-flag.
* If no longer available, the file will disappear.
* Otherwise, it can be redownloaded.
*
* @param file the available, non-local file to reset
*/
public void resetAvailableFile(LXCFile file) {
if (file.isAvailable() && !file.isLocal() && !file.isLocked()) {
file.setAvailable(false);
if (!recentFileLists.containsKey(file.getInstance()) || !recentFileLists.get(file.getInstance()).contains(file)) {
files.remove(file);
}
} else {
throw new IllegalArgumentException("Cannot reset given file! (debug: "
+ file.getShownName() + " " + file.isAvailable() + " "
+ file.isLocal() + " " + file.isLocked());
}
}
}
| true | true | public void computeFileList(TransFileList receivedList, LXCInstance sender) {
List<LXCFile> rawList = receivedList.getAll();
recentFileLists.put(sender, rawList);
Iterator<LXCFile> iter = files.iterator();
// Remove all files no longer offerd by this instance
while (iter.hasNext()) {
LXCFile file = iter.next();
if (sender.equals(file.getInstance())) {
if (!rawList.contains(file)) {
// no longer offered, remove it, if not download{ing,ed}
if (file.getJobs().isEmpty() && !file.isAvailable()) {
iter.remove();
} else {
// keep, ignore in next step:
rawList.remove(file);
}
} else {
// already known, ignore in next step
rawList.remove(file);
}
}
}
receivedList.setInstance(sender);
receivedList.limitTransVersions();
files.addAll(rawList);
}
| public void computeFileList(TransFileList receivedList, LXCInstance sender) {
List<LXCFile> rawList = receivedList.getAll();
recentFileLists.put(sender, new ArrayList<LXCFile>(rawList)); // store a copy!
Iterator<LXCFile> iter = files.iterator();
// Remove all files no longer offerd by this instance
while (iter.hasNext()) {
LXCFile file = iter.next();
if (sender.equals(file.getInstance())) {
if (!rawList.contains(file)) {
// no longer offered, remove it, if not download{ing,ed}
if (file.getJobs().isEmpty() && !file.isAvailable()) {
iter.remove();
} else {
// keep, ignore in next step:
rawList.remove(file);
}
} else {
// already known, ignore in next step
rawList.remove(file);
}
}
}
receivedList.setInstance(sender);
receivedList.limitTransVersions();
files.addAll(rawList);
}
|
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/script/EngineScriptableClassInfo.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/script/EngineScriptableClassInfo.java
index c1ba20f00..bb2311ad0 100644
--- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/script/EngineScriptableClassInfo.java
+++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/script/EngineScriptableClassInfo.java
@@ -1,49 +1,49 @@
/***********************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.report.engine.api.script;
import org.eclipse.birt.report.model.api.metadata.IClassInfo;
import org.eclipse.birt.report.model.api.scripts.ClassInfo;
import org.eclipse.birt.report.model.api.scripts.IScriptableObjectClassInfo;
import org.eclipse.birt.report.model.api.scripts.ScriptableClassInfo;
public class EngineScriptableClassInfo extends ScriptableClassInfo
implements
IScriptableObjectClassInfo
{
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.api.scripts.IScriptableObjectClassInfo#
* getScriptableClass(java.lang.String)
*/
public IClassInfo getScriptableClass( String className )
{
try
{
Class clazz = Class.forName( className );
ClassInfo info = new ClassInfo( clazz );
return info;
}
catch ( ClassNotFoundException e )
{
- return getScriptableClass( className );
+ return getClass( className );
}
catch ( RuntimeException e )
{
return null;
}
}
}
| true | true | public IClassInfo getScriptableClass( String className )
{
try
{
Class clazz = Class.forName( className );
ClassInfo info = new ClassInfo( clazz );
return info;
}
catch ( ClassNotFoundException e )
{
return getScriptableClass( className );
}
catch ( RuntimeException e )
{
return null;
}
}
| public IClassInfo getScriptableClass( String className )
{
try
{
Class clazz = Class.forName( className );
ClassInfo info = new ClassInfo( clazz );
return info;
}
catch ( ClassNotFoundException e )
{
return getClass( className );
}
catch ( RuntimeException e )
{
return null;
}
}
|
diff --git a/intermediate/tx-synch/src/main/java/org/springframework/integration/samples/advice/TransactionSynchronizationDemo.java b/intermediate/tx-synch/src/main/java/org/springframework/integration/samples/advice/TransactionSynchronizationDemo.java
index 5841110a..944a7b9f 100755
--- a/intermediate/tx-synch/src/main/java/org/springframework/integration/samples/advice/TransactionSynchronizationDemo.java
+++ b/intermediate/tx-synch/src/main/java/org/springframework/integration/samples/advice/TransactionSynchronizationDemo.java
@@ -1,63 +1,63 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.samples.advice;
import org.apache.log4j.Logger;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Gary Russell
* @since 2.2
*
*/
public class TransactionSynchronizationDemo {
private static final Logger LOGGER = Logger.getLogger(TransactionSynchronizationDemo.class);
public static void main(String[] args) throws Exception {
LOGGER.info("\n========================================================="
+ "\n "
+ "\n Welcome to Spring Integration! "
+ "\n "
+ "\n For more information please visit: "
+ "\n http://www.springsource.org/spring-integration "
+ "\n "
+ "\n=========================================================" );
final AbstractApplicationContext context =
new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/transaction-synch-context.xml");
context.registerShutdownHook();
LOGGER.info("\n========================================================="
+ "\n "
+ "\n This is the Transaction Synchronization Sample - "
+ "\n "
+ "\n Press 'Enter' to terminate. "
+ "\n "
+ "\n Place a file in " + System.getProperty("java.io.tmpdir") + "/txSynchDemo ending "
+ "\n with .txt "
+ "\n If the first line begins with 'fail' the transaction "
+ "\n transaction will be rolled back.The result of the "
+ "\n expression evaluation is logged. "
+ "\n "
+ "\n=========================================================" );
- System.out.println(System.getProperty("java.io.tmpdir") + "/txSynchDir");
+ System.out.println(System.getProperty("java.io.tmpdir") + "/txSynchDemo");
System.in.read();
System.exit(0);
}
}
| true | true | public static void main(String[] args) throws Exception {
LOGGER.info("\n========================================================="
+ "\n "
+ "\n Welcome to Spring Integration! "
+ "\n "
+ "\n For more information please visit: "
+ "\n http://www.springsource.org/spring-integration "
+ "\n "
+ "\n=========================================================" );
final AbstractApplicationContext context =
new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/transaction-synch-context.xml");
context.registerShutdownHook();
LOGGER.info("\n========================================================="
+ "\n "
+ "\n This is the Transaction Synchronization Sample - "
+ "\n "
+ "\n Press 'Enter' to terminate. "
+ "\n "
+ "\n Place a file in " + System.getProperty("java.io.tmpdir") + "/txSynchDemo ending "
+ "\n with .txt "
+ "\n If the first line begins with 'fail' the transaction "
+ "\n transaction will be rolled back.The result of the "
+ "\n expression evaluation is logged. "
+ "\n "
+ "\n=========================================================" );
System.out.println(System.getProperty("java.io.tmpdir") + "/txSynchDir");
System.in.read();
System.exit(0);
}
| public static void main(String[] args) throws Exception {
LOGGER.info("\n========================================================="
+ "\n "
+ "\n Welcome to Spring Integration! "
+ "\n "
+ "\n For more information please visit: "
+ "\n http://www.springsource.org/spring-integration "
+ "\n "
+ "\n=========================================================" );
final AbstractApplicationContext context =
new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/transaction-synch-context.xml");
context.registerShutdownHook();
LOGGER.info("\n========================================================="
+ "\n "
+ "\n This is the Transaction Synchronization Sample - "
+ "\n "
+ "\n Press 'Enter' to terminate. "
+ "\n "
+ "\n Place a file in " + System.getProperty("java.io.tmpdir") + "/txSynchDemo ending "
+ "\n with .txt "
+ "\n If the first line begins with 'fail' the transaction "
+ "\n transaction will be rolled back.The result of the "
+ "\n expression evaluation is logged. "
+ "\n "
+ "\n=========================================================" );
System.out.println(System.getProperty("java.io.tmpdir") + "/txSynchDemo");
System.in.read();
System.exit(0);
}
|
diff --git a/src/edu/ucla/loni/server/Upload.java b/src/edu/ucla/loni/server/Upload.java
index bcb0107..00517c0 100644
--- a/src/edu/ucla/loni/server/Upload.java
+++ b/src/edu/ucla/loni/server/Upload.java
@@ -1,142 +1,142 @@
package edu.ucla.loni.server;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jdom2.Document;
import edu.ucla.loni.shared.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
@SuppressWarnings("serial")
public class Upload extends HttpServlet {
/**
* Writes a file
*/
private void writeFile(String filename, InputStream in, String root, String packageName) throws Exception{
Document doc = ServerUtils.readXML(in);
Pipefile pipe = ServerUtils.parse(doc);
// Update the packageName
if (packageName != null && packageName.length() > 0){
pipe.packageName = packageName;
doc = ServerUtils.update(doc, pipe, true);
}
// Write the document
String destPath = ServerUtils.newAbsolutePath(root, pipe.packageName, pipe.type, filename);
File dest = new File(destPath);
// Create parent folders if needed
File destDir = dest.getParentFile();
if (destDir.exists() == false){
boolean success = destDir.mkdirs();
if (!success){
throw new Exception("Destination folders could not be created");
}
}
// Create a new file
if (dest.createNewFile() == false){
// TODO rename file to something else
throw new Exception("File already exists");
}
ServerUtils.writeXML(dest, doc);
pipe.absolutePath = destPath;
int dirId = Database.selectOrInsertDirectory(root);
Timestamp fs_lastModified = new Timestamp(dest.lastModified());
Database.insertPipefile(dirId, pipe, fs_lastModified);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
if ( ServletFileUpload.isMultipartContent( req ) ){
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload( factory );
try {
@SuppressWarnings("unchecked")
List<FileItem> items = upload.parseRequest( req );
// Go through the items and get the root and package
String root = "";
String packageName = "";
for ( FileItem item : items ){
if ( item.isFormField() ){
if (item.getFieldName().equals("root")){
root = item.getString();
} else if (item.getFieldName().equals("packageName")){
packageName = item.getString();
}
}
}
if (root == ""){
res.getWriter().println("error :: Root directory has not been found.");
return;
}
// Go through items and process urls and files
for ( FileItem item : items ){
// Uploaded File
if (item.isFormField() == false){
String filename = item.getName();;
try {
InputStream in = item.getInputStream();
writeFile(filename, in, root, packageName);
in.close();
}
catch (Exception e) {
res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage() );
}
}
// URLs
- if (item.isFormField() && item.getFieldName().equals("urls") && item.getString() != ""){
+ if (item.isFormField() && item.getFieldName().equals("urls") && item.getString().equals("") == false){
String urlListAsStr = item.getString();
String[] urlList = urlListAsStr.split("\n");
for (String urlStr : urlList){
try{
URL url = new URL(urlStr);
URLConnection urlc = url.openConnection();
String filename = ServerUtils.extractNameFromURL(urlStr);
InputStream in = urlc.getInputStream();
writeFile(filename, in, root, packageName);
in.close();
}
catch(Exception e){
res.getWriter().println("Failed to upload " + urlStr);
return;
}
}
}
}
}
catch ( Exception e ){
res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage());
}
}
}
}
| true | true | public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
if ( ServletFileUpload.isMultipartContent( req ) ){
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload( factory );
try {
@SuppressWarnings("unchecked")
List<FileItem> items = upload.parseRequest( req );
// Go through the items and get the root and package
String root = "";
String packageName = "";
for ( FileItem item : items ){
if ( item.isFormField() ){
if (item.getFieldName().equals("root")){
root = item.getString();
} else if (item.getFieldName().equals("packageName")){
packageName = item.getString();
}
}
}
if (root == ""){
res.getWriter().println("error :: Root directory has not been found.");
return;
}
// Go through items and process urls and files
for ( FileItem item : items ){
// Uploaded File
if (item.isFormField() == false){
String filename = item.getName();;
try {
InputStream in = item.getInputStream();
writeFile(filename, in, root, packageName);
in.close();
}
catch (Exception e) {
res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage() );
}
}
// URLs
if (item.isFormField() && item.getFieldName().equals("urls") && item.getString() != ""){
String urlListAsStr = item.getString();
String[] urlList = urlListAsStr.split("\n");
for (String urlStr : urlList){
try{
URL url = new URL(urlStr);
URLConnection urlc = url.openConnection();
String filename = ServerUtils.extractNameFromURL(urlStr);
InputStream in = urlc.getInputStream();
writeFile(filename, in, root, packageName);
in.close();
}
catch(Exception e){
res.getWriter().println("Failed to upload " + urlStr);
return;
}
}
}
}
}
catch ( Exception e ){
res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage());
}
}
}
| public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
if ( ServletFileUpload.isMultipartContent( req ) ){
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload( factory );
try {
@SuppressWarnings("unchecked")
List<FileItem> items = upload.parseRequest( req );
// Go through the items and get the root and package
String root = "";
String packageName = "";
for ( FileItem item : items ){
if ( item.isFormField() ){
if (item.getFieldName().equals("root")){
root = item.getString();
} else if (item.getFieldName().equals("packageName")){
packageName = item.getString();
}
}
}
if (root == ""){
res.getWriter().println("error :: Root directory has not been found.");
return;
}
// Go through items and process urls and files
for ( FileItem item : items ){
// Uploaded File
if (item.isFormField() == false){
String filename = item.getName();;
try {
InputStream in = item.getInputStream();
writeFile(filename, in, root, packageName);
in.close();
}
catch (Exception e) {
res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage() );
}
}
// URLs
if (item.isFormField() && item.getFieldName().equals("urls") && item.getString().equals("") == false){
String urlListAsStr = item.getString();
String[] urlList = urlListAsStr.split("\n");
for (String urlStr : urlList){
try{
URL url = new URL(urlStr);
URLConnection urlc = url.openConnection();
String filename = ServerUtils.extractNameFromURL(urlStr);
InputStream in = urlc.getInputStream();
writeFile(filename, in, root, packageName);
in.close();
}
catch(Exception e){
res.getWriter().println("Failed to upload " + urlStr);
return;
}
}
}
}
}
catch ( Exception e ){
res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage());
}
}
}
|
diff --git a/CenterConsole.java b/CenterConsole.java
index 07462e0..25d10ef 100644
--- a/CenterConsole.java
+++ b/CenterConsole.java
@@ -1,180 +1,180 @@
//this panel is the center panel that contains the info of the current track playing.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
class CenterConsole extends JPanel {
JLabel artistLabel; //artist
JLabel titleLabel; //song name
JLabel albumLabel; //album title
JButton setTagButton; //button to set tag
JLabel timeNowLabel; //shows current time in track
JLabel totTimeLabel; //shows total time in track
JProgressBar trackTimeBar; //shows current time position in song
//trackTime can maybe be a JSlider
JPanel tagButtonPanel; //holds buttons for tags
JPanel tagPanel; //holds the visual tags
JButton tagButton1;
JButton tagButton2;
JButton tagButton3;
JButton tagButton4;
JButton tagButton5;
JButton tagButton6;
JButton tabRemoveButton;
CenterConsole() {
setBorder(BorderFactory.createLineBorder(Color.BLACK,1));
//set layout
setLayout(new GridBagLayout());
//initialize Components
initComponents();
//set size
Dimension size = new Dimension(400,200); //dimension of panel
this.setPreferredSize(size); //set size of panel
this.setBackground(Color.BLACK);
}
public void initComponents(){
artistLabel = new JLabel("Artist");
titleLabel = new JLabel("Title");
albumLabel = new JLabel("Album");
setTagButton = new JButton("Tag");
timeNowLabel = new JLabel("0:00");
totTimeLabel = new JLabel("0:00");
trackTimeBar = new JProgressBar(0,0); //initializes JProgressBar to 0 until a track is linked up
tagPanel = new JPanel();
GridBagConstraints c = new GridBagConstraints();
//add artistLabel
c.gridx = 3;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
this.add(artistLabel,c);
//add titleArtist
c.gridx = 3;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
this.add(titleLabel,c);
//add albumLabel
c.gridx = 3;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
this.add(albumLabel,c);
//add setTagButton
c.gridx = 4;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
this.add(setTagButton,c);
//add timeNowLabel
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = .2;
this.add(timeNowLabel,c);
//add trackTimeBar
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 3;
c.gridheight = 1;
c.weightx = .6;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(trackTimeBar,c);
//add totTimeLabel
c.gridx = 4;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = .2;
this.add(totTimeLabel,c);
//add tagPanel
c.gridx = 0;
c.gridy = 4;
c.weightx = 1;
c.gridwidth = 6;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(tagPanel,c);
//adds listeners to CenterContent
setTagButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//tag the current point in the track
postTag();
}
});
trackTimeBar.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e){
//updates timeNowLabel as track progresses
- timeNowLabel.setText(trackTimeBar.getValue().toString());
+ // timeNowLabel.setText(trackTimeBar.getValue().toString());
}
});
}
public void changeTrackInfo(Track t){
titleLabel.setText(t.title);
if(t.artist != null){
artistLabel.setText(t.artist);
}else{
artistLabel.setText("");
}
if(t.album != null){
albumLabel.setText(t.album);
}else{
albumLabel.setText("");
}
//set totTimeLabel with the length of the track
}
public void postTag(){
//post tag at current time position of the track
}
}
/*
NEED LISTENERS FOR
-JButton setTag
-JLabel timeNow needs to always update with current time position
-JProgressBar trackTime should always update with current time position
-JButton setTag needs actionListener
**JPanel tagPanel should update whenever a new tag is created and should load a tag when a tag is chosen
--also this 'tagPanel' should hold buttons for the tags
--do we want to generate a new button anytime a setTag is pushed and a new tag is made or
have a static amount of buttons?
-tagPanel has a static number of buttons. unused ones are grayed out or invisible
-JLabel totTime is a static label...shouldn't change
*/
| true | true | public void initComponents(){
artistLabel = new JLabel("Artist");
titleLabel = new JLabel("Title");
albumLabel = new JLabel("Album");
setTagButton = new JButton("Tag");
timeNowLabel = new JLabel("0:00");
totTimeLabel = new JLabel("0:00");
trackTimeBar = new JProgressBar(0,0); //initializes JProgressBar to 0 until a track is linked up
tagPanel = new JPanel();
GridBagConstraints c = new GridBagConstraints();
//add artistLabel
c.gridx = 3;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
this.add(artistLabel,c);
//add titleArtist
c.gridx = 3;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
this.add(titleLabel,c);
//add albumLabel
c.gridx = 3;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
this.add(albumLabel,c);
//add setTagButton
c.gridx = 4;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
this.add(setTagButton,c);
//add timeNowLabel
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = .2;
this.add(timeNowLabel,c);
//add trackTimeBar
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 3;
c.gridheight = 1;
c.weightx = .6;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(trackTimeBar,c);
//add totTimeLabel
c.gridx = 4;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = .2;
this.add(totTimeLabel,c);
//add tagPanel
c.gridx = 0;
c.gridy = 4;
c.weightx = 1;
c.gridwidth = 6;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(tagPanel,c);
//adds listeners to CenterContent
setTagButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//tag the current point in the track
postTag();
}
});
trackTimeBar.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e){
//updates timeNowLabel as track progresses
timeNowLabel.setText(trackTimeBar.getValue().toString());
}
});
}
| public void initComponents(){
artistLabel = new JLabel("Artist");
titleLabel = new JLabel("Title");
albumLabel = new JLabel("Album");
setTagButton = new JButton("Tag");
timeNowLabel = new JLabel("0:00");
totTimeLabel = new JLabel("0:00");
trackTimeBar = new JProgressBar(0,0); //initializes JProgressBar to 0 until a track is linked up
tagPanel = new JPanel();
GridBagConstraints c = new GridBagConstraints();
//add artistLabel
c.gridx = 3;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
this.add(artistLabel,c);
//add titleArtist
c.gridx = 3;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
this.add(titleLabel,c);
//add albumLabel
c.gridx = 3;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
this.add(albumLabel,c);
//add setTagButton
c.gridx = 4;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
this.add(setTagButton,c);
//add timeNowLabel
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = .2;
this.add(timeNowLabel,c);
//add trackTimeBar
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 3;
c.gridheight = 1;
c.weightx = .6;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(trackTimeBar,c);
//add totTimeLabel
c.gridx = 4;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = .2;
this.add(totTimeLabel,c);
//add tagPanel
c.gridx = 0;
c.gridy = 4;
c.weightx = 1;
c.gridwidth = 6;
c.fill = GridBagConstraints.HORIZONTAL;
this.add(tagPanel,c);
//adds listeners to CenterContent
setTagButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//tag the current point in the track
postTag();
}
});
trackTimeBar.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e){
//updates timeNowLabel as track progresses
// timeNowLabel.setText(trackTimeBar.getValue().toString());
}
});
}
|
diff --git a/software/nosql/src/main/java/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetImpl.java b/software/nosql/src/main/java/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetImpl.java
index d65e5ad09..8b9b07da2 100644
--- a/software/nosql/src/main/java/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetImpl.java
+++ b/software/nosql/src/main/java/brooklyn/entity/nosql/mongodb/MongoDBReplicaSetImpl.java
@@ -1,351 +1,352 @@
package brooklyn.entity.nosql.mongodb;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.enricher.Enrichers;
import brooklyn.entity.Entity;
import brooklyn.entity.basic.Lifecycle;
import brooklyn.entity.group.AbstractMembershipTrackingPolicy;
import brooklyn.entity.group.DynamicClusterImpl;
import brooklyn.entity.proxying.EntitySpec;
import brooklyn.entity.trait.Startable;
import brooklyn.event.AttributeSensor;
import brooklyn.event.SensorEvent;
import brooklyn.event.SensorEventListener;
import brooklyn.location.Location;
import brooklyn.util.collections.MutableList;
import brooklyn.util.collections.MutableMap;
import brooklyn.util.collections.MutableSet;
import brooklyn.util.text.Strings;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
/**
* Implementation of {@link MongoDBReplicaSet}.
*
* Replica sets have a <i>minimum</i> of three members.
*
* Removal strategy is always {@link #NON_PRIMARY_REMOVAL_STRATEGY}.
*/
public class MongoDBReplicaSetImpl extends DynamicClusterImpl implements MongoDBReplicaSet {
private static final Logger LOG = LoggerFactory.getLogger(MongoDBReplicaSetImpl.class);
// Provides IDs for replica set members. The first member will have ID 0.
private final AtomicInteger nextMemberId = new AtomicInteger(0);
private AbstractMembershipTrackingPolicy policy;
private final AtomicBoolean mustInitialise = new AtomicBoolean(true);
@SuppressWarnings("unchecked")
protected static final List<AttributeSensor<Long>> SENSORS_TO_SUM = Arrays.asList(
MongoDBServer.OPCOUNTERS_INSERTS,
MongoDBServer.OPCOUNTERS_QUERIES,
MongoDBServer.OPCOUNTERS_UPDATES,
MongoDBServer.OPCOUNTERS_DELETES,
MongoDBServer.OPCOUNTERS_GETMORE,
MongoDBServer.OPCOUNTERS_COMMAND,
MongoDBServer.NETWORK_BYTES_IN,
MongoDBServer.NETWORK_BYTES_OUT,
MongoDBServer.NETWORK_NUM_REQUESTS);
public MongoDBReplicaSetImpl() {
}
/**
* Manages member addition and removal.
*
* It's important that this is a single thread: the concurrent addition and removal
* of members from the set would almost certainly have unintended side effects,
* like reconfigurations using outdated ReplicaSetConfig instances.
*/
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
/** true iff input is a non-null MongoDBServer with attribute REPLICA_SET_MEMBER_STATUS PRIMARY. */
static final Predicate<Entity> IS_PRIMARY = new Predicate<Entity>() {
// getPrimary relies on instanceof check
@Override public boolean apply(@Nullable Entity input) {
return input != null
&& input instanceof MongoDBServer
&& ReplicaSetMemberStatus.PRIMARY.equals(input.getAttribute(MongoDBServer.REPLICA_SET_MEMBER_STATUS));
}
};
/** true iff. input is a non-null MongoDBServer with attribute REPLICA_SET_MEMBER_STATUS SECONDARY. */
static final Predicate<Entity> IS_SECONDARY = new Predicate<Entity>() {
@Override public boolean apply(@Nullable Entity input) {
// getSecondaries relies on instanceof check
return input != null
&& input instanceof MongoDBServer
&& ReplicaSetMemberStatus.SECONDARY.equals(input.getAttribute(MongoDBServer.REPLICA_SET_MEMBER_STATUS));
}
};
/**
* {@link Function} for use as the cluster's removal strategy. Chooses any entity with
* {@link MongoDBServer#IS_PRIMARY_FOR_REPLICA_SET} true last of all.
*/
private static final Function<Collection<Entity>, Entity> NON_PRIMARY_REMOVAL_STRATEGY = new Function<Collection<Entity>, Entity>() {
@Override
public Entity apply(@Nullable Collection<Entity> entities) {
checkArgument(entities != null && entities.size() > 0, "Expect list of MongoDBServers to have at least one entry");
return Iterables.tryFind(entities, Predicates.not(IS_PRIMARY)).or(Iterables.get(entities, 0));
}
};
/** @return {@link #NON_PRIMARY_REMOVAL_STRATEGY} */
@Override
public Function<Collection<Entity>, Entity> getRemovalStrategy() {
return NON_PRIMARY_REMOVAL_STRATEGY;
}
@Override
protected EntitySpec<?> getMemberSpec() {
return getConfig(MEMBER_SPEC, EntitySpec.create(MongoDBServer.class));
}
/**
* Sets {@link MongoDBServer#REPLICA_SET}.
*/
@Override
protected Map<?,?> getCustomChildFlags() {
return ImmutableMap.builder()
.putAll(super.getCustomChildFlags())
.put(MongoDBServer.REPLICA_SET, getProxy())
.build();
}
@Override
public String getName() {
return getConfig(REPLICA_SET_NAME);
}
@Override
public MongoDBServer getPrimary() {
return Iterables.tryFind(getReplicas(), IS_PRIMARY).orNull();
}
@Override
public Collection<MongoDBServer> getSecondaries() {
return FluentIterable.from(getReplicas())
.filter(IS_SECONDARY)
.toList();
}
@Override
public Collection<MongoDBServer> getReplicas() {
return FluentIterable.from(getMembers())
.transform(new Function<Entity, MongoDBServer>() {
@Override public MongoDBServer apply(Entity input) {
return MongoDBServer.class.cast(input);
}
})
.toList();
}
/**
* Initialises the replica set with the given server as primary if {@link #mustInitialise} is true,
* otherwise schedules the addition of a new secondary.
*/
private void serverAdded(MongoDBServer server) {
LOG.debug("Server added: {}. SERVICE_UP: {}", server, server.getAttribute(MongoDBServer.SERVICE_UP));
// Set the primary if the replica set hasn't been initialised.
if (mustInitialise.compareAndSet(true, false)) {
if (LOG.isInfoEnabled())
LOG.info("First server up in {} is: {}", getName(), server);
boolean replicaSetInitialised = server.initializeReplicaSet(getName(), nextMemberId.getAndIncrement());
if (replicaSetInitialised) {
setAttribute(PRIMARY_ENTITY, server);
setAttribute(Startable.SERVICE_UP, true);
} else {
setAttribute(SERVICE_STATE, Lifecycle.ON_FIRE);
}
} else {
if (LOG.isDebugEnabled())
LOG.debug("Scheduling addition of member to {}: {}", getName(), server);
addSecondaryWhenPrimaryIsNonNull(server);
}
}
/**
* Adds a server as a secondary in the replica set.
* <p/>
* If {@link #getPrimary} returns non-null submit the secondary to the primary's
* {@link MongoDBClientSupport}. Otherwise, reschedule the task to run again in three
* seconds time (in the hope that next time the primary will be available).
*/
private void addSecondaryWhenPrimaryIsNonNull(final MongoDBServer secondary) {
executor.submit(new Runnable() {
@Override
public void run() {
// SERVICE_UP is not guaranteed when additional members are added to the set.
Boolean isAvailable = secondary.getAttribute(MongoDBServer.SERVICE_UP);
MongoDBServer primary = getPrimary();
if (Boolean.TRUE.equals(isAvailable) && primary != null) {
primary.addMemberToReplicaSet(secondary, nextMemberId.incrementAndGet());
if (LOG.isInfoEnabled()) {
LOG.info("{} added to replica set {}", secondary, getName());
}
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("Rescheduling addition of member {} to replica set {}: service_up={}, primary={}",
new Object[]{secondary, getName(), isAvailable, primary});
}
// Could limit number of retries
executor.schedule(this, 3, TimeUnit.SECONDS);
}
}
});
}
/**
* Removes a server from the replica set.
* <p/>
* Submits a task that waits for the member to be down and for the replica set to have a primary
* member, then reconfigures the set to remove the member, to {@link #executor}. If either of the
* two conditions are not met then the task reschedules itself.
*
* @param member The server to be removed from the replica set.
*/
private void serverRemoved(final MongoDBServer member) {
if (LOG.isDebugEnabled())
LOG.debug("Scheduling removal of member from {}: {}", getName(), member);
// FIXME is there a chance of race here?
if (member.equals(getAttribute(PRIMARY_ENTITY)))
setAttribute(PRIMARY_ENTITY, null);
executor.submit(new Runnable() {
@Override
public void run() {
// Wait until the server has been stopped before reconfiguring the set. Quoth the MongoDB doc:
// for best results always shut down the mongod instance before removing it from a replica set.
Boolean isAvailable = member.getAttribute(MongoDBServer.SERVICE_UP);
// Wait for the replica set to elect a new primary if the set is reconfiguring itself.
MongoDBServer primary = getPrimary();
if (primary != null && !isAvailable) {
primary.removeMemberFromReplicaSet(member);
if (LOG.isInfoEnabled()) {
LOG.info("Removed {} from replica set {}", member, getName());
}
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("Rescheduling removal of member {} from replica set {}: service_up={}, primary={}",
new Object[]{member, getName(), isAvailable, primary});
}
executor.schedule(this, 3, TimeUnit.SECONDS);
}
}
});
}
@Override
public void start(Collection<? extends Location> locations) {
// Promises that all the cluster's members have SERVICE_UP true on returning.
super.start(locations);
policy = new AbstractMembershipTrackingPolicy(MutableMap.of("name", getName() + " membership tracker")) {
@Override protected void onEntityChange(Entity member) {
// Ignored
}
@Override protected void onEntityAdded(Entity member) {
serverAdded((MongoDBServer) member);
}
@Override protected void onEntityRemoved(Entity member) {
serverRemoved((MongoDBServer) member);
}
};
addPolicy(policy);
policy.setGroup(this);
for (AttributeSensor<Long> sensor: SENSORS_TO_SUM)
addEnricher(Enrichers.builder()
.aggregating(sensor)
.publishing(sensor)
.fromMembers()
+ .computingSum()
.valueToReportIfNoSensors(null)
.defaultValueForUnreportedSensors(null)
.build());
// FIXME would it be simpler to have a *subscription* on four or five sensors on allMembers, including SERVICE_UP
// (which we currently don't check), rather than an enricher, and call to an "update" method?
addEnricher(Enrichers.builder()
.aggregating(MongoDBServer.REPLICA_SET_PRIMARY_ENDPOINT)
.publishing(MongoDBServer.REPLICA_SET_PRIMARY_ENDPOINT)
.fromMembers()
.valueToReportIfNoSensors(null)
.computing(new Function<Collection<String>,String>() {
@Override
public String apply(Collection<String> input) {
if (input==null || input.isEmpty()) return null;
Set<String> distinct = MutableSet.of();
for (String endpoint: input)
if (!Strings.isBlank(endpoint))
distinct.add(endpoint);
if (distinct.size()>1)
LOG.warn("Mongo replica set "+MongoDBReplicaSetImpl.this+" detetcted multiple masters (transitioning?): "+distinct);
return input.iterator().next();
}})
.build());
addEnricher(Enrichers.builder()
.aggregating(MongoDBServer.MONGO_SERVER_ENDPOINT)
.publishing(REPLICA_SET_ENDPOINTS)
.fromMembers()
.valueToReportIfNoSensors(null)
.computing(new Function<Collection<String>,List<String>>() {
@Override
public List<String> apply(Collection<String> input) {
Set<String> endpoints = new TreeSet<String>();
for (String endpoint: input) {
if (!Strings.isBlank(endpoint)) {
endpoints.add(endpoint);
}
}
return MutableList.copyOf(endpoints);
}})
.build());
subscribeToMembers(this, MongoDBServer.IS_PRIMARY_FOR_REPLICA_SET, new SensorEventListener<Boolean>() {
@Override public void onEvent(SensorEvent<Boolean> event) {
if (Boolean.TRUE == event.getValue())
setAttribute(PRIMARY_ENTITY, (MongoDBServer)event.getSource());
}
});
}
@Override
public void stop() {
// Do we want to remove the members from the replica set?
// - if the set is being stopped forever it's irrelevant
// - if the set might be restarted I think it just inconveniences us
// Terminate the executor immediately.
// Note that after this the executor will not run if the set is restarted.
executor.shutdownNow();
super.stop();
setAttribute(Startable.SERVICE_UP, false);
}
}
| true | true | public void start(Collection<? extends Location> locations) {
// Promises that all the cluster's members have SERVICE_UP true on returning.
super.start(locations);
policy = new AbstractMembershipTrackingPolicy(MutableMap.of("name", getName() + " membership tracker")) {
@Override protected void onEntityChange(Entity member) {
// Ignored
}
@Override protected void onEntityAdded(Entity member) {
serverAdded((MongoDBServer) member);
}
@Override protected void onEntityRemoved(Entity member) {
serverRemoved((MongoDBServer) member);
}
};
addPolicy(policy);
policy.setGroup(this);
for (AttributeSensor<Long> sensor: SENSORS_TO_SUM)
addEnricher(Enrichers.builder()
.aggregating(sensor)
.publishing(sensor)
.fromMembers()
.valueToReportIfNoSensors(null)
.defaultValueForUnreportedSensors(null)
.build());
// FIXME would it be simpler to have a *subscription* on four or five sensors on allMembers, including SERVICE_UP
// (which we currently don't check), rather than an enricher, and call to an "update" method?
addEnricher(Enrichers.builder()
.aggregating(MongoDBServer.REPLICA_SET_PRIMARY_ENDPOINT)
.publishing(MongoDBServer.REPLICA_SET_PRIMARY_ENDPOINT)
.fromMembers()
.valueToReportIfNoSensors(null)
.computing(new Function<Collection<String>,String>() {
@Override
public String apply(Collection<String> input) {
if (input==null || input.isEmpty()) return null;
Set<String> distinct = MutableSet.of();
for (String endpoint: input)
if (!Strings.isBlank(endpoint))
distinct.add(endpoint);
if (distinct.size()>1)
LOG.warn("Mongo replica set "+MongoDBReplicaSetImpl.this+" detetcted multiple masters (transitioning?): "+distinct);
return input.iterator().next();
}})
.build());
addEnricher(Enrichers.builder()
.aggregating(MongoDBServer.MONGO_SERVER_ENDPOINT)
.publishing(REPLICA_SET_ENDPOINTS)
.fromMembers()
.valueToReportIfNoSensors(null)
.computing(new Function<Collection<String>,List<String>>() {
@Override
public List<String> apply(Collection<String> input) {
Set<String> endpoints = new TreeSet<String>();
for (String endpoint: input) {
if (!Strings.isBlank(endpoint)) {
endpoints.add(endpoint);
}
}
return MutableList.copyOf(endpoints);
}})
.build());
subscribeToMembers(this, MongoDBServer.IS_PRIMARY_FOR_REPLICA_SET, new SensorEventListener<Boolean>() {
@Override public void onEvent(SensorEvent<Boolean> event) {
if (Boolean.TRUE == event.getValue())
setAttribute(PRIMARY_ENTITY, (MongoDBServer)event.getSource());
}
});
}
| public void start(Collection<? extends Location> locations) {
// Promises that all the cluster's members have SERVICE_UP true on returning.
super.start(locations);
policy = new AbstractMembershipTrackingPolicy(MutableMap.of("name", getName() + " membership tracker")) {
@Override protected void onEntityChange(Entity member) {
// Ignored
}
@Override protected void onEntityAdded(Entity member) {
serverAdded((MongoDBServer) member);
}
@Override protected void onEntityRemoved(Entity member) {
serverRemoved((MongoDBServer) member);
}
};
addPolicy(policy);
policy.setGroup(this);
for (AttributeSensor<Long> sensor: SENSORS_TO_SUM)
addEnricher(Enrichers.builder()
.aggregating(sensor)
.publishing(sensor)
.fromMembers()
.computingSum()
.valueToReportIfNoSensors(null)
.defaultValueForUnreportedSensors(null)
.build());
// FIXME would it be simpler to have a *subscription* on four or five sensors on allMembers, including SERVICE_UP
// (which we currently don't check), rather than an enricher, and call to an "update" method?
addEnricher(Enrichers.builder()
.aggregating(MongoDBServer.REPLICA_SET_PRIMARY_ENDPOINT)
.publishing(MongoDBServer.REPLICA_SET_PRIMARY_ENDPOINT)
.fromMembers()
.valueToReportIfNoSensors(null)
.computing(new Function<Collection<String>,String>() {
@Override
public String apply(Collection<String> input) {
if (input==null || input.isEmpty()) return null;
Set<String> distinct = MutableSet.of();
for (String endpoint: input)
if (!Strings.isBlank(endpoint))
distinct.add(endpoint);
if (distinct.size()>1)
LOG.warn("Mongo replica set "+MongoDBReplicaSetImpl.this+" detetcted multiple masters (transitioning?): "+distinct);
return input.iterator().next();
}})
.build());
addEnricher(Enrichers.builder()
.aggregating(MongoDBServer.MONGO_SERVER_ENDPOINT)
.publishing(REPLICA_SET_ENDPOINTS)
.fromMembers()
.valueToReportIfNoSensors(null)
.computing(new Function<Collection<String>,List<String>>() {
@Override
public List<String> apply(Collection<String> input) {
Set<String> endpoints = new TreeSet<String>();
for (String endpoint: input) {
if (!Strings.isBlank(endpoint)) {
endpoints.add(endpoint);
}
}
return MutableList.copyOf(endpoints);
}})
.build());
subscribeToMembers(this, MongoDBServer.IS_PRIMARY_FOR_REPLICA_SET, new SensorEventListener<Boolean>() {
@Override public void onEvent(SensorEvent<Boolean> event) {
if (Boolean.TRUE == event.getValue())
setAttribute(PRIMARY_ENTITY, (MongoDBServer)event.getSource());
}
});
}
|
diff --git a/media/sse/src/main/java/org/glassfish/jersey/media/sse/OutboundEventWriter.java b/media/sse/src/main/java/org/glassfish/jersey/media/sse/OutboundEventWriter.java
index a1990ecee..20fc4aeaf 100644
--- a/media/sse/src/main/java/org/glassfish/jersey/media/sse/OutboundEventWriter.java
+++ b/media/sse/src/main/java/org/glassfish/jersey/media/sse/OutboundEventWriter.java
@@ -1,126 +1,126 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* http://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.jersey.media.sse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import org.glassfish.jersey.internal.util.collection.Ref;
import org.glassfish.jersey.message.MessageBodyWorkers;
import org.glassfish.hk2.Services;
import org.glassfish.hk2.inject.Injector;
import org.jvnet.hk2.annotations.Inject;
/**
* Writer for {@link OutboundEvent}.
*
* @author Pavel Bucek (pavel.bucek at oracle.com)
*/
public class OutboundEventWriter implements MessageBodyWriter<OutboundEvent> {
private static final class References {
@Inject
private Ref<MessageBodyWorkers> messageBodyWorkers;
}
@Inject
private Services services;
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return (type.equals(OutboundEvent.class));
}
@Override
public long getSize(OutboundEvent incomingEvent, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
@SuppressWarnings("unchecked")
public void writeTo(OutboundEvent outboundEvent, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException {
final References references = services.forContract(Injector.class).get().inject(References.class);
if(outboundEvent.getComment() != null) {
entityStream.write(String.format(": %s\n", outboundEvent.getComment()).getBytes());
}
if(outboundEvent.getType() != null) {
final MessageBodyWorkers messageBodyWorkers = references.messageBodyWorkers.get();
final MessageBodyWriter messageBodyWriter = messageBodyWorkers.getMessageBodyWriter(outboundEvent.getType(),
null, annotations, (outboundEvent.getMediaType() == null ? MediaType.TEXT_PLAIN_TYPE : outboundEvent.getMediaType()));
if(outboundEvent.getName() != null) {
entityStream.write(String.format("event: %s\n", outboundEvent.getName()).getBytes());
}
if(outboundEvent.getId() != null) {
- entityStream.write(String.format("id: %s\n", outboundEvent.getName()).getBytes());
+ entityStream.write(String.format("id: %s\n", outboundEvent.getId()).getBytes());
}
messageBodyWriter.writeTo(outboundEvent.getData(), outboundEvent.getClass(), null, annotations, mediaType, httpHeaders, new OutputStream() {
private boolean start = true;
@Override
public void write(int i) throws IOException {
if(start) {
entityStream.write("data: ".getBytes());
start = false;
}
entityStream.write(i);
if(i == '\n') {
entityStream.write("data: ".getBytes());
}
}
});
}
entityStream.write("\n\n".getBytes());
entityStream.flush();
}
}
| true | true | public void writeTo(OutboundEvent outboundEvent, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException {
final References references = services.forContract(Injector.class).get().inject(References.class);
if(outboundEvent.getComment() != null) {
entityStream.write(String.format(": %s\n", outboundEvent.getComment()).getBytes());
}
if(outboundEvent.getType() != null) {
final MessageBodyWorkers messageBodyWorkers = references.messageBodyWorkers.get();
final MessageBodyWriter messageBodyWriter = messageBodyWorkers.getMessageBodyWriter(outboundEvent.getType(),
null, annotations, (outboundEvent.getMediaType() == null ? MediaType.TEXT_PLAIN_TYPE : outboundEvent.getMediaType()));
if(outboundEvent.getName() != null) {
entityStream.write(String.format("event: %s\n", outboundEvent.getName()).getBytes());
}
if(outboundEvent.getId() != null) {
entityStream.write(String.format("id: %s\n", outboundEvent.getName()).getBytes());
}
messageBodyWriter.writeTo(outboundEvent.getData(), outboundEvent.getClass(), null, annotations, mediaType, httpHeaders, new OutputStream() {
private boolean start = true;
@Override
public void write(int i) throws IOException {
if(start) {
entityStream.write("data: ".getBytes());
start = false;
}
entityStream.write(i);
if(i == '\n') {
entityStream.write("data: ".getBytes());
}
}
});
}
entityStream.write("\n\n".getBytes());
entityStream.flush();
}
| public void writeTo(OutboundEvent outboundEvent, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException {
final References references = services.forContract(Injector.class).get().inject(References.class);
if(outboundEvent.getComment() != null) {
entityStream.write(String.format(": %s\n", outboundEvent.getComment()).getBytes());
}
if(outboundEvent.getType() != null) {
final MessageBodyWorkers messageBodyWorkers = references.messageBodyWorkers.get();
final MessageBodyWriter messageBodyWriter = messageBodyWorkers.getMessageBodyWriter(outboundEvent.getType(),
null, annotations, (outboundEvent.getMediaType() == null ? MediaType.TEXT_PLAIN_TYPE : outboundEvent.getMediaType()));
if(outboundEvent.getName() != null) {
entityStream.write(String.format("event: %s\n", outboundEvent.getName()).getBytes());
}
if(outboundEvent.getId() != null) {
entityStream.write(String.format("id: %s\n", outboundEvent.getId()).getBytes());
}
messageBodyWriter.writeTo(outboundEvent.getData(), outboundEvent.getClass(), null, annotations, mediaType, httpHeaders, new OutputStream() {
private boolean start = true;
@Override
public void write(int i) throws IOException {
if(start) {
entityStream.write("data: ".getBytes());
start = false;
}
entityStream.write(i);
if(i == '\n') {
entityStream.write("data: ".getBytes());
}
}
});
}
entityStream.write("\n\n".getBytes());
entityStream.flush();
}
|
diff --git a/src/impl/java/org/wyona/yarep/impl/DefaultRepository.java b/src/impl/java/org/wyona/yarep/impl/DefaultRepository.java
index 81ed86c..90c9aa8 100644
--- a/src/impl/java/org/wyona/yarep/impl/DefaultRepository.java
+++ b/src/impl/java/org/wyona/yarep/impl/DefaultRepository.java
@@ -1,502 +1,502 @@
package org.wyona.yarep.impl;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.log4j.Category;
import org.wyona.yarep.core.Map;
import org.wyona.yarep.core.NoSuchNodeException;
import org.wyona.yarep.core.Node;
import org.wyona.yarep.core.Path;
import org.wyona.yarep.core.Repository;
import org.wyona.yarep.core.RepositoryException;
import org.wyona.yarep.core.Storage;
import org.wyona.yarep.core.UID;
/**
*
*/
public class DefaultRepository implements Repository {
private static Category log = Category.getInstance(DefaultRepository.class);
protected String id;
protected File configFile;
protected String name;
protected Map map;
protected Storage storage;
private boolean fallback = false;
/**
*
*/
public DefaultRepository() {
}
/**
*
*/
public DefaultRepository(String id, File configFile) throws RepositoryException {
setID(id);
readConfiguration(configFile);
}
/**
* Read respectively load repository configuration
*/
public void readConfiguration(File configFile) throws RepositoryException {
this.configFile = configFile;
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
Configuration config;
try {
config = builder.buildFromFile(configFile);
name = config.getChild("name", false).getValue();
Configuration pathConfig = config.getChild("paths", false);
fallback = pathConfig.getAttributeAsBoolean("fallback", false);
String pathsClassname = pathConfig.getAttribute("class", null);
if (pathsClassname != null) {
log.debug(pathsClassname);
Class pathsClass = Class.forName(pathsClassname);
map = (Map) pathsClass.newInstance();
} else {
map = (Map) Class.forName("org.wyona.yarep.impl.DefaultMapImpl").newInstance();
//map = new org.wyona.yarep.impl.DefaultMapImpl();
- log.warn("No paths class specified. Use 'org.wyona.yarep.impl.DefaultMapImpl' as fallsback!");
+ log.info("No paths class specified. Use 'org.wyona.yarep.impl.DefaultMapImpl' as fallback!");
}
map.readConfig(pathConfig, configFile);
Configuration storageConfig = config.getChild("storage", false);
String storageClassname = storageConfig.getAttribute("class", null);
log.debug(storageClassname);
Class storageClass = Class.forName(storageClassname);
storage = (Storage) storageClass.newInstance();
storage.readConfig(storageConfig, configFile);
log.debug(storage.getClass().getName());
} catch (Exception e) {
log.error(e.toString());
throw new RepositoryException("Could not read repository configuration: "
+ e.getMessage(), e);
}
}
/**
*
*/
public String toString() {
return "Default Repository Impl: ID = " + id + ", Configuration-File = " + configFile + ", Name = " + name;
}
/**
* Get repository ID
*/
public String getID() {
return id;
}
/**
* Set repository ID
*/
public void setID(String id) {
this.id = id;
}
/**
* Get repository name
*/
public String getName() {
return name;
}
/**
* Get repository configuration file
*/
public File getConfigFile() {
return configFile;
}
/**
*
*/
public Writer getWriter(Path path) throws RepositoryException {
OutputStream out = getOutputStream(path);
try {
if (out != null) {
return new OutputStreamWriter(getOutputStream(path), "UTF-8");
} else {
return null;
}
} catch (UnsupportedEncodingException e) {
throw new RepositoryException("Could not read path: " + path + ": " + e.getMessage(), e);
}
}
/**
*
*/
public OutputStream getOutputStream(Path path) throws RepositoryException {
UID uid = getUID(path);
if (uid == null) {
if (fallback) {
log.warn("No path to get UID from! Fallback to : " + path);
uid = new UID(path.toString());
map.addSymbolicLink(path, uid);
} else {
uid = map.create(path, org.wyona.yarep.core.NodeType.RESOURCE);
}
}
log.debug(uid.toString());
return storage.getOutputStream(uid, path);
}
/**
*
*/
public Reader getReader(Path path) throws RepositoryException {
try {
return new InputStreamReader(getInputStream(path), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RepositoryException("Could not read path: " + path + ": " + e.getMessage(), e);
}
}
/**
*
*/
public InputStream getInputStream(Path path) throws RepositoryException {
UID uid = null;
if (!existsWithinMap(path)) {
if (fallback) {
log.info("No UID! Fallback to : " + path);
uid = new UID(path.toString());
} else {
throw new NoSuchNodeException(path, this);
}
} else {
uid = getUID(path);
}
if (uid == null) {
log.error("No UID: " + path);
return null;
}
log.debug(uid.toString());
return storage.getInputStream(uid, path);
}
/**
*
*/
public long getLastModified(Path path) throws RepositoryException {
UID uid = getUID(path);
if (uid == null) {
log.error("No UID: " + path);
return -1;
}
return storage.getLastModified(uid, path);
}
/**
*
*/
public long getSize(Path path) throws RepositoryException {
UID uid = getUID(path);
if (uid == null) {
log.error("No UID: " + path);
return -1;
}
return storage.getSize(uid, path);
}
/**
* @return true if node has been deleted, otherwise false
*/
public boolean delete(Path path) throws RepositoryException {
if (log.isDebugEnabled()) log.info("Try to delete: " + path);
if(map.isCollection(path)) {
if (map.getChildren(path).length > 0) {
log.error("Node is a non-empty collection: " + path);
return false;
} else {
log.warn("Node is an empty collection: " + path);
}
}
boolean deletedStorage = false;
UID uid = getUID(path);
if (uid == null) {
if (fallback) {
log.warn("Fallback: " + path);
deletedStorage = storage.delete(new UID(path.toString()), path);
if (!deletedStorage) {
log.error("Could not delete from storage: " + path);
}
} else {
log.error("Neither UID nor Fallback: " + path);
return false;
}
} else {
deletedStorage = storage.delete(uid, path);
if (!deletedStorage) {
log.error("Could not delete from storage: " + path);
}
}
boolean deletedMap = map.delete(path);
if (!deletedMap) {
log.error("Could not delete from map: " + path);
}
return deletedMap && deletedStorage;
}
/**
* @return true if node has been deleted, otherwise false
*/
public boolean delete(Path path, boolean recursive) throws RepositoryException {
Node node = getNode(path.toString());
Node[] children = node.getNodes();
if (recursive && children.length > 0) {;
for (int i = 0; i < children.length; i++) {
if (!delete(new Path(children[i].getPath()), true)) {
throw new RepositoryException("Could not delete node: " + children[i]);
}
}
}
return delete(path);
}
/**
* Not implemented yet
* http://excalibur.apache.org/apidocs/org/apache/excalibur/source/impl/FileSource.html#getValidity()
* http://excalibur.apache.org/apidocs/org/apache/excalibur/source/SourceValidity.html
*/
public void getValidity(Path path) throws RepositoryException {
log.error("TODO: No implemented yet!");
}
/**
* Not implemented yet
* http://excalibur.apache.org/apidocs/org/apache/excalibur/source/impl/FileSource.html#getContentLength()
*/
public void getContentLength(Path path) throws RepositoryException {
log.error("TODO: No implemented yet!");
}
/**
* Not implemented yet
* http://excalibur.apache.org/apidocs/org/apache/excalibur/source/impl/FileSource.html#getURI()
*/
public void getURI(Path path) throws RepositoryException {
log.error("TODO: No implemented yet!");
}
/**
*
*/
public boolean isResource(Path path) throws RepositoryException {
return map.isResource(path);
}
/**
* One might want to discuss what is a collection. A resource for instance could
* also be a collection, but a collection with some default content.
* In the case of JCR there are only nodes and properties!
*/
public boolean isCollection(Path path) throws RepositoryException {
return map.isCollection(path);
}
/**
*
*/
public boolean exists(Path path) throws RepositoryException {
return existsWithinMapAndStorage(path);
}
/**
*
*/
public boolean existsWithinMap(Path path) throws RepositoryException {
return map.exists(path);
}
/**
*
*/
public boolean existsWithinMapAndStorage(Path path) throws RepositoryException {
if (map.exists(path) && storage.exists(getUID(path), path)) {
return true;
} else {
if (fallback && storage.exists(null, path)) {
return true;
} else {
return false;
}
}
}
/**
*
*/
public Path[] getChildren(Path path) throws RepositoryException {
if (fallback) {
log.warn("Repository " + getName() + " has fallback enabled and hence some children might be missed because these only exist within the storage (Path: " + path + ")");
}
// TODO: Order by last modified resp. alphabetical resp. ...
return map.getChildren(path);
}
/**
* Get UID
*
* http://www.ietf.org/rfc/rfc4122.txt
* http://incubator.apache.org/jackrabbit/apidocs/org/apache/jackrabbit/uuid/UUID.html
* http://www.webdav.org/specs/draft-leach-uuids-guids-01.txt
*/
public synchronized UID getUID(Path path) throws RepositoryException {
return map.getUID(path);
}
/**
* Get all revision numbers of the given path.
* @return Array of revision number strings. Newest revision first.
*/
public String[] getRevisions(Path path) throws RepositoryException {
UID uid = getUID(path);
//if (uid == null) throw new NoSuchNodeException("Path not found: " + path);
// fallback?
return storage.getRevisions(uid, path);
}
/**
* Add symbolic link
*/
public void addSymbolicLink(Path target, Path link) throws NoSuchNodeException, RepositoryException {
log.debug("Target: " + target);
UID uid = null;
if (!existsWithinMap(target)) {
if (fallback) {
log.warn("No UID! Fallback to : " + target);
uid = new UID(target.toString());
} else {
throw new NoSuchNodeException(target, this);
}
} else {
uid = getUID(target);
}
log.debug("UID of Target: " + uid);
log.debug("Link: " + link);
map.addSymbolicLink(link, uid);
}
///////////////////////////////////////////////////////////////////////////
// New methods for node based repository
///////////////////////////////////////////////////////////////////////////
/**
* @see org.wyona.yarep.core.Repository#copy(java.lang.String, java.lang.String)
*/
public void copy(String srcPath, String destPath) throws RepositoryException {
// TODO: not implemented yet
log.warn("Not implemented yet.");
}
/**
* @see org.wyona.yarep.core.Repository#existsNode(java.lang.String)
*/
public boolean existsNode(String path) throws RepositoryException {
return existsWithinMapAndStorage(new Path(path));
}
/**
* @see org.wyona.yarep.core.Repository#getNode(java.lang.String)
*/
public Node getNode(String path) throws NoSuchNodeException, RepositoryException {
// strip trailing slash:
if (path.length() > 1 && path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
String uuid;
if (!map.exists(new Path(path))) {
if (fallback) {
log.info("No UID! Fallback to : " + path);
uuid = new UID(path).toString();
} else {
throw new NoSuchNodeException(path, this);
}
} else {
UID uid = map.getUID(new Path(path));
uuid = (uid == null) ? path : uid.toString();
}
return new DummyNode(this, path, uuid);
}
/**
* @see org.wyona.yarep.core.Repository#getNodeByUUID(java.lang.String)
*/
public Node getNodeByUUID(String uuid) throws NoSuchNodeException, RepositoryException {
// TODO: not implemented yet
log.warn("Not implemented yet.");
return null;
}
/**
* @see org.wyona.yarep.core.Repository#getRootNode()
*/
public Node getRootNode() throws RepositoryException {
return getNode("/");
}
/**
* @see org.wyona.yarep.core.Repository#move(java.lang.String, java.lang.String)
*/
public void move(String srcPath, String destPath) throws RepositoryException {
// TODO: not implemented yet
log.warn("Not implemented yet.");
}
// implementation specific methods:
public Map getMap() {
return this.map;
}
public Storage getStorage() {
return this.storage;
}
/**
*
*/
public void close() throws RepositoryException {
log.warn("Not implemented!");
}
/**
* Search content
*/
public Node[] search(String query) throws RepositoryException {
log.error("Not implemented yet!");
return null;
}
public Node[] searchProperty(String pName, String pValue, String path) throws RepositoryException {
throw new RepositoryException("Not implemented yet!");
}
}
| true | true | public void readConfiguration(File configFile) throws RepositoryException {
this.configFile = configFile;
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
Configuration config;
try {
config = builder.buildFromFile(configFile);
name = config.getChild("name", false).getValue();
Configuration pathConfig = config.getChild("paths", false);
fallback = pathConfig.getAttributeAsBoolean("fallback", false);
String pathsClassname = pathConfig.getAttribute("class", null);
if (pathsClassname != null) {
log.debug(pathsClassname);
Class pathsClass = Class.forName(pathsClassname);
map = (Map) pathsClass.newInstance();
} else {
map = (Map) Class.forName("org.wyona.yarep.impl.DefaultMapImpl").newInstance();
//map = new org.wyona.yarep.impl.DefaultMapImpl();
log.warn("No paths class specified. Use 'org.wyona.yarep.impl.DefaultMapImpl' as fallsback!");
}
map.readConfig(pathConfig, configFile);
Configuration storageConfig = config.getChild("storage", false);
String storageClassname = storageConfig.getAttribute("class", null);
log.debug(storageClassname);
Class storageClass = Class.forName(storageClassname);
storage = (Storage) storageClass.newInstance();
storage.readConfig(storageConfig, configFile);
log.debug(storage.getClass().getName());
} catch (Exception e) {
log.error(e.toString());
throw new RepositoryException("Could not read repository configuration: "
+ e.getMessage(), e);
}
}
| public void readConfiguration(File configFile) throws RepositoryException {
this.configFile = configFile;
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
Configuration config;
try {
config = builder.buildFromFile(configFile);
name = config.getChild("name", false).getValue();
Configuration pathConfig = config.getChild("paths", false);
fallback = pathConfig.getAttributeAsBoolean("fallback", false);
String pathsClassname = pathConfig.getAttribute("class", null);
if (pathsClassname != null) {
log.debug(pathsClassname);
Class pathsClass = Class.forName(pathsClassname);
map = (Map) pathsClass.newInstance();
} else {
map = (Map) Class.forName("org.wyona.yarep.impl.DefaultMapImpl").newInstance();
//map = new org.wyona.yarep.impl.DefaultMapImpl();
log.info("No paths class specified. Use 'org.wyona.yarep.impl.DefaultMapImpl' as fallback!");
}
map.readConfig(pathConfig, configFile);
Configuration storageConfig = config.getChild("storage", false);
String storageClassname = storageConfig.getAttribute("class", null);
log.debug(storageClassname);
Class storageClass = Class.forName(storageClassname);
storage = (Storage) storageClass.newInstance();
storage.readConfig(storageConfig, configFile);
log.debug(storage.getClass().getName());
} catch (Exception e) {
log.error(e.toString());
throw new RepositoryException("Could not read repository configuration: "
+ e.getMessage(), e);
}
}
|
diff --git a/Disasteroids/trunk/src/disasteroids/gui/GameCanvas.java b/Disasteroids/trunk/src/disasteroids/gui/GameCanvas.java
index 59a2ec2..b22de36 100644
--- a/Disasteroids/trunk/src/disasteroids/gui/GameCanvas.java
+++ b/Disasteroids/trunk/src/disasteroids/gui/GameCanvas.java
@@ -1,732 +1,732 @@
/*
* DISASTEROIDS | GUI
* AsteroidsPanel.java
*/
package disasteroids.gui;
import disasteroids.*;
import disasteroids.networking.*;
import disasteroids.sound.*;
import java.awt.*;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* The screen-sized canvas where we draw everything.
*/
public class GameCanvas extends Canvas
{
/**
* The <code>Image</code> used for double buffering.
* @since Classic
*/
Image virtualMem;
/**
* The star background.
* @since Classic
*/
Background background;
/**
* The time stored at the beginning of the last call to paint; Used for FPS.
* @since December 15, 2007
*/
long timeOfLastRepaint;
/**
* Notification messages always shown in the top-left corner.
* @since December 19, 2004
*/
ConcurrentLinkedQueue<NotificationMessage> notificationMessages = new ConcurrentLinkedQueue<NotificationMessage>();
/**
* The current amount of FPS. Updated in <code>paint</code>.
* @since December 18, 2007
*/
int lastFPS = 0;
LinkedList<Integer> benchmarkFPS;
int averageFPS = 0;
/*
* Whether to show localPlayer's coordinates.
* @since January 18, 2008
*/
boolean showTracker = false, showHelp = false, showWarpDialog = false, drawScoreboard = false;
/**
* The number of times that the paint method has been called, for FPS.
* @since January 10, 2008
*/
int paintCount = 0;
/**
* Positive number at which the screen rumbles; the greater the value, the greater the (random) distance.
* @since April 7, 2008
*/
double rumble = 0.0;
/**
* Offsets that objects should be drawn at during rumbling.
* @since April 7, 2008
*/
int rumbleX = 0, rumbleY = 0;
/**
* The parent frame containing this.
* @since January 15, 2008
*/
MainWindow parent;
/**
* Whether we're in the draw() loop.
*/
private boolean isDrawing = false;
public GameCanvas( MainWindow parent )
{
this.parent = parent;
background = new Background( Game.getInstance().GAME_WIDTH, Game.getInstance().GAME_HEIGHT );
benchmarkFPS = new LinkedList<Integer>();
setKeyListener();
}
public void setKeyListener()
{
// Receive key events.
removeKeyListener( KeystrokeManager.getInstance() );
addKeyListener( KeystrokeManager.getInstance() );
}
/**
* Draws all of the game elements.
*/
private void draw( Graphics g )
{
if ( Local.isStuffNull() )
return;
if ( !GameLoop.isRunning() )
{
isDrawing = false;
return;
}
isDrawing = true;
// Adjust the thread's priority if it's in the foreground/background.
if ( parent.isActive() && Thread.currentThread().getPriority() != Thread.NORM_PRIORITY )
Thread.currentThread().setPriority( Thread.NORM_PRIORITY );
else if ( Thread.currentThread().getPriority() != Thread.MIN_PRIORITY )
Thread.currentThread().setPriority( Thread.MIN_PRIORITY );
// Anti-alias, if the user wants it.
updateQualityRendering( g, Settings.isQualityRendering() );
// Calculate FPS.
if ( ++paintCount % 10 == 0 )
{
long timeSinceLast = -timeOfLastRepaint + ( timeOfLastRepaint = System.currentTimeMillis() );
if ( timeSinceLast > 0 )
{
lastFPS = ( int ) ( 10000.0 / timeSinceLast );
if ( benchmarkFPS != null )
{
benchmarkFPS.addLast( lastFPS );
if ( benchmarkFPS.size() > 60 )
benchmarkFPS.removeFirst();
int total = 0;
for ( int i : benchmarkFPS )
total += i;
averageFPS = total / benchmarkFPS.size();
}
}
// Update high and low scores.
Ship highestScorer = Game.getInstance().getObjectManager().getPlayers().peek();
for ( Ship s : Game.getInstance().getObjectManager().getPlayers() )
{
if ( s.getScore() > highestScorer.score() )
highestScorer = s;
}
// Regression!
if ( highestScorer.getScore() < Settings.getOldHighScore() && Settings.getHighScore() != Settings.getOldHighScore() )
{
Main.log( "The high score record has been returned to " + Settings.getOldHighScorer() + ".", 800 );
Settings.setHighScore( Settings.getOldHighScore() );
Settings.setHighScoreName( Settings.getOldHighScorer() );
}
else if ( highestScorer.getScore() > Settings.getHighScore() )
{
Settings.setHighScore( highestScorer.getScore() );
if ( !highestScorer.getName().equals( Settings.getHighScoreName() ) )
{
Settings.setHighScoreName( highestScorer.getName() );
Main.log( highestScorer.getName() + " just broke the high score record of " + Util.insertThousandCommas( highestScorer.getScore() ) + "!", 800 );
}
}
}
// Draw the star background.
if ( background == null )
background = new Background( Game.getInstance().GAME_WIDTH, Game.getInstance().GAME_HEIGHT );
else
g.drawImage( background.render(), 0, 0, this );
// Draw stuff in order of importance, from least to most.
ParticleManager.draw( g );
Game.getInstance().getObjectManager().draw( g );
// Draw the on-screen HUD.
drawHud( g );
// Draw the entire scoreboard.
if ( drawScoreboard )
drawScoreboard( g );
isDrawing = false;
}
/**
* Does all of the gamer's rendering.
*/
@Override
public void paint( Graphics g )
{
// Create the image if needed.
if ( virtualMem == null )
virtualMem = createImage( getWidth(), getHeight() );
// Flashing game objects.
Util.flipGlobalFlash();
// Shake the screen when hit.
if ( rumble < 0.1 )
rumble = 0;
else
{
rumbleX = ( int ) ( Util.getRandomGenerator().nextDouble() * rumble - rumble / 2 );
rumbleY = ( int ) ( Util.getRandomGenerator().nextDouble() * rumble - rumble / 2 );
rumble *= 0.9;
}
if ( showWarpDialog )
{
Game.getInstance().getGameMode().optionsKey();
showWarpDialog = false;
}
// Draw the game's graphics.
draw( virtualMem.getGraphics() );
// Flip the buffer to the screen.
g.drawImage( virtualMem, 0, 0, this );
repaint();
}
/**
* Shows a dialog to warps to a particular level.
*/
public void warpDialog()
{
showWarpDialog = true;
}
public void nextLevel()
{
background.init();
}
/**
* Draws the on-screen information for the local player.
*/
private void drawHud( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
String text = "";
int x = 0, y = 0;
// Draw game mode status.
Game.getInstance().getGameMode().draw( g );
if ( showHelp )
{
g2d.setColor( Color.white );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 56 ) );
g2d.drawString( "Help", 250, 250 );
y = 340;
g2d.setFont( new Font( "Tahoma", Font.BOLD, 18 ) );
g2d.drawString( "BASICS", 250, y );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 14 ) );
g2d.setColor( Color.lightGray );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Arrow keys = move", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Space = shoot", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Q = change weapons", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
y += 50;
g2d.setColor( Color.white );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 18 ) );
g2d.drawString( "ADVANCED", 250, y );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 14 ) );
g2d.setColor( Color.lightGray );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Ctrl and Numpad0 = strafe", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "End = brake", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "~ = berserk!", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Number keys = quick switch to weapons", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Home = detonate missiles", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
if ( Server.is() || Client.is() )
{
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() * 2 );
g2d.drawString( "Server IP: " + ( Server.is() ? Server.getLocalIP() : Client.getInstance().getServerAddress().toString() ), 250, y );
}
}
- if ( parent.localPlayer().livesLeft() < 0 )
+ if ( Local.getLocalPlayer().livesLeft() < 0 && !Server.is() && !Client.is() )
{
g2d.setFont( new Font( "Tahoma", Font.BOLD, 32 ) );
g2d.setColor( parent.localPlayer().getColor() );
text = "GAME OVER!";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y = ( int ) ( getHeight() / 2 - g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() ) - 32;
g2d.drawString( text, x, y );
return;
}
// Draw the score counter.
g2d.setColor( Color.gray );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 16 ) );
text = Util.insertThousandCommas( parent.localPlayer().getScore() );
y = 18;
x = getWidth() - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() - 12;
g2d.drawString( text, x, y );
// Draw the "score" string.
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
text = "score";
x -= ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() + 8;
g2d.drawString( text, x, y );
x -= ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() + 8;
if ( showTracker )
g2d.drawString( parent.localPlayer().toString(), 60, 60 );
// Draw the "lives" string.
g2d.setColor( parent.localPlayer().getColor() );
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
if ( parent.localPlayer().livesLeft() == 1 )
text = "life";
else
text = "lives";
g2d.drawString( text, x, y );
x -= 10;
// Draw the lives counter.
g2d.setFont( new Font( "Tahoma", Font.BOLD, 16 ) );
text = "" + parent.localPlayer().livesLeft();
x -= ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth();
g2d.drawString( text, x, y );
x -= 15;
// Draw the fps counter.
g2d.setColor( Color.darkGray );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 16 ) );
text = "" + lastFPS;
x = 8;
y = ( int ) ( getHeight() - g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() ) - 2;
g2d.drawString( text, x, y );
// Draw the "fps" string.
x += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() + 8;
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
text = "fps";
g2d.drawString( text, x, y );
// Draw the average FPS for this session.
if ( benchmarkFPS != null && benchmarkFPS.size() >= 60 )
{
g2d.setColor( benchmarkFPS.size() == 1 ? Color.lightGray : Color.darkGray );
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
x -= 10;
y += 15;
text = "[avg this session: " + averageFPS + " ]";
g2d.drawString( text, x, y );
}
// Draw energy.
x = getWidth() / 2 - 50;
y = 18;
{
g2d.setColor( new Color( 9, 68, 12 ) );
g2d.fillRect( x, y, ( int ) ( parent.localPlayer().getHealth() ), 20 );
g2d.setColor( new Color( 21, 98, 28 ) );
g2d.drawRect( x, y, 100, 20 );
}
if ( parent.localPlayer().getShield() > 0 )
{
g2d.setColor( new Color( 5, 100, 100 ) );
g2d.fillRect( x, y, ( int ) ( Math.min( 100, parent.localPlayer().getShield() ) ), 20 );
g2d.setColor( new Color( 5, 150, 150 ) );
g2d.drawRect( x, y, 100, 20 );
}
// Draw notification messages.
x = 8;
y = 20;
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
g2d.setColor( Color.lightGray );
Iterator<NotificationMessage> itr = notificationMessages.iterator();
while ( itr.hasNext() )
{
NotificationMessage m = itr.next();
text = m.message;
g2d.drawString( text, x, y );
y += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() + 2;
if ( m.life-- <= 0 )
itr.remove();
}
// Draw "waiting for server...".
if ( Client.is() && Client.getInstance().serverTimeout() )
{
g2d.setFont( new Font( "Tahoma", Font.BOLD, 18 ) );
g2d.setColor( Color.GREEN );
text = "Waiting for server...";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y = getHeight() / 2 - 50;
g2d.drawString( text, x, y );
}
// Draw "pauses"...
if ( Game.getInstance().isPaused() )
{
g2d.setFont( new Font( "Tahoma", Font.BOLD, 24 ) );
g2d.setColor( Local.getLocalPlayer().getColor() );
text = "Paused.";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y = getHeight() / 3 - 50;
g2d.drawString( text, x, y );
}
}
/**
* Draws the full scoreboard of all players.
*
* @param g <code>Graphics</code> context to draw on
* @since December 15, 2007
*/
private void drawScoreboard( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
String text = "";
int x = 0, y = 0;
// Draw the "scoreboard" string.
g2d.setColor( Color.white );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 24 ) );
text = "Scoreboard";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y = getHeight() / 4;
g2d.drawString( text, x, y );
y += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() + 10;
// Draw the asteroid count.
g2d.setColor( Color.lightGray );
g2d.setFont( new Font( "Tahoma", Font.PLAIN, 16 ) );
text = Util.insertThousandCommas( Game.getInstance().getObjectManager().getAsteroids().size() ) + " asteroid" + ( Game.getInstance().getObjectManager().getAsteroids().size() == 1 ? ", " : "s, " );
text += Util.insertThousandCommas( Game.getInstance().getObjectManager().getBaddies().size() ) + " baddie" + ( Game.getInstance().getObjectManager().getBaddies().size() == 1 ? "" : "s" );
text += " remain";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
g2d.drawString( text, x, y );
y += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() + 10;
// Create the columns.
ScoreboardColumn[] columns = new ScoreboardColumn[ 4 ];
if ( Game.getInstance().getGameType() == Game.GameType.COOPERATIVE )
{
columns[0] = new ScoreboardColumn( getWidth() * 2 / 7, ScoreboardContent.NAME );
columns[1] = new ScoreboardColumn( getWidth() * 1 / 2, ScoreboardContent.SCORE );
columns[2] = new ScoreboardColumn( getWidth() * 3 / 5, ScoreboardContent.LIVES );
columns[3] = new ScoreboardColumn( getWidth() * 2 / 3, ScoreboardContent.ASTEROIDSDESTROYED );
}
else
{
columns[0] = new ScoreboardColumn( getWidth() * 2 / 7, ScoreboardContent.NAME );
columns[1] = new ScoreboardColumn( getWidth() * 1 / 2, ScoreboardContent.FRAGS );
columns[2] = new ScoreboardColumn( getWidth() * 3 / 5, ScoreboardContent.SCORE );
columns[3] = new ScoreboardColumn( getWidth() * 2 / 3, ScoreboardContent.ASTEROIDSDESTROYED );
}
// Draw the column headers.
y += 15;
g2d.setColor( Color.darkGray );
g2d.setFont( new Font( "Tahoma", Font.PLAIN, 14 ) );
for ( ScoreboardColumn c : columns )
g2d.drawString( c.type.getHeader(), c.x, y );
g2d.drawLine( columns[0].x, y + 5, columns[columns.length - 1].x + ( int ) g2d.getFont().getStringBounds( columns[columns.length - 1].type.getHeader(), g2d.getFontRenderContext() ).getWidth(), y + 5 );
y += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() + 10;
// Draw the entries.
for ( Ship s : Game.getInstance().getObjectManager().getPlayers() )
{
g2d.setColor( s.getColor() );
if ( s == parent.localPlayer() )
g2d.setFont( g2d.getFont().deriveFont( Font.BOLD ) );
else
g2d.setFont( g2d.getFont().deriveFont( Font.PLAIN ) );
for ( int i = 0; i < columns.length; i++ )
{
g2d.drawString( ScoreboardContent.getContent( columns[i].type, s ), columns[i].x, y );
}
y += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() + 3;
}
// Draw the high scorer.
g2d.setFont( new Font( "Tahoma", Font.PLAIN, 12 ) );
text = "All-time high scorer " + ( Settings.getOldHighScore() >= Settings.getHighScore() ? "is " : "was " ) + Settings.getOldHighScorer() + " with " + Util.insertThousandCommas( ( int ) Settings.getOldHighScore() ) + " points.";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y += 40;
g2d.setColor( Color.white );
g2d.drawString( text, x, y );
// Boost player egos.
if ( Settings.getOldHighScore() < Settings.getHighScore() )
{
y += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() + 3;
if ( Settings.getHighScoreName().equals( Settings.getOldHighScorer() ) )
text = "But hey, everyone likes to beat their own score.";
else
text = "But you're much better with your shiny " + Util.insertThousandCommas( ( int ) Settings.getHighScore() ) + "!";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
g2d.drawString( text, x, y );
}
}
/**
* Toggles music on/off, and writes the setting to the background.
*
* @since November 15, 2007
*/
public void toggleMusic()
{
Main.log( "Music " + ( Sound.toggleMusic() ? "on." : "off." ) );
}
/**
* Toggles sound on/off, and writes the setting to the background.
*
* @since November 15, 2007
*/
public void toggleSound()
{
Main.log( "Sound " + ( Sound.toggleSound() ? "on." : "off." ) );
}
/**
* Toggles high-quality rendering on/off, and writes the setting to the background.
*
* @since December 15, 2007
*/
public void toggleReneringQuality()
{
Settings.setQualityRendering( !Settings.isQualityRendering() );
Main.log( ( Settings.isQualityRendering() ? "Quality rendering." : "Speed rendering." ) );
}
public void toggleTracker()
{
showTracker = !showTracker;
}
public void toggleHelp()
{
showHelp = !showHelp;
}
public void toggleScoreboard()
{
drawScoreboard = !drawScoreboard;
}
/**
* Enables or disables fancy rendering of the provided <code>Graphics</code>.
*
* @param qualityRendering whether to use higher-quality rendering
* @since December 15, 2007
*/
private void updateQualityRendering( Graphics g, boolean qualityRendering )
{
Graphics2D g2d = ( Graphics2D ) g;
// Adjust the setting.
if ( qualityRendering )
{
g2d.setRenderingHint( RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY );
g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
g2d.setRenderingHint( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
g2d.setRenderingHint( RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE );
g2d.setRenderingHint( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON );
g2d.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC );
g2d.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
g2d.setRenderingHint( RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE );
g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON );
}
else
{
g2d.setRenderingHint( RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED );
g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
g2d.setRenderingHint( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED );
g2d.setRenderingHint( RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE );
g2d.setRenderingHint( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF );
g2d.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR );
g2d.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED );
g2d.setRenderingHint( RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT );
g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF );
}
}
public void addNotificationMessage( String message, int life )
{
if ( message.equals( "" ) )
return;
notificationMessages.add( new NotificationMessage( message, life ) );
}
/**
* Included to prevent the clearing of the screen between repaints.
*/
@Override
public void update( Graphics g )
{
paint( g );
}
public Background getStarBackground()
{
return background;
}
private enum ScoreboardContent
{
NAME( "Name" ), SCORE( "Score" ), FRAGS( "Frags" ), LIVES( "Lives" ), ASTEROIDSDESTROYED( "# Destroyed" );
private String header;
private ScoreboardContent( String header )
{
this.header = header;
}
public String getHeader()
{
return header;
}
public static String getContent( ScoreboardContent type, Ship s )
{
switch ( type )
{
case NAME:
return s.getName();
case SCORE:
return Util.insertThousandCommas( s.score() );
case FRAGS:
return Util.insertThousandCommas( s.getNumShipsKilled() );
case LIVES:
return Util.insertThousandCommas( s.livesLeft() );
case ASTEROIDSDESTROYED:
return Util.insertThousandCommas( s.getNumAsteroidsKilled() );
default:
return "";
}
}
}
/**
* A small class for the storage of scoreboard colums.
*
* @see <code>drawScoreboard</code>
* @author Phillip Cohen
* @since December 15, 2007
*/
private static class ScoreboardColumn
{
/**
* x coordinate of the column's left edge.
*/
public int x;
/**
* Header text.
*/
public ScoreboardContent type;
public ScoreboardColumn( int x, ScoreboardContent type )
{
this.x = x;
this.type = type;
}
}
/**
*/
private static class NotificationMessage
{
public String message;
public int life;
public NotificationMessage( String message, int life )
{
this.message = message;
this.life = life;
}
}
/**
* Returns whether the panel is drawing game elements.
*
* Should be used with <code>GameLoop.stopLoop()</code> to change the game's structure without the panel trying to draw it and getting NullPointers.
* @see GameLoop#stopLoop()
*/
public boolean isDrawing()
{
return isDrawing;
}
}
| true | true | private void drawHud( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
String text = "";
int x = 0, y = 0;
// Draw game mode status.
Game.getInstance().getGameMode().draw( g );
if ( showHelp )
{
g2d.setColor( Color.white );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 56 ) );
g2d.drawString( "Help", 250, 250 );
y = 340;
g2d.setFont( new Font( "Tahoma", Font.BOLD, 18 ) );
g2d.drawString( "BASICS", 250, y );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 14 ) );
g2d.setColor( Color.lightGray );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Arrow keys = move", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Space = shoot", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Q = change weapons", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
y += 50;
g2d.setColor( Color.white );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 18 ) );
g2d.drawString( "ADVANCED", 250, y );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 14 ) );
g2d.setColor( Color.lightGray );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Ctrl and Numpad0 = strafe", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "End = brake", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "~ = berserk!", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Number keys = quick switch to weapons", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Home = detonate missiles", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
if ( Server.is() || Client.is() )
{
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() * 2 );
g2d.drawString( "Server IP: " + ( Server.is() ? Server.getLocalIP() : Client.getInstance().getServerAddress().toString() ), 250, y );
}
}
if ( parent.localPlayer().livesLeft() < 0 )
{
g2d.setFont( new Font( "Tahoma", Font.BOLD, 32 ) );
g2d.setColor( parent.localPlayer().getColor() );
text = "GAME OVER!";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y = ( int ) ( getHeight() / 2 - g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() ) - 32;
g2d.drawString( text, x, y );
return;
}
// Draw the score counter.
g2d.setColor( Color.gray );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 16 ) );
text = Util.insertThousandCommas( parent.localPlayer().getScore() );
y = 18;
x = getWidth() - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() - 12;
g2d.drawString( text, x, y );
// Draw the "score" string.
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
text = "score";
x -= ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() + 8;
g2d.drawString( text, x, y );
x -= ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() + 8;
if ( showTracker )
g2d.drawString( parent.localPlayer().toString(), 60, 60 );
// Draw the "lives" string.
g2d.setColor( parent.localPlayer().getColor() );
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
if ( parent.localPlayer().livesLeft() == 1 )
text = "life";
else
text = "lives";
g2d.drawString( text, x, y );
x -= 10;
// Draw the lives counter.
g2d.setFont( new Font( "Tahoma", Font.BOLD, 16 ) );
text = "" + parent.localPlayer().livesLeft();
x -= ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth();
g2d.drawString( text, x, y );
x -= 15;
// Draw the fps counter.
g2d.setColor( Color.darkGray );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 16 ) );
text = "" + lastFPS;
x = 8;
y = ( int ) ( getHeight() - g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() ) - 2;
g2d.drawString( text, x, y );
// Draw the "fps" string.
x += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() + 8;
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
text = "fps";
g2d.drawString( text, x, y );
// Draw the average FPS for this session.
if ( benchmarkFPS != null && benchmarkFPS.size() >= 60 )
{
g2d.setColor( benchmarkFPS.size() == 1 ? Color.lightGray : Color.darkGray );
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
x -= 10;
y += 15;
text = "[avg this session: " + averageFPS + " ]";
g2d.drawString( text, x, y );
}
// Draw energy.
x = getWidth() / 2 - 50;
y = 18;
{
g2d.setColor( new Color( 9, 68, 12 ) );
g2d.fillRect( x, y, ( int ) ( parent.localPlayer().getHealth() ), 20 );
g2d.setColor( new Color( 21, 98, 28 ) );
g2d.drawRect( x, y, 100, 20 );
}
if ( parent.localPlayer().getShield() > 0 )
{
g2d.setColor( new Color( 5, 100, 100 ) );
g2d.fillRect( x, y, ( int ) ( Math.min( 100, parent.localPlayer().getShield() ) ), 20 );
g2d.setColor( new Color( 5, 150, 150 ) );
g2d.drawRect( x, y, 100, 20 );
}
// Draw notification messages.
x = 8;
y = 20;
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
g2d.setColor( Color.lightGray );
Iterator<NotificationMessage> itr = notificationMessages.iterator();
while ( itr.hasNext() )
{
NotificationMessage m = itr.next();
text = m.message;
g2d.drawString( text, x, y );
y += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() + 2;
if ( m.life-- <= 0 )
itr.remove();
}
// Draw "waiting for server...".
if ( Client.is() && Client.getInstance().serverTimeout() )
{
g2d.setFont( new Font( "Tahoma", Font.BOLD, 18 ) );
g2d.setColor( Color.GREEN );
text = "Waiting for server...";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y = getHeight() / 2 - 50;
g2d.drawString( text, x, y );
}
// Draw "pauses"...
if ( Game.getInstance().isPaused() )
{
g2d.setFont( new Font( "Tahoma", Font.BOLD, 24 ) );
g2d.setColor( Local.getLocalPlayer().getColor() );
text = "Paused.";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y = getHeight() / 3 - 50;
g2d.drawString( text, x, y );
}
}
| private void drawHud( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
String text = "";
int x = 0, y = 0;
// Draw game mode status.
Game.getInstance().getGameMode().draw( g );
if ( showHelp )
{
g2d.setColor( Color.white );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 56 ) );
g2d.drawString( "Help", 250, 250 );
y = 340;
g2d.setFont( new Font( "Tahoma", Font.BOLD, 18 ) );
g2d.drawString( "BASICS", 250, y );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 14 ) );
g2d.setColor( Color.lightGray );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Arrow keys = move", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Space = shoot", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Q = change weapons", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
y += 50;
g2d.setColor( Color.white );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 18 ) );
g2d.drawString( "ADVANCED", 250, y );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 14 ) );
g2d.setColor( Color.lightGray );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Ctrl and Numpad0 = strafe", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "End = brake", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "~ = berserk!", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Number keys = quick switch to weapons", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
g2d.drawString( "Home = detonate missiles", 250, y );
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() );
if ( Server.is() || Client.is() )
{
y += ( int ) ( g2d.getFont().getStringBounds( "A", g2d.getFontRenderContext() ).getHeight() * 2 );
g2d.drawString( "Server IP: " + ( Server.is() ? Server.getLocalIP() : Client.getInstance().getServerAddress().toString() ), 250, y );
}
}
if ( Local.getLocalPlayer().livesLeft() < 0 && !Server.is() && !Client.is() )
{
g2d.setFont( new Font( "Tahoma", Font.BOLD, 32 ) );
g2d.setColor( parent.localPlayer().getColor() );
text = "GAME OVER!";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y = ( int ) ( getHeight() / 2 - g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() ) - 32;
g2d.drawString( text, x, y );
return;
}
// Draw the score counter.
g2d.setColor( Color.gray );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 16 ) );
text = Util.insertThousandCommas( parent.localPlayer().getScore() );
y = 18;
x = getWidth() - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() - 12;
g2d.drawString( text, x, y );
// Draw the "score" string.
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
text = "score";
x -= ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() + 8;
g2d.drawString( text, x, y );
x -= ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() + 8;
if ( showTracker )
g2d.drawString( parent.localPlayer().toString(), 60, 60 );
// Draw the "lives" string.
g2d.setColor( parent.localPlayer().getColor() );
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
if ( parent.localPlayer().livesLeft() == 1 )
text = "life";
else
text = "lives";
g2d.drawString( text, x, y );
x -= 10;
// Draw the lives counter.
g2d.setFont( new Font( "Tahoma", Font.BOLD, 16 ) );
text = "" + parent.localPlayer().livesLeft();
x -= ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth();
g2d.drawString( text, x, y );
x -= 15;
// Draw the fps counter.
g2d.setColor( Color.darkGray );
g2d.setFont( new Font( "Tahoma", Font.BOLD, 16 ) );
text = "" + lastFPS;
x = 8;
y = ( int ) ( getHeight() - g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() ) - 2;
g2d.drawString( text, x, y );
// Draw the "fps" string.
x += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() + 8;
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
text = "fps";
g2d.drawString( text, x, y );
// Draw the average FPS for this session.
if ( benchmarkFPS != null && benchmarkFPS.size() >= 60 )
{
g2d.setColor( benchmarkFPS.size() == 1 ? Color.lightGray : Color.darkGray );
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
x -= 10;
y += 15;
text = "[avg this session: " + averageFPS + " ]";
g2d.drawString( text, x, y );
}
// Draw energy.
x = getWidth() / 2 - 50;
y = 18;
{
g2d.setColor( new Color( 9, 68, 12 ) );
g2d.fillRect( x, y, ( int ) ( parent.localPlayer().getHealth() ), 20 );
g2d.setColor( new Color( 21, 98, 28 ) );
g2d.drawRect( x, y, 100, 20 );
}
if ( parent.localPlayer().getShield() > 0 )
{
g2d.setColor( new Color( 5, 100, 100 ) );
g2d.fillRect( x, y, ( int ) ( Math.min( 100, parent.localPlayer().getShield() ) ), 20 );
g2d.setColor( new Color( 5, 150, 150 ) );
g2d.drawRect( x, y, 100, 20 );
}
// Draw notification messages.
x = 8;
y = 20;
g2d.setFont( new Font( "Tahoma", Font.ITALIC, 12 ) );
g2d.setColor( Color.lightGray );
Iterator<NotificationMessage> itr = notificationMessages.iterator();
while ( itr.hasNext() )
{
NotificationMessage m = itr.next();
text = m.message;
g2d.drawString( text, x, y );
y += ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getHeight() + 2;
if ( m.life-- <= 0 )
itr.remove();
}
// Draw "waiting for server...".
if ( Client.is() && Client.getInstance().serverTimeout() )
{
g2d.setFont( new Font( "Tahoma", Font.BOLD, 18 ) );
g2d.setColor( Color.GREEN );
text = "Waiting for server...";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y = getHeight() / 2 - 50;
g2d.drawString( text, x, y );
}
// Draw "pauses"...
if ( Game.getInstance().isPaused() )
{
g2d.setFont( new Font( "Tahoma", Font.BOLD, 24 ) );
g2d.setColor( Local.getLocalPlayer().getColor() );
text = "Paused.";
x = getWidth() / 2 - ( int ) g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2;
y = getHeight() / 3 - 50;
g2d.drawString( text, x, y );
}
}
|
diff --git a/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java b/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java
index 7938ce86..fd66235e 100644
--- a/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java
+++ b/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java
@@ -1,467 +1,466 @@
/*******************************************************************************
* Copyright (c) 2010 Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams, James Pence. All rights reserved.
* This program and the accompanying materials are made available under the terms of the new BSD license which
* accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.html Contributors:
* Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams, James Pence - initial API and implementation
******************************************************************************/
package org.vivoweb.harvester.update;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vivoweb.harvester.util.InitLog;
import org.vivoweb.harvester.util.IterableAdaptor;
import org.vivoweb.harvester.util.args.ArgDef;
import org.vivoweb.harvester.util.args.ArgList;
import org.vivoweb.harvester.util.args.ArgParser;
import org.vivoweb.harvester.util.repo.JenaConnect;
import org.xml.sax.SAXException;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.Syntax;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.sparql.util.StringUtils;
import com.hp.hpl.jena.util.ResourceUtils;
/**
* Changes the namespace for all matching uris
* @author Christopher Haines ([email protected])
*/
public class ChangeNamespace {
/**
* SLF4J Logger
*/
private static Logger log = LoggerFactory.getLogger(ChangeNamespace.class);
/**
* The model to change uris in
*/
private JenaConnect model;
/**
* The old namespace
*/
private String oldNamespace;
/**
* The new namespace
*/
private String newNamespace;
/**
* the propeties to match on
*/
private List<Property> properties;
/**
* The search model
*/
private JenaConnect vivo;
/**
* Constructor
* @param argList parsed argument list
* @throws IOException error reading config
* @throws SAXException error parsing config
* @throws ParserConfigurationException error parsing config
*/
public ChangeNamespace(ArgList argList) throws ParserConfigurationException, SAXException, IOException {
this.model = JenaConnect.parseConfig(argList.get("i"), argList.getProperties("I"));
this.vivo = JenaConnect.parseConfig(argList.get("v"), argList.getProperties("V"));
this.oldNamespace = argList.get("o");
this.newNamespace = argList.get("n");
List<String> predicates = argList.getAll("p");
this.properties = new ArrayList<Property>(predicates.size());
for (String pred : predicates) {
this.properties.add(ResourceFactory.createProperty(pred));
}
}
/**
* Get either a matching uri from the given model or an unused uri
* @param current the current resource
* @param namespace the namespace to match in
* @param properties the propeties to match on
* @param uriCheck list of new uris generated during this changenamespace run
* @param errorOnNewURI Log ERROR messages when a new URI is generated
* @param vivo the model to match in
* @param model model to check for duplicates
* @return the uri of the first matched resource or an unused uri if none found
*/
public static String getURI(Resource current, String namespace, List<Property> properties, ArrayList<String> uriCheck, boolean errorOnNewURI, JenaConnect vivo, JenaConnect model) {
String uri = null;
if (properties != null && !properties.isEmpty()) {
uri = getMatchingURI(current, namespace, properties, vivo);
}
if (uri == null) {
uri = getUnusedURI(namespace, uriCheck, vivo, model);
if (errorOnNewURI) {
log.error("Generated New Unused URI <"+uri+"> for rdf node <"+current.getURI()+">");
}
}
log.debug("Using URI: <"+uri+">");
return uri;
}
/**
* Gets an unused URI in the the given namespace for the given models
* @param namespace the namespace
* @param uriCheck list of new uris generated during this changenamespace run
* @param models models to check in
* @return the uri
* @throws IllegalArgumentException empty namespace
*/
public static String getUnusedURI(String namespace, ArrayList<String> uriCheck, JenaConnect... models) throws IllegalArgumentException {
if (namespace == null || namespace.equals("")) {
throw new IllegalArgumentException("namespace cannot be empty");
}
String uri = null;
Random random = new Random();
while (uri == null) {
uri = namespace + "n" + random.nextInt(Integer.MAX_VALUE);
log.trace("uriCheck: "+uriCheck.contains(uri));
if (uriCheck.contains(uri)) {
uri = null;
}
for (JenaConnect model : models) {
if (model.containsURI(uri)) {
uri = null;
}
}
}
uriCheck.add(uri);
log.debug("Using new URI: <"+uri+">");
return uri;
}
/**
* Matches the current resource to a resource in the given namespace in the given model based on the given properties
* @param current the current resource
* @param namespace the namespace to match in
* @param properties the propeties to match on
* @param vivo the model to match in
* @return the uri of the first matched resource or null if none found
*/
public static String getMatchingURI(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
List<String> uris = getMatchingURIs(current, namespace, properties, vivo);
String uri = uris.isEmpty()?null:uris.get(0);
if (uri != null) {
log.debug("Matched URI: <"+uri+">");
} else {
log.debug("No Matched URI");
}
return uri;
}
/**
* Matches the current resource to resources in the given namespace in the given model based on the given properties
* @param current the current resource
* @param namespace the namespace to match in
* @param properties the propeties to match on
* @param vivo the model to match in
* @return the uris of the matched resources (empty set if none found)
*/
public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
log.debug("properties size: "+properties.size());
if (properties.size() < 1) {
throw new IllegalArgumentException("No properties! SELECT cannot be created!");
}
for (Property p : properties) {
StmtIterator stmntit = current.listProperties(p);
if (!stmntit.hasNext()) {
throw new IllegalArgumentException("Resource <"+current.getURI()+"> does not have property <"+p.getURI()+">! SELECT cannot be created!");
}
for (Statement s : IterableAdaptor.adapt(stmntit)) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if (s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if (!filters.isEmpty()) {
sbQuery.append("\tFILTER (");
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
sbQuery.append(")\n");
}
sbQuery.append("}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for (QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if (res == null) {
throw new IllegalArgumentException("res is null! SELECT for resource <"+current.getURI()+"> is most likely corrupted!");
}
String resns = res.getNameSpace();
if (resns.equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}
/**
* Changes the namespace for all matching uris
* @param model the model to change namespaces for
* @param vivo the model to search for uris in
* @param oldNamespace the old namespace
* @param newNamespace the new namespace
* @param properties the properties to match on
* @throws IllegalArgumentException empty namespace
*/
public static void changeNS(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, List<Property> properties) throws IllegalArgumentException {
if (oldNamespace == null || oldNamespace.equals("")) {
throw new IllegalArgumentException("old namespace cannot be empty");
}
if (newNamespace == null || newNamespace.equals("")) {
throw new IllegalArgumentException("new namespace cannot be empty");
}
if (oldNamespace.equals(newNamespace)) {
return;
}
ArrayList<String> uriCheck = new ArrayList<String>();
int count = 0;
String uri;
Resource res;
QuerySolution solution;
if (properties.size() < 1) {
throw new IllegalArgumentException("No properties! SELECT cannot be created!");
}
batchMatch(model, vivo, oldNamespace, newNamespace, properties, count);
batchRename(model, vivo, oldNamespace, newNamespace, uriCheck, count);
}
/**
* @param model
* @param vivo
* @param oldNamespace
* @param newNamespace
* @param uriCheck
* @param count
*/
private static void batchRename(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, ArrayList<String> uriCheck, int count) {
String uri;
Resource res;
QuerySolution solution;
//Grab all namespaces needing changed
log.trace("Begin Change Query Build");
String subjectQuery = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " +
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
"PREFIX owl: <http://www.w3.org/2002/07/owl#> " +
"PREFIX swrl: <http://www.w3.org/2003/11/swrl#> " +
"PREFIX swrlb: <http://www.w3.org/2003/11/swrlb#> " +
"PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> " +
"PREFIX bibo: <http://purl.org/ontology/bibo/> " +
"PREFIX dcelem: <http://purl.org/dc/elements/1.1/> " +
"PREFIX dcterms: <http://purl.org/dc/terms/> " +
"PREFIX event: <http://purl.org/NET/c4dm/event.owl#> " +
"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"PREFIX geo: <http://aims.fao.org/aos/geopolitical.owl#> " +
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#> " +
"PREFIX ufVivo: <http://vivo.ufl.edu/ontology/vivo-ufl/> " +
"PREFIX core: <http://vivoweb.org/ontology/core#> " +
"SELECT ?sNew " +
"WHERE " +
"{ " +
"?sNew ?p ?o . " +
"FILTER regex(str(?sNew), \"" + oldNamespace + "\" ) " +
"}";
log.debug(subjectQuery);
log.trace("End Change Query Build");
log.trace("Begin Execute Query");
ResultSet changeList = model.executeQuery(subjectQuery);
ArrayList<String> changeArray = new ArrayList<String>();
log.trace("End Execute Query");
log.trace("Begin Rename Changes");
while (changeList.hasNext()) {
solution = changeList.next();
changeArray.add(solution.getResource("sNew").toString());
count++;
}
for(int i = 0; i < count; i++) {
res = model.getJenaModel().getResource(changeArray.get(i));
uri = getUnusedURI(newNamespace, uriCheck, vivo, model);
ResourceUtils.renameResource(res, uri);
}
log.info("Changed namespace for "+count+" rdf nodes");
log.trace("End Rename Changes");
}
/**
* @param model
* @param vivo
* @param oldNamespace
* @param newNamespace
* @param properties
* @param count
* @return
*/
private static void batchMatch(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, List<Property> properties, int count) {
Resource res;
QuerySolution solution;
log.trace("Begin Match Query Build");
//Find all namespace matches
StringBuilder sQuery = new StringBuilder("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " +
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
"PREFIX owl: <http://www.w3.org/2002/07/owl#> " +
"PREFIX swrl: <http://www.w3.org/2003/11/swrl#> " +
"PREFIX swrlb: <http://www.w3.org/2003/11/swrlb#> " +
"PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> " +
"PREFIX bibo: <http://purl.org/ontology/bibo/> " +
"PREFIX dcelem: <http://purl.org/dc/elements/1.1/> " +
"PREFIX dcterms: <http://purl.org/dc/terms/> " +
"PREFIX event: <http://purl.org/NET/c4dm/event.owl#> " +
"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"PREFIX geo: <http://aims.fao.org/aos/geopolitical.owl#> " +
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#> " +
"PREFIX ufVivo: <http://vivo.ufl.edu/ontology/vivo-ufl/> " +
"PREFIX core: <http://vivoweb.org/ontology/core#> " +
"SELECT ?sNew ?sOld " +
"WHERE " +
"{ ");
int counter = 0;
for (Property p : properties) {
sQuery.append("\t?sNew <");
sQuery.append(p.getURI());
sQuery.append("> ");
sQuery.append("?o" + counter );
sQuery.append(" .\n");
sQuery.append("\t?sOld <");
sQuery.append(p.getURI());
sQuery.append("> ");
sQuery.append("\t?o" + counter );
sQuery.append(" .\n");
}
sQuery.append("FILTER regex(str(?sNew), \"");
sQuery.append(oldNamespace + "\" ) .");
sQuery.append("FILTER regex(str(?sOld), \"");
sQuery.append(newNamespace + "\" ) }");
log.debug(sQuery.toString());
log.trace("End Match Query Build");
log.trace("Begin Union Model");
Model unionModel = model.getJenaModel().union(vivo.getJenaModel());
log.trace("End Union Model");
log.trace("Begin Run Query to ResultSet");
Query query = QueryFactory.create(sQuery.toString(), Syntax.syntaxARQ);
QueryExecution queryExec = QueryExecutionFactory.create(query, unionModel);
ResultSet matchList = queryExec.execSelect();
log.trace("End Run Query to ResultSet");
log.trace("Begin Rename Matches");
ArrayList<String[]> uriArray = new ArrayList<String[]>();
String matchArray[];
while (matchList.hasNext()) {
solution = matchList.next();
matchArray = new String[2];
matchArray[0] = solution.getResource("sNew").toString();
matchArray[1] = solution.getResource("sOld").toString();
uriArray.add(matchArray);
count++;
}
for(int i = 0; i < count; i++) {
matchArray = uriArray.get(i);
res = model.getJenaModel().getResource(matchArray[0]);
ResourceUtils.renameResource(res, matchArray[1]);
}
log.info("Matched namespace for "+count+" rdf nodes");
log.trace("Begin Rename Matches");
count = 0;
- return count;
}
/**
* Change namespace
*/
private void execute() {
changeNS(this.model, this.vivo, this.oldNamespace, this.newNamespace, this.properties);
}
/**
* Get the ArgParser for this task
* @return the ArgParser
*/
private static ArgParser getParser() {
ArgParser parser = new ArgParser("ChangeNamespace");
// Inputs
parser.addArgument(new ArgDef().setShortOption('i').setLongOpt("inputModel").withParameter(true, "CONFIG_FILE").setDescription("config file for input jena model").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('I').setLongOpt("inputModelOverride").withParameterProperties("JENA_PARAM", "VALUE").setDescription("override the JENA_PARAM of input jena model config using VALUE").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('v').setLongOpt("vivoModel").withParameter(true, "CONFIG_FILE").setDescription("config file for vivo jena model").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('V').setLongOpt("vivoModelOverride").withParameterProperties("JENA_PARAM", "VALUE").setDescription("override the JENA_PARAM of vivo jena model config using VALUE").setRequired(false));
// Params
parser.addArgument(new ArgDef().setShortOption('o').setLongOpt("oldNamespace").withParameter(true, "OLD_NAMESPACE").setDescription("The old namespace").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('n').setLongOpt("newNamespace").withParameter(true, "NEW_NAMESPACE").setDescription("The new namespace").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('p').setLongOpt("predicate").withParameters(true, "MATCH_PREDICATE").setDescription("Predicate to match on").setRequired(true));
return parser;
}
/**
* Main method
* @param args commandline arguments
*/
public static void main(String... args) {
InitLog.initLogger(ChangeNamespace.class);
log.info(getParser().getAppName()+": Start");
try {
new ChangeNamespace(new ArgList(getParser(), args)).execute();
} catch (IllegalArgumentException e) {
log.error(e.getMessage());
System.out.println(getParser().getUsage());
} catch (IOException e) {
log.error(e.getMessage(), e);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
log.info(getParser().getAppName()+": End");
}
}
| true | true | private static void batchMatch(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, List<Property> properties, int count) {
Resource res;
QuerySolution solution;
log.trace("Begin Match Query Build");
//Find all namespace matches
StringBuilder sQuery = new StringBuilder("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " +
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
"PREFIX owl: <http://www.w3.org/2002/07/owl#> " +
"PREFIX swrl: <http://www.w3.org/2003/11/swrl#> " +
"PREFIX swrlb: <http://www.w3.org/2003/11/swrlb#> " +
"PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> " +
"PREFIX bibo: <http://purl.org/ontology/bibo/> " +
"PREFIX dcelem: <http://purl.org/dc/elements/1.1/> " +
"PREFIX dcterms: <http://purl.org/dc/terms/> " +
"PREFIX event: <http://purl.org/NET/c4dm/event.owl#> " +
"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"PREFIX geo: <http://aims.fao.org/aos/geopolitical.owl#> " +
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#> " +
"PREFIX ufVivo: <http://vivo.ufl.edu/ontology/vivo-ufl/> " +
"PREFIX core: <http://vivoweb.org/ontology/core#> " +
"SELECT ?sNew ?sOld " +
"WHERE " +
"{ ");
int counter = 0;
for (Property p : properties) {
sQuery.append("\t?sNew <");
sQuery.append(p.getURI());
sQuery.append("> ");
sQuery.append("?o" + counter );
sQuery.append(" .\n");
sQuery.append("\t?sOld <");
sQuery.append(p.getURI());
sQuery.append("> ");
sQuery.append("\t?o" + counter );
sQuery.append(" .\n");
}
sQuery.append("FILTER regex(str(?sNew), \"");
sQuery.append(oldNamespace + "\" ) .");
sQuery.append("FILTER regex(str(?sOld), \"");
sQuery.append(newNamespace + "\" ) }");
log.debug(sQuery.toString());
log.trace("End Match Query Build");
log.trace("Begin Union Model");
Model unionModel = model.getJenaModel().union(vivo.getJenaModel());
log.trace("End Union Model");
log.trace("Begin Run Query to ResultSet");
Query query = QueryFactory.create(sQuery.toString(), Syntax.syntaxARQ);
QueryExecution queryExec = QueryExecutionFactory.create(query, unionModel);
ResultSet matchList = queryExec.execSelect();
log.trace("End Run Query to ResultSet");
log.trace("Begin Rename Matches");
ArrayList<String[]> uriArray = new ArrayList<String[]>();
String matchArray[];
while (matchList.hasNext()) {
solution = matchList.next();
matchArray = new String[2];
matchArray[0] = solution.getResource("sNew").toString();
matchArray[1] = solution.getResource("sOld").toString();
uriArray.add(matchArray);
count++;
}
for(int i = 0; i < count; i++) {
matchArray = uriArray.get(i);
res = model.getJenaModel().getResource(matchArray[0]);
ResourceUtils.renameResource(res, matchArray[1]);
}
log.info("Matched namespace for "+count+" rdf nodes");
log.trace("Begin Rename Matches");
count = 0;
return count;
}
| private static void batchMatch(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, List<Property> properties, int count) {
Resource res;
QuerySolution solution;
log.trace("Begin Match Query Build");
//Find all namespace matches
StringBuilder sQuery = new StringBuilder("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " +
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
"PREFIX owl: <http://www.w3.org/2002/07/owl#> " +
"PREFIX swrl: <http://www.w3.org/2003/11/swrl#> " +
"PREFIX swrlb: <http://www.w3.org/2003/11/swrlb#> " +
"PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> " +
"PREFIX bibo: <http://purl.org/ontology/bibo/> " +
"PREFIX dcelem: <http://purl.org/dc/elements/1.1/> " +
"PREFIX dcterms: <http://purl.org/dc/terms/> " +
"PREFIX event: <http://purl.org/NET/c4dm/event.owl#> " +
"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"PREFIX geo: <http://aims.fao.org/aos/geopolitical.owl#> " +
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#> " +
"PREFIX ufVivo: <http://vivo.ufl.edu/ontology/vivo-ufl/> " +
"PREFIX core: <http://vivoweb.org/ontology/core#> " +
"SELECT ?sNew ?sOld " +
"WHERE " +
"{ ");
int counter = 0;
for (Property p : properties) {
sQuery.append("\t?sNew <");
sQuery.append(p.getURI());
sQuery.append("> ");
sQuery.append("?o" + counter );
sQuery.append(" .\n");
sQuery.append("\t?sOld <");
sQuery.append(p.getURI());
sQuery.append("> ");
sQuery.append("\t?o" + counter );
sQuery.append(" .\n");
}
sQuery.append("FILTER regex(str(?sNew), \"");
sQuery.append(oldNamespace + "\" ) .");
sQuery.append("FILTER regex(str(?sOld), \"");
sQuery.append(newNamespace + "\" ) }");
log.debug(sQuery.toString());
log.trace("End Match Query Build");
log.trace("Begin Union Model");
Model unionModel = model.getJenaModel().union(vivo.getJenaModel());
log.trace("End Union Model");
log.trace("Begin Run Query to ResultSet");
Query query = QueryFactory.create(sQuery.toString(), Syntax.syntaxARQ);
QueryExecution queryExec = QueryExecutionFactory.create(query, unionModel);
ResultSet matchList = queryExec.execSelect();
log.trace("End Run Query to ResultSet");
log.trace("Begin Rename Matches");
ArrayList<String[]> uriArray = new ArrayList<String[]>();
String matchArray[];
while (matchList.hasNext()) {
solution = matchList.next();
matchArray = new String[2];
matchArray[0] = solution.getResource("sNew").toString();
matchArray[1] = solution.getResource("sOld").toString();
uriArray.add(matchArray);
count++;
}
for(int i = 0; i < count; i++) {
matchArray = uriArray.get(i);
res = model.getJenaModel().getResource(matchArray[0]);
ResourceUtils.renameResource(res, matchArray[1]);
}
log.info("Matched namespace for "+count+" rdf nodes");
log.trace("Begin Rename Matches");
count = 0;
}
|
diff --git a/virtual-repository-service/src/main/java/org/virtualrepository/service/utils/TypeUtilities.java b/virtual-repository-service/src/main/java/org/virtualrepository/service/utils/TypeUtilities.java
index f597550..78adc5c 100644
--- a/virtual-repository-service/src/main/java/org/virtualrepository/service/utils/TypeUtilities.java
+++ b/virtual-repository-service/src/main/java/org/virtualrepository/service/utils/TypeUtilities.java
@@ -1,37 +1,37 @@
/**
* (c) 2013 FAO / UN (project: virtual-repository-service)
*/
package org.virtualrepository.service.utils;
import org.virtualrepository.AssetType;
/**
* Place your class / interface description here.
*
* History:
*
* ------------- --------------- -----------------------
* Date Author Comment
* ------------- --------------- -----------------------
* 27 Aug 2013 Fiorellato Creation.
*
* @version 1.0
* @since 27 Aug 2013
*/
final public class TypeUtilities {
private TypeUtilities() { }
static public AssetType forName(AssetType[] types, String name) throws RuntimeException {
if(types == null || types.length == 0)
throw new RuntimeException("Please provide a non-NULL and non-empty list of available asset types");
if(name == null)
throw new RuntimeException("Please provide a non-NULL asset type name");
for(AssetType type : types)
if(type.name().equals(name))
return type;
- throw new RuntimeException("Unknown / unavailable asset type name " + name);
+ throw new RuntimeException("Unknown / unavailable asset type '" + name + "'");
}
}
| true | true | static public AssetType forName(AssetType[] types, String name) throws RuntimeException {
if(types == null || types.length == 0)
throw new RuntimeException("Please provide a non-NULL and non-empty list of available asset types");
if(name == null)
throw new RuntimeException("Please provide a non-NULL asset type name");
for(AssetType type : types)
if(type.name().equals(name))
return type;
throw new RuntimeException("Unknown / unavailable asset type name " + name);
}
| static public AssetType forName(AssetType[] types, String name) throws RuntimeException {
if(types == null || types.length == 0)
throw new RuntimeException("Please provide a non-NULL and non-empty list of available asset types");
if(name == null)
throw new RuntimeException("Please provide a non-NULL asset type name");
for(AssetType type : types)
if(type.name().equals(name))
return type;
throw new RuntimeException("Unknown / unavailable asset type '" + name + "'");
}
|
diff --git a/addons/ofxAndroid/ofAndroidLib/src/cc/openframeworks/OFAndroidVideoGrabber.java b/addons/ofxAndroid/ofAndroidLib/src/cc/openframeworks/OFAndroidVideoGrabber.java
index 16f3b40b..987d3860 100644
--- a/addons/ofxAndroid/ofAndroidLib/src/cc/openframeworks/OFAndroidVideoGrabber.java
+++ b/addons/ofxAndroid/ofAndroidLib/src/cc/openframeworks/OFAndroidVideoGrabber.java
@@ -1,247 +1,247 @@
package cc.openframeworks;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.OrientationEventListener;
public class OFAndroidVideoGrabber extends OFAndroidObject implements Runnable, Camera.PreviewCallback {
public OFAndroidVideoGrabber(){
id=nextId++;
camera_instances.put(id, this);
}
public int getId(){
return id;
}
public static OFAndroidVideoGrabber getInstance(int id){
return camera_instances.get(id);
}
void setDeviceID(int id){
deviceID = id;
}
void initGrabber(int w, int h, int _targetFps){
if(deviceID==-1)
camera = Camera.open();
else{
try {
int numCameras = (Integer) Camera.class.getMethod("getNumberOfCameras").invoke(null);
Class<?> cameraInfoClass = Class.forName("android.hardware.Camera$CameraInfo");
Object cameraInfo = null;
Field field = null;
if ( cameraInfoClass != null ) {
cameraInfo = cameraInfoClass.newInstance();
}
if ( cameraInfo != null ) {
field = cameraInfo.getClass().getField( "facing" );
}
Method getCameraInfoMethod = Camera.class.getMethod( "getCameraInfo", Integer.TYPE, cameraInfoClass );
for(int i=0;i<numCameras;i++){
getCameraInfoMethod.invoke( null, i, cameraInfo );
int facing = field.getInt( cameraInfo );
Log.v("OF","Camera " + i + " facing: " + facing);
}
camera = (Camera) Camera.class.getMethod("open", Integer.TYPE).invoke(null, deviceID);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("OF","Error trying to open specific camera, trying default",e);
+ camera = Camera.open();
}
- camera = Camera.open();
}
Camera.Parameters config = camera.getParameters();
Log.i("OF","Grabber supported sizes");
for(Size s : config.getSupportedPreviewSizes()){
Log.i("OF",s.width + " " + s.height);
}
Log.i("OF","Grabber supported formats");
for(Integer i : config.getSupportedPreviewFormats()){
Log.i("OF",i.toString());
}
Log.i("OF","Grabber supported fps");
for(Integer i : config.getSupportedPreviewFrameRates()){
Log.i("OF",i.toString());
}
Log.i("OF", "Grabber default format: " + config.getPreviewFormat());
Log.i("OF", "Grabber default preview size: " + config.getPreviewSize().width + "," + config.getPreviewSize().height);
config.setPreviewSize(w, h);
config.setPreviewFormat(ImageFormat.NV21);
try{
camera.setParameters(config);
}catch(Exception e){
Log.e("OF","couldn init camera", e);
}
config = camera.getParameters();
width = config.getPreviewSize().width;
height = config.getPreviewSize().height;
if(width!=w || height!=h) Log.w("OF","camera size different than asked for, resizing (this can slow the app)");
if(_targetFps!=-1){
config = camera.getParameters();
config.setPreviewFrameRate(_targetFps);
try{
camera.setParameters(config);
}catch(Exception e){
Log.e("OF","couldn init camera", e);
}
}
targetFps = _targetFps;
Log.i("OF","camera settings: " + width + "x" + height);
buffer = new byte[width*height*2];
orientationListener = new OrientationListener(OFAndroid.getContext());
orientationListener.enable();
thread = new Thread(this);
thread.start();
initialized = true;
}
@Override
public void stop(){
if(initialized){
Log.i("OF","stopping camera");
camera.stopPreview();
try {
thread.join();
} catch (InterruptedException e) {
Log.e("OF", "problem trying to close camera thread", e);
}
camera.release();
orientationListener.disable();
}
}
@Override
public void pause(){
stop();
}
@Override
public void resume(){
if(initialized){
initGrabber(width,height,targetFps);
orientationListener.enable();
}
}
public void onPreviewFrame(byte[] data, Camera camera) {
//Log.i("OF","video buffer length: " + data.length);
//Log.i("OF", "size: " + camera.getParameters().getPreviewSize().width + "x" + camera.getParameters().getPreviewSize().height);
//Log.i("OF", "format " + camera.getParameters().getPreviewFormat());
newFrame(data, width, height);
if(addBufferMethod!=null){
try {
addBufferMethod.invoke(camera, buffer);
} catch (Exception e) {
Log.e("OF","error adding buffer",e);
}
}
//camera.addCallbackBuffer(data);
}
public void run() {
thread.setPriority(Thread.MAX_PRIORITY);
try {
addBufferMethod = Camera.class.getMethod("addCallbackBuffer", byte[].class);
addBufferMethod.invoke(camera, buffer);
Camera.class.getMethod("setPreviewCallbackWithBuffer", Camera.PreviewCallback.class).invoke(camera, this);
Log.i("OF","setting camera callback with buffer");
} catch (SecurityException e) {
Log.e("OF","security exception, check permissions to acces to the camera",e);
} catch (NoSuchMethodException e) {
try {
Camera.class.getMethod("setPreviewCallback", Camera.PreviewCallback.class).invoke(camera, this);
Log.i("OF","setting camera callback without buffer");
} catch (SecurityException e1) {
Log.e("OF","security exception, check permissions to acces to the camera",e1);
} catch (Exception e1) {
Log.e("OF","cannot create callback, the camera can only be used from api v7",e1);
}
} catch (Exception e) {
Log.e("OF","error adding callback",e);
}
//camera.addCallbackBuffer(buffer);
//camera.setPreviewCallbackWithBuffer(this);
try{
camera.startPreview();
} catch (Exception e) {
Log.e("OF","error starting preview",e);
}
}
private class OrientationListener extends OrientationEventListener{
public OrientationListener(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
public void onOrientationChanged(int orientation) {
if (orientation == ORIENTATION_UNKNOWN) return;
try{
Camera.Parameters config = camera.getParameters();
/*Camera.CameraInfo info =
new Camera.CameraInfo();*/
//Camera.getCameraInfo(camera, info);
orientation = (orientation + 45) / 90 * 90;
int rotation = orientation % 360;
//if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
//rotation = (info.orientation - orientation + 360) % 360;
/*} else { // back-facing camera
rotation = (info.orientation + orientation) % 360;
}*/
config.setRotation(rotation);
camera.setParameters(config);
}catch(Exception e){
}
}
}
public static native int newFrame(byte[] data, int width, int height);
private Camera camera;
private int deviceID = -1;
private byte[] buffer;
private int width, height, targetFps;
private Thread thread;
private int id;
private static int nextId=0;
public static Map<Integer,OFAndroidVideoGrabber> camera_instances = new HashMap<Integer,OFAndroidVideoGrabber>();
private boolean initialized = false;
private Method addBufferMethod;
private OrientationListener orientationListener;
}
| false | true | void initGrabber(int w, int h, int _targetFps){
if(deviceID==-1)
camera = Camera.open();
else{
try {
int numCameras = (Integer) Camera.class.getMethod("getNumberOfCameras").invoke(null);
Class<?> cameraInfoClass = Class.forName("android.hardware.Camera$CameraInfo");
Object cameraInfo = null;
Field field = null;
if ( cameraInfoClass != null ) {
cameraInfo = cameraInfoClass.newInstance();
}
if ( cameraInfo != null ) {
field = cameraInfo.getClass().getField( "facing" );
}
Method getCameraInfoMethod = Camera.class.getMethod( "getCameraInfo", Integer.TYPE, cameraInfoClass );
for(int i=0;i<numCameras;i++){
getCameraInfoMethod.invoke( null, i, cameraInfo );
int facing = field.getInt( cameraInfo );
Log.v("OF","Camera " + i + " facing: " + facing);
}
camera = (Camera) Camera.class.getMethod("open", Integer.TYPE).invoke(null, deviceID);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("OF","Error trying to open specific camera, trying default",e);
}
camera = Camera.open();
}
Camera.Parameters config = camera.getParameters();
Log.i("OF","Grabber supported sizes");
for(Size s : config.getSupportedPreviewSizes()){
Log.i("OF",s.width + " " + s.height);
}
Log.i("OF","Grabber supported formats");
for(Integer i : config.getSupportedPreviewFormats()){
Log.i("OF",i.toString());
}
Log.i("OF","Grabber supported fps");
for(Integer i : config.getSupportedPreviewFrameRates()){
Log.i("OF",i.toString());
}
Log.i("OF", "Grabber default format: " + config.getPreviewFormat());
Log.i("OF", "Grabber default preview size: " + config.getPreviewSize().width + "," + config.getPreviewSize().height);
config.setPreviewSize(w, h);
config.setPreviewFormat(ImageFormat.NV21);
try{
camera.setParameters(config);
}catch(Exception e){
Log.e("OF","couldn init camera", e);
}
config = camera.getParameters();
width = config.getPreviewSize().width;
height = config.getPreviewSize().height;
if(width!=w || height!=h) Log.w("OF","camera size different than asked for, resizing (this can slow the app)");
if(_targetFps!=-1){
config = camera.getParameters();
config.setPreviewFrameRate(_targetFps);
try{
camera.setParameters(config);
}catch(Exception e){
Log.e("OF","couldn init camera", e);
}
}
targetFps = _targetFps;
Log.i("OF","camera settings: " + width + "x" + height);
buffer = new byte[width*height*2];
orientationListener = new OrientationListener(OFAndroid.getContext());
orientationListener.enable();
thread = new Thread(this);
thread.start();
initialized = true;
}
| void initGrabber(int w, int h, int _targetFps){
if(deviceID==-1)
camera = Camera.open();
else{
try {
int numCameras = (Integer) Camera.class.getMethod("getNumberOfCameras").invoke(null);
Class<?> cameraInfoClass = Class.forName("android.hardware.Camera$CameraInfo");
Object cameraInfo = null;
Field field = null;
if ( cameraInfoClass != null ) {
cameraInfo = cameraInfoClass.newInstance();
}
if ( cameraInfo != null ) {
field = cameraInfo.getClass().getField( "facing" );
}
Method getCameraInfoMethod = Camera.class.getMethod( "getCameraInfo", Integer.TYPE, cameraInfoClass );
for(int i=0;i<numCameras;i++){
getCameraInfoMethod.invoke( null, i, cameraInfo );
int facing = field.getInt( cameraInfo );
Log.v("OF","Camera " + i + " facing: " + facing);
}
camera = (Camera) Camera.class.getMethod("open", Integer.TYPE).invoke(null, deviceID);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("OF","Error trying to open specific camera, trying default",e);
camera = Camera.open();
}
}
Camera.Parameters config = camera.getParameters();
Log.i("OF","Grabber supported sizes");
for(Size s : config.getSupportedPreviewSizes()){
Log.i("OF",s.width + " " + s.height);
}
Log.i("OF","Grabber supported formats");
for(Integer i : config.getSupportedPreviewFormats()){
Log.i("OF",i.toString());
}
Log.i("OF","Grabber supported fps");
for(Integer i : config.getSupportedPreviewFrameRates()){
Log.i("OF",i.toString());
}
Log.i("OF", "Grabber default format: " + config.getPreviewFormat());
Log.i("OF", "Grabber default preview size: " + config.getPreviewSize().width + "," + config.getPreviewSize().height);
config.setPreviewSize(w, h);
config.setPreviewFormat(ImageFormat.NV21);
try{
camera.setParameters(config);
}catch(Exception e){
Log.e("OF","couldn init camera", e);
}
config = camera.getParameters();
width = config.getPreviewSize().width;
height = config.getPreviewSize().height;
if(width!=w || height!=h) Log.w("OF","camera size different than asked for, resizing (this can slow the app)");
if(_targetFps!=-1){
config = camera.getParameters();
config.setPreviewFrameRate(_targetFps);
try{
camera.setParameters(config);
}catch(Exception e){
Log.e("OF","couldn init camera", e);
}
}
targetFps = _targetFps;
Log.i("OF","camera settings: " + width + "x" + height);
buffer = new byte[width*height*2];
orientationListener = new OrientationListener(OFAndroid.getContext());
orientationListener.enable();
thread = new Thread(this);
thread.start();
initialized = true;
}
|
diff --git a/corelib-solr/src/test/java/eu/europeana/corelib/solr/ContentLoader.java b/corelib-solr/src/test/java/eu/europeana/corelib/solr/ContentLoader.java
index 4439b5e2..2770b536 100644
--- a/corelib-solr/src/test/java/eu/europeana/corelib/solr/ContentLoader.java
+++ b/corelib-solr/src/test/java/eu/europeana/corelib/solr/ContentLoader.java
@@ -1,272 +1,272 @@
/*
* Copyright 2007-2012 The Europeana Foundation
*
* Licenced under the EUPL, Version 1.1 (the "Licence") and subsequent versions as approved
* by the European Commission;
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* http://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the Licence is distributed on an "AS IS" basis, without warranties or conditions of
* any kind, either express or implied.
* See the Licence for the specific language governing permissions and limitations under
* the Licence.
*/
package eu.europeana.corelib.solr;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import eu.europeana.corelib.definitions.jibx.RDF;
import eu.europeana.corelib.solr.bean.impl.FullBeanImpl;
import eu.europeana.corelib.solr.server.MongoDBServer;
import eu.europeana.corelib.solr.util.MongoConstructor;
import eu.europeana.corelib.solr.util.SolrConstructor;
import eu.europeana.corelib.solr.utils.MongoUtils;
/**
* Sample Class for uploading content in a local Mongo and Solr Instance
*
* @author Yorgos.Mamakis@ kb.nl
*/
public class ContentLoader {
private static String COLLECTION = "src/test/resources/records.zip";
private static String TEMP_DIR = "/tmp/europeana/records";
private MongoDBServer mongoDBServer;
private SolrServer solrServer;
private List<File> collectionXML = new ArrayList<File>();
private List<SolrInputDocument> records = new ArrayList<SolrInputDocument>();
private int i = 0;
private int failed = 0;
private int imported = 0;
private static ContentLoader instance = null;
public static ContentLoader getInstance(MongoDBServer mongoDBServer, SolrServer solrServer) {
if (instance == null) {
instance = new ContentLoader(mongoDBServer, solrServer);
}
return instance;
}
private ContentLoader(MongoDBServer mongoDBServer, SolrServer solrServer) {
this.mongoDBServer = mongoDBServer;
this.solrServer = solrServer;
}
public void readRecords(String collectionName) {
if (StringUtils.isBlank(collectionName)) {
System.out.println("Parameter collectionName is not set correctly");
System.out.println("Using default collectionName: " + collectionName);
}
if (isZipped(collectionName)) {
collectionXML = unzip(collectionName);
} else {
if (new File(collectionName).isDirectory()) {
for (File file : new File(collectionName).listFiles()) {
if (StringUtils.endsWith(file.getName(), ".xml")) {
collectionXML.add(file);
}
}
} else {
collectionXML.add(new File(collectionName));
}
}
}
public int parse() {
MongoConstructor mongoConstructor = new MongoConstructor();
mongoConstructor.setMongoServer(mongoDBServer);
for (File f : collectionXML) {
try {
IBindingFactory bfact = BindingDirectory.getFactory(RDF.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
i++;
RDF rdf = (RDF) uctx.unmarshalDocument(new FileInputStream(f), null);
FullBeanImpl fullBean = mongoConstructor.constructFullBean(rdf);
if(mongoDBServer.searchByAbout(FullBeanImpl.class, fullBean.getAbout())!=null){
MongoUtils.updateFullBean(fullBean, mongoDBServer);
}else {
mongoDBServer.getDatastore().save(fullBean);
}
records.add(SolrConstructor.constructSolrDocument(rdf));
if (i % 1000 == 0 || i == collectionXML.size()) {
System.out.println("Sending " + i + " records to SOLR");
imported += records.size();
solrServer.add(records);
records.clear();
}
} catch (JiBXException e) {
failed++;
System.out.println("Error unmarshalling document " + f.getName()
- + " from the input file. Check for Schema changes");
+ + " from the input file. Check for Schema changes ("+e.getMessage()+")");
// e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return failed;
}
public void commit() {
try {
solrServer.commit();
solrServer.optimize();
System.out.println("Finished Importing");
System.out.println("Records read: " + i);
System.out.println("Records imported: " + imported);
System.out.println("Records failed: " + failed);
solrServer = null;
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void cleanFiles() {
System.out.println("Deleting files");
for (File f : collectionXML) {
f.delete();
}
System.out.println("Files deleted");
}
/**
* Unzip a zipped collection file
*
* @param collectionName
* The path to the collection file
* @return The unzipped file
*/
private ArrayList<File> unzip(String collectionName) {
BufferedOutputStream dest = null;
String fileName = "";
ArrayList<File> records = new ArrayList<File>();
try {
FileInputStream fis = new FileInputStream(collectionName);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
File workingDir = new File(TEMP_DIR);
workingDir.mkdirs();
while ((entry = zis.getNextEntry()) != null) {
int count;
byte data[] = new byte[2048];
fileName = workingDir.getAbsolutePath() + "/" + entry.getName();
records.add(new File(fileName));
FileOutputStream fos = new FileOutputStream(fileName);
dest = new BufferedOutputStream(fos, 2048);
while ((count = zis.read(data, 0, 2048)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
zis.close();
} catch (Exception e) {
System.out.println("The zip file is destroyed. Could not import records");
e.printStackTrace();
}
return records;
}
/**
* Check if the collection file is zipped
*
* @param collectionName
* @return true if it is in gzip or zip format, false if not
*/
private boolean isZipped(String collectionName) {
return StringUtils.endsWith(collectionName, ".gzip") || StringUtils.endsWith(collectionName, ".zip");
}
/**
* Method to load content in SOLR and MongoDB
*
* @param args
* solrHome parameter holding "solr.solr.home" mongoHost the host the mongoDB is located mongoPort the
* port mongoDB listens databaseName the databaseName to save collectionName the name of the collection
* (an XML, a folder or a Zip file)
*
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext( "/corelib-solr-context.xml", "/corelib-solr-test.xml" );
SolrServer solrServer = context.getBean("corelib_solr_solrEmbedded", SolrServer.class);
MongoDBServer mongoDBServer = context.getBean("corelib_solr_mongoServer", MongoDBServer.class);
if ( (solrServer != null) && (mongoDBServer != null)) {
ContentLoader contentLoader = null;
try {
contentLoader = ContentLoader.getInstance(mongoDBServer, solrServer);
contentLoader.readRecords(COLLECTION);
contentLoader.parse();
contentLoader.commit();
}
catch(Exception e){
e.printStackTrace();
}
finally {
if (contentLoader != null) {
contentLoader.cleanFiles();
}
}
}
}
}
| true | true | public int parse() {
MongoConstructor mongoConstructor = new MongoConstructor();
mongoConstructor.setMongoServer(mongoDBServer);
for (File f : collectionXML) {
try {
IBindingFactory bfact = BindingDirectory.getFactory(RDF.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
i++;
RDF rdf = (RDF) uctx.unmarshalDocument(new FileInputStream(f), null);
FullBeanImpl fullBean = mongoConstructor.constructFullBean(rdf);
if(mongoDBServer.searchByAbout(FullBeanImpl.class, fullBean.getAbout())!=null){
MongoUtils.updateFullBean(fullBean, mongoDBServer);
}else {
mongoDBServer.getDatastore().save(fullBean);
}
records.add(SolrConstructor.constructSolrDocument(rdf));
if (i % 1000 == 0 || i == collectionXML.size()) {
System.out.println("Sending " + i + " records to SOLR");
imported += records.size();
solrServer.add(records);
records.clear();
}
} catch (JiBXException e) {
failed++;
System.out.println("Error unmarshalling document " + f.getName()
+ " from the input file. Check for Schema changes");
// e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return failed;
}
| public int parse() {
MongoConstructor mongoConstructor = new MongoConstructor();
mongoConstructor.setMongoServer(mongoDBServer);
for (File f : collectionXML) {
try {
IBindingFactory bfact = BindingDirectory.getFactory(RDF.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
i++;
RDF rdf = (RDF) uctx.unmarshalDocument(new FileInputStream(f), null);
FullBeanImpl fullBean = mongoConstructor.constructFullBean(rdf);
if(mongoDBServer.searchByAbout(FullBeanImpl.class, fullBean.getAbout())!=null){
MongoUtils.updateFullBean(fullBean, mongoDBServer);
}else {
mongoDBServer.getDatastore().save(fullBean);
}
records.add(SolrConstructor.constructSolrDocument(rdf));
if (i % 1000 == 0 || i == collectionXML.size()) {
System.out.println("Sending " + i + " records to SOLR");
imported += records.size();
solrServer.add(records);
records.clear();
}
} catch (JiBXException e) {
failed++;
System.out.println("Error unmarshalling document " + f.getName()
+ " from the input file. Check for Schema changes ("+e.getMessage()+")");
// e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return failed;
}
|
diff --git a/plexus-archiver/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java b/plexus-archiver/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java
index d574a486..19e60c0e 100644
--- a/plexus-archiver/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java
+++ b/plexus-archiver/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java
@@ -1,74 +1,74 @@
package org.codehaus.plexus.archiver.util;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.util.Os;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import java.io.File;
public final class ArchiveEntryUtils
{
private ArchiveEntryUtils()
{
}
public static void chmod( File file, int mode, Logger logger )
throws ArchiverException
{
if ( !Os.isFamily( "unix" ) )
{
return;
}
String m = Integer.toOctalString( mode & 0xfff );
try
{
Commandline commandline = new Commandline();
commandline.setWorkingDirectory( file.getParentFile().getAbsolutePath() );
commandline.setExecutable( "chmod" );
commandline.createArgument().setValue( m );
String path = file.getAbsolutePath();
- commandline.createArgument().setValue( "\'" + path + "\'" );
+ commandline.createArgument().setValue( path );
// commenting this debug statement, since it can produce VERY verbose output...
// this method is called often during archive creation.
// logger.debug( "Executing:\n\n" + commandline.toString() + "\n\n" );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
int exitCode = CommandLineUtils.executeCommandLine( commandline, stderr, stdout );
if ( exitCode != 0 )
{
logger.warn( "-------------------------------" );
logger.warn( "Standard error:" );
logger.warn( "-------------------------------" );
logger.warn( stderr.getOutput() );
logger.warn( "-------------------------------" );
logger.warn( "Standard output:" );
logger.warn( "-------------------------------" );
logger.warn( stdout.getOutput() );
logger.warn( "-------------------------------" );
throw new ArchiverException( "chmod exit code was: " + exitCode );
}
}
catch ( CommandLineException e )
{
throw new ArchiverException( "Error while executing chmod.", e );
}
}
}
| true | true | public static void chmod( File file, int mode, Logger logger )
throws ArchiverException
{
if ( !Os.isFamily( "unix" ) )
{
return;
}
String m = Integer.toOctalString( mode & 0xfff );
try
{
Commandline commandline = new Commandline();
commandline.setWorkingDirectory( file.getParentFile().getAbsolutePath() );
commandline.setExecutable( "chmod" );
commandline.createArgument().setValue( m );
String path = file.getAbsolutePath();
commandline.createArgument().setValue( "\'" + path + "\'" );
// commenting this debug statement, since it can produce VERY verbose output...
// this method is called often during archive creation.
// logger.debug( "Executing:\n\n" + commandline.toString() + "\n\n" );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
int exitCode = CommandLineUtils.executeCommandLine( commandline, stderr, stdout );
if ( exitCode != 0 )
{
logger.warn( "-------------------------------" );
logger.warn( "Standard error:" );
logger.warn( "-------------------------------" );
logger.warn( stderr.getOutput() );
logger.warn( "-------------------------------" );
logger.warn( "Standard output:" );
logger.warn( "-------------------------------" );
logger.warn( stdout.getOutput() );
logger.warn( "-------------------------------" );
throw new ArchiverException( "chmod exit code was: " + exitCode );
}
}
catch ( CommandLineException e )
{
throw new ArchiverException( "Error while executing chmod.", e );
}
}
| public static void chmod( File file, int mode, Logger logger )
throws ArchiverException
{
if ( !Os.isFamily( "unix" ) )
{
return;
}
String m = Integer.toOctalString( mode & 0xfff );
try
{
Commandline commandline = new Commandline();
commandline.setWorkingDirectory( file.getParentFile().getAbsolutePath() );
commandline.setExecutable( "chmod" );
commandline.createArgument().setValue( m );
String path = file.getAbsolutePath();
commandline.createArgument().setValue( path );
// commenting this debug statement, since it can produce VERY verbose output...
// this method is called often during archive creation.
// logger.debug( "Executing:\n\n" + commandline.toString() + "\n\n" );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
int exitCode = CommandLineUtils.executeCommandLine( commandline, stderr, stdout );
if ( exitCode != 0 )
{
logger.warn( "-------------------------------" );
logger.warn( "Standard error:" );
logger.warn( "-------------------------------" );
logger.warn( stderr.getOutput() );
logger.warn( "-------------------------------" );
logger.warn( "Standard output:" );
logger.warn( "-------------------------------" );
logger.warn( stdout.getOutput() );
logger.warn( "-------------------------------" );
throw new ArchiverException( "chmod exit code was: " + exitCode );
}
}
catch ( CommandLineException e )
{
throw new ArchiverException( "Error while executing chmod.", e );
}
}
|
diff --git a/src/com/google/videoeditor/widgets/AudioTrackView.java b/src/com/google/videoeditor/widgets/AudioTrackView.java
index 8008ca8..3663ca2 100755
--- a/src/com/google/videoeditor/widgets/AudioTrackView.java
+++ b/src/com/google/videoeditor/widgets/AudioTrackView.java
@@ -1,366 +1,366 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.videoeditor.widgets;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.videoeditor.WaveformData;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import com.google.videoeditor.R;
import com.google.videoeditor.service.MovieAudioTrack;
/**
* Audio track view
*/
public class AudioTrackView extends View {
// Instance variables
private final GestureDetector mSimpleGestureDetector;
private final Paint mLinePaint;
private final Paint mLoopPaint;
private final Rect mProgressDestRect;
private final ScrollViewListener mScrollListener;
private double[] mNormalizedGains;
private long mTimelineDurationMs;
private int mProgress;
private ItemSimpleGestureListener mGestureListener;
private WaveformData mWaveformData;
private int mScrollX;
private int mScreenWidth;
/*
* {@inheritDoc}
*/
public AudioTrackView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final Resources resources = getResources();
// Use this Paint for drawing the audio samples
mLinePaint = new Paint();
mLinePaint.setAntiAlias(false);
mLinePaint.setStrokeWidth(1);
mLinePaint.setColor(resources.getColor(R.color.audio_waveform));
// Use this Paint to draw the loop separator
mLoopPaint = new Paint();
mLoopPaint.setAntiAlias(false);
mLoopPaint.setStrokeWidth(1);
mLoopPaint.setColor(resources.getColor(R.color.audio_loop_separator));
// Prepare the bitmap rectangles
final ProgressBar progressBar = ProgressBar.getProgressBar(context);
final int layoutHeight = (int)resources.getDimension(R.dimen.audio_layout_height);
mProgressDestRect = new Rect(getPaddingLeft(),
layoutHeight - progressBar.getHeight() - getPaddingBottom(), 0,
layoutHeight - getPaddingBottom());
// Setup the gesture listener
mSimpleGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
/*
* {@inheritDoc}
*/
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (mGestureListener != null) {
return mGestureListener.onSingleTapConfirmed(AudioTrackView.this, -1,
e);
} else {
return false;
}
}
/*
* {@inheritDoc}
*/
@Override
public void onLongPress (MotionEvent e) {
if (mGestureListener != null) {
mGestureListener.onLongPress(AudioTrackView.this, e);
}
}
});
mScrollListener = new ScrollViewListener() {
/*
* {@inheritDoc}
*/
public void onScrollBegin(View view, int scrollX, int scrollY, boolean appScroll) {
}
/*
* {@inheritDoc}
*/
public void onScrollProgress(View view, int scrollX, int scrollY, boolean appScroll) {
}
/*
* {@inheritDoc}
*/
public void onScrollEnd(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
invalidate();
}
};
// Get the screen width
final Display display = ((WindowManager)context.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
final DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScreenWidth = metrics.widthPixels;
mProgress = -1;
}
/*
* {@inheritDoc}
*/
public AudioTrackView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/*
* {@inheritDoc}
*/
public AudioTrackView(Context context) {
this(context, null, 0);
}
/*
* {@inheritDoc}
*/
@Override
protected void onAttachedToWindow() {
final TimelineHorizontalScrollView scrollView =
(TimelineHorizontalScrollView)((View)((View)getParent()).getParent()).getParent();
mScrollX = scrollView.getScrollX();
scrollView.addScrollListener(mScrollListener);
}
/*
* {@inheritDoc}
*/
@Override
protected void onDetachedFromWindow() {
final TimelineHorizontalScrollView scrollView =
(TimelineHorizontalScrollView)((View)((View)getParent()).getParent()).getParent();
scrollView.removeScrollListener(mScrollListener);
}
/**
* @param listener The gesture listener
*/
public void setGestureListener(ItemSimpleGestureListener listener) {
mGestureListener = listener;
}
/**
* Set the waveform data
*
* @param waveformData The waveform data
*/
public void setWaveformData(WaveformData waveformData) {
mWaveformData = waveformData;
final int numFrames = mWaveformData.getFramesCount();
final short[] frameGains = mWaveformData.getFrameGains();
final double[] smoothedGains = new double[numFrames];
if (numFrames == 1) {
smoothedGains[0] = frameGains[0];
} else if (numFrames == 2) {
smoothedGains[0] = frameGains[0];
smoothedGains[1] = frameGains[1];
} else if (numFrames > 2) {
smoothedGains[0] = (frameGains[0] / 2.0) + (frameGains[1] / 2.0);
for (int i = 1; i < numFrames - 1; i++) {
smoothedGains[i] =
(frameGains[i - 1] / 3.0) + (frameGains[i] / 3.0) + (frameGains[i + 1] / 3.0);
}
smoothedGains[numFrames - 1] = (frameGains[numFrames - 2] / 2.0) +
(frameGains[numFrames - 1] / 2.0);
}
// Make sure the range is no more than 0 - 255
double maxGain = 1.0;
for (int i = 0; i < numFrames; i++) {
if (smoothedGains[i] > maxGain) {
maxGain = smoothedGains[i];
}
}
double scaleFactor = 1.0;
if (maxGain > 255.0) {
scaleFactor = 255 / maxGain;
}
// Build histogram of 256 bins and figure out the new scaled max
maxGain = 0;
final int gainHist[] = new int[256];
for (int i = 0; i < numFrames; i++) {
int smoothedGain = (int)(smoothedGains[i] * scaleFactor);
if (smoothedGain < 0) {
smoothedGain = 0;
}
if (smoothedGain > 255) {
smoothedGain = 255;
}
if (smoothedGain > maxGain) {
maxGain = smoothedGain;
}
gainHist[smoothedGain]++;
}
// Re-calibrate the minimum to be 5%
double minGain = 0;
int sum = 0;
while (minGain < 255 && sum < numFrames / 20) {
sum += gainHist[(int)minGain];
minGain++;
}
// Re-calibrate the max to be 99%
sum = 0;
while (maxGain > 2 && sum < numFrames / 100) {
sum += gainHist[(int)maxGain];
maxGain--;
}
// Compute the normalized heights
final int halfHeight =
(int)((getResources().getDimension(R.dimen.audio_layout_height) - getPaddingTop() -
- getPaddingBottom()) / 2);
+ getPaddingBottom() - 4) / 2);
final MovieAudioTrack audioTrack = (MovieAudioTrack)getTag();
final int numFramesComp = (int)audioTrack.getDuration() / mWaveformData.getFrameDuration();
mNormalizedGains = new double[Math.max(numFramesComp, numFrames)];
final double range = maxGain - minGain;
for (int i = 0; i < numFrames; i++) {
double value = (smoothedGains[i] * scaleFactor - minGain) / range;
if (value < 0.0) {
value = 0.0;
}
if (value > 1.0) {
value = 1.0;
}
mNormalizedGains[i] = value * value * halfHeight;
}
}
/**
* The project duration has changed
*
* @param timelineDurationMs The new timeline duration
*/
public void updateTimelineDuration(long timelineDurationMs) {
mTimelineDurationMs = timelineDurationMs;
}
/**
* The audio track processing progress
*
* @param progress The progress
*/
public void updateProgress(int progress) {
mProgress = progress;
invalidate();
}
/*
* {@inheritDoc}
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mWaveformData == null) {
if (mProgress >= 0) {
ProgressBar.getProgressBar(getContext()).draw(canvas, mProgress,
mProgressDestRect, getPaddingLeft(), getWidth() - getPaddingRight());
}
} else if (mTimelineDurationMs > 0) { // Draw waveform
// Compute the number of frames in the trimmed audio track
final MovieAudioTrack audioTrack = (MovieAudioTrack)getTag();
final int startFrame = (int)(audioTrack.getBoundaryBeginTime() /
mWaveformData.getFrameDuration());
final int numFrames =
(int)(audioTrack.getTimelineDuration() / mWaveformData.getFrameDuration());
final int ctr = getHeight() / 2;
short value;
int index;
final int start = Math.max(mScrollX - mScreenWidth / 2, getPaddingLeft());
final int limit = Math.min(mScrollX + mScreenWidth, getWidth() - getPaddingRight());
if (audioTrack.isAppLooping()) {
// Compute the milliseconds / pixel at the current zoom level
final float framesPerPixel = mTimelineDurationMs /
((float)(mWaveformData.getFrameDuration() *
(((View)getParent()).getWidth() - mScreenWidth)));
for (int i = start; i < limit; i++) {
index = startFrame + (int)(framesPerPixel * i);
index = index % numFrames;
value = (short)mNormalizedGains[index];
canvas.drawLine(i, ctr - value, i, ctr + 1 + value, mLinePaint);
if (index == startFrame) { // Draw the loop delineation
canvas.drawLine(i, getPaddingTop(), i,
getHeight() - getPaddingBottom(), mLinePaint);
}
}
} else {
// Compute the milliseconds / pixel at the current zoom level
final float framesPerPixel = audioTrack.getTimelineDuration() /
((float)(mWaveformData.getFrameDuration() * getWidth()));
for (int i = start; i < limit; i++) {
index = startFrame + (int)(framesPerPixel * i);
value = (short)(mNormalizedGains[index]);
canvas.drawLine(i, ctr - value, i, ctr + 1 + value, mLinePaint);
}
}
}
}
/*
* {@inheritDoc}
*/
@Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the gesture detector inspect all events.
mSimpleGestureDetector.onTouchEvent(ev);
super.onTouchEvent(ev);
return true;
}
}
| true | true | public void setWaveformData(WaveformData waveformData) {
mWaveformData = waveformData;
final int numFrames = mWaveformData.getFramesCount();
final short[] frameGains = mWaveformData.getFrameGains();
final double[] smoothedGains = new double[numFrames];
if (numFrames == 1) {
smoothedGains[0] = frameGains[0];
} else if (numFrames == 2) {
smoothedGains[0] = frameGains[0];
smoothedGains[1] = frameGains[1];
} else if (numFrames > 2) {
smoothedGains[0] = (frameGains[0] / 2.0) + (frameGains[1] / 2.0);
for (int i = 1; i < numFrames - 1; i++) {
smoothedGains[i] =
(frameGains[i - 1] / 3.0) + (frameGains[i] / 3.0) + (frameGains[i + 1] / 3.0);
}
smoothedGains[numFrames - 1] = (frameGains[numFrames - 2] / 2.0) +
(frameGains[numFrames - 1] / 2.0);
}
// Make sure the range is no more than 0 - 255
double maxGain = 1.0;
for (int i = 0; i < numFrames; i++) {
if (smoothedGains[i] > maxGain) {
maxGain = smoothedGains[i];
}
}
double scaleFactor = 1.0;
if (maxGain > 255.0) {
scaleFactor = 255 / maxGain;
}
// Build histogram of 256 bins and figure out the new scaled max
maxGain = 0;
final int gainHist[] = new int[256];
for (int i = 0; i < numFrames; i++) {
int smoothedGain = (int)(smoothedGains[i] * scaleFactor);
if (smoothedGain < 0) {
smoothedGain = 0;
}
if (smoothedGain > 255) {
smoothedGain = 255;
}
if (smoothedGain > maxGain) {
maxGain = smoothedGain;
}
gainHist[smoothedGain]++;
}
// Re-calibrate the minimum to be 5%
double minGain = 0;
int sum = 0;
while (minGain < 255 && sum < numFrames / 20) {
sum += gainHist[(int)minGain];
minGain++;
}
// Re-calibrate the max to be 99%
sum = 0;
while (maxGain > 2 && sum < numFrames / 100) {
sum += gainHist[(int)maxGain];
maxGain--;
}
// Compute the normalized heights
final int halfHeight =
(int)((getResources().getDimension(R.dimen.audio_layout_height) - getPaddingTop() -
getPaddingBottom()) / 2);
final MovieAudioTrack audioTrack = (MovieAudioTrack)getTag();
final int numFramesComp = (int)audioTrack.getDuration() / mWaveformData.getFrameDuration();
mNormalizedGains = new double[Math.max(numFramesComp, numFrames)];
final double range = maxGain - minGain;
for (int i = 0; i < numFrames; i++) {
double value = (smoothedGains[i] * scaleFactor - minGain) / range;
if (value < 0.0) {
value = 0.0;
}
if (value > 1.0) {
value = 1.0;
}
mNormalizedGains[i] = value * value * halfHeight;
}
}
| public void setWaveformData(WaveformData waveformData) {
mWaveformData = waveformData;
final int numFrames = mWaveformData.getFramesCount();
final short[] frameGains = mWaveformData.getFrameGains();
final double[] smoothedGains = new double[numFrames];
if (numFrames == 1) {
smoothedGains[0] = frameGains[0];
} else if (numFrames == 2) {
smoothedGains[0] = frameGains[0];
smoothedGains[1] = frameGains[1];
} else if (numFrames > 2) {
smoothedGains[0] = (frameGains[0] / 2.0) + (frameGains[1] / 2.0);
for (int i = 1; i < numFrames - 1; i++) {
smoothedGains[i] =
(frameGains[i - 1] / 3.0) + (frameGains[i] / 3.0) + (frameGains[i + 1] / 3.0);
}
smoothedGains[numFrames - 1] = (frameGains[numFrames - 2] / 2.0) +
(frameGains[numFrames - 1] / 2.0);
}
// Make sure the range is no more than 0 - 255
double maxGain = 1.0;
for (int i = 0; i < numFrames; i++) {
if (smoothedGains[i] > maxGain) {
maxGain = smoothedGains[i];
}
}
double scaleFactor = 1.0;
if (maxGain > 255.0) {
scaleFactor = 255 / maxGain;
}
// Build histogram of 256 bins and figure out the new scaled max
maxGain = 0;
final int gainHist[] = new int[256];
for (int i = 0; i < numFrames; i++) {
int smoothedGain = (int)(smoothedGains[i] * scaleFactor);
if (smoothedGain < 0) {
smoothedGain = 0;
}
if (smoothedGain > 255) {
smoothedGain = 255;
}
if (smoothedGain > maxGain) {
maxGain = smoothedGain;
}
gainHist[smoothedGain]++;
}
// Re-calibrate the minimum to be 5%
double minGain = 0;
int sum = 0;
while (minGain < 255 && sum < numFrames / 20) {
sum += gainHist[(int)minGain];
minGain++;
}
// Re-calibrate the max to be 99%
sum = 0;
while (maxGain > 2 && sum < numFrames / 100) {
sum += gainHist[(int)maxGain];
maxGain--;
}
// Compute the normalized heights
final int halfHeight =
(int)((getResources().getDimension(R.dimen.audio_layout_height) - getPaddingTop() -
getPaddingBottom() - 4) / 2);
final MovieAudioTrack audioTrack = (MovieAudioTrack)getTag();
final int numFramesComp = (int)audioTrack.getDuration() / mWaveformData.getFrameDuration();
mNormalizedGains = new double[Math.max(numFramesComp, numFrames)];
final double range = maxGain - minGain;
for (int i = 0; i < numFrames; i++) {
double value = (smoothedGains[i] * scaleFactor - minGain) / range;
if (value < 0.0) {
value = 0.0;
}
if (value > 1.0) {
value = 1.0;
}
mNormalizedGains[i] = value * value * halfHeight;
}
}
|
diff --git a/component/dashboard/src/main/java/org/exoplatform/dashboard/webui/component/UIAddGadgetForm.java b/component/dashboard/src/main/java/org/exoplatform/dashboard/webui/component/UIAddGadgetForm.java
index f2242f060..0fccd9ed4 100644
--- a/component/dashboard/src/main/java/org/exoplatform/dashboard/webui/component/UIAddGadgetForm.java
+++ b/component/dashboard/src/main/java/org/exoplatform/dashboard/webui/component/UIAddGadgetForm.java
@@ -1,125 +1,130 @@
/*
* Copyright (C) 2003-2008 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see<http://www.gnu.org/licenses/>.
*/
package org.exoplatform.dashboard.webui.component;
import java.net.URL;
import org.exoplatform.application.gadget.Gadget;
import org.exoplatform.application.gadget.GadgetRegistryService;
import org.exoplatform.application.registry.Application;
import org.exoplatform.application.registry.ApplicationCategory;
import org.exoplatform.application.registry.ApplicationRegistryService;
import org.exoplatform.portal.config.model.PortalConfig;
import org.exoplatform.portal.webui.application.GadgetUtil;
import org.exoplatform.portal.webui.application.UIGadget;
import org.exoplatform.portal.webui.workspace.UIPortalApplication;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.portal.application.UserGadgetStorage;
import org.exoplatform.web.application.ApplicationMessage;
import org.exoplatform.web.application.gadget.GadgetApplication;
import org.exoplatform.webui.application.WebuiRequestContext;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.UIApplication;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.form.UIForm;
import org.exoplatform.webui.form.UIFormStringInput;
/**
* Created by The eXo Platform SAS
* Oct 15, 2008
*/
@ComponentConfig (
lifecycle = UIFormLifecycle.class,
template = "classpath:groovy/dashboard/webui/component/UIAddGadgetForm.gtmpl",
events = @EventConfig (listeners = UIAddGadgetForm.AddGadgetByUrlActionListener.class)
)
public class UIAddGadgetForm extends UIForm {
public static String FIELD_URL = "url" ;
public UIAddGadgetForm() throws Exception {
addUIFormInput(new UIFormStringInput(FIELD_URL, FIELD_URL, null)) ;
}
static public class AddGadgetByUrlActionListener extends EventListener<UIAddGadgetForm> {
public void execute(final Event<UIAddGadgetForm> event) throws Exception {
WebuiRequestContext context = event.getRequestContext() ;
UIAddGadgetForm uiForm = event.getSource() ;
UIDashboard uiDashboard = uiForm.getAncestorOfType(UIDashboard.class) ;
UIDashboardContainer uiContainer = uiDashboard.getChild(UIDashboardContainer.class) ;
GadgetRegistryService service = uiForm.getApplicationComponent(GadgetRegistryService.class) ;
String url = uiForm.getUIStringInput(FIELD_URL).getValue();
+ UIApplication uiApplication = context.getUIApplication() ;
+ if(url == null || url.trim().length() == 0) {
+ uiApplication.addMessage(new ApplicationMessage("UIDashboard.msg.required", null)) ;
+ context.addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ;
+ return ;
+ }
try {
new URL(url) ;
} catch (Exception e) {
- UIApplication uiApplication = context.getUIApplication() ;
- uiApplication.addMessage(new ApplicationMessage("UIDashboard.message.notUrl", null)) ;
+ uiApplication.addMessage(new ApplicationMessage("UIDashboard.msg.notUrl", null)) ;
context.addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ;
return ;
}
Gadget gadget;
UIGadget uiGadget;
//TODO check the way we create the unique ID, is it really unique?
try {
String name = "gadget" + url.hashCode();
gadget = GadgetUtil.toGadget(name, url, false) ;
service.saveGadget(gadget);
StringBuilder windowId = new StringBuilder(PortalConfig.USER_TYPE);
windowId.append("#").append(context.getRemoteUser());
windowId.append(":/dashboard/").append(gadget.getName()).append('/');
uiGadget = uiForm.createUIComponent(context, UIGadget.class, null, null);
//TODO why do we do +1
uiGadget.setId(Integer.toString(uiGadget.hashCode()+1));
windowId.append(uiGadget.hashCode());
uiGadget.setApplicationInstanceId(windowId.toString());
} catch (Exception e) {
//rssAggregator
gadget = service.getGadget("rssAggregator");
//TODO make sure it's an rss feed
StringBuilder windowId = new StringBuilder(PortalConfig.USER_TYPE);
windowId.append("#").append(context.getRemoteUser());
windowId.append(":/dashboard/").append(gadget.getName()).append('/');
uiGadget = uiForm.createUIComponent(context, UIGadget.class, null, null);
uiGadget.setId(Integer.toString(url.hashCode()+1));
windowId.append(url.hashCode());
uiGadget.setApplicationInstanceId(windowId.toString());
String params = "{'rssurl':'" + url + "'}";
UserGadgetStorage userGadgetStorage = uiForm.getApplicationComponent(UserGadgetStorage.class);
userGadgetStorage.save(Util.getPortalRequestContext().getRemoteUser(), gadget.getName(), "" + url.hashCode(), UIGadget.PREF_KEY, params);
}
uiContainer.addUIGadget(uiGadget, 0, 0) ;
uiContainer.save() ;
uiForm.reset() ;
context.addUIComponentToUpdateByAjax(uiForm) ;
context.addUIComponentToUpdateByAjax(uiContainer) ;
}
}
}
| false | true | public void execute(final Event<UIAddGadgetForm> event) throws Exception {
WebuiRequestContext context = event.getRequestContext() ;
UIAddGadgetForm uiForm = event.getSource() ;
UIDashboard uiDashboard = uiForm.getAncestorOfType(UIDashboard.class) ;
UIDashboardContainer uiContainer = uiDashboard.getChild(UIDashboardContainer.class) ;
GadgetRegistryService service = uiForm.getApplicationComponent(GadgetRegistryService.class) ;
String url = uiForm.getUIStringInput(FIELD_URL).getValue();
try {
new URL(url) ;
} catch (Exception e) {
UIApplication uiApplication = context.getUIApplication() ;
uiApplication.addMessage(new ApplicationMessage("UIDashboard.message.notUrl", null)) ;
context.addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ;
return ;
}
Gadget gadget;
UIGadget uiGadget;
//TODO check the way we create the unique ID, is it really unique?
try {
String name = "gadget" + url.hashCode();
gadget = GadgetUtil.toGadget(name, url, false) ;
service.saveGadget(gadget);
StringBuilder windowId = new StringBuilder(PortalConfig.USER_TYPE);
windowId.append("#").append(context.getRemoteUser());
windowId.append(":/dashboard/").append(gadget.getName()).append('/');
uiGadget = uiForm.createUIComponent(context, UIGadget.class, null, null);
//TODO why do we do +1
uiGadget.setId(Integer.toString(uiGadget.hashCode()+1));
windowId.append(uiGadget.hashCode());
uiGadget.setApplicationInstanceId(windowId.toString());
} catch (Exception e) {
//rssAggregator
gadget = service.getGadget("rssAggregator");
//TODO make sure it's an rss feed
StringBuilder windowId = new StringBuilder(PortalConfig.USER_TYPE);
windowId.append("#").append(context.getRemoteUser());
windowId.append(":/dashboard/").append(gadget.getName()).append('/');
uiGadget = uiForm.createUIComponent(context, UIGadget.class, null, null);
uiGadget.setId(Integer.toString(url.hashCode()+1));
windowId.append(url.hashCode());
uiGadget.setApplicationInstanceId(windowId.toString());
String params = "{'rssurl':'" + url + "'}";
UserGadgetStorage userGadgetStorage = uiForm.getApplicationComponent(UserGadgetStorage.class);
userGadgetStorage.save(Util.getPortalRequestContext().getRemoteUser(), gadget.getName(), "" + url.hashCode(), UIGadget.PREF_KEY, params);
}
uiContainer.addUIGadget(uiGadget, 0, 0) ;
uiContainer.save() ;
uiForm.reset() ;
context.addUIComponentToUpdateByAjax(uiForm) ;
context.addUIComponentToUpdateByAjax(uiContainer) ;
}
| public void execute(final Event<UIAddGadgetForm> event) throws Exception {
WebuiRequestContext context = event.getRequestContext() ;
UIAddGadgetForm uiForm = event.getSource() ;
UIDashboard uiDashboard = uiForm.getAncestorOfType(UIDashboard.class) ;
UIDashboardContainer uiContainer = uiDashboard.getChild(UIDashboardContainer.class) ;
GadgetRegistryService service = uiForm.getApplicationComponent(GadgetRegistryService.class) ;
String url = uiForm.getUIStringInput(FIELD_URL).getValue();
UIApplication uiApplication = context.getUIApplication() ;
if(url == null || url.trim().length() == 0) {
uiApplication.addMessage(new ApplicationMessage("UIDashboard.msg.required", null)) ;
context.addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ;
return ;
}
try {
new URL(url) ;
} catch (Exception e) {
uiApplication.addMessage(new ApplicationMessage("UIDashboard.msg.notUrl", null)) ;
context.addUIComponentToUpdateByAjax(uiApplication.getUIPopupMessages()) ;
return ;
}
Gadget gadget;
UIGadget uiGadget;
//TODO check the way we create the unique ID, is it really unique?
try {
String name = "gadget" + url.hashCode();
gadget = GadgetUtil.toGadget(name, url, false) ;
service.saveGadget(gadget);
StringBuilder windowId = new StringBuilder(PortalConfig.USER_TYPE);
windowId.append("#").append(context.getRemoteUser());
windowId.append(":/dashboard/").append(gadget.getName()).append('/');
uiGadget = uiForm.createUIComponent(context, UIGadget.class, null, null);
//TODO why do we do +1
uiGadget.setId(Integer.toString(uiGadget.hashCode()+1));
windowId.append(uiGadget.hashCode());
uiGadget.setApplicationInstanceId(windowId.toString());
} catch (Exception e) {
//rssAggregator
gadget = service.getGadget("rssAggregator");
//TODO make sure it's an rss feed
StringBuilder windowId = new StringBuilder(PortalConfig.USER_TYPE);
windowId.append("#").append(context.getRemoteUser());
windowId.append(":/dashboard/").append(gadget.getName()).append('/');
uiGadget = uiForm.createUIComponent(context, UIGadget.class, null, null);
uiGadget.setId(Integer.toString(url.hashCode()+1));
windowId.append(url.hashCode());
uiGadget.setApplicationInstanceId(windowId.toString());
String params = "{'rssurl':'" + url + "'}";
UserGadgetStorage userGadgetStorage = uiForm.getApplicationComponent(UserGadgetStorage.class);
userGadgetStorage.save(Util.getPortalRequestContext().getRemoteUser(), gadget.getName(), "" + url.hashCode(), UIGadget.PREF_KEY, params);
}
uiContainer.addUIGadget(uiGadget, 0, 0) ;
uiContainer.save() ;
uiForm.reset() ;
context.addUIComponentToUpdateByAjax(uiForm) ;
context.addUIComponentToUpdateByAjax(uiContainer) ;
}
|
diff --git a/src/de/uni_koblenz/jgralab/graphmarker/DoubleArrayGraphMarker.java b/src/de/uni_koblenz/jgralab/graphmarker/DoubleArrayGraphMarker.java
index fa264bf17..b4628d8e2 100644
--- a/src/de/uni_koblenz/jgralab/graphmarker/DoubleArrayGraphMarker.java
+++ b/src/de/uni_koblenz/jgralab/graphmarker/DoubleArrayGraphMarker.java
@@ -1,131 +1,131 @@
package de.uni_koblenz.jgralab.graphmarker;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.GraphElement;
import de.uni_koblenz.jgralab.Vertex;
public abstract class DoubleArrayGraphMarker<T extends GraphElement> extends
AbstractGraphMarker<T> {
private static final double DEFAULT_UNMARKED_VALUE = Double.NaN;
protected double[] temporaryAttributes;
protected int marked;
protected double unmarkedValue;
protected DoubleArrayGraphMarker(Graph graph, int size) {
super(graph);
unmarkedValue = DEFAULT_UNMARKED_VALUE;
temporaryAttributes = createNewArray(size);
}
private double[] createNewArray(int size) {
double[] newArray = new double[size];
for (int i = 0; i < size; i++) {
newArray[i] = unmarkedValue;
}
return newArray;
}
@Override
public void clear() {
for (int i = 0; i < temporaryAttributes.length; i++) {
temporaryAttributes[i] = unmarkedValue;
}
marked = 0;
}
@Override
public boolean isEmpty() {
return marked == 0;
}
@Override
public boolean isMarked(T graphElement) {
assert (graphElement.getGraph() == graph);
assert (graphElement.getId() <= (graphElement instanceof Vertex ? graph
.getMaxVCount() : graph.getMaxECount()));
return temporaryAttributes[graphElement.getId()] != unmarkedValue;
}
/**
* marks the given element with the given value
*
* @param elem
* the graph element to mark
* @param value
* the object that should be used as marking
* @return The previous element the given graph element has been marked
* with, <code>null</code> if the given element has not been marked.
*/
public double mark(T graphElement, double value) {
assert (graphElement.getGraph() == graph);
assert (graphElement.getId() <= (graphElement instanceof Vertex ? graph
.getMaxVCount() : graph.getMaxECount()));
double out = temporaryAttributes[graphElement.getId()];
temporaryAttributes[graphElement.getId()] = value;
marked += 1;
return out;
}
public double getMark(T graphElement) {
assert (graphElement.getGraph() == graph);
assert (graphElement.getId() <= (graphElement instanceof Vertex ? graph
.getMaxVCount() : graph.getMaxECount()));
double out = temporaryAttributes[graphElement.getId()];
return out;
}
@Override
public boolean removeMark(T graphElement) {
assert (graphElement.getGraph() == graph);
assert (graphElement.getId() <= (graphElement instanceof Vertex ? graph
.getMaxVCount() : graph.getMaxECount()));
if (temporaryAttributes[graphElement.getId()] == unmarkedValue) {
return false;
}
temporaryAttributes[graphElement.getId()] = unmarkedValue;
marked -= 1;
return true;
}
@Override
public int size() {
return marked;
}
public int maxSize() {
return temporaryAttributes.length - 1;
}
protected void expand(int newSize) {
assert (newSize > temporaryAttributes.length);
double[] newTemporaryAttributes = createNewArray(newSize);
System.arraycopy(temporaryAttributes, 0, newTemporaryAttributes, 0,
temporaryAttributes.length);
// for (int i = 0; i < temporaryAttributes.length; i++) {
// newTemporaryAttributes[i] = temporaryAttributes[i];
// }
temporaryAttributes = newTemporaryAttributes;
}
public double getUnmarkedValue() {
return unmarkedValue;
}
public void setUnmarkedValue(double newUnmarkedValue) {
for (int i = 0; i < temporaryAttributes.length; i++) {
// keep track of implicitly unmarked values
if (temporaryAttributes[i] == newUnmarkedValue) {
marked -= 1;
}
// set all unmarked elements to new value
- if (temporaryAttributes[i] == this.unmarkedValue) {
+ if (Double.compare(temporaryAttributes[i], this.unmarkedValue) == 0) {
temporaryAttributes[i] = newUnmarkedValue;
}
}
this.unmarkedValue = newUnmarkedValue;
}
}
| true | true | public void setUnmarkedValue(double newUnmarkedValue) {
for (int i = 0; i < temporaryAttributes.length; i++) {
// keep track of implicitly unmarked values
if (temporaryAttributes[i] == newUnmarkedValue) {
marked -= 1;
}
// set all unmarked elements to new value
if (temporaryAttributes[i] == this.unmarkedValue) {
temporaryAttributes[i] = newUnmarkedValue;
}
}
this.unmarkedValue = newUnmarkedValue;
}
| public void setUnmarkedValue(double newUnmarkedValue) {
for (int i = 0; i < temporaryAttributes.length; i++) {
// keep track of implicitly unmarked values
if (temporaryAttributes[i] == newUnmarkedValue) {
marked -= 1;
}
// set all unmarked elements to new value
if (Double.compare(temporaryAttributes[i], this.unmarkedValue) == 0) {
temporaryAttributes[i] = newUnmarkedValue;
}
}
this.unmarkedValue = newUnmarkedValue;
}
|
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GitProjectImporter.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GitProjectImporter.java
index 33661ab46..4a33999da 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GitProjectImporter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GitProjectImporter.java
@@ -1,114 +1,121 @@
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
import com.google.gerrit.reviewdb.Project;
import com.google.gerrit.reviewdb.ReviewDb;
import com.google.gerrit.reviewdb.Project.SubmitType;
import com.google.gwtorm.client.OrmException;
import com.google.gwtorm.client.SchemaFactory;
import com.google.inject.Inject;
import org.eclipse.jgit.lib.RepositoryCache.FileKey;
import org.eclipse.jgit.util.FS;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/** Imports all projects found within the repository manager. */
public class GitProjectImporter {
public interface Messages {
void info(String msg);
void warning(String msg);
}
private final LocalDiskRepositoryManager repositoryManager;
private final SchemaFactory<ReviewDb> schema;
private Messages messages;
@Inject
GitProjectImporter(final LocalDiskRepositoryManager repositoryManager,
final SchemaFactory<ReviewDb> schema) {
this.repositoryManager = repositoryManager;
this.schema = schema;
}
public void run(final Messages msg) throws OrmException, IOException {
messages = msg;
messages.info("Scanning " + repositoryManager.getBasePath());
final ReviewDb db = schema.open();
try {
final HashSet<String> have = new HashSet<String>();
for (Project p : db.projects().all()) {
have.add(p.getName());
}
importProjects(repositoryManager.getBasePath(), "", db, have);
} finally {
db.close();
}
}
private void importProjects(final File dir, final String prefix,
final ReviewDb db, final Set<String> have) throws OrmException,
IOException {
final File[] ls = dir.listFiles();
if (ls == null) {
return;
}
for (File f : ls) {
String name = f.getName();
if (".".equals(name) || "..".equals(name)) {
continue;
}
if (FileKey.isGitRepository(f, FS.DETECTED)) {
if (name.equals(".git")) {
+ if ("".equals(prefix)) {
+ // If the git base path is itself a git repository working
+ // directory, this is a bit nonsensical for Gerrit Code Review.
+ // Skip the path and do the next one.
+ messages.warning("Skipping " + f.getAbsolutePath());
+ continue;
+ }
name = prefix.substring(0, prefix.length() - 1);
} else if (name.endsWith(".git")) {
name = prefix + name.substring(0, name.length() - 4);
} else {
name = prefix + name;
if (!have.contains(name)) {
messages.warning("Importing non-standard name '" + name + "'");
}
}
if (have.contains(name)) {
continue;
}
final Project.NameKey nameKey = new Project.NameKey(name);
final Project p = new Project(nameKey);
p.setDescription(repositoryManager.getProjectDescription(name));
p.setSubmitType(SubmitType.MERGE_IF_NECESSARY);
p.setUseContributorAgreements(false);
p.setUseSignedOffBy(false);
p.setUseContentMerge(false);
p.setRequireChangeID(false);
db.projects().insert(Collections.singleton(p));
} else if (f.isDirectory()) {
importProjects(f, prefix + f.getName() + "/", db, have);
}
}
}
}
| true | true | private void importProjects(final File dir, final String prefix,
final ReviewDb db, final Set<String> have) throws OrmException,
IOException {
final File[] ls = dir.listFiles();
if (ls == null) {
return;
}
for (File f : ls) {
String name = f.getName();
if (".".equals(name) || "..".equals(name)) {
continue;
}
if (FileKey.isGitRepository(f, FS.DETECTED)) {
if (name.equals(".git")) {
name = prefix.substring(0, prefix.length() - 1);
} else if (name.endsWith(".git")) {
name = prefix + name.substring(0, name.length() - 4);
} else {
name = prefix + name;
if (!have.contains(name)) {
messages.warning("Importing non-standard name '" + name + "'");
}
}
if (have.contains(name)) {
continue;
}
final Project.NameKey nameKey = new Project.NameKey(name);
final Project p = new Project(nameKey);
p.setDescription(repositoryManager.getProjectDescription(name));
p.setSubmitType(SubmitType.MERGE_IF_NECESSARY);
p.setUseContributorAgreements(false);
p.setUseSignedOffBy(false);
p.setUseContentMerge(false);
p.setRequireChangeID(false);
db.projects().insert(Collections.singleton(p));
} else if (f.isDirectory()) {
importProjects(f, prefix + f.getName() + "/", db, have);
}
}
}
| private void importProjects(final File dir, final String prefix,
final ReviewDb db, final Set<String> have) throws OrmException,
IOException {
final File[] ls = dir.listFiles();
if (ls == null) {
return;
}
for (File f : ls) {
String name = f.getName();
if (".".equals(name) || "..".equals(name)) {
continue;
}
if (FileKey.isGitRepository(f, FS.DETECTED)) {
if (name.equals(".git")) {
if ("".equals(prefix)) {
// If the git base path is itself a git repository working
// directory, this is a bit nonsensical for Gerrit Code Review.
// Skip the path and do the next one.
messages.warning("Skipping " + f.getAbsolutePath());
continue;
}
name = prefix.substring(0, prefix.length() - 1);
} else if (name.endsWith(".git")) {
name = prefix + name.substring(0, name.length() - 4);
} else {
name = prefix + name;
if (!have.contains(name)) {
messages.warning("Importing non-standard name '" + name + "'");
}
}
if (have.contains(name)) {
continue;
}
final Project.NameKey nameKey = new Project.NameKey(name);
final Project p = new Project(nameKey);
p.setDescription(repositoryManager.getProjectDescription(name));
p.setSubmitType(SubmitType.MERGE_IF_NECESSARY);
p.setUseContributorAgreements(false);
p.setUseSignedOffBy(false);
p.setUseContentMerge(false);
p.setRequireChangeID(false);
db.projects().insert(Collections.singleton(p));
} else if (f.isDirectory()) {
importProjects(f, prefix + f.getName() + "/", db, have);
}
}
}
|
diff --git a/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/ExperimentEligibilityCheckingProcess.java b/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/ExperimentEligibilityCheckingProcess.java
index bb66fc0..c98c6c2 100644
--- a/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/ExperimentEligibilityCheckingProcess.java
+++ b/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/ExperimentEligibilityCheckingProcess.java
@@ -1,979 +1,983 @@
package uk.ac.ebi.fgpt.conan.process.atlas;
import net.sourceforge.fluxion.spi.ServiceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.MAGETABInvestigation;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.graph.Node;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.*;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.ArrayDesignAttribute;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.CharacteristicsAttribute;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.FactorValueAttribute;
import uk.ac.ebi.arrayexpress2.magetab.exception.ParseException;
import uk.ac.ebi.arrayexpress2.magetab.parser.MAGETABParser;
import uk.ac.ebi.fgpt.conan.ae.AccessionParameter;
import uk.ac.ebi.fgpt.conan.dao.DatabaseConanControlledVocabularyDAO;
import uk.ac.ebi.fgpt.conan.model.ConanParameter;
import uk.ac.ebi.fgpt.conan.model.ConanProcess;
import uk.ac.ebi.fgpt.conan.service.exception.ProcessExecutionException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Process to check experiment eligibility for Atlas. Consists of six steps: 1
* check for experiment type, 2 check for two-channel experiment, 3 check for
* factor values, 4 check for factor types from controlled vocabulary only, 5
* check for array design existence in Atlas, 6 check for raw data files for
* Affy and derived data files for all other platforms.
*
* @author Natalja Kurbatova
* @date 15/02/11
*/
@ServiceProvider
public class ExperimentEligibilityCheckingProcess implements ConanProcess {
private final Collection<ConanParameter> parameters;
private final AccessionParameter accessionParameter;
private final List<String> ArrayDesignAccessions = new ArrayList<String>();
private final DatabaseConanControlledVocabularyDAO controlledVocabularyDAO;
private Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
/**
* Constructor for process. Initializes conan2 parameters for the process.
*/
public ExperimentEligibilityCheckingProcess() {
parameters = new ArrayList<ConanParameter>();
accessionParameter = new AccessionParameter();
parameters.add(accessionParameter);
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("controlled-vocabulary-context.xml");
controlledVocabularyDAO =
ctx.getBean("databaseConanControlledVocabularyDAO",
DatabaseConanControlledVocabularyDAO.class);
}
public boolean execute(Map<ConanParameter, String> parameters)
throws ProcessExecutionException, IllegalArgumentException,
InterruptedException {
int exitValue = 0;
// Add to the desired logger
BufferedWriter log;
String error_val = "";
//deal with parameters
final AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
String reportsDir =
accession.getFile().getParentFile().getAbsolutePath() + File.separator +
"reports";
File reportsDirFile = new File(reportsDir);
if (!reportsDirFile.exists()) {
reportsDirFile.mkdirs();
}
String fileName = reportsDir + File.separator + accession.getAccession() +
"_AtlasEligibilityCheck" +
"_" + new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()) +
".report";
try {
log = new BufferedWriter(new FileWriter(fileName));
log.write("Atlas Eligibility Check: START\n");
}
catch (IOException e) {
exitValue = 1;
e.printStackTrace();
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
"Can't create report file '" +
fileName +
"'");
String[] errors = new String[1];
errors[0] = "Can't create report file '" + fileName + "'";
pex.setProcessOutput(errors);
throw pex;
}
// make a new parser
MAGETABParser parser = new MAGETABParser();
try {
MAGETABInvestigation investigation =
parser.parse(accession.getFile().getAbsoluteFile());
// 1 check: experiment types
boolean isAtlasType = false;
String restrictedExptType = "";
if (investigation.IDF.getComments().containsKey("AEExperimentType")) {
for (String exptType : investigation.IDF.getComments()
.get("AEExperimentType")) {
for (String AtlasType : controlledVocabularyDAO
.getAtlasExperimentTypes()) {
if (exptType.equals(AtlasType)) {
isAtlasType = true;
}
else {
restrictedExptType = exptType;
}
}
}
}
else {
for (String exptType : investigation.IDF.experimentalDesign) {
for (String AtlasType : controlledVocabularyDAO
.getAtlasExperimentTypes()) {
if (exptType.equals(AtlasType)) {
isAtlasType = true;
}
}
}
}
if (!isAtlasType)
//not in Atlas Experiment Types
{
exitValue = 1;
log.write(
"'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas\n");
getLog().debug(
"'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas");
error_val = "'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas.\n";
}
//2 two-channel experiment
if (investigation.SDRF.getNumberOfChannels() > 1) {
exitValue = 1;
log.write(
"Two-channel experiment is not accepted by Atlas\n");
getLog().debug(
"Two-channel experiment is not accepted by Atlas");
error_val = error_val + "Two-channel experiment is not accepted by Atlas. \n";
}
Collection<HybridizationNode> hybridizationNodes =
investigation.SDRF.getNodes(HybridizationNode.class);
Collection<ArrayDataNode> rawDataNodes =
investigation.SDRF.getNodes(ArrayDataNode.class);
Collection<DerivedArrayDataNode> processedDataNodes =
investigation.SDRF.getNodes(DerivedArrayDataNode.class);
Collection<DerivedArrayDataMatrixNode> processedDataMatrixNodes =
investigation.SDRF.getNodes(DerivedArrayDataMatrixNode.class);
int factorValues = 0;
for (HybridizationNode hybNode : hybridizationNodes) {
if (hybNode.factorValues.size() > 0) {
factorValues++;
}
ArrayDesignAccessions.clear();
for (ArrayDesignAttribute arrayDesign : hybNode.arrayDesigns) {
if (!ArrayDesignAccessions
.contains(arrayDesign.getAttributeValue())) {
ArrayDesignAccessions.add(arrayDesign.getAttributeValue());
}
}
}
boolean replicates = true;
// All experiments must have replicates for at least 1 factor
Hashtable<String,Hashtable> factorTypesCounts = new Hashtable<String, Hashtable>();
for (String factorType : investigation.IDF.experimentalFactorType) {
Hashtable<String,Integer> factorValuesCounts = new Hashtable<String, Integer>();
for (HybridizationNode hybNode : hybridizationNodes) {
String arrayDesignName = "";
for (ArrayDesignAttribute arrayDesign : hybNode.arrayDesigns) {
arrayDesignName=arrayDesign.getAttributeValue() ;
}
for (FactorValueAttribute fva : hybNode.factorValues) {
if (fva.getAttributeType().toLowerCase().contains(factorType.toLowerCase())) {
String key = arrayDesignName+"_"+fva.getAttributeValue();
if (factorValuesCounts.get(key)==null){
factorValuesCounts.put(key,1);
}
else {
int value = factorValuesCounts.get(key);
value++;
factorValuesCounts.put(key,value);
}
}
}
}
factorTypesCounts.put(factorType,factorValuesCounts);
}
for (Hashtable<String,Integer> fvc : factorTypesCounts.values() ) {
for (int val : fvc.values()){
if (val == 1){
replicates = false;
}
}
}
// replicates
if (replicates == false) {
exitValue = 1;
log.write(
"Experiment does not have replicates for at least 1 factor type\n");
getLog().debug(
"Experiment does not have replicates for at least 1 factor type");
error_val = error_val + "Experiment does not have replicates for at least 1 factor type. \n";
}
//3 factor values
if (factorValues == 0) {
exitValue = 1;
log.write(
"Experiment does not have Factor Values\n");
getLog().debug(
"Experiment does not have Factor Values");
error_val = error_val + "Experiment does not have Factor Values. \n";
}
//6 and 7 factor types are from controlled vocabulary and not repeated
boolean factorTypesFromCV = true;
boolean factorTypesVariable = true;
boolean characteristicsFromCV = true;
boolean characteristicsVariable = true;
List<String> missedFactorTypes = new ArrayList<String>();
List<String> missedCharacteristics = new ArrayList<String>();
List<String> repeatedFactorTypes = new ArrayList<String>();
List<String> repeatedCharacteristics = new ArrayList<String>();
for (String factorType : investigation.IDF.experimentalFactorType) {
if (!controlledVocabularyDAO
.getAtlasFactorTypes().contains(factorType.toLowerCase())) {
factorTypesFromCV = false;
missedFactorTypes.add(factorType);
}
if (repeatedFactorTypes.contains(factorType)) {
factorTypesVariable = false;
}
repeatedFactorTypes.add(factorType);
}
for (SampleNode sampleNode : investigation.SDRF.getNodes(SampleNode.class)) {
for (CharacteristicsAttribute ca : sampleNode.characteristics) {
if (repeatedCharacteristics.contains(ca.type)) {
characteristicsVariable = false;
}
repeatedCharacteristics.add(ca.type);
if (!controlledVocabularyDAO
.getAtlasFactorTypes().contains(ca.type.toLowerCase())) {
characteristicsFromCV = false;
- missedCharacteristics.add(ca.type);
+ if (!missedCharacteristics.contains(ca.type)){
+ missedCharacteristics.add(ca.type);
+ }
}
}
}
for (SourceNode sourceNode : investigation.SDRF.getNodes(SourceNode.class)) {
for (CharacteristicsAttribute ca : sourceNode.characteristics) {
if (repeatedCharacteristics.contains(ca.type)) {
characteristicsVariable = false;
}
repeatedCharacteristics.add(ca.type);
if (!controlledVocabularyDAO
.getAtlasFactorTypes().contains(ca.type.toLowerCase())) {
characteristicsFromCV = false;
- missedCharacteristics.add(ca.type);
+ if (!missedCharacteristics.contains(ca.type)){
+ missedCharacteristics.add(ca.type);
+ }
}
}
}
if (!factorTypesFromCV) {
exitValue = 1;
log.write(
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes + "\n");
getLog().debug(
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes);
error_val = error_val +
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes + ".\n";
}
if (!characteristicsFromCV) {
exitValue = 1;
log.write(
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics + "\n");
getLog().debug(
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics);
error_val = error_val +
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics + ".\n";
}
if (!factorTypesVariable) {
exitValue = 1;
log.write("Experiment has repeated Factor Types.\n");
getLog().debug("Experiment has repeated Factor Types.");
error_val = error_val + "Experiment has repeated Factor Types.\n";
}
if (!characteristicsVariable) {
exitValue = 1;
log.write("Experiment has repeated Characteristics.\n");
getLog().debug("Experiment has repeated Characteristics.");
error_val = error_val + "Experiment has repeated Characteristics.\n";
}
// 5 check: array design is in Atlas
for (String arrayDesign : ArrayDesignAccessions) {
ArrayDesignExistenceChecking arrayDesignExistenceChecking =
new ArrayDesignExistenceChecking();
String arrayCheckResult =
arrayDesignExistenceChecking.execute(arrayDesign);
if (arrayCheckResult.equals("empty") ||
arrayCheckResult.equals("no")) {
exitValue = 1;
log.write("Array design '" +
arrayDesign +
"' used in experiment is not in Atlas\n");
getLog().debug("Array design '" +
arrayDesign +
"' used in experiment is not in Atlas");
error_val = error_val + "Array design '" +
arrayDesign +
"' used in experiment is not in Atlas. \n";
}
else {
//Array Design is in Atlas
Collection<HybridizationNode> hybridizationSubNodes =
new ArrayList<HybridizationNode>();
Collection<Node> rawDataSubNodes = new ArrayList<Node>();
Collection<Node> processedDataSubNodes = new ArrayList<Node>();
Collection<Node> processedDataMatrixSubNodes =
new ArrayList<Node>();
//Number of arrays in experiment
if (ArrayDesignAccessions.size() > 1) {
for (HybridizationNode hybNode : hybridizationNodes) {
ArrayDesignAttribute attribute = new ArrayDesignAttribute();
attribute.setAttributeValue(arrayDesign);
if (hybNode.arrayDesigns.contains(attribute)) {
//get data nodes for particular array design
hybridizationSubNodes.add(hybNode);
getNodes(hybNode, ArrayDataNode.class, rawDataSubNodes);
getNodes(hybNode, DerivedArrayDataNode.class,
processedDataSubNodes);
getNodes(hybNode, DerivedArrayDataMatrixNode.class,
processedDataMatrixSubNodes);
}
}
}
else {
//one array design in experiment
hybridizationSubNodes = hybridizationNodes;
for (ArrayDataNode node : rawDataNodes) {
rawDataSubNodes.add(node);
}
for (DerivedArrayDataNode node : processedDataNodes) {
processedDataSubNodes.add(node);
}
for (DerivedArrayDataMatrixNode node : processedDataMatrixNodes) {
processedDataMatrixSubNodes.add(node);
}
}
//6 check: if Affy then check for raw data files, else for derived
if (arrayCheckResult.equals("affy") &&
hybridizationSubNodes.size() != rawDataSubNodes.size()) { //6a affy
exitValue = 1;
if (rawDataSubNodes.size()==0) {
log.write(
"Affymetrix experiment without raw data files\n");
getLog().debug(
"Affymetrix experiment without raw data files");
error_val = error_val + "Affymetrix experiment without raw data files.\n";
}
else {
log.write(
"Affymetrix experiment with different numbers of hybs ("
+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+") \n");
getLog().debug(
"Affymetrix experiment with different numbers of hybs ("
+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+")");
error_val = error_val + "Affymetrix experiment with different numbers of hybs ("
+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+").\n";
}
}
else {
//6b not affy without processed data
if (!arrayCheckResult.equals("affy") &&
//processedDataSubNodes.size() == 0 &&
processedDataMatrixSubNodes.size() == 0) {
exitValue = 1;
log.write(
"Non-Affymetrix experiment without processed data files\n");
getLog().debug(
"Non-Affymetrix experiment without processed data files");
error_val = error_val +
"Non-Affymetrix experiment without processed data files. \n";
}
}
}
}
if (exitValue == 1) {
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
error_val);
String[] errors = new String[1];
errors[0] = error_val;
pex.setProcessOutput(errors);
throw pex;
}
}
catch (ParseException e) {
exitValue = 1;
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
errors[1] =
"Please check MAGE-TAB files and/or run validation process.\n";
pex.setProcessOutput(errors);
throw pex;
}
catch (IOException e) {
exitValue = 1;
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
pex.setProcessOutput(errors);
throw pex;
}
catch (RuntimeException e) {
exitValue = 1;
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
pex.setProcessOutput(errors);
throw pex;
}
finally {
try {
if (exitValue == 0) {
log.write("Experiment \"" +
accession.getAccession() +
"\" is eligible for Atlas\n");
}
else {
log.write("Experiment \"" +
accession.getAccession() +
"\" is NOT eligible for Atlas\n");
log.write(error_val);
}
log.write("Atlas Eligibility Check: FINISHED\n");
log.write(
"Eligibility checks for Gene Expression Atlas version 2.0.9.3: \n" +
"1. Experiment has raw data for Affymetrix platforms or normalized data for all other platforms;\n" +
"2. Array design(s) used in experiment are loaded into Atlas;\n" +
"3. Type of experiment is from the list: \n" +
" - transcription profiling by array,\n" +
" - methylation profiling by array,\n" +
" - tiling path by array,\n" +
" - comparative genomic hybridization by array,\n" +
" - microRNA profiling by array,\n" +
" - RNAi profiling by array,\n" +
" - ChIP-chip by array;\n" +
"4. Experiments is not two-channel;\n" +
"5. Experiment has factor values;\n" +
- "6. Experiment has replicates for at least 1 factor type;"+
+ "6. Experiment has replicates for at least 1 factor type;\n"+
"7. Factor types and Characteristics are from controlled vocabulary;\n" +
"8. Factor types and Characteristics are variable (not repeated).");
log.close();
}
catch (IOException e) {
e.printStackTrace();
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
pex.setProcessOutput(errors);
throw pex;
}
}
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
"Something wrong in the code ");
if (exitValue == 0) {
return true;
}
else {
String[] errors = new String[1];
errors[0] = "Something wrong in the code ";
pex.setProcessOutput(errors);
throw pex;
}
}
public boolean executeMockup(String file)
throws ProcessExecutionException, IllegalArgumentException {
// Add to the desired logger
BufferedWriter log;
boolean result = false;
// now, parse from a file
File idfFile = new File(file);
int exitValue = 0;
String error_val = "";
String reportsDir =
idfFile.getParentFile().getAbsolutePath() + File.separator +
"reports";
File reportsDirFile = new File(reportsDir);
if (!reportsDirFile.exists()) {
reportsDirFile.mkdirs();
}
String fileName = reportsDir + File.separator + idfFile.getName() +
"_AtlasEligibilityCheck" +
"_" + new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()) +
".report";
try {
log = new BufferedWriter(new FileWriter(fileName));
log.write("Atlas Eligibility Check: START\n");
}
catch (IOException e) {
e.printStackTrace();
throw new ProcessExecutionException(1, "Can't create report file '" +
fileName + "'", e);
}
// make a new parser
MAGETABParser parser = new MAGETABParser();
try {
MAGETABInvestigation investigation = parser.parse(idfFile);
// I check: experiment types
boolean isAtlasType = true;
String restrictedExptType = "";
/* if (investigation.IDF.getComments().containsKey("AEExperimentType")) {
for (String exptType : investigation.IDF.getComments()
.get("AEExperimentType")) {
for (String AtlasType : controlledVocabularyDAO
.getAtlasExperimentTypes()) {
if (exptType.equals(AtlasType)) {
isAtlasType = true;
}
else {
restrictedExptType = exptType;
}
}
}
}
else {
for (String exptType : investigation.IDF.experimentalDesign) {
for (String AtlasType : controlledVocabularyDAO
.getAtlasExperimentTypes()) {
if (exptType.equals(AtlasType)) {
isAtlasType = true;
}
}
}
} */
if (!isAtlasType)
//not in Atlas Experiment Types
{
exitValue = 1;
log.write(
"'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas\n");
getLog().debug(
"'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas");
error_val = "'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas.\n";
}
//2 two-channel experiment
if (investigation.SDRF.getNumberOfChannels() > 1) {
exitValue = 1;
log.write(
"Two-channel experiment is not accepted by Atlas\n");
getLog().debug(
"Two-channel experiment is not accepted by Atlas");
error_val = error_val + "Two-channel experiment is not accepted by Atlas. \n";
}
Collection<HybridizationNode> hybridizationNodes =
investigation.SDRF.getNodes(HybridizationNode.class);
Collection<ArrayDataNode> rawDataNodes =
investigation.SDRF.getNodes(ArrayDataNode.class);
Collection<DerivedArrayDataNode> processedDataNodes =
investigation.SDRF.getNodes(DerivedArrayDataNode.class);
Collection<DerivedArrayDataMatrixNode> processedDataMatrixNodes =
investigation.SDRF.getNodes(DerivedArrayDataMatrixNode.class);
int factorValues = 0;
for (HybridizationNode hybNode : hybridizationNodes) {
if (hybNode.factorValues.size() > 0) {
factorValues++;
}
ArrayDesignAccessions.clear();
for (ArrayDesignAttribute arrayDesign : hybNode.arrayDesigns) {
if (!ArrayDesignAccessions
.contains(arrayDesign.getAttributeValue())) {
ArrayDesignAccessions.add(arrayDesign.getAttributeValue());
}
}
}
boolean replicates = true;
// All experiments must have replicates for at least 1 factor
Hashtable<String,Hashtable> factorTypesCounts = new Hashtable<String, Hashtable>();
for (String factorType : investigation.IDF.experimentalFactorType) {
Hashtable<String,Integer> factorValuesCounts = new Hashtable<String, Integer>();
for (HybridizationNode hybNode : hybridizationNodes) {
String arrayDesignName = "";
for (ArrayDesignAttribute arrayDesign : hybNode.arrayDesigns) {
arrayDesignName=arrayDesign.getAttributeValue() ;
}
for (FactorValueAttribute fva : hybNode.factorValues) {
if (fva.getAttributeType().toLowerCase().contains(factorType.toLowerCase())) {
String key = arrayDesignName+"_"+fva.getAttributeValue();
if (factorValuesCounts.get(key)==null){
factorValuesCounts.put(key,1);
}
else {
int value = factorValuesCounts.get(key);
value++;
factorValuesCounts.put(key,value);
}
}
}
}
factorTypesCounts.put(factorType,factorValuesCounts);
}
for (Hashtable<String,Integer> fvc : factorTypesCounts.values() ) {
for (int val : fvc.values()){
if (val == 1){
replicates = false;
}
}
}
// replicates
if (replicates == false) {
exitValue = 1;
log.write(
"Experiment does not have replicates for at least 1 factor type\n");
getLog().debug(
"Experiment does not have replicates for at least 1 factor type");
error_val = error_val + "Experiment does not have replicates for at least 1 factor type. \n";
}
//3 factor values
if (factorValues == 0) {
exitValue = 1;
log.write(
"Experiment does not have Factor Values\n");
getLog().debug(
"Experiment does not have Factor Values");
error_val = error_val + "Experiment does not have Factor Values. \n";
}
//6 and 7 factor types are from controlled vocabulary and not repeated
boolean factorTypesFromCV = true;
boolean factorTypesVariable = true;
boolean characteristicsFromCV = true;
boolean characteristicsVariable = true;
List<String> missedFactorTypes = new ArrayList<String>();
List<String> missedCharacteristics = new ArrayList<String>();
List<String> repeatedFactorTypes = new ArrayList<String>();
List<String> repeatedCharacteristics = new ArrayList<String>();
for (String factorType : investigation.IDF.experimentalFactorType) {
System.out.println("Repeated1");
if (repeatedFactorTypes.contains(factorType)) {
factorTypesVariable = false;
}
repeatedFactorTypes.add(factorType);
}
for (SampleNode sampleNode : investigation.SDRF.getNodes(SampleNode.class)) {
System.out.println("Repeated2");
for (CharacteristicsAttribute ca : sampleNode.characteristics) {
if (repeatedCharacteristics.contains(ca.type)) {
characteristicsVariable = false;
}
repeatedCharacteristics.add(ca.type);
}
}
for (SourceNode sourceNode : investigation.SDRF.getNodes(SourceNode.class)) {
System.out.println("Repeated2");
for (CharacteristicsAttribute ca : sourceNode.characteristics) {
if (repeatedCharacteristics.contains(ca.type)) {
characteristicsVariable = false;
}
repeatedCharacteristics.add(ca.type);
}
}
if (!factorTypesFromCV) {
exitValue = 1;
log.write(
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes + "\n");
getLog().debug(
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes);
error_val = error_val +
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes + ".\n";
}
if (!characteristicsFromCV) {
exitValue = 1;
log.write(
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics + "\n");
getLog().debug(
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics);
error_val = error_val +
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics + ".\n";
}
if (!factorTypesVariable) {
exitValue = 1;
log.write("Experiment has repeated Factor Types.\n");
getLog().debug("Experiment has repeated Factor Types.");
error_val = error_val + "Experiment has repeated Factor Types.\n";
}
if (!characteristicsVariable) {
exitValue = 1;
log.write("Experiment has repeated Characteristics.\n");
getLog().debug("Experiment has repeated Characteristics.");
error_val = error_val + "Experiment has repeated Characteristics.\n";
}
// 5 check: array design is in Atlas
for (String arrayDesign : ArrayDesignAccessions) {
ArrayDesignExistenceChecking arrayDesignExistenceChecking =
new ArrayDesignExistenceChecking();
String arrayCheckResult =
arrayDesignExistenceChecking.execute(arrayDesign);
if (arrayCheckResult.equals("empty") ||
arrayCheckResult.equals("no")) {
exitValue = 1;
log.write("Array design '" +
arrayDesign +
"' used in experiment is not in Atlas\n");
getLog().debug("Array design '" +
arrayDesign +
"' used in experiment is not in Atlas");
error_val = error_val + "Array design '" +
arrayDesign +
"' used in experiment is not in Atlas. \n";
}
else {
//Array Design is in Atlas
Collection<HybridizationNode> hybridizationSubNodes =
new ArrayList<HybridizationNode>();
Collection<Node> rawDataSubNodes = new ArrayList<Node>();
Collection<Node> processedDataSubNodes = new ArrayList<Node>();
Collection<Node> processedDataMatrixSubNodes =
new ArrayList<Node>();
//Number of arrays in experiment
if (ArrayDesignAccessions.size() > 1) {
for (HybridizationNode hybNode : hybridizationNodes) {
ArrayDesignAttribute attribute = new ArrayDesignAttribute();
attribute.setAttributeValue(arrayDesign);
if (hybNode.arrayDesigns.contains(attribute)) {
//get data nodes for particular array design
hybridizationSubNodes.add(hybNode);
getNodes(hybNode, ArrayDataNode.class, rawDataSubNodes);
getNodes(hybNode, DerivedArrayDataNode.class,
processedDataSubNodes);
getNodes(hybNode, DerivedArrayDataMatrixNode.class,
processedDataMatrixSubNodes);
}
}
}
else {
//one array design in experiment
hybridizationSubNodes = hybridizationNodes;
for (ArrayDataNode node : rawDataNodes) {
rawDataSubNodes.add(node);
}
for (DerivedArrayDataNode node : processedDataNodes) {
processedDataSubNodes.add(node);
}
for (DerivedArrayDataMatrixNode node : processedDataMatrixNodes) {
processedDataMatrixSubNodes.add(node);
}
}
//6 check: if Affy then check for raw data files, else for derived
if (arrayCheckResult.equals("affy") &&
hybridizationSubNodes.size() != rawDataSubNodes.size()) {
exitValue = 1;
if (rawDataSubNodes.size()==0) {
log.write(
"Affymetrix experiment without raw data files\n");
getLog().debug(
"Affymetrix experiment without raw data files");
error_val = error_val + "Affymetrix experiment without raw data files.\n";
}
else {
log.write(
"Affymetrix experiment with different numbers of hybs ("+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+") \n");
getLog().debug(
"Affymetrix experiment with different numbers of hybs ("+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+")");
error_val = error_val + "Affymetrix experiment with different numbers of hybs ("+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+").\n";
}
}
else {
//6b not affy without processed data
if (!arrayCheckResult.equals("affy") &&
//processedDataSubNodes.size() == 0 &&
processedDataMatrixSubNodes.size() == 0) {
exitValue = 1;
log.write(
"Non-Affymetrix experiment without processed data files\n");
getLog().debug(
"Non-Affymetrix experiment without processed data files");
error_val = error_val +
"Non-Affymetrix experiment without processed data files. \n";
}
}
}
}
}
catch (Exception e) {
result = false;
e.printStackTrace();
throw new ProcessExecutionException(1,
"Atlas Eligibility Check: something is wrong in the code",
e);
}
finally {
try {
if (result) {
log.write(
"Atlas Eligibility Check: experiment \"" + idfFile.getName() +
"\" is eligible for ArrayExpress.\n");
}
else {
log.write(
"Atlas Eligibility Check: experiment \"" + idfFile.getName() +
"\" is NOT eligible for ArrayExpress.\n");
}
log.write(error_val);
System.out.println(error_val);
log.write("Atlas Eligibility Check: FINISHED\n");
log.write(
"Eligibility checks for Gene Expression Atlas version 2.0.9.3: \n" +
"1. Experiment has raw data for Affymetrix platforms or normalized data for all other platforms;\n" +
"2. Array design(s) used in experiment are loaded into Atlas;\n" +
"3. Type of experiment: transcription profiling by array,\n" +
"methylation profiling by array,\n" +
"tiling path by array,\n" +
"comparative genomic hybridization by array,\n" +
"microRNA profiling by array,\n" +
"RNAi profiling by array,\n" +
"ChIP-chip by array;\n" +
"4. Two-channel experiments - can't be loaded into Atlas;\n" +
"5. Experiment has factor values;\n" +
"6. Factor types are from controlled vocabulary;\n" +
"7. Factor types are variable (not repeated).");
log.close();
}
catch (IOException e) {
e.printStackTrace();
throw new ProcessExecutionException(1,
"Atlas Eligibility Check: can't close report file",
e);
}
}
return result;
}
private Collection<Node> getNodes(Node parentNode, Class typeOfNode,
Collection<Node> nodes) {
for (Node childNode : parentNode.getChildNodes()) {
if (childNode.getClass().equals(typeOfNode) &&
!nodes.contains(childNode)) {
nodes.add(childNode);
}
else {
getNodes(childNode, typeOfNode, nodes);
}
}
return nodes;
}
/**
* Returns the name of this process.
*
* @return the name of this process
*/
public String getName() {
return "atlas eligibility";
}
/**
* Returns a collection of strings representing the names of the parameters.
*
* @return the parameter names required to generate a task
*/
public Collection<ConanParameter> getParameters() {
return parameters;
}
}
| false | true | public boolean execute(Map<ConanParameter, String> parameters)
throws ProcessExecutionException, IllegalArgumentException,
InterruptedException {
int exitValue = 0;
// Add to the desired logger
BufferedWriter log;
String error_val = "";
//deal with parameters
final AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
String reportsDir =
accession.getFile().getParentFile().getAbsolutePath() + File.separator +
"reports";
File reportsDirFile = new File(reportsDir);
if (!reportsDirFile.exists()) {
reportsDirFile.mkdirs();
}
String fileName = reportsDir + File.separator + accession.getAccession() +
"_AtlasEligibilityCheck" +
"_" + new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()) +
".report";
try {
log = new BufferedWriter(new FileWriter(fileName));
log.write("Atlas Eligibility Check: START\n");
}
catch (IOException e) {
exitValue = 1;
e.printStackTrace();
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
"Can't create report file '" +
fileName +
"'");
String[] errors = new String[1];
errors[0] = "Can't create report file '" + fileName + "'";
pex.setProcessOutput(errors);
throw pex;
}
// make a new parser
MAGETABParser parser = new MAGETABParser();
try {
MAGETABInvestigation investigation =
parser.parse(accession.getFile().getAbsoluteFile());
// 1 check: experiment types
boolean isAtlasType = false;
String restrictedExptType = "";
if (investigation.IDF.getComments().containsKey("AEExperimentType")) {
for (String exptType : investigation.IDF.getComments()
.get("AEExperimentType")) {
for (String AtlasType : controlledVocabularyDAO
.getAtlasExperimentTypes()) {
if (exptType.equals(AtlasType)) {
isAtlasType = true;
}
else {
restrictedExptType = exptType;
}
}
}
}
else {
for (String exptType : investigation.IDF.experimentalDesign) {
for (String AtlasType : controlledVocabularyDAO
.getAtlasExperimentTypes()) {
if (exptType.equals(AtlasType)) {
isAtlasType = true;
}
}
}
}
if (!isAtlasType)
//not in Atlas Experiment Types
{
exitValue = 1;
log.write(
"'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas\n");
getLog().debug(
"'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas");
error_val = "'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas.\n";
}
//2 two-channel experiment
if (investigation.SDRF.getNumberOfChannels() > 1) {
exitValue = 1;
log.write(
"Two-channel experiment is not accepted by Atlas\n");
getLog().debug(
"Two-channel experiment is not accepted by Atlas");
error_val = error_val + "Two-channel experiment is not accepted by Atlas. \n";
}
Collection<HybridizationNode> hybridizationNodes =
investigation.SDRF.getNodes(HybridizationNode.class);
Collection<ArrayDataNode> rawDataNodes =
investigation.SDRF.getNodes(ArrayDataNode.class);
Collection<DerivedArrayDataNode> processedDataNodes =
investigation.SDRF.getNodes(DerivedArrayDataNode.class);
Collection<DerivedArrayDataMatrixNode> processedDataMatrixNodes =
investigation.SDRF.getNodes(DerivedArrayDataMatrixNode.class);
int factorValues = 0;
for (HybridizationNode hybNode : hybridizationNodes) {
if (hybNode.factorValues.size() > 0) {
factorValues++;
}
ArrayDesignAccessions.clear();
for (ArrayDesignAttribute arrayDesign : hybNode.arrayDesigns) {
if (!ArrayDesignAccessions
.contains(arrayDesign.getAttributeValue())) {
ArrayDesignAccessions.add(arrayDesign.getAttributeValue());
}
}
}
boolean replicates = true;
// All experiments must have replicates for at least 1 factor
Hashtable<String,Hashtable> factorTypesCounts = new Hashtable<String, Hashtable>();
for (String factorType : investigation.IDF.experimentalFactorType) {
Hashtable<String,Integer> factorValuesCounts = new Hashtable<String, Integer>();
for (HybridizationNode hybNode : hybridizationNodes) {
String arrayDesignName = "";
for (ArrayDesignAttribute arrayDesign : hybNode.arrayDesigns) {
arrayDesignName=arrayDesign.getAttributeValue() ;
}
for (FactorValueAttribute fva : hybNode.factorValues) {
if (fva.getAttributeType().toLowerCase().contains(factorType.toLowerCase())) {
String key = arrayDesignName+"_"+fva.getAttributeValue();
if (factorValuesCounts.get(key)==null){
factorValuesCounts.put(key,1);
}
else {
int value = factorValuesCounts.get(key);
value++;
factorValuesCounts.put(key,value);
}
}
}
}
factorTypesCounts.put(factorType,factorValuesCounts);
}
for (Hashtable<String,Integer> fvc : factorTypesCounts.values() ) {
for (int val : fvc.values()){
if (val == 1){
replicates = false;
}
}
}
// replicates
if (replicates == false) {
exitValue = 1;
log.write(
"Experiment does not have replicates for at least 1 factor type\n");
getLog().debug(
"Experiment does not have replicates for at least 1 factor type");
error_val = error_val + "Experiment does not have replicates for at least 1 factor type. \n";
}
//3 factor values
if (factorValues == 0) {
exitValue = 1;
log.write(
"Experiment does not have Factor Values\n");
getLog().debug(
"Experiment does not have Factor Values");
error_val = error_val + "Experiment does not have Factor Values. \n";
}
//6 and 7 factor types are from controlled vocabulary and not repeated
boolean factorTypesFromCV = true;
boolean factorTypesVariable = true;
boolean characteristicsFromCV = true;
boolean characteristicsVariable = true;
List<String> missedFactorTypes = new ArrayList<String>();
List<String> missedCharacteristics = new ArrayList<String>();
List<String> repeatedFactorTypes = new ArrayList<String>();
List<String> repeatedCharacteristics = new ArrayList<String>();
for (String factorType : investigation.IDF.experimentalFactorType) {
if (!controlledVocabularyDAO
.getAtlasFactorTypes().contains(factorType.toLowerCase())) {
factorTypesFromCV = false;
missedFactorTypes.add(factorType);
}
if (repeatedFactorTypes.contains(factorType)) {
factorTypesVariable = false;
}
repeatedFactorTypes.add(factorType);
}
for (SampleNode sampleNode : investigation.SDRF.getNodes(SampleNode.class)) {
for (CharacteristicsAttribute ca : sampleNode.characteristics) {
if (repeatedCharacteristics.contains(ca.type)) {
characteristicsVariable = false;
}
repeatedCharacteristics.add(ca.type);
if (!controlledVocabularyDAO
.getAtlasFactorTypes().contains(ca.type.toLowerCase())) {
characteristicsFromCV = false;
missedCharacteristics.add(ca.type);
}
}
}
for (SourceNode sourceNode : investigation.SDRF.getNodes(SourceNode.class)) {
for (CharacteristicsAttribute ca : sourceNode.characteristics) {
if (repeatedCharacteristics.contains(ca.type)) {
characteristicsVariable = false;
}
repeatedCharacteristics.add(ca.type);
if (!controlledVocabularyDAO
.getAtlasFactorTypes().contains(ca.type.toLowerCase())) {
characteristicsFromCV = false;
missedCharacteristics.add(ca.type);
}
}
}
if (!factorTypesFromCV) {
exitValue = 1;
log.write(
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes + "\n");
getLog().debug(
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes);
error_val = error_val +
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes + ".\n";
}
if (!characteristicsFromCV) {
exitValue = 1;
log.write(
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics + "\n");
getLog().debug(
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics);
error_val = error_val +
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics + ".\n";
}
if (!factorTypesVariable) {
exitValue = 1;
log.write("Experiment has repeated Factor Types.\n");
getLog().debug("Experiment has repeated Factor Types.");
error_val = error_val + "Experiment has repeated Factor Types.\n";
}
if (!characteristicsVariable) {
exitValue = 1;
log.write("Experiment has repeated Characteristics.\n");
getLog().debug("Experiment has repeated Characteristics.");
error_val = error_val + "Experiment has repeated Characteristics.\n";
}
// 5 check: array design is in Atlas
for (String arrayDesign : ArrayDesignAccessions) {
ArrayDesignExistenceChecking arrayDesignExistenceChecking =
new ArrayDesignExistenceChecking();
String arrayCheckResult =
arrayDesignExistenceChecking.execute(arrayDesign);
if (arrayCheckResult.equals("empty") ||
arrayCheckResult.equals("no")) {
exitValue = 1;
log.write("Array design '" +
arrayDesign +
"' used in experiment is not in Atlas\n");
getLog().debug("Array design '" +
arrayDesign +
"' used in experiment is not in Atlas");
error_val = error_val + "Array design '" +
arrayDesign +
"' used in experiment is not in Atlas. \n";
}
else {
//Array Design is in Atlas
Collection<HybridizationNode> hybridizationSubNodes =
new ArrayList<HybridizationNode>();
Collection<Node> rawDataSubNodes = new ArrayList<Node>();
Collection<Node> processedDataSubNodes = new ArrayList<Node>();
Collection<Node> processedDataMatrixSubNodes =
new ArrayList<Node>();
//Number of arrays in experiment
if (ArrayDesignAccessions.size() > 1) {
for (HybridizationNode hybNode : hybridizationNodes) {
ArrayDesignAttribute attribute = new ArrayDesignAttribute();
attribute.setAttributeValue(arrayDesign);
if (hybNode.arrayDesigns.contains(attribute)) {
//get data nodes for particular array design
hybridizationSubNodes.add(hybNode);
getNodes(hybNode, ArrayDataNode.class, rawDataSubNodes);
getNodes(hybNode, DerivedArrayDataNode.class,
processedDataSubNodes);
getNodes(hybNode, DerivedArrayDataMatrixNode.class,
processedDataMatrixSubNodes);
}
}
}
else {
//one array design in experiment
hybridizationSubNodes = hybridizationNodes;
for (ArrayDataNode node : rawDataNodes) {
rawDataSubNodes.add(node);
}
for (DerivedArrayDataNode node : processedDataNodes) {
processedDataSubNodes.add(node);
}
for (DerivedArrayDataMatrixNode node : processedDataMatrixNodes) {
processedDataMatrixSubNodes.add(node);
}
}
//6 check: if Affy then check for raw data files, else for derived
if (arrayCheckResult.equals("affy") &&
hybridizationSubNodes.size() != rawDataSubNodes.size()) { //6a affy
exitValue = 1;
if (rawDataSubNodes.size()==0) {
log.write(
"Affymetrix experiment without raw data files\n");
getLog().debug(
"Affymetrix experiment without raw data files");
error_val = error_val + "Affymetrix experiment without raw data files.\n";
}
else {
log.write(
"Affymetrix experiment with different numbers of hybs ("
+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+") \n");
getLog().debug(
"Affymetrix experiment with different numbers of hybs ("
+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+")");
error_val = error_val + "Affymetrix experiment with different numbers of hybs ("
+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+").\n";
}
}
else {
//6b not affy without processed data
if (!arrayCheckResult.equals("affy") &&
//processedDataSubNodes.size() == 0 &&
processedDataMatrixSubNodes.size() == 0) {
exitValue = 1;
log.write(
"Non-Affymetrix experiment without processed data files\n");
getLog().debug(
"Non-Affymetrix experiment without processed data files");
error_val = error_val +
"Non-Affymetrix experiment without processed data files. \n";
}
}
}
}
if (exitValue == 1) {
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
error_val);
String[] errors = new String[1];
errors[0] = error_val;
pex.setProcessOutput(errors);
throw pex;
}
}
catch (ParseException e) {
exitValue = 1;
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
errors[1] =
"Please check MAGE-TAB files and/or run validation process.\n";
pex.setProcessOutput(errors);
throw pex;
}
catch (IOException e) {
exitValue = 1;
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
pex.setProcessOutput(errors);
throw pex;
}
catch (RuntimeException e) {
exitValue = 1;
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
pex.setProcessOutput(errors);
throw pex;
}
finally {
try {
if (exitValue == 0) {
log.write("Experiment \"" +
accession.getAccession() +
"\" is eligible for Atlas\n");
}
else {
log.write("Experiment \"" +
accession.getAccession() +
"\" is NOT eligible for Atlas\n");
log.write(error_val);
}
log.write("Atlas Eligibility Check: FINISHED\n");
log.write(
"Eligibility checks for Gene Expression Atlas version 2.0.9.3: \n" +
"1. Experiment has raw data for Affymetrix platforms or normalized data for all other platforms;\n" +
"2. Array design(s) used in experiment are loaded into Atlas;\n" +
"3. Type of experiment is from the list: \n" +
" - transcription profiling by array,\n" +
" - methylation profiling by array,\n" +
" - tiling path by array,\n" +
" - comparative genomic hybridization by array,\n" +
" - microRNA profiling by array,\n" +
" - RNAi profiling by array,\n" +
" - ChIP-chip by array;\n" +
"4. Experiments is not two-channel;\n" +
"5. Experiment has factor values;\n" +
"6. Experiment has replicates for at least 1 factor type;"+
"7. Factor types and Characteristics are from controlled vocabulary;\n" +
"8. Factor types and Characteristics are variable (not repeated).");
log.close();
}
catch (IOException e) {
e.printStackTrace();
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
pex.setProcessOutput(errors);
throw pex;
}
}
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
"Something wrong in the code ");
if (exitValue == 0) {
return true;
}
else {
String[] errors = new String[1];
errors[0] = "Something wrong in the code ";
pex.setProcessOutput(errors);
throw pex;
}
}
| public boolean execute(Map<ConanParameter, String> parameters)
throws ProcessExecutionException, IllegalArgumentException,
InterruptedException {
int exitValue = 0;
// Add to the desired logger
BufferedWriter log;
String error_val = "";
//deal with parameters
final AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
String reportsDir =
accession.getFile().getParentFile().getAbsolutePath() + File.separator +
"reports";
File reportsDirFile = new File(reportsDir);
if (!reportsDirFile.exists()) {
reportsDirFile.mkdirs();
}
String fileName = reportsDir + File.separator + accession.getAccession() +
"_AtlasEligibilityCheck" +
"_" + new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()) +
".report";
try {
log = new BufferedWriter(new FileWriter(fileName));
log.write("Atlas Eligibility Check: START\n");
}
catch (IOException e) {
exitValue = 1;
e.printStackTrace();
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
"Can't create report file '" +
fileName +
"'");
String[] errors = new String[1];
errors[0] = "Can't create report file '" + fileName + "'";
pex.setProcessOutput(errors);
throw pex;
}
// make a new parser
MAGETABParser parser = new MAGETABParser();
try {
MAGETABInvestigation investigation =
parser.parse(accession.getFile().getAbsoluteFile());
// 1 check: experiment types
boolean isAtlasType = false;
String restrictedExptType = "";
if (investigation.IDF.getComments().containsKey("AEExperimentType")) {
for (String exptType : investigation.IDF.getComments()
.get("AEExperimentType")) {
for (String AtlasType : controlledVocabularyDAO
.getAtlasExperimentTypes()) {
if (exptType.equals(AtlasType)) {
isAtlasType = true;
}
else {
restrictedExptType = exptType;
}
}
}
}
else {
for (String exptType : investigation.IDF.experimentalDesign) {
for (String AtlasType : controlledVocabularyDAO
.getAtlasExperimentTypes()) {
if (exptType.equals(AtlasType)) {
isAtlasType = true;
}
}
}
}
if (!isAtlasType)
//not in Atlas Experiment Types
{
exitValue = 1;
log.write(
"'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas\n");
getLog().debug(
"'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas");
error_val = "'Experiment Type' " + restrictedExptType +
" is not accepted by Atlas.\n";
}
//2 two-channel experiment
if (investigation.SDRF.getNumberOfChannels() > 1) {
exitValue = 1;
log.write(
"Two-channel experiment is not accepted by Atlas\n");
getLog().debug(
"Two-channel experiment is not accepted by Atlas");
error_val = error_val + "Two-channel experiment is not accepted by Atlas. \n";
}
Collection<HybridizationNode> hybridizationNodes =
investigation.SDRF.getNodes(HybridizationNode.class);
Collection<ArrayDataNode> rawDataNodes =
investigation.SDRF.getNodes(ArrayDataNode.class);
Collection<DerivedArrayDataNode> processedDataNodes =
investigation.SDRF.getNodes(DerivedArrayDataNode.class);
Collection<DerivedArrayDataMatrixNode> processedDataMatrixNodes =
investigation.SDRF.getNodes(DerivedArrayDataMatrixNode.class);
int factorValues = 0;
for (HybridizationNode hybNode : hybridizationNodes) {
if (hybNode.factorValues.size() > 0) {
factorValues++;
}
ArrayDesignAccessions.clear();
for (ArrayDesignAttribute arrayDesign : hybNode.arrayDesigns) {
if (!ArrayDesignAccessions
.contains(arrayDesign.getAttributeValue())) {
ArrayDesignAccessions.add(arrayDesign.getAttributeValue());
}
}
}
boolean replicates = true;
// All experiments must have replicates for at least 1 factor
Hashtable<String,Hashtable> factorTypesCounts = new Hashtable<String, Hashtable>();
for (String factorType : investigation.IDF.experimentalFactorType) {
Hashtable<String,Integer> factorValuesCounts = new Hashtable<String, Integer>();
for (HybridizationNode hybNode : hybridizationNodes) {
String arrayDesignName = "";
for (ArrayDesignAttribute arrayDesign : hybNode.arrayDesigns) {
arrayDesignName=arrayDesign.getAttributeValue() ;
}
for (FactorValueAttribute fva : hybNode.factorValues) {
if (fva.getAttributeType().toLowerCase().contains(factorType.toLowerCase())) {
String key = arrayDesignName+"_"+fva.getAttributeValue();
if (factorValuesCounts.get(key)==null){
factorValuesCounts.put(key,1);
}
else {
int value = factorValuesCounts.get(key);
value++;
factorValuesCounts.put(key,value);
}
}
}
}
factorTypesCounts.put(factorType,factorValuesCounts);
}
for (Hashtable<String,Integer> fvc : factorTypesCounts.values() ) {
for (int val : fvc.values()){
if (val == 1){
replicates = false;
}
}
}
// replicates
if (replicates == false) {
exitValue = 1;
log.write(
"Experiment does not have replicates for at least 1 factor type\n");
getLog().debug(
"Experiment does not have replicates for at least 1 factor type");
error_val = error_val + "Experiment does not have replicates for at least 1 factor type. \n";
}
//3 factor values
if (factorValues == 0) {
exitValue = 1;
log.write(
"Experiment does not have Factor Values\n");
getLog().debug(
"Experiment does not have Factor Values");
error_val = error_val + "Experiment does not have Factor Values. \n";
}
//6 and 7 factor types are from controlled vocabulary and not repeated
boolean factorTypesFromCV = true;
boolean factorTypesVariable = true;
boolean characteristicsFromCV = true;
boolean characteristicsVariable = true;
List<String> missedFactorTypes = new ArrayList<String>();
List<String> missedCharacteristics = new ArrayList<String>();
List<String> repeatedFactorTypes = new ArrayList<String>();
List<String> repeatedCharacteristics = new ArrayList<String>();
for (String factorType : investigation.IDF.experimentalFactorType) {
if (!controlledVocabularyDAO
.getAtlasFactorTypes().contains(factorType.toLowerCase())) {
factorTypesFromCV = false;
missedFactorTypes.add(factorType);
}
if (repeatedFactorTypes.contains(factorType)) {
factorTypesVariable = false;
}
repeatedFactorTypes.add(factorType);
}
for (SampleNode sampleNode : investigation.SDRF.getNodes(SampleNode.class)) {
for (CharacteristicsAttribute ca : sampleNode.characteristics) {
if (repeatedCharacteristics.contains(ca.type)) {
characteristicsVariable = false;
}
repeatedCharacteristics.add(ca.type);
if (!controlledVocabularyDAO
.getAtlasFactorTypes().contains(ca.type.toLowerCase())) {
characteristicsFromCV = false;
if (!missedCharacteristics.contains(ca.type)){
missedCharacteristics.add(ca.type);
}
}
}
}
for (SourceNode sourceNode : investigation.SDRF.getNodes(SourceNode.class)) {
for (CharacteristicsAttribute ca : sourceNode.characteristics) {
if (repeatedCharacteristics.contains(ca.type)) {
characteristicsVariable = false;
}
repeatedCharacteristics.add(ca.type);
if (!controlledVocabularyDAO
.getAtlasFactorTypes().contains(ca.type.toLowerCase())) {
characteristicsFromCV = false;
if (!missedCharacteristics.contains(ca.type)){
missedCharacteristics.add(ca.type);
}
}
}
}
if (!factorTypesFromCV) {
exitValue = 1;
log.write(
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes + "\n");
getLog().debug(
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes);
error_val = error_val +
"Experiment has Factor Types that are not in controlled vocabulary:" +
missedFactorTypes + ".\n";
}
if (!characteristicsFromCV) {
exitValue = 1;
log.write(
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics + "\n");
getLog().debug(
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics);
error_val = error_val +
"Experiment has Characteristics that are not in controlled vocabulary:" +
missedCharacteristics + ".\n";
}
if (!factorTypesVariable) {
exitValue = 1;
log.write("Experiment has repeated Factor Types.\n");
getLog().debug("Experiment has repeated Factor Types.");
error_val = error_val + "Experiment has repeated Factor Types.\n";
}
if (!characteristicsVariable) {
exitValue = 1;
log.write("Experiment has repeated Characteristics.\n");
getLog().debug("Experiment has repeated Characteristics.");
error_val = error_val + "Experiment has repeated Characteristics.\n";
}
// 5 check: array design is in Atlas
for (String arrayDesign : ArrayDesignAccessions) {
ArrayDesignExistenceChecking arrayDesignExistenceChecking =
new ArrayDesignExistenceChecking();
String arrayCheckResult =
arrayDesignExistenceChecking.execute(arrayDesign);
if (arrayCheckResult.equals("empty") ||
arrayCheckResult.equals("no")) {
exitValue = 1;
log.write("Array design '" +
arrayDesign +
"' used in experiment is not in Atlas\n");
getLog().debug("Array design '" +
arrayDesign +
"' used in experiment is not in Atlas");
error_val = error_val + "Array design '" +
arrayDesign +
"' used in experiment is not in Atlas. \n";
}
else {
//Array Design is in Atlas
Collection<HybridizationNode> hybridizationSubNodes =
new ArrayList<HybridizationNode>();
Collection<Node> rawDataSubNodes = new ArrayList<Node>();
Collection<Node> processedDataSubNodes = new ArrayList<Node>();
Collection<Node> processedDataMatrixSubNodes =
new ArrayList<Node>();
//Number of arrays in experiment
if (ArrayDesignAccessions.size() > 1) {
for (HybridizationNode hybNode : hybridizationNodes) {
ArrayDesignAttribute attribute = new ArrayDesignAttribute();
attribute.setAttributeValue(arrayDesign);
if (hybNode.arrayDesigns.contains(attribute)) {
//get data nodes for particular array design
hybridizationSubNodes.add(hybNode);
getNodes(hybNode, ArrayDataNode.class, rawDataSubNodes);
getNodes(hybNode, DerivedArrayDataNode.class,
processedDataSubNodes);
getNodes(hybNode, DerivedArrayDataMatrixNode.class,
processedDataMatrixSubNodes);
}
}
}
else {
//one array design in experiment
hybridizationSubNodes = hybridizationNodes;
for (ArrayDataNode node : rawDataNodes) {
rawDataSubNodes.add(node);
}
for (DerivedArrayDataNode node : processedDataNodes) {
processedDataSubNodes.add(node);
}
for (DerivedArrayDataMatrixNode node : processedDataMatrixNodes) {
processedDataMatrixSubNodes.add(node);
}
}
//6 check: if Affy then check for raw data files, else for derived
if (arrayCheckResult.equals("affy") &&
hybridizationSubNodes.size() != rawDataSubNodes.size()) { //6a affy
exitValue = 1;
if (rawDataSubNodes.size()==0) {
log.write(
"Affymetrix experiment without raw data files\n");
getLog().debug(
"Affymetrix experiment without raw data files");
error_val = error_val + "Affymetrix experiment without raw data files.\n";
}
else {
log.write(
"Affymetrix experiment with different numbers of hybs ("
+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+") \n");
getLog().debug(
"Affymetrix experiment with different numbers of hybs ("
+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+")");
error_val = error_val + "Affymetrix experiment with different numbers of hybs ("
+hybridizationSubNodes.size()+") and raw data files ("+rawDataSubNodes.size()+").\n";
}
}
else {
//6b not affy without processed data
if (!arrayCheckResult.equals("affy") &&
//processedDataSubNodes.size() == 0 &&
processedDataMatrixSubNodes.size() == 0) {
exitValue = 1;
log.write(
"Non-Affymetrix experiment without processed data files\n");
getLog().debug(
"Non-Affymetrix experiment without processed data files");
error_val = error_val +
"Non-Affymetrix experiment without processed data files. \n";
}
}
}
}
if (exitValue == 1) {
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
error_val);
String[] errors = new String[1];
errors[0] = error_val;
pex.setProcessOutput(errors);
throw pex;
}
}
catch (ParseException e) {
exitValue = 1;
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
errors[1] =
"Please check MAGE-TAB files and/or run validation process.\n";
pex.setProcessOutput(errors);
throw pex;
}
catch (IOException e) {
exitValue = 1;
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
pex.setProcessOutput(errors);
throw pex;
}
catch (RuntimeException e) {
exitValue = 1;
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
pex.setProcessOutput(errors);
throw pex;
}
finally {
try {
if (exitValue == 0) {
log.write("Experiment \"" +
accession.getAccession() +
"\" is eligible for Atlas\n");
}
else {
log.write("Experiment \"" +
accession.getAccession() +
"\" is NOT eligible for Atlas\n");
log.write(error_val);
}
log.write("Atlas Eligibility Check: FINISHED\n");
log.write(
"Eligibility checks for Gene Expression Atlas version 2.0.9.3: \n" +
"1. Experiment has raw data for Affymetrix platforms or normalized data for all other platforms;\n" +
"2. Array design(s) used in experiment are loaded into Atlas;\n" +
"3. Type of experiment is from the list: \n" +
" - transcription profiling by array,\n" +
" - methylation profiling by array,\n" +
" - tiling path by array,\n" +
" - comparative genomic hybridization by array,\n" +
" - microRNA profiling by array,\n" +
" - RNAi profiling by array,\n" +
" - ChIP-chip by array;\n" +
"4. Experiments is not two-channel;\n" +
"5. Experiment has factor values;\n" +
"6. Experiment has replicates for at least 1 factor type;\n"+
"7. Factor types and Characteristics are from controlled vocabulary;\n" +
"8. Factor types and Characteristics are variable (not repeated).");
log.close();
}
catch (IOException e) {
e.printStackTrace();
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
e.getMessage());
String[] errors = new String[1];
errors[0] = e.getMessage();
pex.setProcessOutput(errors);
throw pex;
}
}
ProcessExecutionException pex = new ProcessExecutionException(exitValue,
"Something wrong in the code ");
if (exitValue == 0) {
return true;
}
else {
String[] errors = new String[1];
errors[0] = "Something wrong in the code ";
pex.setProcessOutput(errors);
throw pex;
}
}
|
diff --git a/src/ljdp/minechem/common/tileentity/TileEntityFission.java b/src/ljdp/minechem/common/tileentity/TileEntityFission.java
index e50a63f..8d3de2a 100644
--- a/src/ljdp/minechem/common/tileentity/TileEntityFission.java
+++ b/src/ljdp/minechem/common/tileentity/TileEntityFission.java
@@ -1,282 +1,282 @@
package ljdp.minechem.common.tileentity;
import ljdp.minechem.api.util.Constants;
import ljdp.minechem.common.MinechemItems;
import ljdp.minechem.common.blueprint.BlueprintFission;
import ljdp.minechem.common.inventory.BoundedInventory;
import ljdp.minechem.common.inventory.Transactor;
import ljdp.minechem.common.items.ItemElement;
import ljdp.minechem.common.utils.MinechemHelper;
import ljdp.minechem.computercraft.IMinechemMachinePeripheral;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.ForgeDirection;
import buildcraft.api.core.SafeTimeTracker;
public class TileEntityFission extends TileEntityMultiBlock implements IMinechemMachinePeripheral {
public static int[] kInput = { 0 };
public static int[] kFuel = { 1};
public static int[] kOutput = { 2};
private final BoundedInventory inputInventory;
private final BoundedInventory outputInventory;
private final BoundedInventory fuelInventory;
private Transactor inputTransactor;
private Transactor outputTransactor;
private Transactor fuelTransactor;
public static int kStartInput = 0;
public static int kStartFuel = 1;
public static int kStartOutput = 2;
public static int kSizeInput = 1;
public static int kSizeFuel = 1;
public static int kSizeOutput = 1;
SafeTimeTracker energyUpdateTracker = new SafeTimeTracker();
boolean shouldSendUpdatePacket;
public TileEntityFission() {
inventory = new ItemStack[getSizeInventory()];
inputInventory = new BoundedInventory(this, kInput);
outputInventory = new BoundedInventory(this, kOutput);
fuelInventory = new BoundedInventory(this, kFuel);
inputTransactor = new Transactor(inputInventory);
outputTransactor = new Transactor(outputInventory);
fuelTransactor = new Transactor(fuelInventory, 1);
this.inventory = new ItemStack[this.getSizeInventory()];
setBlueprint(new BlueprintFission());
}
@Override
public void updateEntity() {
super.updateEntity();
if(!completeStructure)
return;
shouldSendUpdatePacket = false;
if(!worldObj.isRemote && worldObj.getTotalWorldTime()%50==0 && inventory[kStartFuel] != null
&& energyUpdateTracker.markTimeIfDelay(worldObj, Constants.TICKS_PER_SECOND * 2))
{
if(inventory[kStartInput]!=null&&inventory[kStartFuel]!=null&&inventory[kStartFuel].getItemDamage()==91&&inventory[kStartFuel].getItem()instanceof ItemElement){
ItemStack fissionResult = getFissionOutput();
- if(!worldObj.isRemote) {
+ if(fissionResult !=null&&inventory[kOutput[0]]!=null&&fissionResult.itemID==inventory[kOutput[0]].itemID&&fissionResult.getItemDamage()==inventory[kOutput[0]].getItemDamage()&&!worldObj.isRemote) {
addToOutput(fissionResult);
removeInputs();
}
fissionResult = getFissionOutput();
shouldSendUpdatePacket = true;
}
}
if(shouldSendUpdatePacket && !worldObj.isRemote)
sendUpdatePacket();
}
private void addToOutput(ItemStack fusionResult) {
if (fusionResult==null){
return;
}
if (inventory[kOutput[0]] == null) {
ItemStack output = fusionResult.copy();
inventory[kOutput[0]] = output;
} else {
inventory[kOutput[0]].stackSize+=2;
}
}
private void removeInputs() {
decrStackSize(kInput[0], 1);
decrStackSize(kFuel[0], 1);
}
private boolean canFuse(ItemStack fusionResult) {
ItemStack itemInOutput = inventory[kOutput[0]];
if (itemInOutput != null)
return itemInOutput.stackSize < getInventoryStackLimit() && itemInOutput.isItemEqual(fusionResult);
return true;
}
private ItemStack getFissionOutput() {
if (hasInputs()) {
int mass = inventory[kInput[0]].getItemDamage() + 1;
int newMass=mass/2;
if (newMass >1) {
return new ItemStack(MinechemItems.element, 2, newMass - 1);
} else {
return null;
}
} else {
return null;
}
}
private boolean hasInputs() {
return inventory[kInput[0]] != null;
}
@Override
public int getSizeInventory() {
return 3;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack) {
this.inventory[slot] = itemstack;
}
@Override
public String getInvName() {
return "container.minechemFission";
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityPlayer) {
if (!completeStructure)
return false;
return true;
}
@Override
public void writeToNBT(NBTTagCompound nbtTagCompound) {
super.writeToNBT(nbtTagCompound);
NBTTagList inventoryTagList = MinechemHelper.writeItemStackArrayToTagList(inventory);
nbtTagCompound.setTag("inventory", inventoryTagList);
}
@Override
public void readFromNBT(NBTTagCompound nbtTagCompound) {
super.readFromNBT(nbtTagCompound);
inventory = new ItemStack[getSizeInventory()];
MinechemHelper.readTagListToItemStackArray(nbtTagCompound.getTagList("inventory"), inventory);
}
public void setEnergyStored(int amount) {
this.energyStored = amount;
}
@Override
public ItemStack takeEmptyTestTube() {
return null;
}
@Override
public int putEmptyTestTube(ItemStack testTube) {
return 0;
}
@Override
public ItemStack takeOutput() {
return outputTransactor.removeItem(true);
}
@Override
public int putOutput(ItemStack output) {
return outputTransactor.add(output, true);
}
@Override
public ItemStack takeInput() {
return inputTransactor.removeItem(true);
}
@Override
public int putInput(ItemStack input) {
return inputTransactor.add(input, true);
}
@Override
public ItemStack takeJournal() {
return null;
}
@Override
public int putJournal(ItemStack journal) {
return 0;
}
@Override
public String getMachineState() {
//TODO Check for fuel
return "powered";
}
@Override
public boolean isInvNameLocalized() {
return false;
}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
for (int slot : kInput) {
if(i==slot&&itemstack.getItem() instanceof ItemElement){
return true;
}
}
return false;
}
public int[] getSizeInventorySide(int side) {
switch (side) {
case 0:
return kOutput;
case 1:
return kInput;
default:
return kFuel;
}
}
@Override
public boolean canConnect(ForgeDirection direction) {
return false;
}
@Override
void sendUpdatePacket() {
// TODO Auto-generated method stub
}
@Override
public float getProvide(ForgeDirection direction) {
// TODO Auto-generated method stub
return 0;
}
@Override
public float getMaxEnergyStored() {
// TODO Auto-generated method stub
return 0;
}
//Horrible design here
//These are abstract methods
//Of TileEntityMultiBlock
@Override
public ItemStack takeFusionStar() {
// TODO Auto-generated method stub
return null;
}
@Override
public int putFusionStar(ItemStack fusionStar) {
// TODO Auto-generated method stub
return 0;
}
}
| true | true | public void updateEntity() {
super.updateEntity();
if(!completeStructure)
return;
shouldSendUpdatePacket = false;
if(!worldObj.isRemote && worldObj.getTotalWorldTime()%50==0 && inventory[kStartFuel] != null
&& energyUpdateTracker.markTimeIfDelay(worldObj, Constants.TICKS_PER_SECOND * 2))
{
if(inventory[kStartInput]!=null&&inventory[kStartFuel]!=null&&inventory[kStartFuel].getItemDamage()==91&&inventory[kStartFuel].getItem()instanceof ItemElement){
ItemStack fissionResult = getFissionOutput();
if(!worldObj.isRemote) {
addToOutput(fissionResult);
removeInputs();
}
fissionResult = getFissionOutput();
shouldSendUpdatePacket = true;
}
}
if(shouldSendUpdatePacket && !worldObj.isRemote)
sendUpdatePacket();
}
| public void updateEntity() {
super.updateEntity();
if(!completeStructure)
return;
shouldSendUpdatePacket = false;
if(!worldObj.isRemote && worldObj.getTotalWorldTime()%50==0 && inventory[kStartFuel] != null
&& energyUpdateTracker.markTimeIfDelay(worldObj, Constants.TICKS_PER_SECOND * 2))
{
if(inventory[kStartInput]!=null&&inventory[kStartFuel]!=null&&inventory[kStartFuel].getItemDamage()==91&&inventory[kStartFuel].getItem()instanceof ItemElement){
ItemStack fissionResult = getFissionOutput();
if(fissionResult !=null&&inventory[kOutput[0]]!=null&&fissionResult.itemID==inventory[kOutput[0]].itemID&&fissionResult.getItemDamage()==inventory[kOutput[0]].getItemDamage()&&!worldObj.isRemote) {
addToOutput(fissionResult);
removeInputs();
}
fissionResult = getFissionOutput();
shouldSendUpdatePacket = true;
}
}
if(shouldSendUpdatePacket && !worldObj.isRemote)
sendUpdatePacket();
}
|
diff --git a/src/nodebox/client/DraggableNumber.java b/src/nodebox/client/DraggableNumber.java
index e1bbf8f5..f7954571 100644
--- a/src/nodebox/client/DraggableNumber.java
+++ b/src/nodebox/client/DraggableNumber.java
@@ -1,349 +1,348 @@
package nodebox.client;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
/**
* DraggableNumber represents a number that can be edited in a variety of interesting ways:
* by dragging, selecting the arrow buttons, or double-clicking to do direct input.
*/
public class DraggableNumber extends JComponent implements MouseListener, MouseMotionListener, ComponentListener {
private static Image draggerLeft, draggerRight, draggerBackground;
private static int draggerLeftWidth, draggerRightWidth, draggerHeight;
static {
try {
draggerLeft = ImageIO.read(new File("res/dragger-left.png"));
draggerRight = ImageIO.read(new File("res/dragger-right.png"));
draggerBackground = ImageIO.read(new File("res/dragger-background.png"));
draggerLeftWidth = draggerLeft.getWidth(null);
draggerRightWidth = draggerRight.getWidth(null);
draggerHeight = draggerBackground.getHeight(null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// todo: could use something like BoundedRangeModel (but then for floats) for checking bounds.
private JTextField numberField;
private double oldValue, value;
private int previousX;
private Double minimumValue;
private Double maximumValue;
/**
* Only one <code>ChangeEvent</code> is needed per slider instance since the
* event's only (read-only) state is the source property. The source
* of events generated here is always "this". The event is lazily
* created the first time that an event notification is fired.
*
* @see #fireStateChanged
*/
protected transient ChangeEvent changeEvent = null;
private NumberFormat numberFormat;
public DraggableNumber() {
setLayout(null);
addMouseListener(this);
addMouseMotionListener(this);
addComponentListener(this);
Dimension d = new Dimension(87, 20);
setPreferredSize(d);
numberField = new JTextField();
numberField.putClientProperty("JComponent.sizeVariant", "small");
numberField.setFont(Theme.SMALL_BOLD_FONT);
numberField.setHorizontalAlignment(JTextField.CENTER);
numberField.setVisible(false);
numberField.addKeyListener(new EscapeListener());
numberField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
commitNumberField();
}
});
numberField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
commitNumberField();
- numberField.setVisible(false);
}
});
add(numberField);
numberFormat = NumberFormat.getNumberInstance();
numberFormat.setMinimumFractionDigits(2);
numberFormat.setMaximumFractionDigits(2);
setValue(0);
// Set the correct size for the numberField.
componentResized(null);
}
//// Value ranges ////
public Double getMinimumValue() {
return minimumValue;
}
public boolean hasMinimumValue() {
return minimumValue == null;
}
public void setMinimumValue(double minimumValue) {
this.minimumValue = minimumValue;
}
public void clearMinimumValue() {
this.minimumValue = null;
}
public Double getMaximumValue() {
return maximumValue;
}
public boolean hasMaximumValue() {
return maximumValue == null;
}
public void setMaximumValue(double maximumValue) {
this.maximumValue = maximumValue;
}
public void clearMaximumValue() {
this.maximumValue = null;
}
//// Value ////
public double getValue() {
return value;
}
public double clampValue(double value) {
if (minimumValue != null && value < minimumValue)
value = minimumValue;
if (maximumValue != null && value > maximumValue)
value = maximumValue;
return value;
}
public void setValue(double value) {
this.value = clampValue(value);
String formattedNumber = numberFormat.format(getValue());
numberField.setText(formattedNumber);
repaint();
}
public void setValueFromString(String s) throws NumberFormatException {
setValue(Double.parseDouble(s));
}
public String valueAsString() {
return numberFormat.format(value);
}
//// Number formatting ////
public NumberFormat getNumberFormat() {
return numberFormat;
}
public void setNumberFormat(NumberFormat numberFormat) {
this.numberFormat = numberFormat;
// Refresh the label
setValue(getValue());
}
private void commitNumberField() {
numberField.setVisible(false);
String s = numberField.getText();
try {
setValueFromString(s);
fireStateChanged();
} catch (NumberFormatException e) {
Toolkit.getDefaultToolkit().beep();
}
}
//// Component paint ////
private Rectangle getLeftButtonRect(Rectangle r) {
if (r == null)
r = getBounds();
return new Rectangle(0, 0, draggerLeftWidth, draggerHeight);
}
private Rectangle getRightButtonRect(Rectangle r) {
if (r == null)
r = getBounds();
return new Rectangle(r.width - draggerRightWidth, r.y, draggerRightWidth, draggerHeight);
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Rectangle r = getBounds();
int centerWidth = r.width - draggerLeftWidth - draggerRightWidth;
g2.drawImage(draggerLeft, 0, 0, null);
g2.drawImage(draggerRight, r.width - draggerRightWidth, 0, null);
g2.drawImage(draggerBackground, draggerLeftWidth, 0, centerWidth, draggerHeight, null);
g2.setFont(Theme.SMALL_BOLD_FONT);
g2.setColor(Theme.TEXT_NORMAL_COLOR);
SwingUtils.drawCenteredShadowText(g2, valueAsString(), r.width / 2, 14, Theme.DRAGGABLE_NUMBER_HIGLIGHT_COLOR);
}
//// Component size ////
@Override
public Dimension getPreferredSize() {
// The control is actually 20 pixels high, but setting the height to 30 will leave a nice margin.
return new Dimension(120, 30);
}
//// Component listeners
public void componentResized(ComponentEvent e) {
numberField.setBounds(draggerLeftWidth, 1, getWidth() - draggerLeftWidth - draggerRightWidth, draggerHeight - 2);
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
//// Mouse listeners ////
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
oldValue = getValue();
previousX = e.getX();
}
}
public void mouseClicked(MouseEvent e) {
float dx = 1.0F;
if ((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) > 0) {
dx = 10F;
} else if ((e.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) > 0) {
dx = 0.01F;
}
if (getLeftButtonRect(null).contains(e.getPoint())) {
setValue(getValue() - dx);
fireStateChanged();
} else if (getRightButtonRect(null).contains(e.getPoint())) {
setValue(getValue() + dx);
fireStateChanged();
} else if (e.getClickCount() >= 2) {
numberField.setText(valueAsString());
numberField.setVisible(true);
numberField.requestFocus();
numberField.selectAll();
componentResized(null);
repaint();
}
}
public void mouseReleased(MouseEvent e) {
if (oldValue != value)
fireStateChanged();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
float deltaX = e.getX() - previousX;
if (deltaX == 0F) return;
if ((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) > 0) {
deltaX *= 10;
} else if ((e.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) > 0) {
deltaX *= 0.01;
}
setValue(getValue() + deltaX);
previousX = e.getX();
fireStateChanged();
}
/**
* Adds a ChangeListener to the slider.
*
* @param l the ChangeListener to add
* @see #fireStateChanged
* @see #removeChangeListener
*/
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
/**
* Removes a ChangeListener from the slider.
*
* @param l the ChangeListener to remove
* @see #fireStateChanged
* @see #addChangeListener
*/
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/**
* Send a ChangeEvent, whose source is this Slider, to
* each listener. This method method is called each time
* a ChangeEvent is received from the model.
*
* @see #addChangeListener
* @see javax.swing.event.EventListenerList
*/
protected void fireStateChanged() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener) listeners[i + 1]).stateChanged(changeEvent);
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DraggableNumber());
frame.pack();
frame.setVisible(true);
}
/**
* When the escape key is pressed in the numberField, ignore the change and "close" the field.
*/
private class EscapeListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
numberField.setVisible(false);
}
}
}
| true | true | public DraggableNumber() {
setLayout(null);
addMouseListener(this);
addMouseMotionListener(this);
addComponentListener(this);
Dimension d = new Dimension(87, 20);
setPreferredSize(d);
numberField = new JTextField();
numberField.putClientProperty("JComponent.sizeVariant", "small");
numberField.setFont(Theme.SMALL_BOLD_FONT);
numberField.setHorizontalAlignment(JTextField.CENTER);
numberField.setVisible(false);
numberField.addKeyListener(new EscapeListener());
numberField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
commitNumberField();
}
});
numberField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
commitNumberField();
numberField.setVisible(false);
}
});
add(numberField);
numberFormat = NumberFormat.getNumberInstance();
numberFormat.setMinimumFractionDigits(2);
numberFormat.setMaximumFractionDigits(2);
setValue(0);
// Set the correct size for the numberField.
componentResized(null);
}
| public DraggableNumber() {
setLayout(null);
addMouseListener(this);
addMouseMotionListener(this);
addComponentListener(this);
Dimension d = new Dimension(87, 20);
setPreferredSize(d);
numberField = new JTextField();
numberField.putClientProperty("JComponent.sizeVariant", "small");
numberField.setFont(Theme.SMALL_BOLD_FONT);
numberField.setHorizontalAlignment(JTextField.CENTER);
numberField.setVisible(false);
numberField.addKeyListener(new EscapeListener());
numberField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
commitNumberField();
}
});
numberField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
commitNumberField();
}
});
add(numberField);
numberFormat = NumberFormat.getNumberInstance();
numberFormat.setMinimumFractionDigits(2);
numberFormat.setMaximumFractionDigits(2);
setValue(0);
// Set the correct size for the numberField.
componentResized(null);
}
|
diff --git a/src/minecraft/co/uk/flansmods/client/FlansModClient.java b/src/minecraft/co/uk/flansmods/client/FlansModClient.java
index 4dfe8a3a..43fd5b59 100644
--- a/src/minecraft/co/uk/flansmods/client/FlansModClient.java
+++ b/src/minecraft/co/uk/flansmods/client/FlansModClient.java
@@ -1,250 +1,250 @@
package co.uk.flansmods.client;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import co.uk.flansmods.common.BlockGunBox;
import co.uk.flansmods.common.EntityDriveable;
import co.uk.flansmods.common.EntityPlane;
import co.uk.flansmods.common.EntityVehicle;
import co.uk.flansmods.common.FlansMod;
import co.uk.flansmods.common.ItemGun;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
public class FlansModClient extends FlansMod
{
public static boolean doneTutorial = false;
public static boolean controlModeMouse = false; // 0 = Standard controls, 1 = Mouse
public static int controlModeSwitchTimer = 20;
public static int shootTime;
public static String zoomOverlay;
public static float playerRecoil;
public static float antiRecoil;
public static float playerZoom = 1.0F;
public static float newZoom = 1.0F;
public static float lastPlayerZoom;
public static float originalMouseSensitivity = 0.5F;
public static boolean originalHideGUI = false;
public static int originalThirdPerson = 0;
public static boolean inPlane = false;
public void load()
{
if (ABORT)
{
log("Failed to load dependencies! Not loading Flan's Mod.");
return;
}
log("Loading Flan's mod.");
// Properties
// TODO: move to common and proxy-ify
try
{
File file = new File(FMLClientHandler.instance().getClient().getMinecraftDir() + "/Flan/properties.txt");
if (file != null)
{
BufferedReader properties = new BufferedReader(new FileReader(file));
do
{
String line = null;
try
{
line = properties.readLine();
} catch (Exception e)
{
break;
}
if (line == null)
{
break;
}
if (line.startsWith("//"))
continue;
String[] split = line.split(" ");
if (split.length < 2)
continue;
readProperties(split, properties);
} while (true);
log("Loaded properties.");
}
} catch (Exception e)
{
log("No properties file found. Using defaults.");
createNewProperties();
}
}
public static void tick()
{
if (minecraft.thePlayer == null)
return;
// Guns
if (shootTime > 0)
shootTime--;
if (playerRecoil > 0)
playerRecoil *= 0.8F;
minecraft.thePlayer.rotationPitch -= playerRecoil;
antiRecoil += playerRecoil;
minecraft.thePlayer.rotationPitch += antiRecoil * 0.2F;
antiRecoil *= 0.8F;
Item itemInHand = null;
ItemStack itemstackInHand = minecraft.thePlayer.inventory.getCurrentItem();
if (itemstackInHand != null)
itemInHand = itemstackInHand.getItem();
if (itemInHand != null)
{
if (!(itemInHand instanceof ItemGun && ((ItemGun) itemInHand).type.hasScope))
{
newZoom = 1.0F;
}
}
float dZoom = newZoom - playerZoom;
playerZoom += dZoom / 3F;
if (playerZoom < 1.1F && zoomOverlay != null)
{
minecraft.gameSettings.mouseSensitivity = originalMouseSensitivity;
playerZoom = 1.0F;
zoomOverlay = null;
minecraft.gameSettings.hideGUI = originalHideGUI;
minecraft.gameSettings.thirdPersonView = originalThirdPerson;
}
String field = inMCP ? "cameraZoom" : "V";
if (Math.abs(playerZoom - lastPlayerZoom) > 1F / 64F)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, playerZoom, "cameraZoom", "X");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
lastPlayerZoom = playerZoom;
field = inMCP ? "camRoll" : "O";
if (minecraft.thePlayer.ridingEntity instanceof EntityDriveable)
{
inPlane = true;
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityDriveable)minecraft.thePlayer.ridingEntity).axes.getRoll() * (minecraft.thePlayer.ridingEntity instanceof EntityVehicle ? -1 : 1), "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
- if(!inPlane && minecraft.thePlayer.ridingEntity instanceof EntityPlane)
+ if(minecraft.thePlayer.ridingEntity instanceof EntityPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityPlane)minecraft.thePlayer.ridingEntity).getPlaneType().cameraDistance, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
}
else if(inPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 0F, "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 4.0F, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
inPlane = false;
}
if (controlModeSwitchTimer > 0)
controlModeSwitchTimer--;
if (errorStringTimer > 0)
errorStringTimer--;
}
public static void flipControlMode()
{
if (controlModeSwitchTimer > 0)
return;
controlModeMouse = !controlModeMouse;
controlModeSwitchTimer = 40;
}
public static void shoot()
{
// TODO : SMP guns
}
public static void buyGun(BlockGunBox box, int gun)
{
// TODO : SMP gun boxes
}
public static void buyAmmo(BlockGunBox box, int ammo)
{
// TODO : SMP gun boxes
}
private void doPropertyStuff(File file)
{
}
private void readProperties(String[] split, BufferedReader file)
{
try
{
if (split[0].equals("Explosions"))
explosions = split[1].equals("True");
if (split[0].equals("Bombs"))
bombsEnabled = split[1].equals("True");
if (split[0].equals("Bullets"))
bulletsEnabled = split[1].equals("True");
} catch (Exception e)
{
e.printStackTrace();
}
}
private void createNewProperties()
{
try
{
FileOutputStream propsOut = new FileOutputStream(new File(FMLClientHandler.instance().getClient().getMinecraftDir() + "/Flan/properties.txt"));
propsOut.write(("Explosions True\r\nBombs True\r\nBullets True").getBytes());
propsOut.close();
} catch (Exception e)
{
log("Failed to write default properties");
e.printStackTrace();
}
}
public static Minecraft minecraft = FMLClientHandler.instance().getClient();
}
| true | true | public static void tick()
{
if (minecraft.thePlayer == null)
return;
// Guns
if (shootTime > 0)
shootTime--;
if (playerRecoil > 0)
playerRecoil *= 0.8F;
minecraft.thePlayer.rotationPitch -= playerRecoil;
antiRecoil += playerRecoil;
minecraft.thePlayer.rotationPitch += antiRecoil * 0.2F;
antiRecoil *= 0.8F;
Item itemInHand = null;
ItemStack itemstackInHand = minecraft.thePlayer.inventory.getCurrentItem();
if (itemstackInHand != null)
itemInHand = itemstackInHand.getItem();
if (itemInHand != null)
{
if (!(itemInHand instanceof ItemGun && ((ItemGun) itemInHand).type.hasScope))
{
newZoom = 1.0F;
}
}
float dZoom = newZoom - playerZoom;
playerZoom += dZoom / 3F;
if (playerZoom < 1.1F && zoomOverlay != null)
{
minecraft.gameSettings.mouseSensitivity = originalMouseSensitivity;
playerZoom = 1.0F;
zoomOverlay = null;
minecraft.gameSettings.hideGUI = originalHideGUI;
minecraft.gameSettings.thirdPersonView = originalThirdPerson;
}
String field = inMCP ? "cameraZoom" : "V";
if (Math.abs(playerZoom - lastPlayerZoom) > 1F / 64F)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, playerZoom, "cameraZoom", "X");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
lastPlayerZoom = playerZoom;
field = inMCP ? "camRoll" : "O";
if (minecraft.thePlayer.ridingEntity instanceof EntityDriveable)
{
inPlane = true;
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityDriveable)minecraft.thePlayer.ridingEntity).axes.getRoll() * (minecraft.thePlayer.ridingEntity instanceof EntityVehicle ? -1 : 1), "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
if(!inPlane && minecraft.thePlayer.ridingEntity instanceof EntityPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityPlane)minecraft.thePlayer.ridingEntity).getPlaneType().cameraDistance, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
}
else if(inPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 0F, "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 4.0F, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
inPlane = false;
}
if (controlModeSwitchTimer > 0)
controlModeSwitchTimer--;
if (errorStringTimer > 0)
errorStringTimer--;
}
| public static void tick()
{
if (minecraft.thePlayer == null)
return;
// Guns
if (shootTime > 0)
shootTime--;
if (playerRecoil > 0)
playerRecoil *= 0.8F;
minecraft.thePlayer.rotationPitch -= playerRecoil;
antiRecoil += playerRecoil;
minecraft.thePlayer.rotationPitch += antiRecoil * 0.2F;
antiRecoil *= 0.8F;
Item itemInHand = null;
ItemStack itemstackInHand = minecraft.thePlayer.inventory.getCurrentItem();
if (itemstackInHand != null)
itemInHand = itemstackInHand.getItem();
if (itemInHand != null)
{
if (!(itemInHand instanceof ItemGun && ((ItemGun) itemInHand).type.hasScope))
{
newZoom = 1.0F;
}
}
float dZoom = newZoom - playerZoom;
playerZoom += dZoom / 3F;
if (playerZoom < 1.1F && zoomOverlay != null)
{
minecraft.gameSettings.mouseSensitivity = originalMouseSensitivity;
playerZoom = 1.0F;
zoomOverlay = null;
minecraft.gameSettings.hideGUI = originalHideGUI;
minecraft.gameSettings.thirdPersonView = originalThirdPerson;
}
String field = inMCP ? "cameraZoom" : "V";
if (Math.abs(playerZoom - lastPlayerZoom) > 1F / 64F)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, playerZoom, "cameraZoom", "X");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
lastPlayerZoom = playerZoom;
field = inMCP ? "camRoll" : "O";
if (minecraft.thePlayer.ridingEntity instanceof EntityDriveable)
{
inPlane = true;
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityDriveable)minecraft.thePlayer.ridingEntity).axes.getRoll() * (minecraft.thePlayer.ridingEntity instanceof EntityVehicle ? -1 : 1), "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
if(minecraft.thePlayer.ridingEntity instanceof EntityPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityPlane)minecraft.thePlayer.ridingEntity).getPlaneType().cameraDistance, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
}
else if(inPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 0F, "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 4.0F, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
inPlane = false;
}
if (controlModeSwitchTimer > 0)
controlModeSwitchTimer--;
if (errorStringTimer > 0)
errorStringTimer--;
}
|
diff --git a/onebusaway-nyc-transit-data-federation/src/test/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/TestStifTripLoaderTest.java b/onebusaway-nyc-transit-data-federation/src/test/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/TestStifTripLoaderTest.java
index 430cd9fcb..c2a343244 100644
--- a/onebusaway-nyc-transit-data-federation/src/test/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/TestStifTripLoaderTest.java
+++ b/onebusaway-nyc-transit-data-federation/src/test/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/TestStifTripLoaderTest.java
@@ -1,56 +1,56 @@
/**
* Copyright (c) 2011 Metropolitan Transportation Authority
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.onebusaway.nyc.transit_data_federation.bundle.tasks.stif;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.onebusaway.gtfs.impl.GtfsRelationalDaoImpl;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Trip;
import org.onebusaway.gtfs.serialization.GtfsReader;
public class TestStifTripLoaderTest {
@Test
public void testLoader() throws IOException {
InputStream in = getClass().getResourceAsStream("stif.m_0014__.210186.sun");
String gtfs = getClass().getResource("m14.zip").getFile();
GtfsReader reader = new GtfsReader();
GtfsRelationalDaoImpl dao = new GtfsRelationalDaoImpl();
reader.setEntityStore(dao);
reader.setInputLocation(new File(gtfs));
reader.run();
StifTripLoader loader = new StifTripLoader();
loader.setGtfsDao(dao);
- loader.run(in);
+ loader.run(in, new File("stif.m_0014__.210186.sun"));
Map<String, List<AgencyAndId>> mapping = loader.getTripMapping();
assertTrue(mapping.containsKey("1140"));
List<AgencyAndId> trips = mapping.get("1140");
AgencyAndId tripId = trips.get(0);
Trip trip = dao.getTripForId(tripId);
assertEquals(new AgencyAndId("MTA NYCT",
"20100627DA_003000_M14AD_0001_M14AD_1"), trip.getId());
}
}
| true | true | public void testLoader() throws IOException {
InputStream in = getClass().getResourceAsStream("stif.m_0014__.210186.sun");
String gtfs = getClass().getResource("m14.zip").getFile();
GtfsReader reader = new GtfsReader();
GtfsRelationalDaoImpl dao = new GtfsRelationalDaoImpl();
reader.setEntityStore(dao);
reader.setInputLocation(new File(gtfs));
reader.run();
StifTripLoader loader = new StifTripLoader();
loader.setGtfsDao(dao);
loader.run(in);
Map<String, List<AgencyAndId>> mapping = loader.getTripMapping();
assertTrue(mapping.containsKey("1140"));
List<AgencyAndId> trips = mapping.get("1140");
AgencyAndId tripId = trips.get(0);
Trip trip = dao.getTripForId(tripId);
assertEquals(new AgencyAndId("MTA NYCT",
"20100627DA_003000_M14AD_0001_M14AD_1"), trip.getId());
}
| public void testLoader() throws IOException {
InputStream in = getClass().getResourceAsStream("stif.m_0014__.210186.sun");
String gtfs = getClass().getResource("m14.zip").getFile();
GtfsReader reader = new GtfsReader();
GtfsRelationalDaoImpl dao = new GtfsRelationalDaoImpl();
reader.setEntityStore(dao);
reader.setInputLocation(new File(gtfs));
reader.run();
StifTripLoader loader = new StifTripLoader();
loader.setGtfsDao(dao);
loader.run(in, new File("stif.m_0014__.210186.sun"));
Map<String, List<AgencyAndId>> mapping = loader.getTripMapping();
assertTrue(mapping.containsKey("1140"));
List<AgencyAndId> trips = mapping.get("1140");
AgencyAndId tripId = trips.get(0);
Trip trip = dao.getTripForId(tripId);
assertEquals(new AgencyAndId("MTA NYCT",
"20100627DA_003000_M14AD_0001_M14AD_1"), trip.getId());
}
|
diff --git a/amibe/src/org/jcae/mesh/amibe/algos3d/SmoothNodes3DBg.java b/amibe/src/org/jcae/mesh/amibe/algos3d/SmoothNodes3DBg.java
index 527b8f36..839dfcb0 100644
--- a/amibe/src/org/jcae/mesh/amibe/algos3d/SmoothNodes3DBg.java
+++ b/amibe/src/org/jcae/mesh/amibe/algos3d/SmoothNodes3DBg.java
@@ -1,500 +1,500 @@
/* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD
modeler, Finite element mesher, Plugin architecture.
Copyright (C) 2008,2009,2010, by EADS France
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jcae.mesh.amibe.algos3d;
import org.jcae.mesh.amibe.ds.Mesh;
import org.jcae.mesh.amibe.ds.Triangle;
import org.jcae.mesh.amibe.ds.AbstractHalfEdge;
import org.jcae.mesh.amibe.ds.Vertex;
import org.jcae.mesh.amibe.projection.MeshLiaison;
import org.jcae.mesh.amibe.util.QSortedTree;
import org.jcae.mesh.amibe.util.PAVLSortedTree;
import org.jcae.mesh.xmldata.MeshReader;
import org.jcae.mesh.xmldata.MeshWriter;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.Collection;
import java.util.Iterator;
import java.io.IOException;
import gnu.trove.TObjectDoubleHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Node smoothing. Triangle quality is computed for all triangles,
* and vertex quality is the lowest value of its incident triangles.
* Vertices are sorted according to their quality, and processed
* iteratively by beginning with worst vertex. A modified Laplacian
* smoothing is performed, as briefly explained in
* <a href="http://www.ann.jussieu.fr/~frey/publications/ijnme4198.pdf">Adaptive Triangular-Quadrilateral Mesh Generation</a>, by Houman Borouchaky and
* Pascal J. Frey.
* If final position improves vertex quality, point is moved.
*/
public class SmoothNodes3DBg
{
private final static Logger LOGGER = Logger.getLogger(SmoothNodes3DBg.class.getName());
private final Mesh mesh;
private final MeshLiaison liaison;
private double sizeTarget = -1.0;
private int nloop = 10;
private double tolerance = Double.MAX_VALUE / 2.0;
private double minCos = 0.95;
private boolean preserveBoundaries = false;
private boolean checkQuality = true;
private int progressBarStatus = 10000;
private static final double scaleFactor = 12.0 * Math.sqrt(3.0);
private double relaxation = 0.6;
private final QSortedTree<Vertex> tree = new PAVLSortedTree<Vertex>();
private boolean refresh = false;
int processed = 0;
private int notProcessed = 0;
private TObjectDoubleHashMap<Triangle> qualityMap;
private Collection<Vertex> nodeset;
private final Set<Vertex> immutableNodes = new LinkedHashSet<Vertex>();
/**
* Creates a <code>SmoothNodes3DBg</code> instance.
*
* @param m the <code>Mesh</code> instance to refine.
*/
@Deprecated
public SmoothNodes3DBg(Mesh m)
{
this(m, new HashMap<String, String>());
}
/**
* Creates a <code>SmoothNodes3DBg</code> instance.
*
* @param bgMesh the <code>Mesh</code> instance to refine.
* @param options map containing key-value pairs to modify algorithm
* behaviour. Valid keys are <code>size</code>,
* <code>iterations</code>, <code>boundaries</code>,
* <code>tolerance</code>, <code>refresh</code> and
* <code>relaxation</code>.
*/
@Deprecated
public SmoothNodes3DBg(final Mesh bgMesh, final Map<String, String> options)
{
this(new MeshLiaison(bgMesh), options);
}
public SmoothNodes3DBg(final MeshLiaison meshLiaison, final Map<String, String> options)
{
liaison = meshLiaison;
mesh = liaison.getMesh();
for (final Map.Entry<String, String> opt: options.entrySet())
{
final String key = opt.getKey();
final String val = opt.getValue();
if (key.equals("size"))
sizeTarget = Double.valueOf(val).doubleValue();
else if (key.equals("iterations"))
nloop = Integer.valueOf(val).intValue();
else if (key.equals("boundaries"))
preserveBoundaries = Boolean.valueOf(val).booleanValue();
else if (key.equals("tolerance"))
tolerance = Double.valueOf(val).doubleValue();
else if (key.equals("refresh"))
refresh = true;
else if (key.equals("check"))
checkQuality = Boolean.valueOf(val).booleanValue();
else if (key.equals("relaxation"))
relaxation = Double.valueOf(val).doubleValue();
else if (key.equals("coplanarity"))
{
minCos = Double.parseDouble(val);
LOGGER.fine("Minimum dot product of face normals allowed for swapping an edge: "+minCos);
}
else
throw new RuntimeException("Unknown option: "+key);
}
if (meshLiaison == null)
mesh.buildRidges(minCos);
if (LOGGER.isLoggable(Level.FINE))
{
if (sizeTarget > 0.0)
LOGGER.fine("Size: "+sizeTarget);
LOGGER.fine("Iterations: "+nloop);
LOGGER.fine("Refresh: "+refresh);
LOGGER.fine("Relaxation: "+relaxation);
LOGGER.fine("Tolerance: "+tolerance);
LOGGER.fine("Preserve boundaries: "+preserveBoundaries);
}
}
public final Mesh getOutputMesh()
{
return mesh;
}
public void setProgressBarStatus(int n)
{
progressBarStatus = n;
}
/**
* Moves all nodes until all iterations are done.
*/
private void computeTriangleQuality()
{
AbstractHalfEdge ot = null;
for (Triangle f: mesh.getTriangles())
{
if (f.hasAttributes(AbstractHalfEdge.OUTER))
continue;
ot = f.getAbstractHalfEdge(ot);
double val = triangleQuality(ot);
qualityMap.put(f, val);
}
}
public final SmoothNodes3DBg compute()
{
LOGGER.info("Run "+getClass().getName());
if (nloop > 0)
{
// First compute triangle quality
qualityMap = new TObjectDoubleHashMap<Triangle>(mesh.getTriangles().size());
computeTriangleQuality();
nodeset = mesh.getNodes();
if (nodeset == null)
{
nodeset = new LinkedHashSet<Vertex>(mesh.getTriangles().size() / 2);
for (Triangle f: mesh.getTriangles())
{
if (f.hasAttributes(AbstractHalfEdge.OUTER))
continue;
for (Vertex v: f.vertex)
nodeset.add(v);
}
}
// Detect immutable nodes
AbstractHalfEdge ot = null;
for (Triangle f: mesh.getTriangles())
{
if (f.hasAttributes(AbstractHalfEdge.OUTER))
continue;
ot = f.getAbstractHalfEdge(ot);
for (int i = 0; i < 3; i++)
{
ot = ot.next();
if (ot.hasAttributes(AbstractHalfEdge.IMMUTABLE | AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD | AbstractHalfEdge.SHARP))
{
immutableNodes.add(ot.origin());
immutableNodes.add(ot.destination());
}
}
}
for (Vertex v: nodeset)
{
if (!v.isManifold() || (preserveBoundaries && v.getRef() != 0))
immutableNodes.add(v);
}
for (int i = 0; i < nloop; i++)
{
processAllNodes();
postProcessIteration(mesh, i);
}
}
LOGGER.info("Number of moved points: "+processed);
LOGGER.info("Total number of points not moved during processing: "+notProcessed);
assert mesh.checkNoDegeneratedTriangles();
assert mesh.checkNoInvertedTriangles();
return this;
}
final void postProcessIteration(Mesh mesh, int i)
{
// Can be overridden
}
/*
* Moves all nodes using a modified Laplacian smoothing.
*/
private void processAllNodes()
{
AbstractHalfEdge ot = null;
// Compute vertex quality
tree.clear();
for (Vertex v: nodeset)
{
if (immutableNodes.contains(v))
{
notProcessed++;
continue;
}
Triangle f = (Triangle) v.getLink();
ot = f.getAbstractHalfEdge(ot);
if (ot.destination() == v)
ot = ot.next();
else if (ot.apex() == v)
ot = ot.prev();
assert ot.origin() == v;
double qv = vertexQuality(ot);
if (qv <= tolerance)
tree.insert(v, qv);
}
// Now smooth nodes iteratively
while (!tree.isEmpty())
{
Iterator<QSortedTree.Node<Vertex>> itt = tree.iterator();
QSortedTree.Node<Vertex> q = itt.next();
if (q.getValue() > tolerance)
break;
Vertex v = q.getData();
assert !immutableNodes.contains(v);
tree.remove(v);
if (smoothNode(v, ot, q.getValue()))
{
processed++;
if (processed > 0 && (processed % progressBarStatus) == 0)
LOGGER.info("Vertices processed: "+processed);
if (!refresh)
continue;
assert ot != null;
// Update triangle quality
Vertex d = ot.destination();
do
{
ot = ot.nextOriginLoop();
if (ot.hasAttributes(AbstractHalfEdge.OUTER))
continue;
double qt = triangleQuality(ot);
qualityMap.put(ot.getTri(), qt);
}
while (ot.destination() != d);
// Update neighbor vertex quality
do
{
ot = ot.nextOriginLoop();
Vertex n = ot.destination();
if (n == mesh.outerVertex || !tree.contains(n))
continue;
if (ot.hasAttributes(AbstractHalfEdge.OUTER))
continue;
ot = ot.next();
double qv = vertexQuality(ot);
ot = ot.prev();
if (qv <= tolerance)
tree.update(n, qv);
else
{
tree.remove(n);
notProcessed++;
}
}
while (ot.destination() != d);
}
else
notProcessed++;
}
}
private boolean smoothNode(Vertex n, AbstractHalfEdge ot, double quality)
{
Triangle f = (Triangle) n.getLink();
ot = f.getAbstractHalfEdge(ot);
if (ot.destination() == n)
ot = ot.next();
else if (ot.apex() == n)
ot = ot.prev();
assert ot.origin() == n;
double [] oldp3 = n.getUV();
// Compute 3D coordinates centroid
int nn = 0;
double [] centroid3 = new double[3];
assert n.isManifold();
Vertex d = ot.destination();
do
{
ot = ot.nextOriginLoop();
Vertex v = ot.destination();
if (v != mesh.outerVertex)
{
nn++;
double l = n.distance3D(v);
double[] newp3 = v.getUV();
if (sizeTarget > 0.0)
{
- if (l > 1.0)
+ if (l > sizeTarget)
{
// Find the point on this edge which has the
// desired length
- l = sizeTarget / l;
+ double p = sizeTarget / l;
for (int i = 0; i < 3; i++)
- centroid3[i] += newp3[i] + l * (oldp3[i] - newp3[i]);
+ centroid3[i] += newp3[i] + p * (oldp3[i] - newp3[i]);
}
else
{
for (int i = 0; i < 3; i++)
- centroid3[i] += newp3[i];
+ centroid3[i] += oldp3[i];
}
}
else
{
for (int i = 0; i < 3; i++)
centroid3[i] += newp3[i];
}
}
}
while (ot.destination() != d);
assert (nn > 0);
for (int i = 0; i < 3; i++)
centroid3[i] /= nn;
for (int i = 0; i < 3; i++)
centroid3[i] = oldp3[i] + relaxation * (centroid3[i] - oldp3[i]);
double saveX = oldp3[0];
double saveY = oldp3[1];
double saveZ = oldp3[2];
if (!liaison.backupAndMove(n, centroid3))
{
LOGGER.finer("Point not moved, projection failed");
liaison.backupRestore(n, true);
return false;
}
// Temporarily reset n to its previous location, but do not
// modify liaison, this is not needed
System.arraycopy(n.getUV(), 0, centroid3, 0, 3);
n.moveTo(saveX, saveY, saveZ);
if (!mesh.canMoveOrigin(ot, centroid3))
{
liaison.backupRestore(n, true);
LOGGER.finer("Point not moved, some triangles would become inverted");
return false;
}
n.moveTo(centroid3[0], centroid3[1], centroid3[2]);
if (checkQuality)
{
// Check that quality has not been degraded
if (vertexQuality(ot) < quality)
{
n.moveTo(saveX, saveY, saveZ);
liaison.backupRestore(n, true);
LOGGER.finer("Point not moved, quality decreases");
return false;
}
}
liaison.backupRestore(n, false);
return true;
}
private double triangleQuality(AbstractHalfEdge edge)
{
Triangle f = edge.getTri();
assert f.vertex[0] != mesh.outerVertex && f.vertex[1] != mesh.outerVertex && f.vertex[2] != mesh.outerVertex : f;
double p = f.vertex[0].distance3D(f.vertex[1]) + f.vertex[1].distance3D(f.vertex[2]) + f.vertex[2].distance3D(f.vertex[0]);
double area = edge.area(mesh);
double ret = scaleFactor * area / p / p;
assert ret >= 0.0 && ret <= 1.01;
return ret;
}
private double vertexQuality(AbstractHalfEdge edge)
{
Vertex d = edge.destination();
double ret = Double.MAX_VALUE;
do
{
edge = edge.nextOriginLoop();
if (edge.hasAttributes(AbstractHalfEdge.OUTER))
continue;
assert qualityMap.containsKey(edge.getTri());
double qt = qualityMap.get(edge.getTri());
if (qt < ret)
ret = qt;
}
while (edge.destination() != d);
return ret;
}
private static void usage(int rc)
{
System.out.println("Usage: SmoothNodes3DBg [options] xmlDir outDir");
System.out.println("Options:");
System.out.println(" -h, --help Display this message and exit");
System.out.println(" --iterations <n> Iterate <n> times over all nodes");
System.out.println(" --size <s> Set target size");
System.out.println(" --tolerance <t> Consider only nodes with quality lower than <t>");
System.out.println(" --relaxation <r> Set relaxation factor");
System.out.println(" --refresh Update vertex quality before each iteration");
System.exit(rc);
}
/**
*
* @param args [options] xmlDir outDir
*/
public static void main(String[] args)
{
org.jcae.mesh.amibe.traits.MeshTraitsBuilder mtb = org.jcae.mesh.amibe.traits.MeshTraitsBuilder.getDefault3D();
mtb.addNodeList();
Mesh mesh = new Mesh(mtb);
Map<String, String> opts = new HashMap<String, String>();
int argc = 0;
for (String arg: args)
if (arg.equals("--help") || arg.equals("-h"))
usage(0);
while (argc < args.length-1)
{
if (args[argc].length() < 2 || args[argc].charAt(0) != '-' || args[argc].charAt(1) != '-')
break;
if (args[argc].equals("--refresh") || args[argc].equals("--boundaries"))
{
opts.put(args[argc].substring(2), "true");
argc++;
}
else
{
opts.put(args[argc].substring(2), args[argc+1]);
argc += 2;
}
}
if (argc + 2 != args.length)
usage(1);
try
{
MeshReader.readObject3D(mesh, args[argc]);
}
catch (IOException ex)
{
ex.printStackTrace();
throw new RuntimeException(ex);
}
SmoothNodes3DBg smoother = new SmoothNodes3DBg(mesh, opts);
smoother.compute();
try
{
MeshWriter.writeObject3D(smoother.getOutputMesh(), args[argc+1], null);
}
catch (IOException ex)
{
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
}
| false | true | private boolean smoothNode(Vertex n, AbstractHalfEdge ot, double quality)
{
Triangle f = (Triangle) n.getLink();
ot = f.getAbstractHalfEdge(ot);
if (ot.destination() == n)
ot = ot.next();
else if (ot.apex() == n)
ot = ot.prev();
assert ot.origin() == n;
double [] oldp3 = n.getUV();
// Compute 3D coordinates centroid
int nn = 0;
double [] centroid3 = new double[3];
assert n.isManifold();
Vertex d = ot.destination();
do
{
ot = ot.nextOriginLoop();
Vertex v = ot.destination();
if (v != mesh.outerVertex)
{
nn++;
double l = n.distance3D(v);
double[] newp3 = v.getUV();
if (sizeTarget > 0.0)
{
if (l > 1.0)
{
// Find the point on this edge which has the
// desired length
l = sizeTarget / l;
for (int i = 0; i < 3; i++)
centroid3[i] += newp3[i] + l * (oldp3[i] - newp3[i]);
}
else
{
for (int i = 0; i < 3; i++)
centroid3[i] += newp3[i];
}
}
else
{
for (int i = 0; i < 3; i++)
centroid3[i] += newp3[i];
}
}
}
while (ot.destination() != d);
assert (nn > 0);
for (int i = 0; i < 3; i++)
centroid3[i] /= nn;
for (int i = 0; i < 3; i++)
centroid3[i] = oldp3[i] + relaxation * (centroid3[i] - oldp3[i]);
double saveX = oldp3[0];
double saveY = oldp3[1];
double saveZ = oldp3[2];
if (!liaison.backupAndMove(n, centroid3))
{
LOGGER.finer("Point not moved, projection failed");
liaison.backupRestore(n, true);
return false;
}
// Temporarily reset n to its previous location, but do not
// modify liaison, this is not needed
System.arraycopy(n.getUV(), 0, centroid3, 0, 3);
n.moveTo(saveX, saveY, saveZ);
if (!mesh.canMoveOrigin(ot, centroid3))
{
liaison.backupRestore(n, true);
LOGGER.finer("Point not moved, some triangles would become inverted");
return false;
}
n.moveTo(centroid3[0], centroid3[1], centroid3[2]);
if (checkQuality)
{
// Check that quality has not been degraded
if (vertexQuality(ot) < quality)
{
n.moveTo(saveX, saveY, saveZ);
liaison.backupRestore(n, true);
LOGGER.finer("Point not moved, quality decreases");
return false;
}
}
liaison.backupRestore(n, false);
return true;
}
| private boolean smoothNode(Vertex n, AbstractHalfEdge ot, double quality)
{
Triangle f = (Triangle) n.getLink();
ot = f.getAbstractHalfEdge(ot);
if (ot.destination() == n)
ot = ot.next();
else if (ot.apex() == n)
ot = ot.prev();
assert ot.origin() == n;
double [] oldp3 = n.getUV();
// Compute 3D coordinates centroid
int nn = 0;
double [] centroid3 = new double[3];
assert n.isManifold();
Vertex d = ot.destination();
do
{
ot = ot.nextOriginLoop();
Vertex v = ot.destination();
if (v != mesh.outerVertex)
{
nn++;
double l = n.distance3D(v);
double[] newp3 = v.getUV();
if (sizeTarget > 0.0)
{
if (l > sizeTarget)
{
// Find the point on this edge which has the
// desired length
double p = sizeTarget / l;
for (int i = 0; i < 3; i++)
centroid3[i] += newp3[i] + p * (oldp3[i] - newp3[i]);
}
else
{
for (int i = 0; i < 3; i++)
centroid3[i] += oldp3[i];
}
}
else
{
for (int i = 0; i < 3; i++)
centroid3[i] += newp3[i];
}
}
}
while (ot.destination() != d);
assert (nn > 0);
for (int i = 0; i < 3; i++)
centroid3[i] /= nn;
for (int i = 0; i < 3; i++)
centroid3[i] = oldp3[i] + relaxation * (centroid3[i] - oldp3[i]);
double saveX = oldp3[0];
double saveY = oldp3[1];
double saveZ = oldp3[2];
if (!liaison.backupAndMove(n, centroid3))
{
LOGGER.finer("Point not moved, projection failed");
liaison.backupRestore(n, true);
return false;
}
// Temporarily reset n to its previous location, but do not
// modify liaison, this is not needed
System.arraycopy(n.getUV(), 0, centroid3, 0, 3);
n.moveTo(saveX, saveY, saveZ);
if (!mesh.canMoveOrigin(ot, centroid3))
{
liaison.backupRestore(n, true);
LOGGER.finer("Point not moved, some triangles would become inverted");
return false;
}
n.moveTo(centroid3[0], centroid3[1], centroid3[2]);
if (checkQuality)
{
// Check that quality has not been degraded
if (vertexQuality(ot) < quality)
{
n.moveTo(saveX, saveY, saveZ);
liaison.backupRestore(n, true);
LOGGER.finer("Point not moved, quality decreases");
return false;
}
}
liaison.backupRestore(n, false);
return true;
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.