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/src/main/java/org/jenkinsci/plugins/darcs/DarcsRevisionState.java b/src/main/java/org/jenkinsci/plugins/darcs/DarcsRevisionState.java
index 96a91ed..571dc9d 100644
--- a/src/main/java/org/jenkinsci/plugins/darcs/DarcsRevisionState.java
+++ b/src/main/java/org/jenkinsci/plugins/darcs/DarcsRevisionState.java
@@ -1,101 +1,101 @@
/*
* LICENSE
*
* "THE BEER-WARE LICENSE" (Revision 42):
* "Sven Strittmatter" <[email protected]> wrote this file.
* As long as you retain this notice you can do whatever you want with
* this stuff. If we meet some day, and you think this stuff is worth it,
* you can buy me a beer in return.
*/
package org.jenkinsci.plugins.darcs;
import hudson.scm.SCMRevisionState;
import java.util.List;
import java.util.ArrayList;
/**
*
* Feedback from mailing list:
* [email protected]:
* <quote>
* I think you would be better served by computing the sha1 or md5 of all the hashes as strings. Relying on Collections.hashCode is dangerous. Relying on String.hashCode, which is just:
*
* public int hashCode() {
* int h = hash;
* if (h == 0) {
* int off = offset;
* char val[] = value;
* int len = count;
*
* for (int i = 0; i < len; i++) {
* h = 31*h + val[off++];
* }
* hash = h;
* }
* return h;
* }
*
* Is going to be a tad weak given that all the characters are from the set [0-9a-f-] i.e. there are only 17 out of 255.
*
* The List.hashCode speci is
* public int hashCode() {
* int hashCode = 1;
* Iterator<E> i = iterator();
* while (i.hasNext()) {
* E obj = i.next();
* hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
* }
* return hashCode;
* }
*
* Also I would recommend sorting the lists before hashing them.
*
* However, if you are looking for a short path to saying there is a difference, the Collections.sort(list1); Collections.sort(list2); if (list1.hashCode() != list2.hashCode()) check should be OK...
*
* Just remember that list1.hashCode() == list2.hashCode() does not in anyway claim that there is no change, so you will have to go down the long path anyway.
* </quote>
*
* [email protected]:
* <quote>
* There's utility code in Jenkins that computes MD5 digest of arbitrary byte stream or string. I think that seems like a good and cheap enough hashing for this kind of purpose.
*
* Javadoc
* hudson.Util.getDigestOf()
* public static String getDigestOf(InputStream source)
* throws IOException
*
* Computes MD5 digest of the given input stream.
* </quote>
*
* @author Sven Strittmatter <[email protected]>
*/
public class DarcsRevisionState extends SCMRevisionState {
private DarcsChangeSetList changes;
public DarcsRevisionState(DarcsChangeSetList changes) {
super();
this.changes = changes;
}
public DarcsChangeSetList getChanges() {
return changes;
}
@Override
public String toString() {
return "<RevisionState: " + getChanges().digest() + ">";
}
@Override
public boolean equals(Object other) {
boolean result = false;
if (other instanceof DarcsRevisionState) {
DarcsRevisionState that = (DarcsRevisionState) other;
- return getChanges().equals(other.getClass());
+ return getChanges().equals(that.getChanges());
}
return result;
}
}
| true | true | public boolean equals(Object other) {
boolean result = false;
if (other instanceof DarcsRevisionState) {
DarcsRevisionState that = (DarcsRevisionState) other;
return getChanges().equals(other.getClass());
}
return result;
}
| public boolean equals(Object other) {
boolean result = false;
if (other instanceof DarcsRevisionState) {
DarcsRevisionState that = (DarcsRevisionState) other;
return getChanges().equals(that.getChanges());
}
return result;
}
|
diff --git a/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/editors/template/quickfix/AcceleoQuickFixProcessor.java b/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/editors/template/quickfix/AcceleoQuickFixProcessor.java
index 28003775..c19373c4 100644
--- a/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/editors/template/quickfix/AcceleoQuickFixProcessor.java
+++ b/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/editors/template/quickfix/AcceleoQuickFixProcessor.java
@@ -1,132 +1,133 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 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.internal.ide.ui.editors.template.quickfix;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
import org.eclipse.jface.text.quickassist.IQuickAssistProcessor;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.texteditor.MarkerAnnotation;
/**
* Acceleo correction processor used to show quick fixes for syntax problems.
*
* @author <a href="mailto:[email protected]">Jonathan Musset</a>
*/
public class AcceleoQuickFixProcessor implements IQuickAssistProcessor {
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.text.quickassist.IQuickAssistProcessor#canAssist(org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext)
*/
public boolean canAssist(IQuickAssistInvocationContext invocationContext) {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.text.quickassist.IQuickAssistProcessor#canFix(org.eclipse.jface.text.source.Annotation)
*/
public boolean canFix(Annotation annotation) {
return annotation != null
&& "org.eclipse.acceleo.ide.ui.annotation.problem".equals(annotation.getType()); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.text.quickassist.IQuickAssistProcessor#computeQuickAssistProposals(org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext)
*/
public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) {
List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
if (invocationContext != null) {
ISourceViewer sourceViewer = invocationContext.getSourceViewer();
int offset = invocationContext.getOffset();
List<Annotation> annotations = findAnnotationsAt(sourceViewer, offset);
for (Annotation annotation : annotations) {
collectMarkerProposals(annotation, proposals);
}
}
return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
/**
* Returns all the annotations at the given offset.
*
* @param sourceViewer
* is the source viewer
* @param offset
* is the offset
* @return all the annotations
*/
private List<Annotation> findAnnotationsAt(ISourceViewer sourceViewer, int offset) {
List<Annotation> annotations = new ArrayList<Annotation>();
if (sourceViewer != null && offset > -1) {
IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
if (annotationModel != null) {
for (Iterator<?> it = annotationModel.getAnnotationIterator(); it.hasNext();) {
Annotation annotation = (Annotation)it.next();
Position position = annotationModel.getPosition(annotation);
- if (offset >= position.offset && offset <= position.offset + position.length) {
+ if (position != null && offset >= position.offset
+ && offset <= position.offset + position.length) {
annotations.add(annotation);
}
}
}
}
return annotations;
}
/**
* Collect the quick fixes proposals for the given annotation.
*
* @param annotation
* is the annotation
* @param proposals
* are the proposals to create, it's an input/output parameter
*/
private static void collectMarkerProposals(Annotation annotation,
Collection<ICompletionProposal> proposals) {
if (annotation instanceof MarkerAnnotation) {
IMarker marker = ((MarkerAnnotation)annotation).getMarker();
if (marker != null) {
IMarkerResolution[] res = IDE.getMarkerHelpRegistry().getResolutions(marker);
if (res != null && res.length > 0) {
for (int i = 0; i < res.length; i++) {
proposals.add(new ProblemMarkerResolutionProposal(res[i], marker));
}
}
}
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.text.quickassist.IQuickAssistProcessor#getErrorMessage()
*/
public String getErrorMessage() {
return null;
}
}
| true | true | private List<Annotation> findAnnotationsAt(ISourceViewer sourceViewer, int offset) {
List<Annotation> annotations = new ArrayList<Annotation>();
if (sourceViewer != null && offset > -1) {
IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
if (annotationModel != null) {
for (Iterator<?> it = annotationModel.getAnnotationIterator(); it.hasNext();) {
Annotation annotation = (Annotation)it.next();
Position position = annotationModel.getPosition(annotation);
if (offset >= position.offset && offset <= position.offset + position.length) {
annotations.add(annotation);
}
}
}
}
return annotations;
}
| private List<Annotation> findAnnotationsAt(ISourceViewer sourceViewer, int offset) {
List<Annotation> annotations = new ArrayList<Annotation>();
if (sourceViewer != null && offset > -1) {
IAnnotationModel annotationModel = sourceViewer.getAnnotationModel();
if (annotationModel != null) {
for (Iterator<?> it = annotationModel.getAnnotationIterator(); it.hasNext();) {
Annotation annotation = (Annotation)it.next();
Position position = annotationModel.getPosition(annotation);
if (position != null && offset >= position.offset
&& offset <= position.offset + position.length) {
annotations.add(annotation);
}
}
}
}
return annotations;
}
|
diff --git a/tapestry-framework/src/java/org/apache/tapestry/dojo/form/Autocompleter.java b/tapestry-framework/src/java/org/apache/tapestry/dojo/form/Autocompleter.java
index b553c183c..e910a367e 100644
--- a/tapestry-framework/src/java/org/apache/tapestry/dojo/form/Autocompleter.java
+++ b/tapestry-framework/src/java/org/apache/tapestry/dojo/form/Autocompleter.java
@@ -1,262 +1,264 @@
// Copyright May 4, 2006 The Apache Software Foundation
//
// 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.apache.tapestry.dojo.form;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.tapestry.IDirect;
import org.apache.tapestry.IJSONRender;
import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.IScript;
import org.apache.tapestry.PageRenderSupport;
import org.apache.tapestry.Tapestry;
import org.apache.tapestry.TapestryUtils;
import org.apache.tapestry.engine.DirectServiceParameter;
import org.apache.tapestry.engine.IEngineService;
import org.apache.tapestry.engine.ILink;
import org.apache.tapestry.form.ValidatableField;
import org.apache.tapestry.form.ValidatableFieldSupport;
import org.apache.tapestry.json.IJSONWriter;
import org.apache.tapestry.json.JSONObject;
import org.apache.tapestry.services.DataSqueezer;
import org.apache.tapestry.valid.ValidatorException;
/**
* An html field similar to a <code>select</code> input field that
* is wrapped by a dojo ComboBox widget.
*
* This component uses the {@link IAutocompleteModel} to retrieve and match against
* selected values.
*
* @author jkuhnert
*/
public abstract class Autocompleter extends AbstractFormWidget
implements ValidatableField, IJSONRender, IDirect
{
// mode, can be remote or local (local being from html rendered option elements)
private static final String MODE_REMOTE = "remote";
/**
*
* {@inheritDoc}
*/
protected void renderFormWidget(IMarkupWriter writer, IRequestCycle cycle)
{
renderDelegatePrefix(writer, cycle);
writer.begin("select");
writer.attribute("name", getName());
if (isDisabled())
writer.attribute("disabled", "disabled");
renderIdAttribute(writer, cycle);
renderDelegateAttributes(writer, cycle);
getValidatableFieldSupport().renderContributions(this, writer, cycle);
// Apply informal attributes.
renderInformalParameters(writer, cycle);
writer.end();
renderDelegateSuffix(writer, cycle);
ILink link = getDirectService().getLink(true, new DirectServiceParameter(this));
Map parms = new HashMap();
parms.put("id", getClientId());
JSONObject json = new JSONObject();
json.put("dataUrl", link.getURL() + "&filter=%{searchString}");
json.put("mode", MODE_REMOTE);
json.put("widgetId", getName());
json.put("name", getName());
+ json.put("searchDelay", getSearchDelay());
+ json.put("fadeTime", getFadeTime());
IAutocompleteModel model = getModel();
if (model == null)
throw Tapestry.createRequiredParameterException(this, "model");
Object value = getValue();
Object key = value != null ? model.getPrimaryKey(value) : null;
if (value != null && key != null) {
json.put("value", getDataSqueezer().squeeze(key));
json.put("label", model.getLabelFor(value));
}
parms.put("props", json.toString());
parms.put("form", getForm().getName());
PageRenderSupport prs = TapestryUtils.getPageRenderSupport(cycle, this);
getScript().execute(this, cycle, prs, parms);
}
/**
* {@inheritDoc}
*/
public void renderComponent(IJSONWriter writer, IRequestCycle cycle)
{
IAutocompleteModel model = getModel();
if (model == null)
throw Tapestry.createRequiredParameterException(this, "model");
Map filteredValues = model.filterValues(getFilter());
if (filteredValues == null)
return;
Iterator it = filteredValues.keySet().iterator();
Object key = null;
while (it.hasNext()) {
key = it.next();
writer.put(getDataSqueezer().squeeze(key), filteredValues.get(key));
}
}
/**
* @see org.apache.tapestry.form.AbstractFormComponent#rewindFormComponent(org.apache.tapestry.IMarkupWriter, org.apache.tapestry.IRequestCycle)
*/
protected void rewindFormWidget(IMarkupWriter writer, IRequestCycle cycle)
{
String value = cycle.getParameter(getName());
Object object = getModel().getValue(getDataSqueezer().unsqueeze(value));
try
{
getValidatableFieldSupport().validate(this, writer, cycle, object);
setValue(object);
}
catch (ValidatorException e)
{
getForm().getDelegate().record(e);
}
}
/**
* {@inheritDoc}
*/
public boolean isStateful()
{
return true;
}
/**
* Triggerd by using filterOnChange logic.
*
* {@inheritDoc}
*/
public void trigger(IRequestCycle cycle)
{
setFilter(cycle.getParameter("filter"));
}
public abstract IAutocompleteModel getModel();
/** @since 4.1 */
public abstract boolean isFilterOnChange();
/** whether or not to autocomplete the input text. */
public abstract boolean isAutocomplete();
/** How long to wait(in ms) before searching after input is received. */
public abstract int getSearchDelay();
/** The duration(in ms) of the fade effect of list going away. */
public abstract int getFadeTime();
/** The maximum number of items displayed in select list before the scrollbar is activated. */
public abstract int getMaxListLength();
/** @since 2.2 * */
public abstract Object getValue();
/** @since 2.2 * */
public abstract void setValue(Object value);
/** @since 4.1 */
public abstract void setFilter(String value);
/** @since 4.1 */
public abstract String getFilter();
/** Injected. */
public abstract DataSqueezer getDataSqueezer();
/**
* Injected.
*/
public abstract ValidatableFieldSupport getValidatableFieldSupport();
/**
* Injected.
* @return
*/
public abstract IEngineService getDirectService();
/**
* Injected.
* @return
*/
public abstract IScript getScript();
/**
* @see org.apache.tapestry.form.AbstractFormComponent#isRequired()
*/
public boolean isRequired()
{
return getValidatableFieldSupport().isRequired(this);
}
/**
* {@inheritDoc}
*/
public Collection getUpdateComponents()
{
List comps = new ArrayList();
comps.add(getId());
return comps;
}
/**
* {@inheritDoc}
*/
public boolean isAsync()
{
return Boolean.TRUE;
}
/**
* {@inheritDoc}
*/
public boolean isJson()
{
return Boolean.TRUE;
}
}
| true | true | protected void renderFormWidget(IMarkupWriter writer, IRequestCycle cycle)
{
renderDelegatePrefix(writer, cycle);
writer.begin("select");
writer.attribute("name", getName());
if (isDisabled())
writer.attribute("disabled", "disabled");
renderIdAttribute(writer, cycle);
renderDelegateAttributes(writer, cycle);
getValidatableFieldSupport().renderContributions(this, writer, cycle);
// Apply informal attributes.
renderInformalParameters(writer, cycle);
writer.end();
renderDelegateSuffix(writer, cycle);
ILink link = getDirectService().getLink(true, new DirectServiceParameter(this));
Map parms = new HashMap();
parms.put("id", getClientId());
JSONObject json = new JSONObject();
json.put("dataUrl", link.getURL() + "&filter=%{searchString}");
json.put("mode", MODE_REMOTE);
json.put("widgetId", getName());
json.put("name", getName());
IAutocompleteModel model = getModel();
if (model == null)
throw Tapestry.createRequiredParameterException(this, "model");
Object value = getValue();
Object key = value != null ? model.getPrimaryKey(value) : null;
if (value != null && key != null) {
json.put("value", getDataSqueezer().squeeze(key));
json.put("label", model.getLabelFor(value));
}
parms.put("props", json.toString());
parms.put("form", getForm().getName());
PageRenderSupport prs = TapestryUtils.getPageRenderSupport(cycle, this);
getScript().execute(this, cycle, prs, parms);
}
| protected void renderFormWidget(IMarkupWriter writer, IRequestCycle cycle)
{
renderDelegatePrefix(writer, cycle);
writer.begin("select");
writer.attribute("name", getName());
if (isDisabled())
writer.attribute("disabled", "disabled");
renderIdAttribute(writer, cycle);
renderDelegateAttributes(writer, cycle);
getValidatableFieldSupport().renderContributions(this, writer, cycle);
// Apply informal attributes.
renderInformalParameters(writer, cycle);
writer.end();
renderDelegateSuffix(writer, cycle);
ILink link = getDirectService().getLink(true, new DirectServiceParameter(this));
Map parms = new HashMap();
parms.put("id", getClientId());
JSONObject json = new JSONObject();
json.put("dataUrl", link.getURL() + "&filter=%{searchString}");
json.put("mode", MODE_REMOTE);
json.put("widgetId", getName());
json.put("name", getName());
json.put("searchDelay", getSearchDelay());
json.put("fadeTime", getFadeTime());
IAutocompleteModel model = getModel();
if (model == null)
throw Tapestry.createRequiredParameterException(this, "model");
Object value = getValue();
Object key = value != null ? model.getPrimaryKey(value) : null;
if (value != null && key != null) {
json.put("value", getDataSqueezer().squeeze(key));
json.put("label", model.getLabelFor(value));
}
parms.put("props", json.toString());
parms.put("form", getForm().getName());
PageRenderSupport prs = TapestryUtils.getPageRenderSupport(cycle, this);
getScript().execute(this, cycle, prs, parms);
}
|
diff --git a/src/main/java/org/kercheval/gradle/buildversion/BuildVersionTagTask.java b/src/main/java/org/kercheval/gradle/buildversion/BuildVersionTagTask.java
index 076cc64..6fa4cc9 100644
--- a/src/main/java/org/kercheval/gradle/buildversion/BuildVersionTagTask.java
+++ b/src/main/java/org/kercheval/gradle/buildversion/BuildVersionTagTask.java
@@ -1,120 +1,120 @@
package org.kercheval.gradle.buildversion;
import java.io.File;
import java.util.Map;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.TaskExecutionException;
import org.kercheval.gradle.vcs.IVCSAccess;
import org.kercheval.gradle.vcs.VCSAccessFactory;
import org.kercheval.gradle.vcs.VCSException;
import org.kercheval.gradle.vcs.VCSStatus;
import org.kercheval.gradle.vcs.VCSTag;
public class BuildVersionTagTask
extends DefaultTask
{
public static final String DEFAULT_COMMENT = "Tag created by "
+ BuildVersionPlugin.TAG_TASK_NAME;
public static final boolean DEFAULT_ONLYIFCLEAN = true;
//
// The comment is set to a string that will be placed in the comment
// of the tag written to VCS
//
private String comment = DEFAULT_COMMENT;
//
// if onlyifclean is true, then tags are only written to the VCS system
// if the workspace is clean (no files checked out or modified). This
// will prevent tagging based on old commits or build releases that are not
// replicable.
//
private boolean onlyifclean = DEFAULT_ONLYIFCLEAN;
public BuildVersionTagTask()
{
dependsOn(":" + BuildVersionPlugin.MAIN_TASK_NAME);
}
@TaskAction
public void doTask()
{
if (getProject().getVersion() instanceof BuildVersion)
{
final Map<String, ?> props = getProject().getProperties();
final IVCSAccess vcs = VCSAccessFactory.getCurrentVCS((File) props.get("rootDir"),
getProject().getLogger());
if (isOnlyifclean())
{
//
// Tags should be written only if the workspace is clean.
//
VCSStatus status;
try
{
status = vcs.getStatus();
}
catch (final VCSException e)
{
throw new TaskExecutionException(this, e);
}
if (!status.isClean())
{
throw new TaskExecutionException(
this,
new IllegalStateException(
"The current workspace is not clean. Please ensure you have committed all outstanding work."));
}
}
//
// Write a tag into VCS using the current project version
//
try
{
final VCSTag tag = new VCSTag(getProject().getVersion().toString(), getComment());
vcs.createTag(tag);
getProject().getLogger().info(
"Tag '" + tag.getName() + "' written to VCS with comment '" + tag.getComment()
+ "'");
}
catch (final VCSException e)
{
throw new TaskExecutionException(this, e);
}
}
else
{
throw new TaskExecutionException(
this,
new IllegalStateException(
- "Project version is not of type BuildVersion: ensure buildversion task has been run or set project version to an object of type BuildVersion."));
+ "Project version is not of type BuildVersion: ensure buildversion type task has been run or set project version to an object of type BuildVersion."));
}
}
public String getComment()
{
return comment;
}
public boolean isOnlyifclean()
{
return onlyifclean;
}
public void setComment(final String comment)
{
this.comment = comment;
}
public void setOnlyifclean(final boolean onlyifclean)
{
this.onlyifclean = onlyifclean;
}
}
| true | true | public void doTask()
{
if (getProject().getVersion() instanceof BuildVersion)
{
final Map<String, ?> props = getProject().getProperties();
final IVCSAccess vcs = VCSAccessFactory.getCurrentVCS((File) props.get("rootDir"),
getProject().getLogger());
if (isOnlyifclean())
{
//
// Tags should be written only if the workspace is clean.
//
VCSStatus status;
try
{
status = vcs.getStatus();
}
catch (final VCSException e)
{
throw new TaskExecutionException(this, e);
}
if (!status.isClean())
{
throw new TaskExecutionException(
this,
new IllegalStateException(
"The current workspace is not clean. Please ensure you have committed all outstanding work."));
}
}
//
// Write a tag into VCS using the current project version
//
try
{
final VCSTag tag = new VCSTag(getProject().getVersion().toString(), getComment());
vcs.createTag(tag);
getProject().getLogger().info(
"Tag '" + tag.getName() + "' written to VCS with comment '" + tag.getComment()
+ "'");
}
catch (final VCSException e)
{
throw new TaskExecutionException(this, e);
}
}
else
{
throw new TaskExecutionException(
this,
new IllegalStateException(
"Project version is not of type BuildVersion: ensure buildversion task has been run or set project version to an object of type BuildVersion."));
}
}
| public void doTask()
{
if (getProject().getVersion() instanceof BuildVersion)
{
final Map<String, ?> props = getProject().getProperties();
final IVCSAccess vcs = VCSAccessFactory.getCurrentVCS((File) props.get("rootDir"),
getProject().getLogger());
if (isOnlyifclean())
{
//
// Tags should be written only if the workspace is clean.
//
VCSStatus status;
try
{
status = vcs.getStatus();
}
catch (final VCSException e)
{
throw new TaskExecutionException(this, e);
}
if (!status.isClean())
{
throw new TaskExecutionException(
this,
new IllegalStateException(
"The current workspace is not clean. Please ensure you have committed all outstanding work."));
}
}
//
// Write a tag into VCS using the current project version
//
try
{
final VCSTag tag = new VCSTag(getProject().getVersion().toString(), getComment());
vcs.createTag(tag);
getProject().getLogger().info(
"Tag '" + tag.getName() + "' written to VCS with comment '" + tag.getComment()
+ "'");
}
catch (final VCSException e)
{
throw new TaskExecutionException(this, e);
}
}
else
{
throw new TaskExecutionException(
this,
new IllegalStateException(
"Project version is not of type BuildVersion: ensure buildversion type task has been run or set project version to an object of type BuildVersion."));
}
}
|
diff --git a/bundles/org.eclipse.wst.xsl.debug.ui/src/org/eclipse/wst/xsl/internal/debug/ui/XSLLaunchShortcut.java b/bundles/org.eclipse.wst.xsl.debug.ui/src/org/eclipse/wst/xsl/internal/debug/ui/XSLLaunchShortcut.java
index 0ddb436..a852d7a 100644
--- a/bundles/org.eclipse.wst.xsl.debug.ui/src/org/eclipse/wst/xsl/internal/debug/ui/XSLLaunchShortcut.java
+++ b/bundles/org.eclipse.wst.xsl.debug.ui/src/org/eclipse/wst/xsl/internal/debug/ui/XSLLaunchShortcut.java
@@ -1,441 +1,442 @@
/*******************************************************************************
* Copyright (c) 2007, 2013 Chase Technology Ltd - http://www.chasetechnology.co.uk
* 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:
* Doug Satchwell (Chase Technology Ltd) - initial API and implementation
* Jesper Steen Moller - Bug 404956: Launching an XML file as 'XSL Transformation' doesn't transform anything
*******************************************************************************/
package org.eclipse.wst.xsl.internal.debug.ui;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.variables.VariablesPlugin;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.debug.ui.IDebugModelPresentation;
import org.eclipse.debug.ui.ILaunchShortcut;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.wst.xsl.core.XSLCore;
import org.eclipse.wst.xsl.internal.debug.ui.tabs.main.InputFileBlock;
import org.eclipse.wst.xsl.internal.debug.ui.tabs.main.TransformsBlock;
import org.eclipse.wst.xsl.launching.XSLLaunchConfigurationConstants;
import org.eclipse.wst.xsl.launching.config.BaseLaunchHelper;
import org.eclipse.wst.xsl.launching.config.LaunchPipeline;
import org.eclipse.wst.xsl.launching.config.LaunchTransform;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* <table border=1>
* <th>
* <tr>
* <td>XML Files</td>
* <td>XSL Files</td>
* <td>Action</td>
* </tr>
* </th>
* <tbody>
* <tr>
* <td>1</td>
* <td>0</td>
* <td>Launch assuming embedded stylesheet instruction</td>
* </tr>
* <tr>
* <td>0</td>
* <td>>=1</td>
* <td>Open dialog - prompt for input file</td>
* </tr>
* <tr>
* <td>1</td>
* <td>>=1</td>
* <td>Launch</td>
* </tr>
* </tbody>
* </table>
*
* <p>
* The launch shortcut should not appear in the menu for any other combination
* of files
* </p>
* <p>
* In all cases, a check must be performed to find any existing launch
* configuration that uses the selected files.
* </p>
*
* @author Doug
* @since 1.0
*/
public class XSLLaunchShortcut implements ILaunchShortcut {
private static final String XML_STYLESHEET_PI = "xml-stylesheet"; //$NON-NLS-1$
private IFile xmlFile;
private IPath xmlFilePath;
private IFile[] xslFiles;
private String xslFilePath; // always an external path
private LaunchPipeline pipeline;
public void launch(ISelection selection, String mode) {
if (selection instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) selection;
searchAndLaunch(ssel.toArray(), mode);
}
}
public void launch(IEditorPart editor, String mode) {
IEditorInput input = editor.getEditorInput();
if (input != null) {
IFile file = (IFile) input.getAdapter(IFile.class);
if (file != null)
searchAndLaunch(new Object[] { file }, mode);
}
}
private void searchAndLaunch(Object[] objects, String mode) {
if (fillFiles(objects)) {
// ensure we have an input file
if (xmlFile == null) {
promptForInput();
}
if (xslFiles == null || xslFiles.length == 0 && xslFilePath == null) {
promptForStylesheet();
}
if (xmlFile != null || xmlFilePath != null)
launch(mode);
}
}
private void promptForInput() {
// prompt for input xml file
StatusDialog dialog = new StatusDialog(getShell()) {
private InputFileBlock inputFileBlock = new InputFileBlock(null);
@Override
protected Control createDialogArea(Composite parent) {
Composite comp = (Composite) super.createDialogArea(parent);
comp.setFont(parent.getFont());
GridLayout layout = new GridLayout(1, false);
comp.setLayout(layout);
Label label = new Label(comp, SWT.NONE);
label.setFont(comp.getFont());
GridData gd = new GridData();
gd.horizontalIndent = 5;
gd.verticalIndent = 5;
gd.widthHint = 380;
label.setLayoutData(gd);
label.setText(Messages.XSLLaunchShortcut_0);
inputFileBlock.createControl(comp);
return comp;
}
@Override
protected void okPressed() {
saveSelectedXmlFile();
super.okPressed();
}
private void saveSelectedXmlFile() {
IResource res = inputFileBlock.getResource();
if (res == null)
xmlFilePath = new Path(inputFileBlock.getText());
else if (ResourcesPlugin.getWorkspace().getRoot().exists(
res.getFullPath())
&& res.getType() == IResource.FILE)
xmlFile = (IFile) res;
}
};
dialog.setHelpAvailable(false);
dialog.setStatusLineAboveButtons(true);
dialog.setTitle(Messages.XSLLaunchShortcut_1);
dialog.open();
}
private void promptForStylesheet() {
// prompt for input xml file
final LaunchPipeline promptedPipeline = new LaunchPipeline();
StatusDialog dialog = new StatusDialog(getShell()) {
private TransformsBlock transformsBlock = new TransformsBlock();
@Override
protected Control createDialogArea(Composite parent) {
Composite comp = (Composite) super.createDialogArea(parent);
comp.setFont(parent.getFont());
GridLayout layout = new GridLayout(1, false);
comp.setLayout(layout);
Label label = new Label(comp, SWT.NONE);
label.setFont(comp.getFont());
GridData gd = new GridData();
gd.horizontalIndent = 5;
gd.verticalIndent = 5;
gd.widthHint = 380;
label.setLayoutData(gd);
label.setText(Messages.XSLLaunchShortcut_7);
promptedPipeline.setTransformDefs(new ArrayList<LaunchTransform>());
transformsBlock.setPipeline(promptedPipeline);
transformsBlock.createControl(comp);
transformsBlock.initializeFrom(null);
return comp;
}
@Override
protected void okPressed() {
savePipeline();
super.okPressed();
}
private void savePipeline() {
pipeline = promptedPipeline;
}
};
dialog.setHelpAvailable(false);
dialog.setStatusLineAboveButtons(true);
dialog.setTitle(Messages.XSLLaunchShortcut_1);
dialog.open();
}
private boolean fillFiles(Object[] selections) {
xmlFile = null;
xmlFilePath = null;
List<IFile> xslFileList = new ArrayList<IFile>();
xslFilePath = null;
for (Object object : selections) {
IResource resource = (IResource) object;
if (resource.getType() == IResource.FILE) {
IFile file = (IFile) resource;
if (XSLCore.isXMLFile(file)) {
if (XSLCore.isXSLFile(file))
xslFileList.add(file);
else if (xmlFile == null)
xmlFile = file;
else
return false; // no action if we have more than than 1
// xml file
}
}
}
if (xslFileList.isEmpty() && xmlFile != null) {
// Could it be we have a directive in the file, near the top
// <?xml-stylesheet type="text/xsl" href="test1.xsl"?>
+ // For details, see: http://www.w3.org/TR/xml-stylesheet/#the-xml-stylesheet-processing-instruction
XMLProcessingInstructionSniffer sniffer = new XMLProcessingInstructionSniffer();
try {
sniffer.parseContents(new InputSource(xmlFile.getContents()));
List<Map<String, String>> instructions = sniffer.getProcessingInstructions(XML_STYLESHEET_PI);
if (instructions != null) {
for (Map<String, String> attrs : instructions) {
String alternative = attrs.get("alternative"); //$NON-NLS-1$
if (alternative != null && alternative.equalsIgnoreCase("yes")) continue; //$NON-NLS-1$
String href = attrs.get("href"); //$NON-NLS-1$
if (href == null) continue;
// This is the one, now compute the path
if (new URI(href).isAbsolute()) {
xslFilePath = href;
} else {
xslFileList.add(xmlFile.getProject().getFile(xmlFile.getParent().getProjectRelativePath().append(href)));
}
}
}
} catch (IOException e) {
// ignored
} catch (ParserConfigurationException e) {
// ignored
} catch (SAXException e) {
// ignored
} catch (CoreException e) {
// ignored
} catch (URISyntaxException e) {
// ignored
}
}
xslFiles = xslFileList.toArray(new IFile[0]);
return true;
}
private void launch(String mode) {
if (xmlFile != null)
xmlFilePath = xmlFile.getLocation();
ILaunchConfiguration config = null;
try {
config = findOrCreateLaunchConfiguration();
if (config != null)
DebugUITools.launch(config, mode);
} catch (CoreException e) {
XSLDebugUIPlugin.log(e);
}
}
protected ILaunchManager getLaunchManager() {
return DebugPlugin.getDefault().getLaunchManager();
}
protected ILaunchConfigurationType getConfigurationType() {
return getLaunchManager().getLaunchConfigurationType(
XSLLaunchConfigurationConstants.ID_LAUNCH_CONFIG_TYPE);
}
private ILaunchConfiguration findOrCreateLaunchConfiguration()
throws CoreException {
ILaunchConfiguration[] configs = getLaunchManager()
.getLaunchConfigurations(getConfigurationType());
List<ILaunchConfiguration> candidateConfigs = new ArrayList<ILaunchConfiguration>(
configs.length);
for (ILaunchConfiguration config : configs) {
String inputFile = config.getAttribute(
XSLLaunchConfigurationConstants.ATTR_INPUT_FILE,
(String) null);
try {
inputFile = VariablesPlugin.getDefault()
.getStringVariableManager().performStringSubstitution(
inputFile);
} catch (CoreException e) {
// just ignore this one
continue;
}
Path path = new Path(inputFile);
// the source xml file must be the same
if (path.equals(xmlFilePath)) {
BaseLaunchHelper lh = new BaseLaunchHelper(config);
// all the selected stylesheets must be in the pipeline
boolean found = false;
for (IFile stylesheet : xslFiles) {
found = false;
for (Iterator<LaunchTransform> iter = lh.getPipeline()
.getTransformDefs().iterator(); iter.hasNext();) {
LaunchTransform lt = iter.next();
if (lt.getLocation().equals(stylesheet.getLocation())) {
found = true;
break;
}
}
if (!found)
break;
}
if (found)
candidateConfigs.add(config);
}
}
ILaunchConfiguration config = null;
int candidateCount = candidateConfigs.size();
if (candidateCount == 1)
config = candidateConfigs.get(0);
else if (candidateCount > 1)
config = chooseConfiguration(candidateConfigs);
else
config = createConfiguration();
return config;
}
private ILaunchConfiguration chooseConfiguration(
List<ILaunchConfiguration> configList) {
IDebugModelPresentation labelProvider = DebugUITools
.newDebugModelPresentation();
ElementListSelectionDialog dialog = new ElementListSelectionDialog(
getShell(), labelProvider);
dialog.setElements(configList.toArray());
dialog.setTitle(Messages.XSLLaunchShortcut_2);
dialog.setMessage(Messages.XSLSelectExisting);
dialog.setMultipleSelection(false);
int result = dialog.open();
labelProvider.dispose();
if (result == Window.OK) {
return (ILaunchConfiguration) dialog.getFirstResult();
}
return null;
}
private ILaunchConfiguration createConfiguration() {
ILaunchConfiguration config = null;
try {
ILaunchConfigurationType configType = getConfigurationType();
ILaunchConfigurationWorkingCopy wc = configType.newInstance(null,
getLaunchManager()
.generateUniqueLaunchConfigurationNameFrom(
xmlFilePath.lastSegment()));
if (xmlFile != null)
wc
.setAttribute(
XSLLaunchConfigurationConstants.ATTR_INPUT_FILE,
"${workspace_loc:" + xmlFile.getFullPath().toPortableString() + "}"); //$NON-NLS-1$ //$NON-NLS-2$
else
wc.setAttribute(
XSLLaunchConfigurationConstants.ATTR_INPUT_FILE,
xmlFilePath.toPortableString());
wc
.setAttribute(
XSLLaunchConfigurationConstants.ATTR_USE_DEFAULT_OUTPUT_FILE,
true);
wc.setAttribute(XSLLaunchConfigurationConstants.ATTR_OPEN_FILE,
true);
if (pipeline == null) pipeline = new LaunchPipeline();
for (IFile element : xslFiles) {
pipeline.addTransformDef(new LaunchTransform(element
.getFullPath().toPortableString(),
LaunchTransform.RESOURCE_TYPE));
}
if (xslFilePath != null) {
pipeline.addTransformDef(new LaunchTransform(xslFilePath,
LaunchTransform.EXTERNAL_TYPE));
}
wc.setAttribute(XSLLaunchConfigurationConstants.ATTR_PIPELINE,
pipeline.toXML());
if (xmlFile != null)
wc.setMappedResources(new IResource[] { xmlFile.getProject() });
config = wc.doSave();
} catch (CoreException exception) {
MessageDialog.openError(getShell(), Messages.XSLLaunchShortcut_6,
exception.getStatus().getMessage());
}
return config;
}
protected Shell getShell() {
return XSLDebugUIPlugin.getActiveWorkbenchShell();
}
}
| true | true | private boolean fillFiles(Object[] selections) {
xmlFile = null;
xmlFilePath = null;
List<IFile> xslFileList = new ArrayList<IFile>();
xslFilePath = null;
for (Object object : selections) {
IResource resource = (IResource) object;
if (resource.getType() == IResource.FILE) {
IFile file = (IFile) resource;
if (XSLCore.isXMLFile(file)) {
if (XSLCore.isXSLFile(file))
xslFileList.add(file);
else if (xmlFile == null)
xmlFile = file;
else
return false; // no action if we have more than than 1
// xml file
}
}
}
if (xslFileList.isEmpty() && xmlFile != null) {
// Could it be we have a directive in the file, near the top
// <?xml-stylesheet type="text/xsl" href="test1.xsl"?>
XMLProcessingInstructionSniffer sniffer = new XMLProcessingInstructionSniffer();
try {
sniffer.parseContents(new InputSource(xmlFile.getContents()));
List<Map<String, String>> instructions = sniffer.getProcessingInstructions(XML_STYLESHEET_PI);
if (instructions != null) {
for (Map<String, String> attrs : instructions) {
String alternative = attrs.get("alternative"); //$NON-NLS-1$
if (alternative != null && alternative.equalsIgnoreCase("yes")) continue; //$NON-NLS-1$
String href = attrs.get("href"); //$NON-NLS-1$
if (href == null) continue;
// This is the one, now compute the path
if (new URI(href).isAbsolute()) {
xslFilePath = href;
} else {
xslFileList.add(xmlFile.getProject().getFile(xmlFile.getParent().getProjectRelativePath().append(href)));
}
}
}
} catch (IOException e) {
// ignored
} catch (ParserConfigurationException e) {
// ignored
} catch (SAXException e) {
// ignored
} catch (CoreException e) {
// ignored
} catch (URISyntaxException e) {
// ignored
}
}
xslFiles = xslFileList.toArray(new IFile[0]);
return true;
}
| private boolean fillFiles(Object[] selections) {
xmlFile = null;
xmlFilePath = null;
List<IFile> xslFileList = new ArrayList<IFile>();
xslFilePath = null;
for (Object object : selections) {
IResource resource = (IResource) object;
if (resource.getType() == IResource.FILE) {
IFile file = (IFile) resource;
if (XSLCore.isXMLFile(file)) {
if (XSLCore.isXSLFile(file))
xslFileList.add(file);
else if (xmlFile == null)
xmlFile = file;
else
return false; // no action if we have more than than 1
// xml file
}
}
}
if (xslFileList.isEmpty() && xmlFile != null) {
// Could it be we have a directive in the file, near the top
// <?xml-stylesheet type="text/xsl" href="test1.xsl"?>
// For details, see: http://www.w3.org/TR/xml-stylesheet/#the-xml-stylesheet-processing-instruction
XMLProcessingInstructionSniffer sniffer = new XMLProcessingInstructionSniffer();
try {
sniffer.parseContents(new InputSource(xmlFile.getContents()));
List<Map<String, String>> instructions = sniffer.getProcessingInstructions(XML_STYLESHEET_PI);
if (instructions != null) {
for (Map<String, String> attrs : instructions) {
String alternative = attrs.get("alternative"); //$NON-NLS-1$
if (alternative != null && alternative.equalsIgnoreCase("yes")) continue; //$NON-NLS-1$
String href = attrs.get("href"); //$NON-NLS-1$
if (href == null) continue;
// This is the one, now compute the path
if (new URI(href).isAbsolute()) {
xslFilePath = href;
} else {
xslFileList.add(xmlFile.getProject().getFile(xmlFile.getParent().getProjectRelativePath().append(href)));
}
}
}
} catch (IOException e) {
// ignored
} catch (ParserConfigurationException e) {
// ignored
} catch (SAXException e) {
// ignored
} catch (CoreException e) {
// ignored
} catch (URISyntaxException e) {
// ignored
}
}
xslFiles = xslFileList.toArray(new IFile[0]);
return true;
}
|
diff --git a/src/main/java/com/dianping/wizard/widget/interceptor/MergeInterceptor.java b/src/main/java/com/dianping/wizard/widget/interceptor/MergeInterceptor.java
index 9aa1f0b..e4f5e0e 100644
--- a/src/main/java/com/dianping/wizard/widget/interceptor/MergeInterceptor.java
+++ b/src/main/java/com/dianping/wizard/widget/interceptor/MergeInterceptor.java
@@ -1,79 +1,80 @@
package com.dianping.wizard.widget.interceptor;
import com.dianping.wizard.config.Configuration;
import com.dianping.wizard.exception.WidgetException;
import com.dianping.wizard.widget.InvocationContext;
import com.dianping.wizard.widget.Mode;
import com.dianping.wizard.widget.Widget;
import com.dianping.wizard.widget.merger.FreemarkerMerger;
import com.dianping.wizard.widget.merger.Merger;
import com.dianping.wizard.widget.merger.Template;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateHashModel;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: ltebean
* Date: 13-4-24
* Time: 上午9:13
* To change this template use File | Settings | File Templates.
*/
public class MergeInterceptor implements Interceptor {
private final Map<String, Object> staticModels = new HashMap<String, Object>();
private final Merger merger = FreemarkerMerger.getInstance();
public MergeInterceptor() {
List<String> modelList = Configuration.get("freemarker.staticModels", null, List.class);
if (CollectionUtils.isNotEmpty(modelList)) {
BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
TemplateHashModel models = wrapper.getStaticModels();
for (String clazz : modelList) {
try {
TemplateHashModel model = (TemplateHashModel) models.get(clazz);
staticModels.put(Class.forName(clazz).getSimpleName(), model);
} catch (Exception e) {
throw new WidgetException("static model initialization error", e);
}
}
}
}
@Override
public String intercept(InvocationContext invocation) throws Exception {
String resultCode = invocation.invoke();
if (InvocationContext.NONE.equals(resultCode)) {
return resultCode;
}
Widget widget = invocation.getWidget();
Mode mode = widget.modes.get(invocation.getModeType());
if (mode == null) {
throw new WidgetException("widget(" + widget.name + ") does not support mode:" + invocation.getModeType() + "");
}
//inject staticModels
invocation.getContext().putAll(staticModels);
//merge script and put it into the context
+ String finalScript=invocation.getScript();
if (StringUtils.isNotEmpty(mode.script)) {
String templateName = Template.generateName(widget.name, invocation.getModeType(), "script");
String script = merger.merge(new Template(templateName,mode.script), invocation.getContext());
- String finalScript = script + invocation.getScript();
- invocation.getContext().put("script", finalScript);
- invocation.setScript(finalScript);
+ finalScript+=script;
}
+ invocation.getContext().put("script", finalScript);
+ invocation.setScript(finalScript);
//merge html
if (StringUtils.isNotEmpty(mode.template)) {
String templateName = Template.generateName(widget.name, invocation.getModeType(), "template");
invocation.setOutput(merger.merge(new Template(templateName,mode.template), invocation.getContext()));
}
return InvocationContext.SUCCESS;
}
}
| false | true | public String intercept(InvocationContext invocation) throws Exception {
String resultCode = invocation.invoke();
if (InvocationContext.NONE.equals(resultCode)) {
return resultCode;
}
Widget widget = invocation.getWidget();
Mode mode = widget.modes.get(invocation.getModeType());
if (mode == null) {
throw new WidgetException("widget(" + widget.name + ") does not support mode:" + invocation.getModeType() + "");
}
//inject staticModels
invocation.getContext().putAll(staticModels);
//merge script and put it into the context
if (StringUtils.isNotEmpty(mode.script)) {
String templateName = Template.generateName(widget.name, invocation.getModeType(), "script");
String script = merger.merge(new Template(templateName,mode.script), invocation.getContext());
String finalScript = script + invocation.getScript();
invocation.getContext().put("script", finalScript);
invocation.setScript(finalScript);
}
//merge html
if (StringUtils.isNotEmpty(mode.template)) {
String templateName = Template.generateName(widget.name, invocation.getModeType(), "template");
invocation.setOutput(merger.merge(new Template(templateName,mode.template), invocation.getContext()));
}
return InvocationContext.SUCCESS;
}
| public String intercept(InvocationContext invocation) throws Exception {
String resultCode = invocation.invoke();
if (InvocationContext.NONE.equals(resultCode)) {
return resultCode;
}
Widget widget = invocation.getWidget();
Mode mode = widget.modes.get(invocation.getModeType());
if (mode == null) {
throw new WidgetException("widget(" + widget.name + ") does not support mode:" + invocation.getModeType() + "");
}
//inject staticModels
invocation.getContext().putAll(staticModels);
//merge script and put it into the context
String finalScript=invocation.getScript();
if (StringUtils.isNotEmpty(mode.script)) {
String templateName = Template.generateName(widget.name, invocation.getModeType(), "script");
String script = merger.merge(new Template(templateName,mode.script), invocation.getContext());
finalScript+=script;
}
invocation.getContext().put("script", finalScript);
invocation.setScript(finalScript);
//merge html
if (StringUtils.isNotEmpty(mode.template)) {
String templateName = Template.generateName(widget.name, invocation.getModeType(), "template");
invocation.setOutput(merger.merge(new Template(templateName,mode.template), invocation.getContext()));
}
return InvocationContext.SUCCESS;
}
|
diff --git a/src/com/android/apps/tag/MyTagList.java b/src/com/android/apps/tag/MyTagList.java
index e4541c5..9186389 100644
--- a/src/com/android/apps/tag/MyTagList.java
+++ b/src/com/android/apps/tag/MyTagList.java
@@ -1,661 +1,661 @@
/*
* 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.android.apps.tag;
import com.android.apps.tag.provider.TagContract.NdefMessages;
import com.android.apps.tag.record.RecordEditInfo;
import com.android.apps.tag.record.TextRecord;
import com.android.apps.tag.record.UriRecord;
import com.android.apps.tag.record.VCardRecord;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.CharArrayBuffer;
import android.database.Cursor;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
/**
* Displays the list of tags that can be set as "My tag", and allows the user to select the
* active tag that the device shares.
*/
public class MyTagList
extends Activity
implements OnItemClickListener, View.OnClickListener,
TagService.SaveCallbacks,
DialogInterface.OnClickListener {
static final String TAG = "TagList";
private static final int REQUEST_EDIT = 0;
private static final int DIALOG_ID_SELECT_ACTIVE_TAG = 0;
private static final int DIALOG_ID_ADD_NEW_TAG = 1;
private static final String BUNDLE_KEY_TAG_ID_IN_EDIT = "tag-edit";
private static final String PREF_KEY_ACTIVE_TAG = "active-my-tag";
static final String PREF_KEY_TAG_TO_WRITE = "tag-to-write";
static final String[] SUPPORTED_TYPES = new String[] {
VCardRecord.RECORD_TYPE,
UriRecord.RECORD_TYPE,
TextRecord.RECORD_TYPE,
};
private View mSelectActiveTagAnchor;
private View mActiveTagDetails;
private CheckBox mEnabled;
private ListView mList;
private TagAdapter mAdapter;
private long mActiveTagId;
private Uri mTagBeingSaved;
private NdefMessage mActiveTag;
private WeakReference<SelectActiveTagDialog> mSelectActiveTagDialog;
private long mTagIdInEdit = -1;
private long mTagIdLongPressed;
private boolean mWriteSupport = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
- registerForContextMenu(mList);
}
+ registerForContextMenu(mList);
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}
@Override
protected void onRestart() {
super.onRestart();
mTagIdInEdit = -1;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(BUNDLE_KEY_TAG_ID_IN_EDIT, mTagIdInEdit);
}
@Override
protected void onDestroy() {
if (mAdapter != null) {
mAdapter.changeCursor(null);
}
super.onDestroy();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
editTag(id);
}
/**
* Opens the tag editor for a particular tag.
*/
private void editTag(long id) {
// TODO: use implicit Intent?
Intent intent = new Intent(this, EditTagActivity.class);
intent.setData(ContentUris.withAppendedId(NdefMessages.CONTENT_URI, id));
mTagIdInEdit = id;
startActivityForResult(intent, REQUEST_EDIT);
}
public void setEmptyView() {
// TODO: set empty view.
}
public interface TagQuery {
static final String[] PROJECTION = new String[] {
NdefMessages._ID, // 0
NdefMessages.DATE, // 1
NdefMessages.TITLE, // 2
NdefMessages.BYTES, // 3
};
static final int COLUMN_ID = 0;
static final int COLUMN_DATE = 1;
static final int COLUMN_TITLE = 2;
static final int COLUMN_BYTES = 3;
}
/**
* Asynchronously loads the tags info from the database.
*/
final class TagLoaderTask extends AsyncTask<Void, Void, Cursor> {
@Override
public Cursor doInBackground(Void... args) {
Cursor cursor = getContentResolver().query(
NdefMessages.CONTENT_URI,
TagQuery.PROJECTION,
NdefMessages.IS_MY_TAG + "=1",
null, NdefMessages.DATE + " DESC");
// Ensure the cursor executes and fills its window
if (cursor != null) cursor.getCount();
return cursor;
}
@Override
protected void onPostExecute(Cursor cursor) {
mAdapter.changeCursor(cursor);
if (cursor == null || cursor.getCount() == 0) {
setEmptyView();
} else {
// Find the active tag.
if (mTagBeingSaved != null) {
selectTagBeingSaved(mTagBeingSaved);
} else if (mActiveTagId != -1) {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
if (mActiveTagId == cursor.getLong(TagQuery.COLUMN_ID)) {
selectActiveTag(cursor.getPosition());
break;
}
}
}
}
SelectActiveTagDialog dialog = (mSelectActiveTagDialog == null)
? null : mSelectActiveTagDialog.get();
if (dialog != null) {
dialog.setData(cursor);
}
}
}
/**
* Struct to hold pointers to views in the list items to save time at view binding time.
*/
static final class ViewHolder {
public CharArrayBuffer titleBuffer;
public TextView mainLine;
public ImageView activeIcon;
}
/**
* Adapter to display the the My tag entries.
*/
public class TagAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
public TagAdapter(Context context) {
super(context, null, false);
mInflater = LayoutInflater.from(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
CharArrayBuffer buf = holder.titleBuffer;
cursor.copyStringToBuffer(TagQuery.COLUMN_TITLE, buf);
holder.mainLine.setText(buf.data, 0, buf.sizeCopied);
boolean isActive = cursor.getLong(TagQuery.COLUMN_ID) == mActiveTagId;
holder.activeIcon.setVisibility(isActive ? View.VISIBLE : View.GONE);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.tag_list_item, null);
// Cache items for the view
ViewHolder holder = new ViewHolder();
holder.titleBuffer = new CharArrayBuffer(64);
holder.mainLine = (TextView) view.findViewById(R.id.title);
holder.activeIcon = (ImageView) view.findViewById(R.id.active_tag_icon);
view.findViewById(R.id.date).setVisibility(View.GONE);
view.setTag(holder);
return view;
}
@Override
public void onContentChanged() {
// Kick off an async query to refresh the list
new TagLoaderTask().execute((Void[]) null);
}
}
@Override
public void onClick(View target) {
switch (target.getId()) {
case R.id.toggle_enabled_target:
boolean enabled = !mEnabled.isChecked();
if (enabled) {
if (mActiveTag != null) {
enableSharingAndStoreTag();
return;
}
Toast.makeText(
this,
getResources().getString(R.string.no_tag_selected),
Toast.LENGTH_SHORT).show();
}
disableSharing();
break;
case R.id.add_tag:
showDialog(DIALOG_ID_ADD_NEW_TAG);
break;
case R.id.active_tag:
if (mAdapter.getCursor() == null || mAdapter.getCursor().isClosed()) {
// Hopefully shouldn't happen.
return;
}
if (mAdapter.getCursor().getCount() == 0) {
OnClickListener onAdd = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == AlertDialog.BUTTON_POSITIVE) {
showDialog(DIALOG_ID_ADD_NEW_TAG);
}
}
};
new AlertDialog.Builder(this)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(R.string.add_tag, onAdd)
.setMessage(R.string.no_tags_created)
.show();
return;
}
showDialog(DIALOG_ID_SELECT_ACTIVE_TAG);
break;
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
Cursor cursor = mAdapter.getCursor();
if (cursor == null
|| cursor.isClosed()
|| !cursor.moveToPosition(((AdapterContextMenuInfo) info).position)) {
return;
}
menu.setHeaderTitle(cursor.getString(TagQuery.COLUMN_TITLE));
long id = cursor.getLong(TagQuery.COLUMN_ID);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_tag_list_context_menu, menu);
// Prepare the menu for the item.
menu.findItem(R.id.set_as_active).setVisible(id != mActiveTagId);
mTagIdLongPressed = id;
if (mWriteSupport) {
menu.add(0, 1, 0, "Write to tag");
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
long id = mTagIdLongPressed;
switch (item.getItemId()) {
case R.id.delete:
deleteTag(id);
return true;
case R.id.set_as_active:
Cursor cursor = mAdapter.getCursor();
if (cursor == null || cursor.isClosed()) {
break;
}
for (int position = 0; cursor.moveToPosition(position); position++) {
if (cursor.getLong(TagQuery.COLUMN_ID) == id) {
selectActiveTag(position);
return true;
}
}
break;
case R.id.edit:
editTag(id);
return true;
case 1:
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
break;
}
Intent intent = new Intent(this, WriteTagActivity.class);
intent.putExtra("id", info.id);
startActivity(intent);
return true;
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EDIT && resultCode == RESULT_OK) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
data.getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
if (mTagIdInEdit != -1) {
TagService.updateMyMessage(this, mTagIdInEdit, msg);
} else {
saveNewMessage(msg);
}
}
}
private void saveNewMessage(NdefMessage msg) {
TagService.saveMyMessage(this, msg, this);
}
@Override
public void onSaveComplete(Uri newMsgUri) {
if (isFinishing()) {
// Callback came asynchronously and was after we finished - ignore.
return;
}
mTagBeingSaved = newMsgUri;
selectTagBeingSaved(newMsgUri);
}
@Override
protected Dialog onCreateDialog(int id, Bundle args) {
Context lightTheme = new ContextThemeWrapper(this, android.R.style.Theme_Light);
if (id == DIALOG_ID_SELECT_ACTIVE_TAG) {
SelectActiveTagDialog dialog = new SelectActiveTagDialog(lightTheme,
mAdapter.getCursor());
dialog.setInverseBackgroundForced(true);
mSelectActiveTagDialog = new WeakReference<SelectActiveTagDialog>(dialog);
return dialog;
} else if (id == DIALOG_ID_ADD_NEW_TAG) {
ContentSelectorAdapter adapter = new ContentSelectorAdapter(lightTheme,
SUPPORTED_TYPES);
AlertDialog dialog = new AlertDialog.Builder(lightTheme)
.setTitle(R.string.select_type)
.setIcon(0)
.setNegativeButton(android.R.string.cancel, this)
.setAdapter(adapter, this)
.create();
adapter.setListView(dialog.getListView());
dialog.setInverseBackgroundForced(true);
return dialog;
}
return super.onCreateDialog(id, args);
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dialog.cancel();
} else {
RecordEditInfo info = (RecordEditInfo) ((AlertDialog) dialog).getListView()
.getAdapter().getItem(which);
Intent intent = new Intent(this, EditTagActivity.class);
intent.putExtra(EditTagActivity.EXTRA_NEW_RECORD_INFO, info);
startActivityForResult(intent, REQUEST_EDIT);
}
}
/**
* Selects the tag to be used as the "My tag" shared tag.
*
* This does not necessarily persist the selection to the {@code NfcAdapter}. That must be done
* via {@link #enableSharingAndStoreTag()}. However, it will call {@link #disableSharing()}
* if the tag is invalid.
*/
private void selectActiveTag(int position) {
Cursor cursor = mAdapter.getCursor();
if (cursor != null && cursor.moveToPosition(position)) {
mActiveTagId = cursor.getLong(TagQuery.COLUMN_ID);
try {
mActiveTag = new NdefMessage(cursor.getBlob(TagQuery.COLUMN_BYTES));
// Persist active tag info to preferences.
getPreferences(Context.MODE_PRIVATE)
.edit()
.putLong(PREF_KEY_ACTIVE_TAG, mActiveTagId)
.apply();
updateActiveTagView(cursor.getString(TagQuery.COLUMN_TITLE));
mAdapter.notifyDataSetChanged();
// If there was an existing shared tag, we update the contents, since
// the active tag contents may have been changed. This also forces the
// active tag to be in sync with what the NfcAdapter.
if (NfcAdapter.getDefaultAdapter(this).getLocalNdefMessage() != null) {
enableSharingAndStoreTag();
}
} catch (FormatException e) {
// TODO: handle.
disableSharing();
}
} else {
updateActiveTagView(null);
disableSharing();
}
mTagBeingSaved = null;
}
/**
* Selects the tag to be used as the "My tag" shared tag, if the specified URI is found.
* If the URI is not found, the next load will attempt to look for a matching tag to select.
*
* Commonly used for new tags that was just added to the database, and may not yet be
* reflected in the {@code Cursor}.
*/
private void selectTagBeingSaved(Uri uri) {
Cursor cursor = mAdapter.getCursor();
if (cursor == null) {
return;
}
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
Uri tagUri = ContentUris.withAppendedId(
NdefMessages.CONTENT_URI,
cursor.getLong(TagQuery.COLUMN_ID));
if (tagUri.equals(uri)) {
selectActiveTag(cursor.getPosition());
return;
}
}
}
private void enableSharingAndStoreTag() {
mEnabled.setChecked(true);
NfcAdapter.getDefaultAdapter(this).setLocalNdefMessage(
Preconditions.checkNotNull(mActiveTag));
}
private void disableSharing() {
mEnabled.setChecked(false);
NfcAdapter.getDefaultAdapter(this).setLocalNdefMessage(null);
}
private void updateActiveTagView(String title) {
if (title == null) {
mActiveTagDetails.setVisibility(View.GONE);
mSelectActiveTagAnchor.setVisibility(View.VISIBLE);
} else {
mActiveTagDetails.setVisibility(View.VISIBLE);
((TextView) mActiveTagDetails.findViewById(R.id.active_tag_title)).setText(title);
mSelectActiveTagAnchor.setVisibility(View.GONE);
}
}
/**
* Removes the tag from the "My tag" list.
*/
private void deleteTag(long id) {
if (id == mActiveTagId) {
selectActiveTag(-1);
}
TagService.delete(this, ContentUris.withAppendedId(NdefMessages.CONTENT_URI, id));
}
class SelectActiveTagDialog extends AlertDialog
implements DialogInterface.OnClickListener, OnItemClickListener {
private final ArrayList<HashMap<String, String>> mData;
private final SimpleAdapter mSelectAdapter;
protected SelectActiveTagDialog(Context context, Cursor cursor) {
super(context);
setTitle(context.getResources().getString(R.string.choose_my_tag));
ListView list = new ListView(context);
mData = Lists.newArrayList();
mSelectAdapter = new SimpleAdapter(
context,
mData,
android.R.layout.simple_list_item_1,
new String[] { "title" },
new int[] { android.R.id.text1 });
list.setAdapter(mSelectAdapter);
list.setOnItemClickListener(this);
setView(list);
setIcon(0);
setButton(
DialogInterface.BUTTON_POSITIVE,
context.getString(android.R.string.cancel),
this);
setData(cursor);
}
public void setData(final Cursor cursor) {
if ((cursor == null) || (cursor.getCount() == 0)) {
cancel();
return;
}
mData.clear();
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
mData.add(new HashMap<String, String>() {{
put("title", cursor.getString(MyTagList.TagQuery.COLUMN_TITLE));
}});
}
mSelectAdapter.notifyDataSetChanged();
}
@Override
public void onClick(DialogInterface dialog, int which) {
cancel();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectActiveTag(position);
enableSharingAndStoreTag();
cancel();
}
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
registerForContextMenu(mList);
}
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tag_activity);
if (savedInstanceState != null) {
mTagIdInEdit = savedInstanceState.getLong(BUNDLE_KEY_TAG_ID_IN_EDIT, -1);
}
// Set up the check box to toggle My tag sharing.
mEnabled = (CheckBox) findViewById(R.id.toggle_enabled_checkbox);
mEnabled.setChecked(false); // Set after initial data load completes.
findViewById(R.id.toggle_enabled_target).setOnClickListener(this);
// Setup the active tag selector.
mActiveTagDetails = findViewById(R.id.active_tag_details);
mSelectActiveTagAnchor = findViewById(R.id.choose_my_tag);
findViewById(R.id.active_tag).setOnClickListener(this);
updateActiveTagView(null); // Filled in after initial data load.
mActiveTagId = getPreferences(Context.MODE_PRIVATE).getLong(PREF_KEY_ACTIVE_TAG, -1);
// Setup the list.
mAdapter = new TagAdapter(this);
mList = (ListView) findViewById(android.R.id.list);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(this);
findViewById(R.id.add_tag).setOnClickListener(this);
// Don't setup the empty view until after the first load
// so the empty text doesn't flash when first loading the
// activity.
mList.setEmptyView(null);
// Kick off an async task to load the tags.
new TagLoaderTask().execute((Void[]) null);
// If we're not on a user build offer a back door for writing tags.
// The UX is horrible so we don't want to ship it but need it for testing.
if (!Build.TYPE.equalsIgnoreCase("user")) {
mWriteSupport = true;
}
registerForContextMenu(mList);
if (getIntent().hasExtra(EditTagActivity.EXTRA_RESULT_MSG)) {
NdefMessage msg = (NdefMessage) Preconditions.checkNotNull(
getIntent().getParcelableExtra(EditTagActivity.EXTRA_RESULT_MSG));
saveNewMessage(msg);
}
}
|
diff --git a/core/testframework/src/main/java/org/overturetool/test/framework/ResultTestCase.java b/core/testframework/src/main/java/org/overturetool/test/framework/ResultTestCase.java
index 3811a524e5..f97cc2bb40 100644
--- a/core/testframework/src/main/java/org/overturetool/test/framework/ResultTestCase.java
+++ b/core/testframework/src/main/java/org/overturetool/test/framework/ResultTestCase.java
@@ -1,166 +1,166 @@
/*******************************************************************************
* Copyright (c) 2009, 2011 Overture Team and others.
*
* Overture 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.
*
* Overture 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 Overture. If not, see <http://www.gnu.org/licenses/>.
*
* The Overture Tool web-site: http://overturetool.org/
*******************************************************************************/
package org.overturetool.test.framework;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.overturetool.test.framework.results.IMessage;
import org.overturetool.test.framework.results.IResultCombiner;
import org.overturetool.test.framework.results.Result;
import org.overturetool.test.util.MessageReaderWritter;
import org.overturetool.test.util.XmlResultReaderWritter;
public abstract class ResultTestCase extends BaseTestCase
{
public ResultTestCase()
{
super();
}
public ResultTestCase(File file)
{
super(file);
}
public ResultTestCase(String name, String content)
{
super(name,content);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void compareResults(Result result, String filename)
{
if(Properties.recordTestResults)
{
//MessageReaderWritter mrw = new MessageReaderWritter(createResultFile(filename));
//mrw.set(result);
//mrw.save();
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(createResultFile(filename));
xmlResult.setResult(result);
try {
xmlResult.saveInXml();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
File file = getResultFile(filename);
assertNotNull("Result file " + file.getName() + " was not found", file);
- assertTrue("Result file " + file.getName() + " does not exist", file.exists());
+ assertTrue("Result file " + file.getAbsolutePath() + " does not exist", file.exists());
//MessageReaderWritter mrw = new MessageReaderWritter(file);
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(file);
boolean parsed = xmlResult.loadFromXml();
assertTrue("Could not read result file: " + file.getName(), parsed);
if (parsed)
{
if(file.getAbsolutePath().contains("SAFER"))
{//FIXME: remote this filter when SAFER is fixed in the warning reporting
return;
}
boolean errorsFound = checkMessages("warning", xmlResult.getWarnings(), result.warnings);
errorsFound = checkMessages("error", xmlResult.getErrors(), result.errors) || errorsFound;
assertFalse("Errors found in file \"" + filename + "\"", errorsFound);
}
}
protected abstract File createResultFile(String filename);
protected abstract File getResultFile(String filename);
public boolean checkMessages(String typeName, Set<IMessage> expectedList,
Set<IMessage> list)
{
String TypeName = typeName.toUpperCase().toCharArray()[0]
+ typeName.substring(1);
boolean errorFound = false;
for (IMessage w : list)
{
boolean isContainedIn = containedIn(expectedList, w);
if(!isContainedIn)
{
System.out.println(TypeName + " not expected: " + w);
errorFound = true;
}
// assertTrue(TypeName + " not expected: " + w, isContainedIn);
}
for (IMessage w : expectedList)
{
boolean isContainedIn = containedIn(list, w);
if(!isContainedIn)
{
System.out.println(TypeName + " expected but not found: " + w);
errorFound = true;
}
//assertTrue(TypeName + " expected but not found: " + w, isContainedIn);
}
return errorFound;
}
private static boolean containedIn(Set<IMessage> list, IMessage m)
{
for (IMessage m1 : list)
{
if (m1.equals(m))
{
return true;
}
}
return false;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected <T> Result mergeResults(Set<? extends Result<T>> parse,
IResultCombiner<T> c)
{
Set<IMessage> warnings = new HashSet<IMessage>();
Set<IMessage> errors = new HashSet<IMessage>();
T result = null;
for (Result<T> r : parse)
{
warnings.addAll(r.warnings);
errors.addAll(r.errors);
result = c.combine(result, r.result);
}
return new Result(result, warnings, errors);
}
}
| true | true | protected void compareResults(Result result, String filename)
{
if(Properties.recordTestResults)
{
//MessageReaderWritter mrw = new MessageReaderWritter(createResultFile(filename));
//mrw.set(result);
//mrw.save();
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(createResultFile(filename));
xmlResult.setResult(result);
try {
xmlResult.saveInXml();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
File file = getResultFile(filename);
assertNotNull("Result file " + file.getName() + " was not found", file);
assertTrue("Result file " + file.getName() + " does not exist", file.exists());
//MessageReaderWritter mrw = new MessageReaderWritter(file);
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(file);
boolean parsed = xmlResult.loadFromXml();
assertTrue("Could not read result file: " + file.getName(), parsed);
if (parsed)
{
if(file.getAbsolutePath().contains("SAFER"))
{//FIXME: remote this filter when SAFER is fixed in the warning reporting
return;
}
boolean errorsFound = checkMessages("warning", xmlResult.getWarnings(), result.warnings);
errorsFound = checkMessages("error", xmlResult.getErrors(), result.errors) || errorsFound;
assertFalse("Errors found in file \"" + filename + "\"", errorsFound);
}
}
| protected void compareResults(Result result, String filename)
{
if(Properties.recordTestResults)
{
//MessageReaderWritter mrw = new MessageReaderWritter(createResultFile(filename));
//mrw.set(result);
//mrw.save();
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(createResultFile(filename));
xmlResult.setResult(result);
try {
xmlResult.saveInXml();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
File file = getResultFile(filename);
assertNotNull("Result file " + file.getName() + " was not found", file);
assertTrue("Result file " + file.getAbsolutePath() + " does not exist", file.exists());
//MessageReaderWritter mrw = new MessageReaderWritter(file);
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(file);
boolean parsed = xmlResult.loadFromXml();
assertTrue("Could not read result file: " + file.getName(), parsed);
if (parsed)
{
if(file.getAbsolutePath().contains("SAFER"))
{//FIXME: remote this filter when SAFER is fixed in the warning reporting
return;
}
boolean errorsFound = checkMessages("warning", xmlResult.getWarnings(), result.warnings);
errorsFound = checkMessages("error", xmlResult.getErrors(), result.errors) || errorsFound;
assertFalse("Errors found in file \"" + filename + "\"", errorsFound);
}
}
|
diff --git a/WEB-INF/src/org/cdlib/xtf/textEngine/SnippetMaker.java b/WEB-INF/src/org/cdlib/xtf/textEngine/SnippetMaker.java
index c078a844..0b158ae3 100644
--- a/WEB-INF/src/org/cdlib/xtf/textEngine/SnippetMaker.java
+++ b/WEB-INF/src/org/cdlib/xtf/textEngine/SnippetMaker.java
@@ -1,368 +1,376 @@
package org.cdlib.xtf.textEngine;
/**
* Copyright (c) 2004, Regents of the University of California
* 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 University of California 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.
*/
import java.io.IOException;
import java.io.StringReader;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.chunk.DocNumMap;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.mark.BasicWordIter;
import org.apache.lucene.mark.FieldSpans;
import org.apache.lucene.mark.MarkCollector;
import org.apache.lucene.mark.MarkPos;
import org.apache.lucene.mark.SpanDocument;
import org.apache.lucene.search.spans.Span;
import org.cdlib.xtf.textIndexer.XTFTextAnalyzer;
/**
* Does the heavy lifting of interpreting span hits using the actual document
* text stored in the index. Marks the hit and any matching terms, and
* includes a configurable amount of context words.
*
* @author Martin Haye
*/
public class SnippetMaker
{
/** Lucene index reader used to fetch text data */
public IndexReader reader;
/** Lucene analyzer used for tokenizing text */
private Analyzer analyzer;
/**
* Keeps track of which chunks belong to which source document in the
* index.
*/
private DocNumMap docNumMap;
/** Max # of words in an index chunk */
private int chunkSize;
/** Amount of overlap between adjacent index chunks */
private int chunkOverlap;
/** Set of stop-words removed (e.g. "the", "a", "and", etc.) */
private Set stopSet;
/** Target # of characters to include in the snippet. */
private int maxContext;
/** Where to mark terms (all, only in spans, etc.) */
private int termMode;
// Precompiled patterns for quickly matching common chars special to XML
private static final Pattern ampPattern = Pattern.compile( "&" );
private static final Pattern ltPattern = Pattern.compile( "<" );
private static final Pattern gtPattern = Pattern.compile( ">" );
/**
* Constructs a SnippetMaker, ready to make snippets using the given
* index reader to load text data.
*
* @param reader Index reader to fetch text data from
* @param docNumMap Maps chunk numbers to document numbers
* @param stopSet Stop words removed (e.g. "the", "a", "and", etc.)
* @param maxContext Target # chars for hit + context
* @param termMode Where to mark terms (all, only in spans, etc.)
*/
public SnippetMaker( IndexReader reader,
DocNumMap docNumMap,
Set stopSet,
int maxContext,
int termMode )
{
this.reader = reader;
this.docNumMap = docNumMap;
this.chunkSize = docNumMap.getChunkSize();
this.chunkOverlap = docNumMap.getChunkOverlap();
this.stopSet = stopSet;
this.maxContext = maxContext;
this.termMode = termMode;
// Use the indexer's actual analyzer, so that our results always
// agree (especially the positions which are critical.)
//
analyzer = new XTFTextAnalyzer( null, -1 );
} // constructor
/**
* Obtain a list of stop-words in the index (e.g. "the", "a", "and",
* etc.)
*/
public Set stopSet() {
return stopSet;
}
/** Obtain the document number map used to make snippets */
public DocNumMap docNumMap() {
return docNumMap;
}
/**
* Full-blown snippet formation process.
*
* @param fieldSpans record of the matching spans, and all search terms
* @param mainDocNum document ID of the main doc
* @param fieldName name of the field we're making snippets of
* @param getText true to get the full text of the snippet, false
* if we only want the start/end offsets.
*/
public Snippet[] makeSnippets( FieldSpans fieldSpans, int mainDocNum,
String fieldName, final boolean getText )
{
// Make a chunked iterator to use for traversing the token stream.
XtfChunkedWordIter wordIter =
new XtfChunkedWordIter( reader, docNumMap, mainDocNum,
fieldName, analyzer );
// Make an array to hold the snippets.
int nSnippets = fieldSpans.getSpanCount(fieldName);
final Snippet[] snippets = new Snippet[nSnippets];
// Process all the marks as they come
SpanDocument.markField(
fieldSpans,
fieldName,
wordIter,
getText ? maxContext : 0,
getText ? termMode : SpanDocument.MARK_NO_TERMS,
stopSet,
new MarkCollector()
{
private Snippet curSnippet;
private MarkPos prevPos = null;
private StringBuffer buf = getText ? new StringBuffer() : null;
private void copyUpTo( MarkPos pos ) {
if( prevPos != null )
buf.append( mapXMLChars(prevPos.getTextTo(pos)) );
prevPos = pos;
}
public void beginField(MarkPos pos) { }
public void beginContext(MarkPos pos, Span span) {
if( getText )
buf.setLength( 0 );
prevPos = pos;
}
public void term(MarkPos startPos, MarkPos endPos, String term) {
if( getText ) {
copyUpTo( startPos );
buf.append( "<term>" );
buf.append( startPos.getTextTo(endPos) );
buf.append( "</term>" );
}
prevPos = endPos;
}
public void beginSpan(MarkPos pos, Span span) {
if( getText ) {
copyUpTo( pos );
buf.append( "<hit>" );
}
curSnippet = snippets[span.rank] = new Snippet();
XtfChunkMarkPos xp = (XtfChunkMarkPos) pos;
curSnippet.startNode = xp.nodeNumber;
curSnippet.startOffset = xp.wordOffset;
curSnippet.sectionType = xp.sectionType;
curSnippet.rank = span.rank;
curSnippet.score = span.score;
}
public void endSpan(MarkPos pos) {
if( getText ) {
copyUpTo( pos );
buf.append( "</hit>" );
}
XtfChunkMarkPos xp = (XtfChunkMarkPos) pos;
curSnippet.endNode = xp.nodeNumber;
curSnippet.endOffset = xp.wordOffset;
}
public void endContext(MarkPos pos) {
if( getText ) {
copyUpTo( pos );
curSnippet.text = buf.toString();
}
}
public void endField(MarkPos pos) { }
}
);
// Make sure all the snippets got marked.
for( int i = 0; i < nSnippets; i++ )
assert snippets[i] != null;
// And we're done.
return snippets;
} // makeSnippets()
/**
* Marks all the terms within the given text. Typically used to mark
* terms within a meta-data field.
*
* @param doc document to get matching spans from
* @param fieldName name of the field to mark.
* @param value value of the field to mark
*
* @return Marked up text value.
*/
public String markField( SpanDocument doc, String fieldName,
final String value )
{
try
{
// Get the text, and allocate a buffer for the marked up version.
final StringBuffer buf = new StringBuffer( value.length() * 2 );
// Now make a word iterator to use for traversing the token stream
TokenStream stream = analyzer.tokenStream(fieldName,
new StringReader(value));
BasicWordIter wordIter =
new BoundedWordIter( value, stream, chunkOverlap );
//Trace.debug( "Mark field \"" + fieldName + "\": orig text \"" +
// value + "\"" );
//Trace.debug( " " );
// Process all the marks as they come
doc.markField( fieldName, wordIter, maxContext,
termMode, stopSet,
new MarkCollector()
{
private MarkPos prevPos = null;
private boolean inContext = false;
private int contextSize;
private MarkPos contextStart;
private void copyUpTo( MarkPos pos ) {
if( prevPos != null ) {
String toAdd = prevPos.getTextTo( pos );
//Trace.more( Trace.debug, "[" + toAdd + "]");
buf.append( mapXMLChars(toAdd) );
if( inContext )
contextSize += toAdd.length();
}
prevPos = pos;
}
public void beginField(MarkPos pos) {
prevPos = pos;
}
public void beginContext(MarkPos pos, Span span) {
copyUpTo( pos );
buf.append( "<snippet rank=\"" );
buf.append( Integer.toString(span.rank+1) );
buf.append( "\" score=\"" );
buf.append( Integer.toString((int)(span.score * 100)) );
buf.append( "\">" );
inContext = true;
contextSize = 0;
contextStart = pos;
}
public void term(MarkPos startPos, MarkPos endPos, String term) {
copyUpTo( startPos );
buf.append( "<term>" );
//Trace.more( Trace.debug, "{" + startPos.getTextTo(endPos) + "}");
String toAdd = startPos.getTextTo(endPos) ;
buf.append( toAdd );
buf.append( "</term>" );
prevPos = endPos;
if( inContext )
contextSize += toAdd.length();
}
public void beginSpan(MarkPos pos, Span span) {
copyUpTo( pos );
buf.append( "<hit rank=\"" );
buf.append( Integer.toString(span.rank+1) );
buf.append( "\" score=\"" );
buf.append( Integer.toString((int)(span.score * 100)) );
buf.append( "\">" );
}
public void endSpan(MarkPos pos) {
copyUpTo( pos );
buf.append( "</hit>" );
}
public void endContext(MarkPos pos) {
copyUpTo( pos );
buf.append( "</snippet>" );
if( contextSize > maxContext ) {
int posDiff = contextStart.countTextTo(pos);
- assert false : "ContextMarker made snippet too big";
+ //
+ // NOTE: Do NOT re-enable the assert below. Why? Consider
+ // the situation where the matching search terms are
+ // simply very far apart, and there's no way to
+ // make a snippet that contains all of them within
+ // the specified maxContext. I think you still want
+ // the whole hit in this case.
+ //
+ //assert false : "ContextMarker made snippet too big";
}
inContext = false;
}
public void endField(MarkPos pos) {
copyUpTo( pos );
}
}
);
String strVal = buf.toString();
return strVal;
}
catch( IOException e ) {
throw new RuntimeException(
"How could StringReader throw an exception?" );
}
} // markField()
/**
* Replaces 'special' characters in the given string with their XML
* equivalent.
*/
String mapXMLChars( String s )
{
if( s.indexOf('&') >= 0 )
s = ampPattern.matcher(s).replaceAll("&");
if( s.indexOf('<') >= 0 )
s = ltPattern.matcher(s).replaceAll("<");
if( s.indexOf('>') >= 0 )
s = gtPattern.matcher(s).replaceAll(">");
return s;
} // mapXMLChars()
} // class SnippetMaker
| true | true | public String markField( SpanDocument doc, String fieldName,
final String value )
{
try
{
// Get the text, and allocate a buffer for the marked up version.
final StringBuffer buf = new StringBuffer( value.length() * 2 );
// Now make a word iterator to use for traversing the token stream
TokenStream stream = analyzer.tokenStream(fieldName,
new StringReader(value));
BasicWordIter wordIter =
new BoundedWordIter( value, stream, chunkOverlap );
//Trace.debug( "Mark field \"" + fieldName + "\": orig text \"" +
// value + "\"" );
//Trace.debug( " " );
// Process all the marks as they come
doc.markField( fieldName, wordIter, maxContext,
termMode, stopSet,
new MarkCollector()
{
private MarkPos prevPos = null;
private boolean inContext = false;
private int contextSize;
private MarkPos contextStart;
private void copyUpTo( MarkPos pos ) {
if( prevPos != null ) {
String toAdd = prevPos.getTextTo( pos );
//Trace.more( Trace.debug, "[" + toAdd + "]");
buf.append( mapXMLChars(toAdd) );
if( inContext )
contextSize += toAdd.length();
}
prevPos = pos;
}
public void beginField(MarkPos pos) {
prevPos = pos;
}
public void beginContext(MarkPos pos, Span span) {
copyUpTo( pos );
buf.append( "<snippet rank=\"" );
buf.append( Integer.toString(span.rank+1) );
buf.append( "\" score=\"" );
buf.append( Integer.toString((int)(span.score * 100)) );
buf.append( "\">" );
inContext = true;
contextSize = 0;
contextStart = pos;
}
public void term(MarkPos startPos, MarkPos endPos, String term) {
copyUpTo( startPos );
buf.append( "<term>" );
//Trace.more( Trace.debug, "{" + startPos.getTextTo(endPos) + "}");
String toAdd = startPos.getTextTo(endPos) ;
buf.append( toAdd );
buf.append( "</term>" );
prevPos = endPos;
if( inContext )
contextSize += toAdd.length();
}
public void beginSpan(MarkPos pos, Span span) {
copyUpTo( pos );
buf.append( "<hit rank=\"" );
buf.append( Integer.toString(span.rank+1) );
buf.append( "\" score=\"" );
buf.append( Integer.toString((int)(span.score * 100)) );
buf.append( "\">" );
}
public void endSpan(MarkPos pos) {
copyUpTo( pos );
buf.append( "</hit>" );
}
public void endContext(MarkPos pos) {
copyUpTo( pos );
buf.append( "</snippet>" );
if( contextSize > maxContext ) {
int posDiff = contextStart.countTextTo(pos);
assert false : "ContextMarker made snippet too big";
}
inContext = false;
}
public void endField(MarkPos pos) {
copyUpTo( pos );
}
}
);
String strVal = buf.toString();
return strVal;
}
catch( IOException e ) {
throw new RuntimeException(
"How could StringReader throw an exception?" );
}
} // markField()
| public String markField( SpanDocument doc, String fieldName,
final String value )
{
try
{
// Get the text, and allocate a buffer for the marked up version.
final StringBuffer buf = new StringBuffer( value.length() * 2 );
// Now make a word iterator to use for traversing the token stream
TokenStream stream = analyzer.tokenStream(fieldName,
new StringReader(value));
BasicWordIter wordIter =
new BoundedWordIter( value, stream, chunkOverlap );
//Trace.debug( "Mark field \"" + fieldName + "\": orig text \"" +
// value + "\"" );
//Trace.debug( " " );
// Process all the marks as they come
doc.markField( fieldName, wordIter, maxContext,
termMode, stopSet,
new MarkCollector()
{
private MarkPos prevPos = null;
private boolean inContext = false;
private int contextSize;
private MarkPos contextStart;
private void copyUpTo( MarkPos pos ) {
if( prevPos != null ) {
String toAdd = prevPos.getTextTo( pos );
//Trace.more( Trace.debug, "[" + toAdd + "]");
buf.append( mapXMLChars(toAdd) );
if( inContext )
contextSize += toAdd.length();
}
prevPos = pos;
}
public void beginField(MarkPos pos) {
prevPos = pos;
}
public void beginContext(MarkPos pos, Span span) {
copyUpTo( pos );
buf.append( "<snippet rank=\"" );
buf.append( Integer.toString(span.rank+1) );
buf.append( "\" score=\"" );
buf.append( Integer.toString((int)(span.score * 100)) );
buf.append( "\">" );
inContext = true;
contextSize = 0;
contextStart = pos;
}
public void term(MarkPos startPos, MarkPos endPos, String term) {
copyUpTo( startPos );
buf.append( "<term>" );
//Trace.more( Trace.debug, "{" + startPos.getTextTo(endPos) + "}");
String toAdd = startPos.getTextTo(endPos) ;
buf.append( toAdd );
buf.append( "</term>" );
prevPos = endPos;
if( inContext )
contextSize += toAdd.length();
}
public void beginSpan(MarkPos pos, Span span) {
copyUpTo( pos );
buf.append( "<hit rank=\"" );
buf.append( Integer.toString(span.rank+1) );
buf.append( "\" score=\"" );
buf.append( Integer.toString((int)(span.score * 100)) );
buf.append( "\">" );
}
public void endSpan(MarkPos pos) {
copyUpTo( pos );
buf.append( "</hit>" );
}
public void endContext(MarkPos pos) {
copyUpTo( pos );
buf.append( "</snippet>" );
if( contextSize > maxContext ) {
int posDiff = contextStart.countTextTo(pos);
//
// NOTE: Do NOT re-enable the assert below. Why? Consider
// the situation where the matching search terms are
// simply very far apart, and there's no way to
// make a snippet that contains all of them within
// the specified maxContext. I think you still want
// the whole hit in this case.
//
//assert false : "ContextMarker made snippet too big";
}
inContext = false;
}
public void endField(MarkPos pos) {
copyUpTo( pos );
}
}
);
String strVal = buf.toString();
return strVal;
}
catch( IOException e ) {
throw new RuntimeException(
"How could StringReader throw an exception?" );
}
} // markField()
|
diff --git a/bundles/core/org.openhab.core.library/src/main/java/org/openhab/core/library/items/ColorItem.java b/bundles/core/org.openhab.core.library/src/main/java/org/openhab/core/library/items/ColorItem.java
index e8a38515..7690ec91 100644
--- a/bundles/core/org.openhab.core.library/src/main/java/org/openhab/core/library/items/ColorItem.java
+++ b/bundles/core/org.openhab.core.library/src/main/java/org/openhab/core/library/items/ColorItem.java
@@ -1,103 +1,103 @@
/**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010-2012, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* 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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.openhab.core.library.items;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.HSBType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.PercentType;
import org.openhab.core.types.State;
/**
* A ColorItem can be used for color values, e.g. for LED lights
*
* @author Kai Kreuzer
* @since 1.2.0
*
*/public class ColorItem extends DimmerItem {
static {
acceptedDataTypes.add(HSBType.class);
acceptedCommandTypes.add(HSBType.class);
}
public ColorItem(String name) {
super(name);
}
public void send(HSBType command) {
internalSend(command);
}
/**
* {@inheritDoc}
*/
@Override
public void setState(State state) {
State currentState = this.state;
if(currentState instanceof HSBType) {
DecimalType hue = ((HSBType) currentState).getHue();
PercentType saturation = ((HSBType) currentState).getSaturation();
// we map ON/OFF values to dark/bright, so that the hue and saturation values are not changed
if(state==OnOffType.OFF) {
this.state = new HSBType(hue, saturation, PercentType.ZERO);
} else if(state==OnOffType.ON) {
this.state = new HSBType(hue, saturation, PercentType.HUNDRED);
} else if(state instanceof PercentType && !(state instanceof HSBType)) {
this.state = new HSBType(hue, saturation, (PercentType) state);
} else {
super.setState(state);
}
} else {
// we map ON/OFF values to black/white and percentage values to grey scale
if(state==OnOffType.OFF) {
this.state = HSBType.BLACK;
} else if(state==OnOffType.ON) {
this.state = HSBType.WHITE;
- } else if(state instanceof PercentType) {
+ } else if(state instanceof PercentType && !(state instanceof HSBType)) {
this.state = new HSBType(DecimalType.ZERO, PercentType.ZERO, (PercentType) state);
} else {
super.setState(state);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public State getStateAs(Class<? extends State> typeClass) {
if(typeClass==HSBType.class) {
return this.state;
} else {
return super.getStateAs(typeClass);
}
}
}
| true | true | public void setState(State state) {
State currentState = this.state;
if(currentState instanceof HSBType) {
DecimalType hue = ((HSBType) currentState).getHue();
PercentType saturation = ((HSBType) currentState).getSaturation();
// we map ON/OFF values to dark/bright, so that the hue and saturation values are not changed
if(state==OnOffType.OFF) {
this.state = new HSBType(hue, saturation, PercentType.ZERO);
} else if(state==OnOffType.ON) {
this.state = new HSBType(hue, saturation, PercentType.HUNDRED);
} else if(state instanceof PercentType && !(state instanceof HSBType)) {
this.state = new HSBType(hue, saturation, (PercentType) state);
} else {
super.setState(state);
}
} else {
// we map ON/OFF values to black/white and percentage values to grey scale
if(state==OnOffType.OFF) {
this.state = HSBType.BLACK;
} else if(state==OnOffType.ON) {
this.state = HSBType.WHITE;
} else if(state instanceof PercentType) {
this.state = new HSBType(DecimalType.ZERO, PercentType.ZERO, (PercentType) state);
} else {
super.setState(state);
}
}
}
| public void setState(State state) {
State currentState = this.state;
if(currentState instanceof HSBType) {
DecimalType hue = ((HSBType) currentState).getHue();
PercentType saturation = ((HSBType) currentState).getSaturation();
// we map ON/OFF values to dark/bright, so that the hue and saturation values are not changed
if(state==OnOffType.OFF) {
this.state = new HSBType(hue, saturation, PercentType.ZERO);
} else if(state==OnOffType.ON) {
this.state = new HSBType(hue, saturation, PercentType.HUNDRED);
} else if(state instanceof PercentType && !(state instanceof HSBType)) {
this.state = new HSBType(hue, saturation, (PercentType) state);
} else {
super.setState(state);
}
} else {
// we map ON/OFF values to black/white and percentage values to grey scale
if(state==OnOffType.OFF) {
this.state = HSBType.BLACK;
} else if(state==OnOffType.ON) {
this.state = HSBType.WHITE;
} else if(state instanceof PercentType && !(state instanceof HSBType)) {
this.state = new HSBType(DecimalType.ZERO, PercentType.ZERO, (PercentType) state);
} else {
super.setState(state);
}
}
}
|
diff --git a/collector-client-support/src/main/java/com/ning/arecibo/collector/rest/DefaultCollectorClient.java b/collector-client-support/src/main/java/com/ning/arecibo/collector/rest/DefaultCollectorClient.java
index 07e3000..9899f2f 100644
--- a/collector-client-support/src/main/java/com/ning/arecibo/collector/rest/DefaultCollectorClient.java
+++ b/collector-client-support/src/main/java/com/ning/arecibo/collector/rest/DefaultCollectorClient.java
@@ -1,262 +1,262 @@
/*
* Copyright 2010-2012 Ning, Inc.
*
* Ning 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 com.ning.arecibo.collector.rest;
import com.ning.arecibo.collector.CollectorClient;
import com.ning.arecibo.collector.discovery.CollectorFinder;
import com.ning.arecibo.util.timeline.CategoryAndSampleKinds;
import com.ning.arecibo.util.timeline.SamplesForSampleKindAndHost;
import com.google.inject.Inject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig;
import javax.annotation.Nullable;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Default implementation of the Collector client.
* <p/>
* When using the stream APIs, it is the responsibility of the client to close the streams.
*/
public class DefaultCollectorClient implements CollectorClient
{
private static final Logger log = LoggerFactory.getLogger(DefaultCollectorClient.class);
private static final String USER_AGENT = "NING-CollectorClient/1.0";
private static final String RESOURCE_PATH = "rest/1.0";
private static final ObjectMapper mapper = new ObjectMapper();
private final CollectorFinder collectorFinder;
private Client client;
@Inject
public DefaultCollectorClient(final CollectorFinder collectorFinder)
{
this.collectorFinder = collectorFinder;
createClient();
}
@Override
public InputStream getHostsAsStream() throws UniformInterfaceException
{
return getPathAsStream("hosts");
}
@Override
public Iterable<String> getHosts() throws UniformInterfaceException
{
final TypeReference<List<String>> valueTypeRef = new TypeReference<List<String>>()
{
};
final InputStream stream = getHostsAsStream();
return readValue(stream, valueTypeRef);
}
@Override
public InputStream getSampleKindsAsStream() throws UniformInterfaceException
{
return getPathAsStream("sample_kinds");
}
@Override
public InputStream getSampleKindsAsStream(final Iterable<String> hostNames) throws UniformInterfaceException
{
final MultivaluedMap<String, String> params = new MultivaluedMapImpl();
for (final String hostName : hostNames) {
params.add("host", hostName);
}
return getPathAsStream("sample_kinds", params);
}
@Override
public Iterable<CategoryAndSampleKinds> getSampleKinds() throws UniformInterfaceException
{
final TypeReference<List<CategoryAndSampleKinds>> valueTypeRef = new TypeReference<List<CategoryAndSampleKinds>>()
{
};
final InputStream stream = getSampleKindsAsStream();
return readValue(stream, valueTypeRef);
}
@Override
public Iterable<CategoryAndSampleKinds> getSampleKinds(final Iterable<String> hostNames) throws UniformInterfaceException
{
final TypeReference<List<CategoryAndSampleKinds>> valueTypeRef = new TypeReference<List<CategoryAndSampleKinds>>()
{
};
final InputStream stream = getSampleKindsAsStream(hostNames);
return readValue(stream, valueTypeRef);
}
@Override
public InputStream getHostSamplesAsStream(final Iterable<String> hostNames, final Iterable<String> categoriesAndSampleKinds, final DateTime from, final DateTime to) throws UniformInterfaceException
{
final MultivaluedMap<String, String> params = new MultivaluedMapImpl();
for (final String hostName : hostNames) {
params.add("host", hostName);
}
for (final String categoriesAndSampleKind : categoriesAndSampleKinds) {
params.add("category_and_sample_kind", categoriesAndSampleKind);
}
params.add("from", from.toString());
params.add("to", to.toString());
return getPathAsStream("host_samples", params);
}
@Override
public Iterable<SamplesForSampleKindAndHost> getHostSamples(final Iterable<String> hostNames, final Iterable<String> categoriesAndSampleKinds, final DateTime from, final DateTime to) throws UniformInterfaceException
{
final TypeReference<List<SamplesForSampleKindAndHost>> valueTypeRef = new TypeReference<List<SamplesForSampleKindAndHost>>()
{
};
final InputStream stream = getHostSamplesAsStream(hostNames, categoriesAndSampleKinds, from, to);
// The streaming endpoint will send data out as fast as possible, so we may end up having
// multiple SamplesForSampleKindAndHost per host and sample kind. Let's merge them for convenience.
//[ {
// "hostName" : "abc.foo.com",
// "eventCategory" : "JVM",
// "sampleKind" : "GC"
// "samples" : "1,20,2,23"
// },
// {
// "hostName" : "abc.foo.com",
// "eventCategory" : "JVM",
// "sampleKind" : "GC"
// "samples" : "3,22,4,20"
//} ]
final Iterable<SamplesForSampleKindAndHost> streamedSamples = readValue(stream, valueTypeRef);
final Map<String, Map<String, Map<String, SamplesForSampleKindAndHost>>> mergedSamplesMap = new HashMap<String, Map<String, Map<String, SamplesForSampleKindAndHost>>>();
for (final SamplesForSampleKindAndHost sample : streamedSamples) {
if (mergedSamplesMap.get(sample.getHostName()) == null) {
mergedSamplesMap.put(sample.getHostName(), new HashMap<String, Map<String, SamplesForSampleKindAndHost>>());
}
final Map<String, Map<String, SamplesForSampleKindAndHost>> samplesForHost = mergedSamplesMap.get(sample.getHostName());
if (samplesForHost.get(sample.getEventCategory()) == null) {
samplesForHost.put(sample.getEventCategory(), new HashMap<String, SamplesForSampleKindAndHost>());
}
final Map<String, SamplesForSampleKindAndHost> samplesForHostAndEventCategory = samplesForHost.get(sample.getEventCategory());
if (samplesForHostAndEventCategory.get(sample.getSampleKind()) == null) {
samplesForHostAndEventCategory.put(sample.getSampleKind(),
new SamplesForSampleKindAndHost(sample.getHostName(), sample.getEventCategory(), sample.getSampleKind(), sample.getSamples()));
}
else {
samplesForHostAndEventCategory.put(sample.getSampleKind(),
- new SamplesForSampleKindAndHost(sample.getHostName(), sample.getEventCategory(), sample.getSampleKind(), samplesForHostAndEventCategory.get(sample.getSampleKind()) + "," + sample.getSamples()));
+ new SamplesForSampleKindAndHost(sample.getHostName(), sample.getEventCategory(), sample.getSampleKind(), samplesForHostAndEventCategory.get(sample.getSampleKind()).getSamples() + "," + sample.getSamples()));
}
}
final List<SamplesForSampleKindAndHost> mergedSamples = new ArrayList<SamplesForSampleKindAndHost>();
for (final Map<String, Map<String, SamplesForSampleKindAndHost>> samplesForHost : mergedSamplesMap.values()) {
for (final Map<String, SamplesForSampleKindAndHost> samplesForHostAndEventCategory : samplesForHost.values()) {
mergedSamples.addAll(samplesForHostAndEventCategory.values());
}
}
return mergedSamples;
}
private void createClient()
{
final DefaultAhcConfig config = new DefaultAhcConfig();
client = Client.create(config);
}
private InputStream getPathAsStream(final String path) throws UniformInterfaceException
{
return getPathAsStream(path, null);
}
private InputStream getPathAsStream(final String path, @Nullable final MultivaluedMap<String, String> queryParams) throws UniformInterfaceException
{
WebResource resource = createWebResource().path(path);
if (queryParams != null) {
resource = resource.queryParams(queryParams);
}
log.info("Calling: {}", resource.toString());
return resource.get(InputStream.class);
}
private WebResource createWebResource()
{
String collectorUri = collectorFinder.getCollectorUri();
if (!collectorUri.endsWith("/")) {
collectorUri += "/";
}
collectorUri += RESOURCE_PATH;
final WebResource resource = client.resource(collectorUri);
resource.accept(MediaType.APPLICATION_JSON).header("User-Agent", USER_AGENT);
return resource;
}
private <T> T readValue(final InputStream stream, final TypeReference<T> valueTypeRef)
{
try {
return mapper.<T>readValue(stream, valueTypeRef);
}
catch (JsonMappingException e) {
log.warn("Failed to map response from collector", e);
}
catch (JsonParseException e) {
log.warn("Failed to parse response from collector", e);
}
catch (IOException e) {
log.warn("Generic I/O Exception from collector", e);
}
finally {
if (stream != null) {
try {
stream.close();
}
catch (IOException e) {
log.warn("Failed to close http-client - provided InputStream", e);
}
}
}
return null;
}
}
| true | true | public Iterable<SamplesForSampleKindAndHost> getHostSamples(final Iterable<String> hostNames, final Iterable<String> categoriesAndSampleKinds, final DateTime from, final DateTime to) throws UniformInterfaceException
{
final TypeReference<List<SamplesForSampleKindAndHost>> valueTypeRef = new TypeReference<List<SamplesForSampleKindAndHost>>()
{
};
final InputStream stream = getHostSamplesAsStream(hostNames, categoriesAndSampleKinds, from, to);
// The streaming endpoint will send data out as fast as possible, so we may end up having
// multiple SamplesForSampleKindAndHost per host and sample kind. Let's merge them for convenience.
//[ {
// "hostName" : "abc.foo.com",
// "eventCategory" : "JVM",
// "sampleKind" : "GC"
// "samples" : "1,20,2,23"
// },
// {
// "hostName" : "abc.foo.com",
// "eventCategory" : "JVM",
// "sampleKind" : "GC"
// "samples" : "3,22,4,20"
//} ]
final Iterable<SamplesForSampleKindAndHost> streamedSamples = readValue(stream, valueTypeRef);
final Map<String, Map<String, Map<String, SamplesForSampleKindAndHost>>> mergedSamplesMap = new HashMap<String, Map<String, Map<String, SamplesForSampleKindAndHost>>>();
for (final SamplesForSampleKindAndHost sample : streamedSamples) {
if (mergedSamplesMap.get(sample.getHostName()) == null) {
mergedSamplesMap.put(sample.getHostName(), new HashMap<String, Map<String, SamplesForSampleKindAndHost>>());
}
final Map<String, Map<String, SamplesForSampleKindAndHost>> samplesForHost = mergedSamplesMap.get(sample.getHostName());
if (samplesForHost.get(sample.getEventCategory()) == null) {
samplesForHost.put(sample.getEventCategory(), new HashMap<String, SamplesForSampleKindAndHost>());
}
final Map<String, SamplesForSampleKindAndHost> samplesForHostAndEventCategory = samplesForHost.get(sample.getEventCategory());
if (samplesForHostAndEventCategory.get(sample.getSampleKind()) == null) {
samplesForHostAndEventCategory.put(sample.getSampleKind(),
new SamplesForSampleKindAndHost(sample.getHostName(), sample.getEventCategory(), sample.getSampleKind(), sample.getSamples()));
}
else {
samplesForHostAndEventCategory.put(sample.getSampleKind(),
new SamplesForSampleKindAndHost(sample.getHostName(), sample.getEventCategory(), sample.getSampleKind(), samplesForHostAndEventCategory.get(sample.getSampleKind()) + "," + sample.getSamples()));
}
}
final List<SamplesForSampleKindAndHost> mergedSamples = new ArrayList<SamplesForSampleKindAndHost>();
for (final Map<String, Map<String, SamplesForSampleKindAndHost>> samplesForHost : mergedSamplesMap.values()) {
for (final Map<String, SamplesForSampleKindAndHost> samplesForHostAndEventCategory : samplesForHost.values()) {
mergedSamples.addAll(samplesForHostAndEventCategory.values());
}
}
return mergedSamples;
}
| public Iterable<SamplesForSampleKindAndHost> getHostSamples(final Iterable<String> hostNames, final Iterable<String> categoriesAndSampleKinds, final DateTime from, final DateTime to) throws UniformInterfaceException
{
final TypeReference<List<SamplesForSampleKindAndHost>> valueTypeRef = new TypeReference<List<SamplesForSampleKindAndHost>>()
{
};
final InputStream stream = getHostSamplesAsStream(hostNames, categoriesAndSampleKinds, from, to);
// The streaming endpoint will send data out as fast as possible, so we may end up having
// multiple SamplesForSampleKindAndHost per host and sample kind. Let's merge them for convenience.
//[ {
// "hostName" : "abc.foo.com",
// "eventCategory" : "JVM",
// "sampleKind" : "GC"
// "samples" : "1,20,2,23"
// },
// {
// "hostName" : "abc.foo.com",
// "eventCategory" : "JVM",
// "sampleKind" : "GC"
// "samples" : "3,22,4,20"
//} ]
final Iterable<SamplesForSampleKindAndHost> streamedSamples = readValue(stream, valueTypeRef);
final Map<String, Map<String, Map<String, SamplesForSampleKindAndHost>>> mergedSamplesMap = new HashMap<String, Map<String, Map<String, SamplesForSampleKindAndHost>>>();
for (final SamplesForSampleKindAndHost sample : streamedSamples) {
if (mergedSamplesMap.get(sample.getHostName()) == null) {
mergedSamplesMap.put(sample.getHostName(), new HashMap<String, Map<String, SamplesForSampleKindAndHost>>());
}
final Map<String, Map<String, SamplesForSampleKindAndHost>> samplesForHost = mergedSamplesMap.get(sample.getHostName());
if (samplesForHost.get(sample.getEventCategory()) == null) {
samplesForHost.put(sample.getEventCategory(), new HashMap<String, SamplesForSampleKindAndHost>());
}
final Map<String, SamplesForSampleKindAndHost> samplesForHostAndEventCategory = samplesForHost.get(sample.getEventCategory());
if (samplesForHostAndEventCategory.get(sample.getSampleKind()) == null) {
samplesForHostAndEventCategory.put(sample.getSampleKind(),
new SamplesForSampleKindAndHost(sample.getHostName(), sample.getEventCategory(), sample.getSampleKind(), sample.getSamples()));
}
else {
samplesForHostAndEventCategory.put(sample.getSampleKind(),
new SamplesForSampleKindAndHost(sample.getHostName(), sample.getEventCategory(), sample.getSampleKind(), samplesForHostAndEventCategory.get(sample.getSampleKind()).getSamples() + "," + sample.getSamples()));
}
}
final List<SamplesForSampleKindAndHost> mergedSamples = new ArrayList<SamplesForSampleKindAndHost>();
for (final Map<String, Map<String, SamplesForSampleKindAndHost>> samplesForHost : mergedSamplesMap.values()) {
for (final Map<String, SamplesForSampleKindAndHost> samplesForHostAndEventCategory : samplesForHost.values()) {
mergedSamples.addAll(samplesForHostAndEventCategory.values());
}
}
return mergedSamples;
}
|
diff --git a/src/gui/TerminalTab.java b/src/gui/TerminalTab.java
index 6f934c0..6c93e9e 100644
--- a/src/gui/TerminalTab.java
+++ b/src/gui/TerminalTab.java
@@ -1,45 +1,45 @@
package gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.PrintStream;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
@SuppressWarnings("serial")
public class TerminalTab extends JPanel {
private JTextArea textArea;
public TerminalTab() {
// Setup miscallenous
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
// Setup text area
textArea = new JTextArea(4, 20);
textArea.setEditable(true);
JScrollPane scrollPane = new JScrollPane(textArea,
- ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
- ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
+ ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
+ ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(200, 70));
add(scrollPane, BorderLayout.CENTER);
// Redirect streams
System.setOut(new PrintStream(new JTextAreaOutputStream(textArea)));
System.setErr(new PrintStream(new JTextAreaOutputStream(textArea)));
}
public void setText(String text) {
textArea.append(text);
}
public void clearTerminal() {
textArea.setText("");
}
}
| true | true | public TerminalTab() {
// Setup miscallenous
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
// Setup text area
textArea = new JTextArea(4, 20);
textArea.setEditable(true);
JScrollPane scrollPane = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(200, 70));
add(scrollPane, BorderLayout.CENTER);
// Redirect streams
System.setOut(new PrintStream(new JTextAreaOutputStream(textArea)));
System.setErr(new PrintStream(new JTextAreaOutputStream(textArea)));
}
| public TerminalTab() {
// Setup miscallenous
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
// Setup text area
textArea = new JTextArea(4, 20);
textArea.setEditable(true);
JScrollPane scrollPane = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(200, 70));
add(scrollPane, BorderLayout.CENTER);
// Redirect streams
System.setOut(new PrintStream(new JTextAreaOutputStream(textArea)));
System.setErr(new PrintStream(new JTextAreaOutputStream(textArea)));
}
|
diff --git a/common-composite-component/src/java/org/sakaiproject/component/common/edu/person/SakaiPersonManagerImpl.java b/common-composite-component/src/java/org/sakaiproject/component/common/edu/person/SakaiPersonManagerImpl.java
index e808633..a1dcf4a 100644
--- a/common-composite-component/src/java/org/sakaiproject/component/common/edu/person/SakaiPersonManagerImpl.java
+++ b/common-composite-component/src/java/org/sakaiproject/component/common/edu/person/SakaiPersonManagerImpl.java
@@ -1,572 +1,570 @@
/**********************************************************************************
* $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.component.common.edu.person;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.common.edu.person.SakaiPerson;
import org.sakaiproject.api.common.edu.person.SakaiPersonManager;
import org.sakaiproject.api.common.type.Type;
import org.sakaiproject.api.common.type.TypeManager;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.component.common.manager.PersistableHelper;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/**
* @author <a href="mailto:[email protected]">Lance Speelmon</a>
*/
public class SakaiPersonManagerImpl extends HibernateDaoSupport implements SakaiPersonManager
{
private static final Log LOG = LogFactory.getLog(SakaiPersonManagerImpl.class);
private static final String PERCENT_SIGN = "%";
private static final String SURNAME = "surname";
private static final String GIVENNAME = "givenName";
private static final String UID = "uid";
private static final String TYPE_UUID = "typeUuid";
private static final String AGENT_UUID = "agentUuid";
private static final String AGENT_UUID_COLLECTION = "agentUuidCollection";
private static final String FERPA_ENABLED = "ferpaEnabled";
private static final String HQL_FIND_SAKAI_PERSON_BY_AGENT_AND_TYPE = "findEduPersonByAgentAndType";
private static final String HQL_FIND_SAKAI_PERSONS_BY_AGENTS_AND_TYPE = "findEduPersonsByAgentsAndType";
private static final String HQL_FIND_SAKAI_PERSON_BY_UID = "findSakaiPersonByUid";
private static final int MAX_QUERY_COLLECTION_SIZE = 1000;
private TypeManager typeManager; // dep inj
private PersistableHelper persistableHelper; // dep inj
// SakaiPerson record types
private Type systemMutableType; // oba constant
private Type userMutableType; // oba constant
// hibernate cannot cache BLOB data types - rshastri
// private boolean cacheFindSakaiPersonString = true;
// private boolean cacheFindSakaiPersonStringType = true;
// private boolean cacheFindSakaiPersonSakaiPerson = true;
// private boolean cacheFindSakaiPersonByUid = true;
private static final String[] SYSTEM_MUTBALE_PRIMITIVES = { "org.sakaiproject", "api.common.edu.person",
"SakaiPerson.recordType.systemMutable", "System Mutable SakaiPerson", "System Mutable SakaiPerson", };
private static final String[] USER_MUTBALE_PRIMITIVES = { "org.sakaiproject", "api.common.edu.person",
"SakaiPerson.recordType.userMutable", "User Mutable SakaiPerson", "User Mutable SakaiPerson", };
public void init()
{
LOG.debug("init()");
LOG.debug("// init systemMutableType");
systemMutableType = typeManager.getType(SYSTEM_MUTBALE_PRIMITIVES[0], SYSTEM_MUTBALE_PRIMITIVES[1],
SYSTEM_MUTBALE_PRIMITIVES[2]);
if (systemMutableType == null)
{
systemMutableType = typeManager.createType(SYSTEM_MUTBALE_PRIMITIVES[0], SYSTEM_MUTBALE_PRIMITIVES[1],
SYSTEM_MUTBALE_PRIMITIVES[2], SYSTEM_MUTBALE_PRIMITIVES[3], SYSTEM_MUTBALE_PRIMITIVES[4]);
}
if (systemMutableType == null) throw new IllegalStateException("systemMutableType == null");
LOG.debug("// init userMutableType");
userMutableType = typeManager.getType(USER_MUTBALE_PRIMITIVES[0], USER_MUTBALE_PRIMITIVES[1], USER_MUTBALE_PRIMITIVES[2]);
if (userMutableType == null)
{
userMutableType = typeManager.createType(USER_MUTBALE_PRIMITIVES[0], USER_MUTBALE_PRIMITIVES[1],
USER_MUTBALE_PRIMITIVES[2], USER_MUTBALE_PRIMITIVES[3], USER_MUTBALE_PRIMITIVES[4]);
}
if (userMutableType == null) throw new IllegalStateException("userMutableType == null");
LOG.debug("init() has completed successfully");
}
/**
* @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#create(java.lang.String, java.lang.String, org.sakaiproject.api.common.type.Type)
*/
public SakaiPerson create(String userId, Type recordType)
{
if (LOG.isDebugEnabled())
{
LOG.debug("create(String " + userId + ", Type " + recordType + ")");
}
if (userId == null || userId.length() < 1) throw new IllegalArgumentException("Illegal agentUuid argument passed!");; // a null uid is valid
if (!isSupportedType(recordType)) throw new IllegalArgumentException("Illegal recordType argument passed!");
SakaiPersonImpl spi = new SakaiPersonImpl();
persistableHelper.createPersistableFields(spi);
spi.setUuid(IdManager.createUuid());
spi.setAgentUuid(userId);
spi.setUid(userId);
spi.setTypeUuid(recordType.getUuid());
this.getHibernateTemplate().save(spi);
LOG.debug("return spi;");
return spi;
}
/**
* @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#getSakaiPerson(org.sakaiproject.api.common.type.Type)
*/
public SakaiPerson getSakaiPerson(Type recordType)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getSakaiPerson(Type " + recordType + ")");
}; // no validation required; method is delegated.
LOG.debug("return findSakaiPerson(agent.getUuid(), recordType);");
return getSakaiPerson(SessionManager.getCurrentSessionUserId(), recordType);
}
/**
* @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#getPrototype()
*/
public SakaiPerson getPrototype()
{
LOG.debug("getPrototype()");
return new SakaiPersonImpl();
}
/**
* @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#findSakaiPersonByUid(java.lang.String)
*/
public List findSakaiPersonByUid(final String uid)
{
if (LOG.isDebugEnabled())
{
LOG.debug("findSakaiPersonByUid(String " + uid + ")");
}
if (uid == null || uid.length() < 1) throw new IllegalArgumentException("Illegal uid argument passed!");
final HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException, SQLException
{
final Query q = session.getNamedQuery(HQL_FIND_SAKAI_PERSON_BY_UID);
q.setParameter(UID, uid, Hibernate.STRING);
// q.setCacheable(cacheFindSakaiPersonByUid);
return q.list();
}
};
LOG.debug("return getHibernateTemplate().executeFind(hcb);");
return getHibernateTemplate().executeFind(hcb);
}
/**
* @see SakaiPersonManager#save(SakaiPerson)
*/
public void save(SakaiPerson sakaiPerson)
{
if (LOG.isDebugEnabled())
{
LOG.debug("save(SakaiPerson " + sakaiPerson + ")");
}
if (sakaiPerson == null) throw new IllegalArgumentException("Illegal sakaiPerson argument passed!");
if (!isSupportedType(sakaiPerson.getTypeUuid()))
throw new IllegalArgumentException("The sakaiPerson argument contains an invalid Type!");
// AuthZ
// Only superusers can update system records
if (getSystemMutableType().getUuid().equals(sakaiPerson.getTypeUuid()) && !SecurityService.isSuperUser())
{
throw new IllegalAccessError("System mutable records cannot be updated.");
}
// if it is a user mutable record, enusre the user is updating their own record
if (getUserMutableType().getUuid().equals(sakaiPerson.getTypeUuid()))
{
// AuthZ - Ensure the current user is updating their own record
if (!SessionManager.getCurrentSessionUserId().equals(sakaiPerson.getAgentUuid()))
throw new IllegalAccessError("You do not have permissions to update this record!");
}
// store record
if (!(sakaiPerson instanceof SakaiPersonImpl))
{
// TODO support alternate implementations of SakaiPerson
// copy bean properties into new SakaiPersonImpl with beanutils?
throw new UnsupportedOperationException("Unknown SakaiPerson implementation found!");
}
else
{
// update lastModifiedDate
SakaiPersonImpl spi = (SakaiPersonImpl) sakaiPerson;
persistableHelper.modifyPersistableFields(spi);
// use update(..) method to ensure someone does not try to insert a
// prototype.
getHibernateTemplate().update(spi);
}
}
/**
* @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#findSakaiPerson(java.lang.String, org.sakaiproject.api.common.type.Type)
*/
public SakaiPerson getSakaiPerson(final String agentUuid, final Type recordType)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getSakaiPerson(String " + agentUuid + ", Type " + recordType + ")");
}
if (agentUuid == null || agentUuid.length() < 1) throw new IllegalArgumentException("Illegal agentUuid argument passed!");
if (recordType == null || !isSupportedType(recordType))
throw new IllegalArgumentException("Illegal recordType argument passed!");
final HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException, SQLException
{
Query q = session.getNamedQuery(HQL_FIND_SAKAI_PERSON_BY_AGENT_AND_TYPE);
q.setParameter(AGENT_UUID, agentUuid, Hibernate.STRING);
q.setParameter(TYPE_UUID, recordType.getUuid(), Hibernate.STRING);
// q.setCacheable(false);
return q.uniqueResult();
}
};
LOG.debug("return (SakaiPerson) getHibernateTemplate().execute(hcb);");
return (SakaiPerson) getHibernateTemplate().execute(hcb);
}
public Map<String, SakaiPerson> getSakaiPersons(final Set<String> userIds, final Type recordType)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getSakaiPersons(Collection size " + userIds.size() + ", Type " + recordType + ")");
}
if (userIds == null || userIds.size() == 0) throw new IllegalArgumentException("Illegal agentUuid argument passed!");
if (recordType == null || !isSupportedType(recordType)) throw new IllegalArgumentException("Illegal recordType argument passed!");
int collectionSize = userIds.size();
// Keep an ordered list of userIds
List<String> userIdList = new ArrayList<String>(userIds);
// The map we're return
Map<String, SakaiPerson> map = new HashMap<String, SakaiPerson>(collectionSize);
// Oracle (maybe others, too) can only take up to 1000 parameters total, so chunk the list if necessary
if(collectionSize > MAX_QUERY_COLLECTION_SIZE)
{
int offset = 0;
List<String> userListChunk = new ArrayList<String>();
while(offset < collectionSize)
{
- if((offset+1) % MAX_QUERY_COLLECTION_SIZE == 0) {
+ if(offset > 0 && offset % MAX_QUERY_COLLECTION_SIZE == 0) {
// Our chunk is full, so process the list, clear it, and continue
List<SakaiPerson> personListChunk = listSakaiPersons(userListChunk, recordType);
addSakaiPersonsToMap(personListChunk, map);
userListChunk.clear();
- offset++;
- continue;
}
userListChunk.add(userIdList.get(offset));
offset++;
}
// We may (and probably do) have remaining users that haven't been queried
if( ! userListChunk.isEmpty())
{
List<SakaiPerson> lastChunk = listSakaiPersons(userListChunk, recordType);
addSakaiPersonsToMap(lastChunk, map);
}
}
else
{
addSakaiPersonsToMap(listSakaiPersons(userIds, recordType), map);
}
return map;
}
private void addSakaiPersonsToMap(List<SakaiPerson> sakaiPersons, Map<String, SakaiPerson> map) {
for(Iterator<SakaiPerson> iter = sakaiPersons.iterator(); iter.hasNext();)
{
SakaiPerson person = iter.next();
map.put(person.getAgentUuid(), person);
}
}
private List<SakaiPerson> listSakaiPersons(final Collection<String> userIds, final Type recordType)
{
final HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException, SQLException
{
Query q = session.getNamedQuery(HQL_FIND_SAKAI_PERSONS_BY_AGENTS_AND_TYPE);
q.setParameterList(AGENT_UUID_COLLECTION, userIds);
q.setParameter(TYPE_UUID, recordType.getUuid(), Hibernate.STRING);
// q.setCacheable(false);
return q.list();
}
};
return getHibernateTemplate().executeFind(hcb);
}
/**
* @see SakaiPersonManager#findSakaiPerson(String)
*/
public List findSakaiPerson(final String simpleSearchCriteria)
{
if (LOG.isDebugEnabled())
{
LOG.debug("findSakaiPerson(String " + simpleSearchCriteria + ")");
}
if (simpleSearchCriteria == null || simpleSearchCriteria.length() < 1)
throw new IllegalArgumentException("Illegal simpleSearchCriteria argument passed!");
final String match = PERCENT_SIGN + simpleSearchCriteria + PERCENT_SIGN;
final HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException, SQLException
{
final Criteria c = session.createCriteria(SakaiPersonImpl.class);
c.add(Expression.disjunction().add(Expression.ilike(UID, match)).add(Expression.ilike(GIVENNAME, match)).add(
Expression.ilike(SURNAME, match)));
c.addOrder(Order.asc(SURNAME));
// c.setCacheable(cacheFindSakaiPersonString);
return c.list();
}
};
LOG.debug("return getHibernateTemplate().executeFind(hcb);");
return getHibernateTemplate().executeFind(hcb);
}
/**
* @param typeManager
* The typeManager to set.
*/
public void setTypeManager(TypeManager typeManager)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setTypeManager(TypeManager " + typeManager + ")");
}
this.typeManager = typeManager;
}
/**
* @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#getUserMutableType()
*/
public Type getUserMutableType()
{
LOG.debug("getUserMutableType()");
return userMutableType;
}
/**
* @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#getSystemMutableType()
*/
public Type getSystemMutableType()
{
LOG.debug("getSystemMutableType()");
return systemMutableType;
}
/**
* @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#findSakaiPerson(org.sakaiproject.api.common.edu.person.SakaiPerson)
*/
public List findSakaiPerson(final SakaiPerson queryByExample)
{
if (LOG.isDebugEnabled())
{
LOG.debug("findSakaiPerson(SakaiPerson " + queryByExample + ")");
}
if (queryByExample == null) throw new IllegalArgumentException("Illegal queryByExample argument passed!");
final HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException, SQLException
{
Criteria criteria = session.createCriteria(queryByExample.getClass());
criteria.add(Example.create(queryByExample));
// criteria.setCacheable(cacheFindSakaiPersonSakaiPerson);
return criteria.list();
}
};
LOG.debug("return getHibernateTemplate().executeFind(hcb);");
return getHibernateTemplate().executeFind(hcb);
}
/**
* @see org.sakaiproject.api.common.edu.person.SakaiPersonManager#delete(org.sakaiproject.api.common.edu.person.SakaiPerson)
*/
public void delete(final SakaiPerson sakaiPerson)
{
if (LOG.isDebugEnabled())
{
LOG.debug("delete(SakaiPerson " + sakaiPerson + ")");
}
if (sakaiPerson == null) throw new IllegalArgumentException("Illegal sakaiPerson argument passed!");
LOG.debug("getHibernateTemplate().delete(sakaiPerson);");
getHibernateTemplate().delete(sakaiPerson);
}
private boolean isSupportedType(Type recordType)
{
if (LOG.isDebugEnabled())
{
LOG.debug("isSupportedType(Type " + recordType + ")");
}
if (recordType == null) return false;
if (this.getUserMutableType().equals(recordType)) return true;
if (this.getSystemMutableType().equals(recordType)) return true;
return false;
}
private boolean isSupportedType(String typeUuid)
{
if (LOG.isDebugEnabled())
{
LOG.debug("isSupportedType(String " + typeUuid + ")");
}
if (typeUuid == null) return false;
if (this.getUserMutableType().getUuid().equals(typeUuid)) return true;
if (this.getSystemMutableType().getUuid().equals(typeUuid)) return true;
return false;
}
/**
* @param cacheFindSakaiPersonStringType
* The cacheFindSakaiPersonStringType to set.
*/
// public void setCacheFindSakaiPersonStringType(
// boolean cacheFindSakaiPersonStringType)
// {
// this.cacheFindSakaiPersonStringType = cacheFindSakaiPersonStringType;
// }
/**
* @param cacheFindSakaiPersonString
* The cacheFindSakaiPersonString to set.
*/
// public void setCacheFindSakaiPersonString(boolean cacheFindSakaiPersonString)
// {
// this.cacheFindSakaiPersonString = cacheFindSakaiPersonString;
// }
/**
* @param cacheFindSakaiPersonSakaiPerson
* The cacheFindSakaiPersonSakaiPerson to set.
*/
// public void setCacheFindSakaiPersonSakaiPerson(
// boolean cacheFindSakaiPersonSakaiPerson)
// {
// this.cacheFindSakaiPersonSakaiPerson = cacheFindSakaiPersonSakaiPerson;
// }
/**
* @param cacheFindSakaiPersonByUid
* The cacheFindSakaiPersonByUid to set.
*/
// public void setCacheFindSakaiPersonByUid(boolean cacheFindSakaiPersonByUid)
// {
// this.cacheFindSakaiPersonByUid = cacheFindSakaiPersonByUid;
// }
/**
* @param persistableHelper
* The persistableHelper to set.
*/
public void setPersistableHelper(PersistableHelper persistableHelper)
{
this.persistableHelper = persistableHelper;
}
public List isFerpaEnabled(final Collection agentUuids)
{
if (LOG.isDebugEnabled())
{
LOG.debug("isFerpaEnabled(Set " + agentUuids + ")");
}
if (agentUuids == null || agentUuids.isEmpty())
{
throw new IllegalArgumentException("Illegal Set agentUuids argument!");
}
final HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException, SQLException
{
final Criteria c = session.createCriteria(SakaiPersonImpl.class);
c.add(Expression.in(AGENT_UUID, agentUuids));
c.add(Expression.eq(FERPA_ENABLED, Boolean.TRUE));
return c.list();
}
};
return getHibernateTemplate().executeFind(hcb);
}
public List findAllFerpaEnabled()
{
LOG.debug("findAllFerpaEnabled()");
final HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException, SQLException
{
final Criteria c = session.createCriteria(SakaiPersonImpl.class);
c.add(Expression.eq(FERPA_ENABLED, Boolean.TRUE));
return c.list();
}
};
return getHibernateTemplate().executeFind(hcb);
}
}
| false | true | public Map<String, SakaiPerson> getSakaiPersons(final Set<String> userIds, final Type recordType)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getSakaiPersons(Collection size " + userIds.size() + ", Type " + recordType + ")");
}
if (userIds == null || userIds.size() == 0) throw new IllegalArgumentException("Illegal agentUuid argument passed!");
if (recordType == null || !isSupportedType(recordType)) throw new IllegalArgumentException("Illegal recordType argument passed!");
int collectionSize = userIds.size();
// Keep an ordered list of userIds
List<String> userIdList = new ArrayList<String>(userIds);
// The map we're return
Map<String, SakaiPerson> map = new HashMap<String, SakaiPerson>(collectionSize);
// Oracle (maybe others, too) can only take up to 1000 parameters total, so chunk the list if necessary
if(collectionSize > MAX_QUERY_COLLECTION_SIZE)
{
int offset = 0;
List<String> userListChunk = new ArrayList<String>();
while(offset < collectionSize)
{
if((offset+1) % MAX_QUERY_COLLECTION_SIZE == 0) {
// Our chunk is full, so process the list, clear it, and continue
List<SakaiPerson> personListChunk = listSakaiPersons(userListChunk, recordType);
addSakaiPersonsToMap(personListChunk, map);
userListChunk.clear();
offset++;
continue;
}
userListChunk.add(userIdList.get(offset));
offset++;
}
// We may (and probably do) have remaining users that haven't been queried
if( ! userListChunk.isEmpty())
{
List<SakaiPerson> lastChunk = listSakaiPersons(userListChunk, recordType);
addSakaiPersonsToMap(lastChunk, map);
}
}
else
{
addSakaiPersonsToMap(listSakaiPersons(userIds, recordType), map);
}
return map;
}
| public Map<String, SakaiPerson> getSakaiPersons(final Set<String> userIds, final Type recordType)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getSakaiPersons(Collection size " + userIds.size() + ", Type " + recordType + ")");
}
if (userIds == null || userIds.size() == 0) throw new IllegalArgumentException("Illegal agentUuid argument passed!");
if (recordType == null || !isSupportedType(recordType)) throw new IllegalArgumentException("Illegal recordType argument passed!");
int collectionSize = userIds.size();
// Keep an ordered list of userIds
List<String> userIdList = new ArrayList<String>(userIds);
// The map we're return
Map<String, SakaiPerson> map = new HashMap<String, SakaiPerson>(collectionSize);
// Oracle (maybe others, too) can only take up to 1000 parameters total, so chunk the list if necessary
if(collectionSize > MAX_QUERY_COLLECTION_SIZE)
{
int offset = 0;
List<String> userListChunk = new ArrayList<String>();
while(offset < collectionSize)
{
if(offset > 0 && offset % MAX_QUERY_COLLECTION_SIZE == 0) {
// Our chunk is full, so process the list, clear it, and continue
List<SakaiPerson> personListChunk = listSakaiPersons(userListChunk, recordType);
addSakaiPersonsToMap(personListChunk, map);
userListChunk.clear();
}
userListChunk.add(userIdList.get(offset));
offset++;
}
// We may (and probably do) have remaining users that haven't been queried
if( ! userListChunk.isEmpty())
{
List<SakaiPerson> lastChunk = listSakaiPersons(userListChunk, recordType);
addSakaiPersonsToMap(lastChunk, map);
}
}
else
{
addSakaiPersonsToMap(listSakaiPersons(userIds, recordType), map);
}
return map;
}
|
diff --git a/OUYAControllerANEJava/src/com/gaslightgames/android/ouyacontrollerane/extensions/OUYAControllerANEMotionListener.java b/OUYAControllerANEJava/src/com/gaslightgames/android/ouyacontrollerane/extensions/OUYAControllerANEMotionListener.java
index a12315b..e321ea3 100644
--- a/OUYAControllerANEJava/src/com/gaslightgames/android/ouyacontrollerane/extensions/OUYAControllerANEMotionListener.java
+++ b/OUYAControllerANEJava/src/com/gaslightgames/android/ouyacontrollerane/extensions/OUYAControllerANEMotionListener.java
@@ -1,112 +1,128 @@
package com.gaslightgames.android.ouyacontrollerane.extensions;
import com.adobe.fre.FREContext;
import tv.ouya.console.api.OuyaController;
import android.view.MotionEvent;
import android.view.View;
public class OUYAControllerANEMotionListener implements View.OnGenericMotionListener
{
OUYAControllerANEExtensionContext ouyaExtensionContext;
OuyaController controller;
float leftStickXOld = 0.0f;
float leftStickYOld = 0.0f;
float rightStickXOld = 0.0f;
float rightStickYOld = 0.0f;
float leftStickX = 0.0f;
float leftStickY = 0.0f;
float rightStickX = 0.0f;
float rightStickY = 0.0f;
public OUYAControllerANEMotionListener( FREContext context )
{
this.ouyaExtensionContext = (OUYAControllerANEExtensionContext)context;
}
@Override
public boolean onGenericMotion( View v, MotionEvent event )
{
// -1.5258789E-5
// THIS IS THE "NULL" VALUE!
// Allow the OuyaController class to handle the event - this means we can check which player
// pressed which button/axis.
OuyaController.onGenericMotionEvent( event );
controller = OuyaController.getControllerByDeviceId( event.getDeviceId() );
if( MotionEvent.ACTION_HOVER_MOVE == event.getActionMasked() )
{
// TouchPad movement
this.ouyaExtensionContext.notifyControllerTouchPad( event.getX(), event.getY() );//controller.getPlayerNum(), event.getX(), event.getY() );
}
else
{
// Thumbstick or Trigger move
// Check if Left Thumbstick (Handles +ve and -ve
// Check if X Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_LS_X ) )
{
this.leftStickX = event.getAxisValue( OuyaController.AXIS_LS_X );
}
+ else
+ {
+ this.leftStickX = 0.0f;
+ }
// Check if Y Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_LS_Y ) )
{
this.leftStickY = event.getAxisValue( OuyaController.AXIS_LS_Y );
}
+ else
+ {
+ this.leftStickY = 0.0f;
+ }
- if( this.leftStickXOld != this.leftStickX && this.leftStickYOld != this.leftStickY )
+ if( this.leftStickXOld != this.leftStickX || this.leftStickYOld != this.leftStickY )
{
if( null != controller )
{
this.ouyaExtensionContext.notifyControllerLeftStick( controller.getPlayerNum(), this.leftStickX, this.leftStickY );
}
this.leftStickXOld = this.leftStickX;
this.leftStickYOld = this.leftStickY;
}
// Check if Right Thumbstick
// Check if X Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_RS_X ) )
{
this.rightStickX = event.getAxisValue( OuyaController.AXIS_RS_X );
}
+ else
+ {
+ this.rightStickX = 0.0f;
+ }
// Check if Y Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_RS_Y ) )
{
this.rightStickY = event.getAxisValue( OuyaController.AXIS_RS_Y );
}
+ else
+ {
+ this.rightStickY = 0.0f;
+ }
- if( this.rightStickXOld != this.rightStickX && this.rightStickYOld != this.rightStickY )
+ if( this.rightStickXOld != this.rightStickX || this.rightStickYOld != this.rightStickY )
{
if( null != controller )
{
this.ouyaExtensionContext.notifyControllerRightStick( controller.getPlayerNum(), this.rightStickX, this.rightStickY );
}
this.rightStickXOld = this.rightStickX;
this.rightStickYOld = this.rightStickY;
}
// Check if Left Trigger
if( 0 < event.getAxisValue( OuyaController.AXIS_L2 ) )
{
this.ouyaExtensionContext.notifyControllerLeftTrigger( controller.getPlayerNum(), event.getAxisValue( OuyaController.AXIS_L2 ) );
}
// Check if Right Trigger
if( 0 < event.getAxisValue( OuyaController.AXIS_R2 ) )
{
this.ouyaExtensionContext.notifyControllerRightTrigger( controller.getPlayerNum(), event.getAxisValue( OuyaController.AXIS_R2 ) );
}
}
return true;
}
}
| false | true | public boolean onGenericMotion( View v, MotionEvent event )
{
// -1.5258789E-5
// THIS IS THE "NULL" VALUE!
// Allow the OuyaController class to handle the event - this means we can check which player
// pressed which button/axis.
OuyaController.onGenericMotionEvent( event );
controller = OuyaController.getControllerByDeviceId( event.getDeviceId() );
if( MotionEvent.ACTION_HOVER_MOVE == event.getActionMasked() )
{
// TouchPad movement
this.ouyaExtensionContext.notifyControllerTouchPad( event.getX(), event.getY() );//controller.getPlayerNum(), event.getX(), event.getY() );
}
else
{
// Thumbstick or Trigger move
// Check if Left Thumbstick (Handles +ve and -ve
// Check if X Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_LS_X ) )
{
this.leftStickX = event.getAxisValue( OuyaController.AXIS_LS_X );
}
// Check if Y Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_LS_Y ) )
{
this.leftStickY = event.getAxisValue( OuyaController.AXIS_LS_Y );
}
if( this.leftStickXOld != this.leftStickX && this.leftStickYOld != this.leftStickY )
{
if( null != controller )
{
this.ouyaExtensionContext.notifyControllerLeftStick( controller.getPlayerNum(), this.leftStickX, this.leftStickY );
}
this.leftStickXOld = this.leftStickX;
this.leftStickYOld = this.leftStickY;
}
// Check if Right Thumbstick
// Check if X Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_RS_X ) )
{
this.rightStickX = event.getAxisValue( OuyaController.AXIS_RS_X );
}
// Check if Y Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_RS_Y ) )
{
this.rightStickY = event.getAxisValue( OuyaController.AXIS_RS_Y );
}
if( this.rightStickXOld != this.rightStickX && this.rightStickYOld != this.rightStickY )
{
if( null != controller )
{
this.ouyaExtensionContext.notifyControllerRightStick( controller.getPlayerNum(), this.rightStickX, this.rightStickY );
}
this.rightStickXOld = this.rightStickX;
this.rightStickYOld = this.rightStickY;
}
// Check if Left Trigger
if( 0 < event.getAxisValue( OuyaController.AXIS_L2 ) )
{
this.ouyaExtensionContext.notifyControllerLeftTrigger( controller.getPlayerNum(), event.getAxisValue( OuyaController.AXIS_L2 ) );
}
// Check if Right Trigger
if( 0 < event.getAxisValue( OuyaController.AXIS_R2 ) )
{
this.ouyaExtensionContext.notifyControllerRightTrigger( controller.getPlayerNum(), event.getAxisValue( OuyaController.AXIS_R2 ) );
}
}
return true;
}
| public boolean onGenericMotion( View v, MotionEvent event )
{
// -1.5258789E-5
// THIS IS THE "NULL" VALUE!
// Allow the OuyaController class to handle the event - this means we can check which player
// pressed which button/axis.
OuyaController.onGenericMotionEvent( event );
controller = OuyaController.getControllerByDeviceId( event.getDeviceId() );
if( MotionEvent.ACTION_HOVER_MOVE == event.getActionMasked() )
{
// TouchPad movement
this.ouyaExtensionContext.notifyControllerTouchPad( event.getX(), event.getY() );//controller.getPlayerNum(), event.getX(), event.getY() );
}
else
{
// Thumbstick or Trigger move
// Check if Left Thumbstick (Handles +ve and -ve
// Check if X Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_LS_X ) )
{
this.leftStickX = event.getAxisValue( OuyaController.AXIS_LS_X );
}
else
{
this.leftStickX = 0.0f;
}
// Check if Y Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_LS_Y ) )
{
this.leftStickY = event.getAxisValue( OuyaController.AXIS_LS_Y );
}
else
{
this.leftStickY = 0.0f;
}
if( this.leftStickXOld != this.leftStickX || this.leftStickYOld != this.leftStickY )
{
if( null != controller )
{
this.ouyaExtensionContext.notifyControllerLeftStick( controller.getPlayerNum(), this.leftStickX, this.leftStickY );
}
this.leftStickXOld = this.leftStickX;
this.leftStickYOld = this.leftStickY;
}
// Check if Right Thumbstick
// Check if X Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_RS_X ) )
{
this.rightStickX = event.getAxisValue( OuyaController.AXIS_RS_X );
}
else
{
this.rightStickX = 0.0f;
}
// Check if Y Axis
if( -1.5258789E-5f != event.getAxisValue( OuyaController.AXIS_RS_Y ) )
{
this.rightStickY = event.getAxisValue( OuyaController.AXIS_RS_Y );
}
else
{
this.rightStickY = 0.0f;
}
if( this.rightStickXOld != this.rightStickX || this.rightStickYOld != this.rightStickY )
{
if( null != controller )
{
this.ouyaExtensionContext.notifyControllerRightStick( controller.getPlayerNum(), this.rightStickX, this.rightStickY );
}
this.rightStickXOld = this.rightStickX;
this.rightStickYOld = this.rightStickY;
}
// Check if Left Trigger
if( 0 < event.getAxisValue( OuyaController.AXIS_L2 ) )
{
this.ouyaExtensionContext.notifyControllerLeftTrigger( controller.getPlayerNum(), event.getAxisValue( OuyaController.AXIS_L2 ) );
}
// Check if Right Trigger
if( 0 < event.getAxisValue( OuyaController.AXIS_R2 ) )
{
this.ouyaExtensionContext.notifyControllerRightTrigger( controller.getPlayerNum(), event.getAxisValue( OuyaController.AXIS_R2 ) );
}
}
return true;
}
|
diff --git a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/RuntimeClasspathEntryTests.java b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/RuntimeClasspathEntryTests.java
index 149412133..35fffc824 100644
--- a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/RuntimeClasspathEntryTests.java
+++ b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/RuntimeClasspathEntryTests.java
@@ -1,117 +1,117 @@
package org.eclipse.jdt.debug.tests.core;
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. 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 Corporation - Initial implementation
*********************************************************************/
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.debug.tests.AbstractDebugTest;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.LibraryLocation;
/**
* Tests runtime classpath entry creation/restoration.
*/
public class RuntimeClasspathEntryTests extends AbstractDebugTest {
public RuntimeClasspathEntryTests(String name) {
super(name);
}
public void testProjectEntry() throws Exception {
IProject project = getJavaProject().getProject();
IRuntimeClasspathEntry entry = JavaRuntime.newProjectRuntimeClasspathEntry(getJavaProject());
assertEquals("Paths should be equal", project.getFullPath(), entry.getPath());
assertEquals("Resources should be equal", project, entry.getResource());
assertEquals("Should be of type project", IRuntimeClasspathEntry.PROJECT, entry.getType());
assertEquals("Should be a user entry", IRuntimeClasspathEntry.USER_CLASSES, entry.getClasspathProperty());
String memento = entry.getMemento();
IRuntimeClasspathEntry restored = JavaRuntime.newRuntimeClasspathEntry(memento);
assertEquals("Entries should be equal", entry, restored);
}
public void testJRELIBVariableEntry() throws Exception {
IClasspathEntry[] cp = getJavaProject().getRawClasspath();
IClasspathEntry cpe = null;
for (int i = 0; i < cp.length; i++) {
if (cp[i].getEntryKind() == IClasspathEntry.CPE_VARIABLE && cp[i].getPath().equals(new Path(JavaRuntime.JRELIB_VARIABLE))) {
cpe = cp[i];
break;
}
}
assertNotNull("Did not find a variable entry", cpe);
IRuntimeClasspathEntry entry = JavaRuntime.newVariableRuntimeClasspathEntry(new Path(JavaRuntime.JRELIB_VARIABLE));
entry.setSourceAttachmentPath(cpe.getSourceAttachmentPath());
entry.setSourceAttachmentRootPath(cpe.getSourceAttachmentRootPath());
assertEquals("Paths should be equal", cpe.getPath(), entry.getPath());
assertNull("Resource should be null", entry.getResource());
assertEquals("Should be of type varirable", IRuntimeClasspathEntry.VARIABLE, entry.getType());
assertEquals("Should be a standard entry", IRuntimeClasspathEntry.STANDARD_CLASSES, entry.getClasspathProperty());
String memento = entry.getMemento();
IRuntimeClasspathEntry restored = JavaRuntime.newRuntimeClasspathEntry(memento);
assertEquals("Entries should be equal", entry, restored);
IVMInstall vm = JavaRuntime.getDefaultVMInstall();
LibraryLocation[] libs = vm.getLibraryLocations();
if (libs == null) {
libs = vm.getVMInstallType().getDefaultLibraryLocations(vm.getInstallLocation());
}
- assertEquals("there is one system lib", 1, libs.length);
+ assertTrue("there is at least one system lib", libs.length >= 1);
}
/**
* Tests that a project can be launched if it contains the JRE_CONTAINER variable
* instead of JRE_LIB
*
* XXX: test waiting for bug fix in JCORE - unable to bind container if there
* is no corresponding classpath entry.
*/
// public void testJREContainerEntry() throws Exception {
// ILaunchConfiguration lc = getLaunchConfiguration("Breakpoints");
// ILaunchConfigurationWorkingCopy wc = lc.copy("Breakpoints_JRE_CONTAINER");
//
// IRuntimeClasspathEntry[] cp = JavaRuntime.computeRuntimeClasspath(lc);
// IRuntimeClasspathEntry removed = null;
// List entries = new ArrayList(cp.length);
// // replace JRE_LIB with JRE_CONTAINER
// for (int i = 0; i < cp.length; i++) {
// if (cp[i].getType() == IRuntimeClasspathEntry.VARIABLE) {
// removed = cp[i];
// cp[i] = JavaRuntime.newRuntimeContainerClasspathEntry(new Path(JavaRuntime.JRE_CONTAINER), getJavaProject().getElementName());
// }
// entries.add(cp[i].getMemento());
// }
//
// assertNotNull("Did not replace entry", removed);
// wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false);
// wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, entries);
// lc = wc.doSave();
//
// createLineBreakpoint(52, "Breakpoints");
// IJavaThread thread= null;
// try {
// thread = launch(lc);
// assertNotNull("Launch failed", thread);
// } finally {
// terminateAndRemove(thread);
// removeAllBreakpoints();
// }
// }
}
| true | true | public void testJRELIBVariableEntry() throws Exception {
IClasspathEntry[] cp = getJavaProject().getRawClasspath();
IClasspathEntry cpe = null;
for (int i = 0; i < cp.length; i++) {
if (cp[i].getEntryKind() == IClasspathEntry.CPE_VARIABLE && cp[i].getPath().equals(new Path(JavaRuntime.JRELIB_VARIABLE))) {
cpe = cp[i];
break;
}
}
assertNotNull("Did not find a variable entry", cpe);
IRuntimeClasspathEntry entry = JavaRuntime.newVariableRuntimeClasspathEntry(new Path(JavaRuntime.JRELIB_VARIABLE));
entry.setSourceAttachmentPath(cpe.getSourceAttachmentPath());
entry.setSourceAttachmentRootPath(cpe.getSourceAttachmentRootPath());
assertEquals("Paths should be equal", cpe.getPath(), entry.getPath());
assertNull("Resource should be null", entry.getResource());
assertEquals("Should be of type varirable", IRuntimeClasspathEntry.VARIABLE, entry.getType());
assertEquals("Should be a standard entry", IRuntimeClasspathEntry.STANDARD_CLASSES, entry.getClasspathProperty());
String memento = entry.getMemento();
IRuntimeClasspathEntry restored = JavaRuntime.newRuntimeClasspathEntry(memento);
assertEquals("Entries should be equal", entry, restored);
IVMInstall vm = JavaRuntime.getDefaultVMInstall();
LibraryLocation[] libs = vm.getLibraryLocations();
if (libs == null) {
libs = vm.getVMInstallType().getDefaultLibraryLocations(vm.getInstallLocation());
}
assertEquals("there is one system lib", 1, libs.length);
}
| public void testJRELIBVariableEntry() throws Exception {
IClasspathEntry[] cp = getJavaProject().getRawClasspath();
IClasspathEntry cpe = null;
for (int i = 0; i < cp.length; i++) {
if (cp[i].getEntryKind() == IClasspathEntry.CPE_VARIABLE && cp[i].getPath().equals(new Path(JavaRuntime.JRELIB_VARIABLE))) {
cpe = cp[i];
break;
}
}
assertNotNull("Did not find a variable entry", cpe);
IRuntimeClasspathEntry entry = JavaRuntime.newVariableRuntimeClasspathEntry(new Path(JavaRuntime.JRELIB_VARIABLE));
entry.setSourceAttachmentPath(cpe.getSourceAttachmentPath());
entry.setSourceAttachmentRootPath(cpe.getSourceAttachmentRootPath());
assertEquals("Paths should be equal", cpe.getPath(), entry.getPath());
assertNull("Resource should be null", entry.getResource());
assertEquals("Should be of type varirable", IRuntimeClasspathEntry.VARIABLE, entry.getType());
assertEquals("Should be a standard entry", IRuntimeClasspathEntry.STANDARD_CLASSES, entry.getClasspathProperty());
String memento = entry.getMemento();
IRuntimeClasspathEntry restored = JavaRuntime.newRuntimeClasspathEntry(memento);
assertEquals("Entries should be equal", entry, restored);
IVMInstall vm = JavaRuntime.getDefaultVMInstall();
LibraryLocation[] libs = vm.getLibraryLocations();
if (libs == null) {
libs = vm.getVMInstallType().getDefaultLibraryLocations(vm.getInstallLocation());
}
assertTrue("there is at least one system lib", libs.length >= 1);
}
|
diff --git a/games/matchingpattern/PatternMatchingGame.java b/games/matchingpattern/PatternMatchingGame.java
index 3a88ca4..0a890d1 100644
--- a/games/matchingpattern/PatternMatchingGame.java
+++ b/games/matchingpattern/PatternMatchingGame.java
@@ -1,344 +1,344 @@
package games.matchingpattern;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import render.Geometry;
import render.Material;
import render.Renderer;
import elements.Fonts;
import elements.GameCube;
import games.Game;
import games.maxColorGame.MaxColorGame;
public class PatternMatchingGame extends Game {
java.applet.Applet applet;
Material defaultMaterial;
// Gameplay variables
private int numCubeDimensions = 2;
private double playerScore = 0;
private boolean gameOn = false, gameOver = false, gameWin = false;
// Audio variables
private AudioClip backgroundAudio;
private boolean audioOn = false;
//consecutive elements are pairs
List<Window> images = new ArrayList<Window>();
boolean isTimerOn = false;
MatchingPatternCube mirrorCube;
int currentLevel = 0;
// Loaded constructor
public PatternMatchingGame(java.applet.Applet app, Geometry world, boolean audioStatus)
{
Renderer.setBg("images/background1.png");
// Set game variables
this.applet = app;
this.world = world;
this.audioOn = audioStatus;
// Set cube and tile materials
this.defaultMaterial = new Material();
this.defaultMaterial.setAmbient(0.1, 0.7, 0.1);
this.defaultMaterial.setDiffuse(0.8, 0.8, 0.8);
this.defaultMaterial.setSpecular(0.9, 0.9, 0.9, 10);
}
private void coverCubeWithBGImage()
{
if(this.cube != null)
{
for(int face = 0; face < this.cube.getNumFaces(); face++)
{
for(int row = 1; row <= this.cube.getDimension(); row++)
{
for(int column = 1; column <= this.cube.getDimension(); column++)
{
this.cube.setTileMaterial(face, row, column, defaultMaterial);
((MatchingPatternCube)this.cube).showMeshOnFace(face, row, column,"images/match/background.png");
}
}
}
}
}
@Override
public void initGame() {
// TODO Auto-generated method stub
this.initLevel();
if(this.audioOn)
this.enableAudio();
this.gameOn = true;
}
@Override
public void initLevel() {
playerScore = 0;
currentLevel++;
// If already a cube, clear it out
if(this.cube != null)
{
this.deleteCubeFromWorld();
}
// Re-create the cube
if(currentLevel == 1){
this.cube = new MatchingPatternCube(world, this.numCubeDimensions);
initializeWindowObjects();
coverCubeWithBGImage();
this.gameOn = true;
}else if(currentLevel == 2){
this.cube = new MatchingPatternCube(world, this.numCubeDimensions+1);
initializeWindowObjects();
coverCubeWithBGImage();
this.gameOn = true;
}
}
private void initializeWindowObjects() {
if(this.cube != null)
{
for(int face = 0; face < this.cube.getNumFaces(); face++)
{
for(int row = 1; row <= this.cube.getDimension(); row++)
{
for(int column = 1; column <= this.cube.getDimension(); column++)
{
images.add(new Window(face,row,column));
}
}
}
}
Collections.shuffle(images);
int counter = 1;
for(int i = 0; i<images.size();){
if(counter <= 12){
images.get(i).imageId = counter+".png";
images.get(i+1).imageId = counter+".png";
i= i+2;
}else{
images.get(i).imageId = "default.png";
i++;
}
counter++;
}
for(int i = 0; i< images.size();){
if(i < 24){
images.get(i).matchingpair = images.get(i+1);
images.get(i+1).matchingpair = images.get(i);
i=i+2;
}else{
images.get(i).matchingpair = null;
i++;
}
}
}
@Override
public void stop() {
this.gameOn = false;
// Delete the 3D cube from the world
this.deleteCubeFromWorld();
// End any audio
if(this.backgroundAudio != null)
{
this.backgroundAudio.stop();
this.backgroundAudio = null;
}
}
@Override
public void clickTile(int face, int row, int column) {
if(this.gameOn && getOpenImages() < 2 )
{
// Spread the tile color to the touching side tiles
for(Window w:images){
if(face == w.face && row == w.row && column== w.col){
if(!w.isOpen){
((MatchingPatternCube)this.cube).showMeshOnFace(face, row, column,"images/match/"+w.imageId);
w.isOpen = true;
if(w.matchingpair != null){
if(w.isOpen && w.matchingpair.isOpen){
w.isDiscovered = true;
w.matchingpair.isDiscovered = true;
}
}else{
w.isDiscovered = true;
}
if(!isTimerOn){
isTimerOn = true;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
isTimerOn = false;
refreshAllCubes();
if(islevelOver()){
initLevel();
}
}
- },1000);
+ },5000);
}
}
}
}
}
}
private int getOpenImages() {
int counter = 0;
for(Window w:images){
if(w.isOpen){
counter++;
}
}
return counter;
}
protected void refreshAllCubes() {
if(this.cube != null)
{
for(int face = 0; face < this.cube.getNumFaces(); face++)
{
for(int row = 1; row <= this.cube.getDimension(); row++)
{
for(int column = 1; column <= this.cube.getDimension(); column++)
{
for(Window w:images){
if(face == w.face && row == w.row && column== w.col){
if(!w.isDiscovered){
((MatchingPatternCube)this.cube).showMeshOnFace(face, row, column,"images/match/background.png");
}
w.isOpen = false;
}
}
}
}
}
}
}
public boolean islevelOver(){
for(Window w:images){
if(!w.isDiscovered){
return false;
}
}
return true;
}
//these are gonna be same for all the games
// should be present in super class
@Override
public void toggleAudio(boolean b) {
if(b)
enableAudio();
else
disableAudio();
}
@Override
public void enableAudio()
{
if(this.backgroundAudio == null)
{
this.backgroundAudio = this.applet.getAudioClip(this.applet.getCodeBase(),
"audio/background2.wav");
}
this.backgroundAudio.loop();
}
@Override
public void disableAudio()
{
if (this.backgroundAudio != null) {
this.backgroundAudio.stop();
}
}
@Override
public void animate(double time) {
if(this.cube != null)
{
this.cube.animate(time);
}
}
@Override
public void drawOverlay(Graphics g) {
// If game is over, draw the message
if(this.gameOver)
{
g.setColor(Color.RED);
g.setFont(Fonts.BIG_FONT);
g.drawString("GAME OVER", 220, 200);
}
// Draw lives and level information
g.setColor(Color.BLUE);
g.setFont(Fonts.BIG_FONT);
// Draw the top level text
g.drawString("Match Pictures", 150, 30);
g.setFont(Fonts.SMALL_FONT);
g.drawString("Click on a tile to see its picture", 150, 65);
g.drawString("and find its corresponding pair", 150, 85);
g.drawString("Level "+currentLevel,20,420);
}
}
| true | true | public void clickTile(int face, int row, int column) {
if(this.gameOn && getOpenImages() < 2 )
{
// Spread the tile color to the touching side tiles
for(Window w:images){
if(face == w.face && row == w.row && column== w.col){
if(!w.isOpen){
((MatchingPatternCube)this.cube).showMeshOnFace(face, row, column,"images/match/"+w.imageId);
w.isOpen = true;
if(w.matchingpair != null){
if(w.isOpen && w.matchingpair.isOpen){
w.isDiscovered = true;
w.matchingpair.isDiscovered = true;
}
}else{
w.isDiscovered = true;
}
if(!isTimerOn){
isTimerOn = true;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
isTimerOn = false;
refreshAllCubes();
if(islevelOver()){
initLevel();
}
}
},1000);
}
}
}
}
}
}
| public void clickTile(int face, int row, int column) {
if(this.gameOn && getOpenImages() < 2 )
{
// Spread the tile color to the touching side tiles
for(Window w:images){
if(face == w.face && row == w.row && column== w.col){
if(!w.isOpen){
((MatchingPatternCube)this.cube).showMeshOnFace(face, row, column,"images/match/"+w.imageId);
w.isOpen = true;
if(w.matchingpair != null){
if(w.isOpen && w.matchingpair.isOpen){
w.isDiscovered = true;
w.matchingpair.isDiscovered = true;
}
}else{
w.isDiscovered = true;
}
if(!isTimerOn){
isTimerOn = true;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
isTimerOn = false;
refreshAllCubes();
if(islevelOver()){
initLevel();
}
}
},5000);
}
}
}
}
}
}
|
diff --git a/srcj/com/sun/electric/tool/logicaleffort/LENodable.java b/srcj/com/sun/electric/tool/logicaleffort/LENodable.java
index 661b60097..fd7c52b64 100644
--- a/srcj/com/sun/electric/tool/logicaleffort/LENodable.java
+++ b/srcj/com/sun/electric/tool/logicaleffort/LENodable.java
@@ -1,347 +1,349 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: LENodable.java
* Written by: Jonathan Gainsley, Sun Microsystems.
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.logicaleffort;
import com.sun.electric.database.hierarchy.Nodable;
import com.sun.electric.database.network.Network;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.technologies.Schematics;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class LENodable {
/** Type is a typesafe enum class that describes the type of Instance this is */
protected static class Type {
private final String name;
private Type(String name) { this.name = name; }
public String toString() { return name; }
/** NotSizeable */ protected static final Type STATICGATE = new Type("Static Gate");
/** NotSizeable */ protected static final Type LOAD = new Type("Load");
/** NotSizeable */ protected static final Type WIRE = new Type("Wire");
/** LeGate */ protected static final Type LEGATE = new Type("LE Gate");
/** LeKeeper */ protected static final Type LEKEEPER = new Type("LE Keeper");
/** NotSizeable */ protected static final Type TRANSISTOR = new Type("Transistor");
/** NotSizeable */ protected static final Type CAPACITOR = new Type("Capacitor");
/** Cached cell */ protected static final Type CACHEDCELL = new Type("Cached Cell");
/** Ingore */ protected static final Type IGNORE = new Type("LE Ingore");
}
// --------- Definition fields ----------
/** list of pins */ private List pins; // do not point to networks
/** nodable */ private Nodable no;
/** gate type */ private Type type;
/** output Network */ private Network outputNet;
/** mfactor variable */ private Variable mfactorVar;
/** su variable */ private Variable suVar;
/** parallel group # variable */ private Variable parallelGroupVar;
// --------- instance fields ------------
protected VarContext context;
protected LENetwork outputNetwork; // global network
protected float mfactor;
protected float su;
protected float leX;
protected int parallelGroup;
/**
* Create a new LEInstance tied to the Nodable.
* If the type represents a singular instance, i.e. whose properties
* do not change based on it's location in the hierarchy, then
* leContext is the singular (one and only) context.
* Otherwise, leContext is merely the first of many possible contexts.
* @param no the Nodable
*/
public LENodable(Nodable no, Type type, Variable mfactorVar, Variable suVar, Variable parallelGroupVar) {
this.no = no;
this.type = type;
pins = new ArrayList();
this.outputNet = null;
this.mfactorVar = mfactorVar;
this.suVar = suVar;
this.parallelGroupVar = parallelGroupVar;
this.context = VarContext.globalContext;
}
protected LENodable copy() {
LENodable copy = new LENodable(no, type, mfactorVar, suVar, parallelGroupVar);
for (Iterator it = pins.iterator(); it.hasNext(); ) {
LEPin pin = (LEPin)it.next();
copy.addPort(pin.getName(), pin.getDir(), pin.getLE(), pin.getNetwork());
}
return copy;
}
/**
* Add a port to this LEInstance
* @param name the name of the port
* @param dir the direction of the port
* @param le the logical effort of the port
*/
protected void addPort(String name, LEPin.Dir dir, float le, Network jnet) {
LEPin pin = new LEPin(name, dir, le, jnet, this);
pins.add(pin);
}
/** Set the output network */
protected void setOutputNet(Network jnet) { outputNet = jnet; }
/** Get the output network */
protected Network getOutputNet() { return outputNet; }
/** Get the nodable */
protected Nodable getNodable() { return no; }
/** Get the type */
protected Type getType() { return type; }
/** Get the pins */
protected List getPins() { return pins; }
/** Return true if this is a sizeable gate */
protected boolean isLeGate() {
if (type == Type.LEKEEPER || type == Type.LEGATE) return true;
return false;
}
/** True if this is a gate */
protected boolean isGate() {
if (type == Type.LEGATE || type == Type.LEKEEPER || type == Type.STATICGATE)
return true;
return false;
}
/**
* Set the only context of this LENodable. This is used when the nodable is cacheable,
* and remains the same throughout all contexts above the passed context.
* Returns false if provided context is not enough to evaluate all variables properly.
* @param context the context
* @param outputNetwork the global network loading the output
* @param mfactor the parent's mfactor
* @param su the parent's step-up
*/
protected boolean setOnlyContext(VarContext context, LENetwork outputNetwork, float mfactor, float su, LENetlister2.NetlisterConstants constants) {
boolean evalOk = instantiate(this, context, outputNetwork, mfactor, su, constants, true);
//print();
return evalOk;
}
/**
* Factory method to create a copy of this Nodable with the context-relevant info
* evaluated.
* @param context the context
* @param outputNetwork the global network loading the output
* @param mfactor the parent's mfactor
* @param su the parent's step-up
*/
protected LENodable createUniqueInstance(VarContext context, LENetwork outputNetwork, float mfactor, float su, LENetlister2.NetlisterConstants constants) {
LENodable instance = new LENodable(no, type, mfactorVar, suVar, parallelGroupVar);
// copy pins
for (Iterator it = pins.iterator(); it.hasNext(); ) {
LEPin pin = (LEPin)it.next();
instance.addPort(pin.getName(), pin.getDir(), pin.getLE(), pin.getNetwork());
}
instantiate(instance, context, outputNetwork, mfactor, su, constants, false);
return instance;
}
/**
* Fill-in the given LENodable with evalutated instance-specific info for the given context.
* Returns false if there are variables that cannot be evaluated in the given context
* @param instance the LENodable to fill-in
* @param context the context
* @param outputNetwork the global network loading the output
* @param mfactor the parent's mfactor
* @param su the parent's step-up
*/
private boolean instantiate(LENodable instance, VarContext context, LENetwork outputNetwork, float mfactor, float su,
LENetlister2.NetlisterConstants constants, boolean testCachebility) {
instance.outputNetwork = outputNetwork;
boolean evalOk = true;
// default values
instance.context = context;
instance.leX = getLeX(context, constants, testCachebility);
if (instance.leX == -1f) evalOk = false;
instance.mfactor = mfactor;
instance.su = su;
instance.parallelGroup = 0;
// evaluate variables in context, if any
if (parallelGroupVar != null) {
Object retVal = context.evalVar(parallelGroupVar);
if (retVal == null) evalOk = false;
else instance.parallelGroup = VarContext.objectToInt(retVal, instance.parallelGroup);
}
if (suVar != null) {
Object retVal = context.evalVar(suVar);
if (retVal == null) evalOk = false;
else {
float localsu = VarContext.objectToFloat(retVal, -1f);
instance.su = (localsu == -1f) ? instance.su : localsu;
}
}
if (mfactorVar != null) {
Object retVal = context.evalVar(mfactorVar);
if (retVal == null) evalOk = false;
else instance.mfactor *= VarContext.objectToFloat(retVal, 1f);
}
return evalOk;
}
/**
* Get the leX size for the given LENodable
* Returns -1 if any evaluations failed.
* @param context the VarContext
* @return the leX size, or -1 if eval failed
*/
private float getLeX(VarContext context, LENetlister2.NetlisterConstants constants, boolean testCachebility) {
float leX = (float)0.0;
Variable var = null;
Object retVal = null;
if (type == LENodable.Type.WIRE) {
// Note that if inst is an LEWIRE, it will have no 'le' attributes.
// we therefore assign pins to have default 'le' values of one.
// This creates an instance which has Type LEWIRE, but has
// boolean leGate set to false; it will not be sized
var = no.getVar("ATTR_L");
if (var == null) {
System.out.println("Error, no L attribute found on LEWIRE "+no.getName()+" in Cell "+no.getParent());
if (testCachebility) return -1f;
}
retVal = context.evalVar(var);
+ if (testCachebility && (retVal == null)) return -1f;
float len = VarContext.objectToFloat(retVal, 0.0f);
var = no.getVar(Schematics.ATTR_WIDTH);
if (var == null) {
System.out.println("Warning, no width attribute found on LEWIRE "+no.getName()+" in Cell "+no.getParent());
if (testCachebility) return -1f;
}
retVal = context.evalVar(var);
+ if (testCachebility && (retVal == null)) return -1f;
float width = VarContext.objectToFloat(retVal, 3.0f);
leX = (float)(0.95f*len + 0.05f*len*(width/3.0f))*constants.wireRatio; // equivalent lambda of gate
leX = leX/9.0f; // drive strength X=1 is 9 lambda of gate
}
else if (type == LENodable.Type.TRANSISTOR) {
var = no.getVar(Schematics.ATTR_WIDTH);
if (var == null) {
System.out.println("Error: transistor "+no.getName()+" has no width in Cell "+no.getParent());
//ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+no+" has no width in Cell "+info.getCell(), info.getCell(), 0);
//log.addGeom(ni.getNodeInst(), true, no.getParent(), context);
return -1f;
}
retVal = context.evalVar(var);
//System.out.println("retVal: "+retVal);
float width = VarContext.objectToFloat(retVal, (float)3.0);
var = no.getVar(Schematics.ATTR_LENGTH);
if (var == null) {
System.out.println("Error: transistor "+no.getName()+" has no length in Cell "+no.getParent());
//ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+ni+" has no length in Cell "+info.getCell(), info.getCell(), 0);
//log.addGeom(ni.getNodeInst(), true, info.getCell(), info.getContext());
return -1f;
}
retVal = context.evalVar(var);
if (retVal == null) return -1f;
float length = VarContext.objectToFloat(retVal, (float)2.0);
// not exactly correct because assumes all cap is area cap, which it isn't
leX = (float)(width*length/2.0f);
leX = leX/9.0f;
}
else if (type == Type.CAPACITOR) {
var = no.getVar(Schematics.SCHEM_CAPACITANCE);
if (var == null) {
System.out.println("Error: capacitor "+no.getName()+" has no capacitance in Cell "+no.getParent());
//ErrorLogger.ErrorLog log = errorLogger.logError("Error: capacitor "+no+" has no capacitance in Cell "+info.getCell(), info.getCell(), 0);
//log.addGeom(ni.getNodeInst(), true, no.getParent(), context);
return -1f;
}
retVal = context.evalVar(var);
- if (retVal == null) return -1f;
+ if (testCachebility && (retVal == null)) return -1f;
float cap = VarContext.objectToFloat(retVal, (float)0.0);
leX = (float)(cap/constants.gateCap/1e-15/9.0f);
}
return leX;
}
// -----------------------------------------------------------------
protected String getName() {
if (context == null) return no.getName();
return context.push(getNodable()).getInstPath(".");
}
protected void print() {
System.out.println(getType().toString()+": "+getName());
System.out.println(" Size \t= "+leX);
System.out.println(" Step-up \t= "+su);
System.out.println(" Parallel Group\t= "+parallelGroup);
System.out.println(" M Factor\t= "+mfactor);
}
protected String printOneLine(String indent) {
StringBuffer buf = new StringBuffer(indent);
buf.append(getType().toString());
buf.append(": Size="+TextUtils.formatDouble(leX, 2));
buf.append(" M="+TextUtils.formatDouble(mfactor, 2));
buf.append(" tPG="+parallelGroup);
buf.append(" "+getName());
return buf.toString();
}
protected void printPins() {
for (Iterator it = pins.iterator(); it.hasNext(); ) {
LEPin pin = (LEPin)it.next();
System.out.println("Pin "+pin.getName()+", le="+pin.getLE()+", dir="+pin.getDir()+" on network "+pin.getNetwork());
}
}
protected float printLoadInfo(LEPin pin, float alpha) {
StringBuffer buf = new StringBuffer();
buf.append(getType().toString());
buf.append("\tSize="+TextUtils.formatDouble(leX, 2));
buf.append("\tLE="+TextUtils.formatDouble(pin.getLE(), 2));
buf.append("\tM="+TextUtils.formatDouble(mfactor, 2));
float load;
if (pin.getDir() == LEPin.Dir.OUTPUT) {
load = (float)(leX*pin.getLE()*mfactor*alpha);
buf.append("\tAlpha="+alpha);
buf.append("\tLoad="+TextUtils.formatDouble(load, 2));
} else {
load = (float)(leX*pin.getLE()*mfactor);
buf.append("\tLoad="+TextUtils.formatDouble(load, 2));
}
buf.append("\t"+getName());
System.out.println(buf.toString());
return load;
}
}
| false | true | private float getLeX(VarContext context, LENetlister2.NetlisterConstants constants, boolean testCachebility) {
float leX = (float)0.0;
Variable var = null;
Object retVal = null;
if (type == LENodable.Type.WIRE) {
// Note that if inst is an LEWIRE, it will have no 'le' attributes.
// we therefore assign pins to have default 'le' values of one.
// This creates an instance which has Type LEWIRE, but has
// boolean leGate set to false; it will not be sized
var = no.getVar("ATTR_L");
if (var == null) {
System.out.println("Error, no L attribute found on LEWIRE "+no.getName()+" in Cell "+no.getParent());
if (testCachebility) return -1f;
}
retVal = context.evalVar(var);
float len = VarContext.objectToFloat(retVal, 0.0f);
var = no.getVar(Schematics.ATTR_WIDTH);
if (var == null) {
System.out.println("Warning, no width attribute found on LEWIRE "+no.getName()+" in Cell "+no.getParent());
if (testCachebility) return -1f;
}
retVal = context.evalVar(var);
float width = VarContext.objectToFloat(retVal, 3.0f);
leX = (float)(0.95f*len + 0.05f*len*(width/3.0f))*constants.wireRatio; // equivalent lambda of gate
leX = leX/9.0f; // drive strength X=1 is 9 lambda of gate
}
else if (type == LENodable.Type.TRANSISTOR) {
var = no.getVar(Schematics.ATTR_WIDTH);
if (var == null) {
System.out.println("Error: transistor "+no.getName()+" has no width in Cell "+no.getParent());
//ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+no+" has no width in Cell "+info.getCell(), info.getCell(), 0);
//log.addGeom(ni.getNodeInst(), true, no.getParent(), context);
return -1f;
}
retVal = context.evalVar(var);
//System.out.println("retVal: "+retVal);
float width = VarContext.objectToFloat(retVal, (float)3.0);
var = no.getVar(Schematics.ATTR_LENGTH);
if (var == null) {
System.out.println("Error: transistor "+no.getName()+" has no length in Cell "+no.getParent());
//ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+ni+" has no length in Cell "+info.getCell(), info.getCell(), 0);
//log.addGeom(ni.getNodeInst(), true, info.getCell(), info.getContext());
return -1f;
}
retVal = context.evalVar(var);
if (retVal == null) return -1f;
float length = VarContext.objectToFloat(retVal, (float)2.0);
// not exactly correct because assumes all cap is area cap, which it isn't
leX = (float)(width*length/2.0f);
leX = leX/9.0f;
}
else if (type == Type.CAPACITOR) {
var = no.getVar(Schematics.SCHEM_CAPACITANCE);
if (var == null) {
System.out.println("Error: capacitor "+no.getName()+" has no capacitance in Cell "+no.getParent());
//ErrorLogger.ErrorLog log = errorLogger.logError("Error: capacitor "+no+" has no capacitance in Cell "+info.getCell(), info.getCell(), 0);
//log.addGeom(ni.getNodeInst(), true, no.getParent(), context);
return -1f;
}
retVal = context.evalVar(var);
if (retVal == null) return -1f;
float cap = VarContext.objectToFloat(retVal, (float)0.0);
leX = (float)(cap/constants.gateCap/1e-15/9.0f);
}
return leX;
}
| private float getLeX(VarContext context, LENetlister2.NetlisterConstants constants, boolean testCachebility) {
float leX = (float)0.0;
Variable var = null;
Object retVal = null;
if (type == LENodable.Type.WIRE) {
// Note that if inst is an LEWIRE, it will have no 'le' attributes.
// we therefore assign pins to have default 'le' values of one.
// This creates an instance which has Type LEWIRE, but has
// boolean leGate set to false; it will not be sized
var = no.getVar("ATTR_L");
if (var == null) {
System.out.println("Error, no L attribute found on LEWIRE "+no.getName()+" in Cell "+no.getParent());
if (testCachebility) return -1f;
}
retVal = context.evalVar(var);
if (testCachebility && (retVal == null)) return -1f;
float len = VarContext.objectToFloat(retVal, 0.0f);
var = no.getVar(Schematics.ATTR_WIDTH);
if (var == null) {
System.out.println("Warning, no width attribute found on LEWIRE "+no.getName()+" in Cell "+no.getParent());
if (testCachebility) return -1f;
}
retVal = context.evalVar(var);
if (testCachebility && (retVal == null)) return -1f;
float width = VarContext.objectToFloat(retVal, 3.0f);
leX = (float)(0.95f*len + 0.05f*len*(width/3.0f))*constants.wireRatio; // equivalent lambda of gate
leX = leX/9.0f; // drive strength X=1 is 9 lambda of gate
}
else if (type == LENodable.Type.TRANSISTOR) {
var = no.getVar(Schematics.ATTR_WIDTH);
if (var == null) {
System.out.println("Error: transistor "+no.getName()+" has no width in Cell "+no.getParent());
//ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+no+" has no width in Cell "+info.getCell(), info.getCell(), 0);
//log.addGeom(ni.getNodeInst(), true, no.getParent(), context);
return -1f;
}
retVal = context.evalVar(var);
//System.out.println("retVal: "+retVal);
float width = VarContext.objectToFloat(retVal, (float)3.0);
var = no.getVar(Schematics.ATTR_LENGTH);
if (var == null) {
System.out.println("Error: transistor "+no.getName()+" has no length in Cell "+no.getParent());
//ErrorLogger.ErrorLog log = errorLogger.logError("Error: transistor "+ni+" has no length in Cell "+info.getCell(), info.getCell(), 0);
//log.addGeom(ni.getNodeInst(), true, info.getCell(), info.getContext());
return -1f;
}
retVal = context.evalVar(var);
if (retVal == null) return -1f;
float length = VarContext.objectToFloat(retVal, (float)2.0);
// not exactly correct because assumes all cap is area cap, which it isn't
leX = (float)(width*length/2.0f);
leX = leX/9.0f;
}
else if (type == Type.CAPACITOR) {
var = no.getVar(Schematics.SCHEM_CAPACITANCE);
if (var == null) {
System.out.println("Error: capacitor "+no.getName()+" has no capacitance in Cell "+no.getParent());
//ErrorLogger.ErrorLog log = errorLogger.logError("Error: capacitor "+no+" has no capacitance in Cell "+info.getCell(), info.getCell(), 0);
//log.addGeom(ni.getNodeInst(), true, no.getParent(), context);
return -1f;
}
retVal = context.evalVar(var);
if (testCachebility && (retVal == null)) return -1f;
float cap = VarContext.objectToFloat(retVal, (float)0.0);
leX = (float)(cap/constants.gateCap/1e-15/9.0f);
}
return leX;
}
|
diff --git a/src/com/farproc/wifi/connecter/ReenableAllApsWhenNetworkStateChanged.java b/src/com/farproc/wifi/connecter/ReenableAllApsWhenNetworkStateChanged.java
index 432f21b..5b62256 100644
--- a/src/com/farproc/wifi/connecter/ReenableAllApsWhenNetworkStateChanged.java
+++ b/src/com/farproc/wifi/connecter/ReenableAllApsWhenNetworkStateChanged.java
@@ -1,105 +1,102 @@
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import java.util.List;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.IBinder;
public class ReenableAllApsWhenNetworkStateChanged {
public static void schedule(final Context ctx) {
ctx.startService(new Intent(ctx, BackgroundService.class));
}
private static void reenableAllAps(final Context ctx) {
final WifiManager wifiMgr = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE);
final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
if(configurations != null) {
for(final WifiConfiguration config:configurations) {
wifiMgr.enableNetwork(config.networkId, false);
}
}
}
public static class BackgroundService extends Service {
private boolean mReenabled;
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
final NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
final NetworkInfo.DetailedState detailed = networkInfo.getDetailedState();
- switch(detailed) {
- case DISCONNECTED:
- case DISCONNECTING:
- case SCANNING:
- return;
- default:
+ if(detailed != NetworkInfo.DetailedState.DISCONNECTED
+ && detailed != NetworkInfo.DetailedState.DISCONNECTING
+ && detailed != NetworkInfo.DetailedState.SCANNING) {
if(!mReenabled) {
mReenabled = true;
reenableAllAps(context);
stopSelf();
}
}
}
}
};
private IntentFilter mIntentFilter;
@Override
public IBinder onBind(Intent intent) {
return null; // We need not bind to it at all.
}
@Override
public void onCreate() {
super.onCreate();
mReenabled = false;
mIntentFilter = new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(mReceiver, mIntentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
final NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
final NetworkInfo.DetailedState detailed = networkInfo.getDetailedState();
switch(detailed) {
case DISCONNECTED:
case DISCONNECTING:
case SCANNING:
return;
default:
if(!mReenabled) {
mReenabled = true;
reenableAllAps(context);
stopSelf();
}
}
}
}
| public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
final NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
final NetworkInfo.DetailedState detailed = networkInfo.getDetailedState();
if(detailed != NetworkInfo.DetailedState.DISCONNECTED
&& detailed != NetworkInfo.DetailedState.DISCONNECTING
&& detailed != NetworkInfo.DetailedState.SCANNING) {
if(!mReenabled) {
mReenabled = true;
reenableAllAps(context);
stopSelf();
}
}
}
}
|
diff --git a/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java b/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java
index f59f0f3e7..fe3f05cc7 100644
--- a/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java
+++ b/providers/netty/src/main/java/com/ning/http/client/providers/netty/NettyAsyncHttpProvider.java
@@ -1,2504 +1,2504 @@
/*
* Copyright 2010-2013 Ning, Inc.
*
* Ning 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 com.ning.http.client.providers.netty;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHandler.STATE;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpProvider;
import com.ning.http.client.Body;
import com.ning.http.client.BodyGenerator;
import com.ning.http.client.ConnectionPoolKeyStrategy;
import com.ning.http.client.ConnectionsPool;
import com.ning.http.client.Cookie;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.MaxRedirectException;
import com.ning.http.client.PerRequestConfig;
import com.ning.http.client.ProgressAsyncHandler;
import com.ning.http.client.ProxyServer;
import com.ning.http.client.RandomAccessBody;
import com.ning.http.client.Realm;
import com.ning.http.client.Request;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Response;
import com.ning.http.client.filter.FilterContext;
import com.ning.http.client.filter.FilterException;
import com.ning.http.client.filter.IOExceptionFilter;
import com.ning.http.client.filter.ResponseFilter;
import com.ning.http.client.generators.InputStreamBodyGenerator;
import com.ning.http.client.listener.TransferCompletionHandler;
import com.ning.http.client.ntlm.NTLMEngine;
import com.ning.http.client.ntlm.NTLMEngineException;
import com.ning.http.client.providers.netty.FeedableBodyGenerator.FeedListener;
import com.ning.http.client.providers.netty.spnego.SpnegoEngine;
import com.ning.http.client.websocket.WebSocketUpgradeHandler;
import com.ning.http.multipart.MultipartBody;
import com.ning.http.multipart.MultipartRequestEntity;
import com.ning.http.util.AsyncHttpProviderUtils;
import com.ning.http.util.AuthenticatorUtils;
import com.ning.http.client.providers.netty.util.CleanupChannelGroup;
import com.ning.http.util.ProxyUtils;
import com.ning.http.util.SslUtils;
import com.ning.http.util.UTF8UrlEncoder;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferOutputStream;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureProgressListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DefaultChannelFuture;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.FileRegion;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultCookie;
import org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
import org.jboss.netty.handler.codec.http.HttpClientCodec;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder;
import org.jboss.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.stream.ChunkedFile;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.ning.http.util.MiscUtil.isNonEmpty;
import static com.ning.http.util.AsyncHttpProviderUtils.DEFAULT_CHARSET;
import static org.jboss.netty.channel.Channels.pipeline;
public class NettyAsyncHttpProvider extends SimpleChannelUpstreamHandler implements AsyncHttpProvider {
private final static String WEBSOCKET_KEY = "Sec-WebSocket-Key";
private final static String HTTP_HANDLER = "httpHandler";
protected final static String SSL_HANDLER = "sslHandler";
private final static String HTTPS = "https";
private final static String HTTP = "http";
private static final String WEBSOCKET = "ws";
private static final String WEBSOCKET_SSL = "wss";
private final static Logger log = LoggerFactory.getLogger(NettyAsyncHttpProvider.class);
private final static Charset UTF8 = Charset.forName("UTF-8");
private final ClientBootstrap plainBootstrap;
private final ClientBootstrap secureBootstrap;
private final ClientBootstrap webSocketBootstrap;
private final ClientBootstrap secureWebSocketBootstrap;
private final static int MAX_BUFFERED_BYTES = 8192;
private final AsyncHttpClientConfig config;
private final AtomicBoolean isClose = new AtomicBoolean(false);
private final ClientSocketChannelFactory socketChannelFactory;
private final boolean allowReleaseSocketChannelFactory;
private final ChannelGroup openChannels = new
CleanupChannelGroup("asyncHttpClient") {
@Override
public boolean remove(Object o) {
boolean removed = super.remove(o);
if (removed && trackConnections) {
freeConnections.release();
}
return removed;
}
};
private final ConnectionsPool<String, Channel> connectionsPool;
private Semaphore freeConnections = null;
private final NettyAsyncHttpProviderConfig asyncHttpProviderConfig;
private boolean executeConnectAsync = true;
public static final ThreadLocal<Boolean> IN_IO_THREAD = new ThreadLocalBoolean();
private final boolean trackConnections;
private final boolean useRawUrl;
private final static NTLMEngine ntlmEngine = new NTLMEngine();
private static SpnegoEngine spnegoEngine = null;
private final Protocol httpProtocol = new HttpProtocol();
private final Protocol webSocketProtocol = new WebSocketProtocol();
public NettyAsyncHttpProvider(AsyncHttpClientConfig config) {
if (config.getAsyncHttpProviderConfig() != null
&& NettyAsyncHttpProviderConfig.class.isAssignableFrom(config.getAsyncHttpProviderConfig().getClass())) {
asyncHttpProviderConfig = NettyAsyncHttpProviderConfig.class.cast(config.getAsyncHttpProviderConfig());
} else {
asyncHttpProviderConfig = new NettyAsyncHttpProviderConfig();
}
if (asyncHttpProviderConfig.isUseBlockingIO()) {
socketChannelFactory = new OioClientSocketChannelFactory(config.executorService());
this.allowReleaseSocketChannelFactory = true;
} else {
// check if external NioClientSocketChannelFactory is defined
NioClientSocketChannelFactory scf = asyncHttpProviderConfig.getSocketChannelFactory();
if (scf != null) {
this.socketChannelFactory = scf;
// cannot allow releasing shared channel factory
this.allowReleaseSocketChannelFactory = false;
} else {
ExecutorService e = asyncHttpProviderConfig.getBossExecutorService();
if (e == null) {
e = Executors.newCachedThreadPool();
}
int numWorkers = config.getIoThreadMultiplier() * Runtime.getRuntime().availableProcessors();
log.debug("Number of application's worker threads is {}", numWorkers);
socketChannelFactory = new NioClientSocketChannelFactory(e, config.executorService(), numWorkers);
this.allowReleaseSocketChannelFactory = true;
}
}
plainBootstrap = new ClientBootstrap(socketChannelFactory);
secureBootstrap = new ClientBootstrap(socketChannelFactory);
webSocketBootstrap = new ClientBootstrap(socketChannelFactory);
secureWebSocketBootstrap = new ClientBootstrap(socketChannelFactory);
configureNetty();
this.config = config;
// This is dangerous as we can't catch a wrong typed ConnectionsPool
ConnectionsPool<String, Channel> cp = (ConnectionsPool<String, Channel>) config.getConnectionsPool();
if (cp == null && config.getAllowPoolingConnection()) {
cp = new NettyConnectionsPool(this);
} else if (cp == null) {
cp = new NonConnectionsPool();
}
this.connectionsPool = cp;
if (config.getMaxTotalConnections() != -1) {
trackConnections = true;
freeConnections = new Semaphore(config.getMaxTotalConnections());
} else {
trackConnections = false;
}
useRawUrl = config.isUseRawUrl();
}
@Override
public String toString() {
return String.format("NettyAsyncHttpProvider:\n\t- maxConnections: %d\n\t- openChannels: %s\n\t- connectionPools: %s",
config.getMaxTotalConnections() - freeConnections.availablePermits(),
openChannels.toString(),
connectionsPool.toString());
}
void configureNetty() {
if (asyncHttpProviderConfig != null) {
for (Entry<String, Object> entry : asyncHttpProviderConfig.propertiesSet()) {
String key = entry.getKey();
Object value = entry.getValue();
plainBootstrap.setOption(key, value);
webSocketBootstrap.setOption(key, value);
secureBootstrap.setOption(key, value);
secureWebSocketBootstrap.setOption(key, value);
}
}
plainBootstrap.setPipelineFactory(createPlainPipelineFactory());
DefaultChannelFuture.setUseDeadLockChecker(false);
if (asyncHttpProviderConfig != null) {
executeConnectAsync = asyncHttpProviderConfig.isAsyncConnect();
if (!executeConnectAsync) {
DefaultChannelFuture.setUseDeadLockChecker(true);
}
}
webSocketBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast("ws-decoder", new HttpResponseDecoder());
pipeline.addLast("ws-encoder", new HttpRequestEncoder());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
}
protected HttpClientCodec newHttpClientCodec() {
if (asyncHttpProviderConfig != null) {
return new HttpClientCodec(asyncHttpProviderConfig.getMaxInitialLineLength(), asyncHttpProviderConfig.getMaxHeaderSize(), asyncHttpProviderConfig.getMaxChunkSize(), false);
} else {
return new HttpClientCodec();
}
}
protected ChannelPipelineFactory createPlainPipelineFactory() {
return new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
pipeline.addLast(HTTP_HANDLER, newHttpClientCodec());
if (config.getRequestCompressionLevel() > 0) {
pipeline.addLast("deflater", new HttpContentCompressor(config.getRequestCompressionLevel()));
}
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
};
}
void constructSSLPipeline(final NettyConnectListener<?> cl) {
secureBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
try {
pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
} catch (Throwable ex) {
abort(cl.future(), ex);
}
pipeline.addLast(HTTP_HANDLER, newHttpClientCodec());
if (config.isCompressionEnabled()) {
pipeline.addLast("inflater", new HttpContentDecompressor());
}
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
secureWebSocketBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
/* @Override */
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
try {
pipeline.addLast(SSL_HANDLER, new SslHandler(createSSLEngine()));
} catch (Throwable ex) {
abort(cl.future(), ex);
}
pipeline.addLast("ws-decoder", new HttpResponseDecoder());
pipeline.addLast("ws-encoder", new HttpRequestEncoder());
pipeline.addLast("httpProcessor", NettyAsyncHttpProvider.this);
return pipeline;
}
});
}
private Channel lookupInCache(URI uri, ConnectionPoolKeyStrategy connectionPoolKeyStrategy) {
final Channel channel = connectionsPool.poll(connectionPoolKeyStrategy.getKey(uri));
if (channel != null) {
log.debug("Using cached Channel {}\n for uri {}\n", channel, uri);
try {
// Always make sure the channel who got cached support the proper protocol. It could
// only occurs when a HttpMethod.CONNECT is used agains a proxy that require upgrading from http to
// https.
return verifyChannelPipeline(channel, uri.getScheme());
} catch (Exception ex) {
log.debug(ex.getMessage(), ex);
}
}
return null;
}
private SSLEngine createSSLEngine() throws IOException, GeneralSecurityException {
SSLEngine sslEngine = config.getSSLEngineFactory().newSSLEngine();
if (sslEngine == null) {
sslEngine = SslUtils.getSSLEngine();
}
return sslEngine;
}
private Channel verifyChannelPipeline(Channel channel, String scheme) throws IOException, GeneralSecurityException {
if (channel.getPipeline().get(SSL_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
channel.getPipeline().remove(SSL_HANDLER);
} else if (channel.getPipeline().get(HTTP_HANDLER) != null && HTTP.equalsIgnoreCase(scheme)) {
return channel;
} else if (channel.getPipeline().get(SSL_HANDLER) == null && isSecure(scheme)) {
channel.getPipeline().addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
}
return channel;
}
protected final <T> void writeRequest(final Channel channel,
final AsyncHttpClientConfig config,
final NettyResponseFuture<T> future,
final HttpRequest nettyRequest) {
try {
/**
* If the channel is dead because it was pooled and the remote server decided to close it,
* we just let it go and the closeChannel do it's work.
*/
if (!channel.isOpen() || !channel.isConnected()) {
return;
}
Body body = null;
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
BodyGenerator bg = future.getRequest().getBodyGenerator();
if (bg != null) {
// Netty issue with chunking.
if (InputStreamBodyGenerator.class.isAssignableFrom(bg.getClass())) {
InputStreamBodyGenerator.class.cast(bg).patchNettyChunkingIssue(true);
}
try {
body = bg.createBody();
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
long length = body.getContentLength();
if (length >= 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, length);
} else {
nettyRequest.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
}
} else {
body = null;
}
}
if (TransferCompletionHandler.class.isAssignableFrom(future.getAsyncHandler().getClass())) {
FluentCaseInsensitiveStringsMap h = new FluentCaseInsensitiveStringsMap();
for (String s : future.getNettyRequest().getHeaderNames()) {
for (String header : future.getNettyRequest().getHeaders(s)) {
h.add(s, header);
}
}
TransferCompletionHandler.class.cast(future.getAsyncHandler()).transferAdapter(
new NettyTransferAdapter(h, nettyRequest.getContent(), future.getRequest().getFile()));
}
// Leave it to true.
if (future.getAndSetWriteHeaders(true)) {
try {
channel.write(nettyRequest).addListener(new ProgressListener(true, future.getAsyncHandler(), future));
} catch (Throwable cause) {
log.debug(cause.getMessage(), cause);
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
}
if (future.getAndSetWriteBody(true)) {
if (!future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)) {
if (future.getRequest().getFile() != null) {
final File file = future.getRequest().getFile();
long fileLength = 0;
final RandomAccessFile raf = new RandomAccessFile(file, "r");
try {
fileLength = raf.length();
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) != null) {
writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192));
} else {
final FileRegion region = new OptimizedFileRegion(raf, 0, fileLength);
writeFuture = channel.write(region);
}
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future));
} catch (IOException ex) {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
}
}
throw ex;
}
} else if (body != null || future.getRequest().getParts() != null) {
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (future.getRequest().getParts() != null) {
String boundary = future.getNettyRequest().getHeader("Content-Type");
String length = future.getNettyRequest().getHeader("Content-Length");
body = new MultipartBody(future.getRequest().getParts(), boundary, length);
}
ChannelFuture writeFuture;
if (channel.getPipeline().get(SslHandler.class) == null && (body instanceof RandomAccessBody)) {
BodyFileRegion bodyFileRegion = new BodyFileRegion((RandomAccessBody) body);
writeFuture = channel.write(bodyFileRegion);
} else {
BodyChunkedInput bodyChunkedInput = new BodyChunkedInput(body);
BodyGenerator bg = future.getRequest().getBodyGenerator();
if (bg instanceof FeedableBodyGenerator) {
((FeedableBodyGenerator)bg).setListener(new FeedListener() {
@Override public void onContentAdded() {
channel.getPipeline().get(ChunkedWriteHandler.class).resumeTransfer();
}
});
}
writeFuture = channel.write(bodyChunkedInput);
}
final Body b = body;
writeFuture.addListener(new ProgressListener(false, future.getAsyncHandler(), future) {
public void operationComplete(ChannelFuture cf) {
try {
b.close();
} catch (IOException e) {
log.warn("Failed to close request body: {}", e.getMessage(), e);
}
super.operationComplete(cf);
}
});
}
}
}
} catch (Throwable ioe) {
try {
channel.close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
}
try {
future.touch();
int delay = requestTimeout(config, future.getRequest().getPerRequestConfig());
if (delay != -1 && !future.isDone() && !future.isCancelled()) {
ReaperFuture reaperFuture = new ReaperFuture(future);
Future<?> scheduledFuture = config.reaper().scheduleAtFixedRate(reaperFuture, 0, delay, TimeUnit.MILLISECONDS);
reaperFuture.setScheduledFuture(scheduledFuture);
future.setReaperFuture(reaperFuture);
}
} catch (RejectedExecutionException ex) {
abort(future, ex);
}
}
protected final static HttpRequest buildRequest(AsyncHttpClientConfig config, Request request, URI uri,
boolean allowConnect, ChannelBuffer buffer, ProxyServer proxyServer) throws IOException {
String method = request.getMethod();
if (allowConnect && proxyServer != null && isSecure(uri)) {
method = HttpMethod.CONNECT.toString();
}
return construct(config, request, new HttpMethod(method), uri, buffer, proxyServer);
}
private static SpnegoEngine getSpnegoEngine() {
if(spnegoEngine == null)
spnegoEngine = new SpnegoEngine();
return spnegoEngine;
}
private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri,
ChannelBuffer buffer,
ProxyServer proxyServer) throws IOException {
String host = AsyncHttpProviderUtils.getHost(uri);
boolean webSocket = isWebSocket(uri);
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else {
String path = null;
- if (proxyServer != null)
+ if (proxyServer != null && !isSecure(uri))
path = uri.toString();
else if (uri.getRawQuery() != null)
path = uri.getRawPath() + "?" + uri.getRawQuery();
else
path = uri.getRawPath();
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path);
}
if (webSocket) {
nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
nettyRequest.addHeader("Origin", "http://" + uri.getHost() + ":"
+ (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
nettyRequest.addHeader(WEBSOCKET_KEY, WebSocketUtil.getKey());
nettyRequest.addHeader("Sec-WebSocket-Version", "13");
}
if (host != null) {
if (uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else if (request.getVirtualHost() != null) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
} else {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (isNonEmpty(auth) && auth.get(0).startsWith("NTLM")) {
nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
String domain = realm.getNtlmDomain();
if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
domain = proxyServer.getNtlmDomain();
}
String authHost = realm.getNtlmHost();
if (proxyServer != null && proxyServer.getHost() != null) {
host = proxyServer.getHost();
}
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (isNonEmpty(realm.getNonce())) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost);
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String server = proxyServer == null ? host : proxyServer.getHost();
try {
challengeHeader = getSpnegoEngine().generateToken(server);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
case NONE:
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
if (proxyServer != null) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", "keep-alive");
}
if (proxyServer.getPrincipal() != null) {
if (isNonEmpty(proxyServer.getNtlmDomain())) {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (!(isNonEmpty(auth) && auth.get(0).startsWith("NTLM"))) {
try {
String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(),
proxyServer.getHost());
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
}
} else {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") != null) {
nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else {
nettyRequest.setHeader("User-Agent",
AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class,
config));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (isNonEmpty(request.getCookies())) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
String reqType = request.getMethod();
if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getStringData().getBytes(bodyCharset)));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length));
} else if (isNonEmpty(request.getParams())) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (isSecure(uri)) {
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
}
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
public void close() {
isClose.set(true);
try {
connectionsPool.destroy();
openChannels.close();
for (Channel channel : openChannels) {
ChannelHandlerContext ctx = channel.getPipeline().getContext(NettyAsyncHttpProvider.class);
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.setReaperFuture(null);
}
}
config.executorService().shutdown();
config.reaper().shutdown();
if (this.allowReleaseSocketChannelFactory) {
socketChannelFactory.releaseExternalResources();
plainBootstrap.releaseExternalResources();
secureBootstrap.releaseExternalResources();
webSocketBootstrap.releaseExternalResources();
secureWebSocketBootstrap.releaseExternalResources();
}
} catch (Throwable t) {
log.warn("Unexpected error on close", t);
}
}
/* @Override */
public Response prepareResponse(final HttpResponseStatus status,
final HttpResponseHeaders headers,
final List<HttpResponseBodyPart> bodyParts) {
return new NettyResponse(status, headers, bodyParts);
}
/* @Override */
public <T> ListenableFuture<T> execute(Request request, final AsyncHandler<T> asyncHandler) throws IOException {
return doConnect(request, asyncHandler, null, true, executeConnectAsync, false);
}
private <T> void execute(final Request request, final NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
doConnect(request, f.getAsyncHandler(), f, useCache, asyncConnect, reclaimCache);
}
private <T> ListenableFuture<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f,
boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException {
if (isClose.get()) {
throw new IOException("Closed");
}
if (request.getUrl().startsWith(WEBSOCKET) && !validateWebSocketRequest(request, asyncHandler)) {
throw new IOException("WebSocket method must be a GET");
}
ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
URI uri;
if (useRawUrl) {
uri = request.getRawURI();
} else {
uri = request.getURI();
}
Channel channel = null;
if (useCache) {
if (f != null && f.reuseChannel() && f.channel() != null) {
channel = f.channel();
} else {
channel = lookupInCache(uri, request.getConnectionPoolKeyStrategy());
}
}
ChannelBuffer bufferedBytes = null;
if (f != null && f.getRequest().getFile() == null &&
!f.getNettyRequest().getMethod().getName().equals(HttpMethod.CONNECT.getName())) {
bufferedBytes = f.getNettyRequest().getContent();
}
boolean useSSl = isSecure(uri) && proxyServer == null;
if (channel != null && channel.isOpen() && channel.isConnected()) {
HttpRequest nettyRequest = buildRequest(config, request, uri, f == null ? false : f.isConnectAllowed(), bufferedBytes, proxyServer);
if (f == null) {
f = newFuture(uri, request, asyncHandler, nettyRequest, config, this, proxyServer);
} else {
nettyRequest = buildRequest(config, request, uri, f.isConnectAllowed(), bufferedBytes, proxyServer);
f.setNettyRequest(nettyRequest);
}
f.setState(NettyResponseFuture.STATE.POOLED);
f.attachChannel(channel, false);
log.debug("\nUsing cached Channel {}\n for request \n{}\n", channel, nettyRequest);
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(f);
try {
writeRequest(channel, config, f, nettyRequest);
} catch (Exception ex) {
log.debug("writeRequest failure", ex);
if (useSSl && ex.getMessage() != null && ex.getMessage().contains("SSLEngine")) {
log.debug("SSLEngine failure", ex);
f = null;
} else {
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("doConnect.writeRequest()", t);
}
IOException ioe = new IOException(ex.getMessage());
ioe.initCause(ex);
throw ioe;
}
}
return f;
}
// Do not throw an exception when we need an extra connection for a redirect.
if (!reclaimCache && !connectionsPool.canCacheConnection()) {
IOException ex = new IOException(String.format("Too many connections %s", config.getMaxTotalConnections()));
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("!connectionsPool.canCacheConnection()", t);
}
throw ex;
}
boolean acquiredConnection = false;
if (trackConnections) {
if (!reclaimCache) {
if (!freeConnections.tryAcquire()) {
IOException ex = new IOException(String.format("Too many connections %s", config.getMaxTotalConnections()));
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
log.warn("!connectionsPool.canCacheConnection()", t);
}
throw ex;
} else {
acquiredConnection = true;
}
}
}
NettyConnectListener<T> c = new NettyConnectListener.Builder<T>(config, request, asyncHandler, f, this, bufferedBytes).build(uri);
boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, uri.getHost());
if (useSSl) {
constructSSLPipeline(c);
}
ChannelFuture channelFuture;
ClientBootstrap bootstrap = request.getUrl().startsWith(WEBSOCKET) ? (useSSl ? secureWebSocketBootstrap : webSocketBootstrap) : (useSSl ? secureBootstrap : plainBootstrap);
bootstrap.setOption("connectTimeoutMillis", config.getConnectionTimeoutInMs());
try {
InetSocketAddress remoteAddress;
if (request.getInetAddress() != null) {
remoteAddress = new InetSocketAddress(request.getInetAddress(), AsyncHttpProviderUtils.getPort(uri));
} else if (proxyServer == null || avoidProxy) {
remoteAddress = new InetSocketAddress(AsyncHttpProviderUtils.getHost(uri), AsyncHttpProviderUtils.getPort(uri));
} else {
remoteAddress = new InetSocketAddress(proxyServer.getHost(), proxyServer.getPort());
}
if(request.getLocalAddress() != null){
channelFuture = bootstrap.connect(remoteAddress, new InetSocketAddress(request.getLocalAddress(), 0));
}else{
channelFuture = bootstrap.connect(remoteAddress);
}
} catch (Throwable t) {
if (acquiredConnection) {
freeConnections.release();
}
abort(c.future(), t.getCause() == null ? t : t.getCause());
return c.future();
}
boolean directInvokation = true;
if (IN_IO_THREAD.get() && DefaultChannelFuture.isUseDeadLockChecker()) {
directInvokation = false;
}
if (directInvokation && !asyncConnect && request.getFile() == null) {
int timeOut = config.getConnectionTimeoutInMs() > 0 ? config.getConnectionTimeoutInMs() : Integer.MAX_VALUE;
if (!channelFuture.awaitUninterruptibly(timeOut, TimeUnit.MILLISECONDS)) {
if (acquiredConnection) {
freeConnections.release();
}
channelFuture.cancel();
abort(c.future(), new ConnectException(String.format("Connect operation to %s timeout %s", uri, timeOut)));
}
try {
c.operationComplete(channelFuture);
} catch (Exception e) {
if (acquiredConnection) {
freeConnections.release();
}
IOException ioe = new IOException(e.getMessage());
ioe.initCause(e);
try {
asyncHandler.onThrowable(ioe);
} catch (Throwable t) {
log.warn("c.operationComplete()", t);
}
throw ioe;
}
} else {
channelFuture.addListener(c);
}
log.debug("\nNon cached request \n{}\n\nusing Channel \n{}\n", c.future().getNettyRequest(), channelFuture.getChannel());
if (!c.future().isCancelled() || !c.future().isDone()) {
openChannels.add(channelFuture.getChannel());
c.future().attachChannel(channelFuture.getChannel(), false);
}
return c.future();
}
protected static int requestTimeout(AsyncHttpClientConfig config, PerRequestConfig perRequestConfig) {
int result;
if (perRequestConfig != null) {
int prRequestTimeout = perRequestConfig.getRequestTimeoutInMs();
result = (prRequestTimeout != 0 ? prRequestTimeout : config.getRequestTimeoutInMs());
} else {
result = config.getRequestTimeoutInMs();
}
return result;
}
private void closeChannel(final ChannelHandlerContext ctx) {
connectionsPool.removeAll(ctx.getChannel());
finishChannel(ctx);
}
private void finishChannel(final ChannelHandlerContext ctx) {
ctx.setAttachment(new DiscardEvent());
// The channel may have already been removed if a timeout occurred, and this method may be called just after.
if (ctx.getChannel() == null) {
return;
}
log.debug("Closing Channel {} ", ctx.getChannel());
try {
ctx.getChannel().close();
} catch (Throwable t) {
log.debug("Error closing a connection", t);
}
if (ctx.getChannel() != null) {
openChannels.remove(ctx.getChannel());
}
}
@Override
public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception {
//call super to reset the read timeout
super.messageReceived(ctx, e);
IN_IO_THREAD.set(Boolean.TRUE);
if (ctx.getAttachment() == null) {
log.debug("ChannelHandlerContext wasn't having any attachment");
}
if (ctx.getAttachment() instanceof DiscardEvent) {
return;
} else if (ctx.getAttachment() instanceof AsyncCallable) {
if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (chunk.isLast()) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
} else {
return;
}
} else {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ac.call();
}
ctx.setAttachment(new DiscardEvent());
return;
} else if (!(ctx.getAttachment() instanceof NettyResponseFuture<?>)) {
try {
ctx.getChannel().close();
} catch (Throwable t) {
log.trace("Closing an orphan channel {}", ctx.getChannel());
}
return;
}
Protocol p = (ctx.getPipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
p.handle(ctx, e);
}
private Realm kerberosChallenge(List<String> proxyAuth,
Request request,
ProxyServer proxyServer,
FluentCaseInsensitiveStringsMap headers,
Realm realm,
NettyResponseFuture<?> future) throws NTLMEngineException {
URI uri = request.getURI();
String host = request.getVirtualHost() == null ? AsyncHttpProviderUtils.getHost(uri) : request.getVirtualHost();
String server = proxyServer == null ? host : proxyServer.getHost();
try {
String challengeHeader = getSpnegoEngine().generateToken(server);
headers.remove(HttpHeaders.Names.AUTHORIZATION);
headers.add(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
Realm.RealmBuilder realmBuilder;
if (realm != null) {
realmBuilder = new Realm.RealmBuilder().clone(realm);
} else {
realmBuilder = new Realm.RealmBuilder();
}
return realmBuilder.setUri(uri.getRawPath())
.setMethodName(request.getMethod())
.setScheme(Realm.AuthScheme.KERBEROS)
.build();
} catch (Throwable throwable) {
if (proxyAuth.contains("NTLM")) {
return ntlmChallenge(proxyAuth, request, proxyServer, headers, realm, future);
}
abort(future, throwable);
return null;
}
}
private Realm ntlmChallenge(List<String> wwwAuth,
Request request,
ProxyServer proxyServer,
FluentCaseInsensitiveStringsMap headers,
Realm realm,
NettyResponseFuture<?> future) throws NTLMEngineException {
boolean useRealm = (proxyServer == null && realm != null);
String ntlmDomain = useRealm ? realm.getNtlmDomain() : proxyServer.getNtlmDomain();
String ntlmHost = useRealm ? realm.getNtlmHost() : proxyServer.getHost();
String principal = useRealm ? realm.getPrincipal() : proxyServer.getPrincipal();
String password = useRealm ? realm.getPassword() : proxyServer.getPassword();
Realm newRealm;
if (realm != null && !realm.isNtlmMessageType2Received()) {
String challengeHeader = ntlmEngine.generateType1Msg(ntlmDomain, ntlmHost);
URI uri = request.getURI();
headers.add(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
newRealm = new Realm.RealmBuilder().clone(realm).setScheme(realm.getAuthScheme())
.setUri(uri.getRawPath())
.setMethodName(request.getMethod())
.setNtlmMessageType2Received(true)
.build();
future.getAndSetAuth(false);
} else {
headers.remove(HttpHeaders.Names.AUTHORIZATION);
if (wwwAuth.get(0).startsWith("NTLM ")) {
String serverChallenge = wwwAuth.get(0).trim().substring("NTLM ".length());
String challengeHeader = ntlmEngine.generateType3Msg(principal, password,
ntlmDomain, ntlmHost, serverChallenge);
headers.add(HttpHeaders.Names.AUTHORIZATION, "NTLM " + challengeHeader);
}
Realm.RealmBuilder realmBuilder;
Realm.AuthScheme authScheme;
if (realm != null) {
realmBuilder = new Realm.RealmBuilder().clone(realm);
authScheme = realm.getAuthScheme();
} else {
realmBuilder = new Realm.RealmBuilder();
authScheme = Realm.AuthScheme.NTLM;
}
newRealm = realmBuilder.setScheme(authScheme)
.setUri(request.getURI().getPath())
.setMethodName(request.getMethod())
.build();
}
return newRealm;
}
private Realm ntlmProxyChallenge(List<String> wwwAuth,
Request request,
ProxyServer proxyServer,
FluentCaseInsensitiveStringsMap headers,
Realm realm,
NettyResponseFuture<?> future) throws NTLMEngineException {
future.getAndSetAuth(false);
headers.remove(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (wwwAuth.get(0).startsWith("NTLM ")) {
String serverChallenge = wwwAuth.get(0).trim().substring("NTLM ".length());
String challengeHeader = ntlmEngine.generateType3Msg(proxyServer.getPrincipal(),
proxyServer.getPassword(),
proxyServer.getNtlmDomain(),
proxyServer.getHost(),
serverChallenge);
headers.add(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
Realm newRealm;
Realm.RealmBuilder realmBuilder;
if (realm != null) {
realmBuilder = new Realm.RealmBuilder().clone(realm);
} else {
realmBuilder = new Realm.RealmBuilder();
}
newRealm = realmBuilder//.setScheme(realm.getAuthScheme())
.setUri(request.getURI().getPath())
.setMethodName(request.getMethod())
.build();
return newRealm;
}
private void drainChannel(final ChannelHandlerContext ctx, final NettyResponseFuture<?> future, final boolean keepAlive, final URI uri) {
ctx.setAttachment(new AsyncCallable(future) {
public Object call() throws Exception {
if (keepAlive && ctx.getChannel().isReadable() && connectionsPool.offer(future.getConnectionPoolKeyStrategy().getKey(uri), ctx.getChannel())) {
return null;
}
finishChannel(ctx);
return null;
}
@Override
public String toString() {
return String.format("Draining task for channel %s", ctx.getChannel());
}
});
}
private FilterContext handleIoException(FilterContext fc, NettyResponseFuture<?> future) {
for (IOExceptionFilter asyncFilter : config.getIOExceptionFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
return fc;
}
private void replayRequest(final NettyResponseFuture<?> future, FilterContext fc, HttpResponse response, ChannelHandlerContext ctx) throws IOException {
final Request newRequest = fc.getRequest();
future.setAsyncHandler(fc.getAsyncHandler());
future.setState(NettyResponseFuture.STATE.NEW);
future.touch();
log.debug("\n\nReplaying Request {}\n for Future {}\n", newRequest, future);
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
nextRequest(newRequest, future);
return;
}
private List<String> getAuthorizationToken(List<Entry<String, String>> list, String headerAuth) {
ArrayList<String> l = new ArrayList<String>();
for (Entry<String, String> e : list) {
if (e.getKey().equalsIgnoreCase(headerAuth)) {
l.add(e.getValue().trim());
}
}
return l;
}
private void nextRequest(final Request request, final NettyResponseFuture<?> future) throws IOException {
nextRequest(request, future, true);
}
private void nextRequest(final Request request, final NettyResponseFuture<?> future, final boolean useCache) throws IOException {
execute(request, future, useCache, true, true);
}
private void abort(NettyResponseFuture<?> future, Throwable t) {
Channel channel = future.channel();
if (channel != null && openChannels.contains(channel)) {
closeChannel(channel.getPipeline().getContext(NettyAsyncHttpProvider.class));
openChannels.remove(channel);
}
if (!future.isCancelled() && !future.isDone()) {
log.debug("Aborting Future {}\n", future);
log.debug(t.getMessage(), t);
}
future.abort(t);
}
private void upgradeProtocol(ChannelPipeline p, String scheme) throws IOException, GeneralSecurityException {
if (p.get(HTTP_HANDLER) != null) {
p.remove(HTTP_HANDLER);
}
if (isSecure(scheme)) {
if (p.get(SSL_HANDLER) == null) {
p.addFirst(HTTP_HANDLER, newHttpClientCodec());
p.addFirst(SSL_HANDLER, new SslHandler(createSSLEngine()));
} else {
p.addAfter(SSL_HANDLER, HTTP_HANDLER, newHttpClientCodec());
}
} else {
p.addFirst(HTTP_HANDLER, newHttpClientCodec());
}
}
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
if (isClose.get()) {
return;
}
connectionsPool.removeAll(ctx.getChannel());
try {
super.channelClosed(ctx, e);
} catch (Exception ex) {
log.trace("super.channelClosed", ex);
}
log.debug("Channel Closed: {} with attachment {}", e.getChannel(), ctx.getAttachment());
if (ctx.getAttachment() instanceof AsyncCallable) {
AsyncCallable ac = (AsyncCallable) ctx.getAttachment();
ctx.setAttachment(ac.future());
ac.call();
return;
}
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
if (config.getIOExceptionFilters().size() > 0) {
FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(new IOException("Channel Closed")).build();
fc = handleIoException(fc, future);
if (fc.replayRequest() && !future.cannotBeReplay()) {
replayRequest(future, fc, null, ctx);
return;
}
}
Protocol p = (ctx.getPipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
p.onClose(ctx, e);
if (future != null && !future.isDone() && !future.isCancelled()) {
if (!remotelyClosed(ctx.getChannel(), future)) {
abort(future, new IOException("Remotely Closed " + ctx.getChannel()));
}
} else {
closeChannel(ctx);
}
}
}
protected boolean remotelyClosed(Channel channel, NettyResponseFuture<?> future) {
if (isClose.get()) {
return false;
}
connectionsPool.removeAll(channel);
if (future == null && channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment() != null
&& NettyResponseFuture.class.isAssignableFrom(
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment().getClass())) {
future = (NettyResponseFuture<?>)
channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment();
}
if (future == null || future.cannotBeReplay()) {
log.debug("Unable to recover future {}\n", future);
return false;
}
future.setState(NettyResponseFuture.STATE.RECONNECTED);
future.getAndSetStatusReceived(false);
log.debug("Trying to recover request {}\n", future.getNettyRequest());
try {
nextRequest(future.getRequest(), future);
return true;
} catch (IOException iox) {
future.setState(NettyResponseFuture.STATE.CLOSED);
future.abort(iox);
log.error("Remotely Closed, unable to recover", iox);
}
return false;
}
private void markAsDone(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx) throws MalformedURLException {
// We need to make sure everything is OK before adding the connection back to the pool.
try {
future.done(null);
} catch (Throwable t) {
// Never propagate exception once we know we are done.
log.debug(t.getMessage(), t);
}
if (!future.getKeepAlive() || !ctx.getChannel().isReadable()) {
closeChannel(ctx);
}
}
private void finishUpdate(final NettyResponseFuture<?> future, final ChannelHandlerContext ctx, boolean lastValidChunk) throws IOException {
if (lastValidChunk && future.getKeepAlive()) {
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
} else {
if (future.getKeepAlive() && ctx.getChannel().isReadable() &&
connectionsPool.offer(future.getConnectionPoolKeyStrategy().getKey(future.getURI()), ctx.getChannel())) {
markAsDone(future, ctx);
return;
}
finishChannel(ctx);
}
markAsDone(future, ctx);
}
private final boolean updateStatusAndInterrupt(AsyncHandler<?> handler, HttpResponseStatus c) throws Exception {
return handler.onStatusReceived(c) != STATE.CONTINUE;
}
private final boolean updateHeadersAndInterrupt(AsyncHandler<?> handler, HttpResponseHeaders c) throws Exception {
return handler.onHeadersReceived(c) != STATE.CONTINUE;
}
private final boolean updateBodyAndInterrupt(final NettyResponseFuture<?> future, AsyncHandler<?> handler, HttpResponseBodyPart c) throws Exception {
boolean state = handler.onBodyPartReceived(c) != STATE.CONTINUE;
if (c.closeUnderlyingConnection()) {
future.setKeepAlive(false);
}
return state;
}
//Simple marker for stopping publishing bytes.
final static class DiscardEvent {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
Channel channel = e.getChannel();
Throwable cause = e.getCause();
NettyResponseFuture<?> future = null;
/** Issue 81
if (e.getCause() != null && e.getCause().getClass().isAssignableFrom(PrematureChannelClosureException.class)) {
return;
}
*/
if (e.getCause() != null && e.getCause().getClass().getSimpleName().equals("PrematureChannelClosureException")) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Unexpected I/O exception on channel {}", channel, cause);
}
try {
if (cause != null && ClosedChannelException.class.isAssignableFrom(cause.getClass())) {
return;
}
if (ctx.getAttachment() instanceof NettyResponseFuture<?>) {
future = (NettyResponseFuture<?>) ctx.getAttachment();
future.attachChannel(null, false);
future.touch();
if (IOException.class.isAssignableFrom(cause.getClass())) {
if (config.getIOExceptionFilters().size() > 0) {
FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(new IOException("Channel Closed")).build();
fc = handleIoException(fc, future);
if (fc.replayRequest()) {
replayRequest(future, fc, null, ctx);
return;
}
} else {
// Close the channel so the recovering can occurs.
try {
ctx.getChannel().close();
} catch (Throwable t) {
; // Swallow.
}
return;
}
}
if (abortOnReadCloseException(cause) || abortOnWriteCloseException(cause)) {
log.debug("Trying to recover from dead Channel: {}", channel);
return;
}
} else if (ctx.getAttachment() instanceof AsyncCallable) {
future = ((AsyncCallable) ctx.getAttachment()).future();
}
} catch (Throwable t) {
cause = t;
}
if (future != null) {
try {
log.debug("Was unable to recover Future: {}", future);
abort(future, cause);
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}
Protocol p = (ctx.getPipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol);
p.onError(ctx, e);
closeChannel(ctx);
ctx.sendUpstream(e);
}
protected static boolean abortOnConnectCloseException(Throwable cause) {
try {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketChannelImpl")
&& element.getMethodName().equals("checkConnect")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnConnectCloseException(cause.getCause());
}
} catch (Throwable t) {
}
return false;
}
protected static boolean abortOnDisconnectException(Throwable cause) {
try {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("org.jboss.netty.handler.ssl.SslHandler")
&& element.getMethodName().equals("channelDisconnected")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnConnectCloseException(cause.getCause());
}
} catch (Throwable t) {
}
return false;
}
protected static boolean abortOnReadCloseException(Throwable cause) {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketDispatcher")
&& element.getMethodName().equals("read")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnReadCloseException(cause.getCause());
}
return false;
}
protected static boolean abortOnWriteCloseException(Throwable cause) {
for (StackTraceElement element : cause.getStackTrace()) {
if (element.getClassName().equals("sun.nio.ch.SocketDispatcher")
&& element.getMethodName().equals("write")) {
return true;
}
}
if (cause.getCause() != null) {
return abortOnReadCloseException(cause.getCause());
}
return false;
}
private final static int computeAndSetContentLength(Request request, HttpRequest r) {
int length = (int) request.getContentLength();
if (length == -1 && r.getHeader(HttpHeaders.Names.CONTENT_LENGTH) != null) {
length = Integer.valueOf(r.getHeader(HttpHeaders.Names.CONTENT_LENGTH));
}
if (length >= 0) {
r.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
}
return length;
}
public static <T> NettyResponseFuture<T> newFuture(URI uri,
Request request,
AsyncHandler<T> asyncHandler,
HttpRequest nettyRequest,
AsyncHttpClientConfig config,
NettyAsyncHttpProvider provider,
ProxyServer proxyServer) {
NettyResponseFuture<T> f = new NettyResponseFuture<T>(uri, request, asyncHandler, nettyRequest,
requestTimeout(config, request.getPerRequestConfig()), config.getIdleConnectionTimeoutInMs(), provider, request.getConnectionPoolKeyStrategy(), proxyServer);
if (request.getHeaders().getFirstValue("Expect") != null
&& request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) {
f.getAndSetWriteBody(false);
}
return f;
}
private class ProgressListener implements ChannelFutureProgressListener {
private final boolean notifyHeaders;
private final AsyncHandler<?> asyncHandler;
private final NettyResponseFuture<?> future;
public ProgressListener(boolean notifyHeaders, AsyncHandler<?> asyncHandler, NettyResponseFuture<?> future) {
this.notifyHeaders = notifyHeaders;
this.asyncHandler = asyncHandler;
this.future = future;
}
public void operationComplete(ChannelFuture cf) {
// The write operation failed. If the channel was cached, it means it got asynchronously closed.
// Let's retry a second time.
Throwable cause = cf.getCause();
if (cause != null && future.getState() != NettyResponseFuture.STATE.NEW) {
if (IllegalStateException.class.isAssignableFrom(cause.getClass())) {
log.debug(cause.getMessage(), cause);
try {
cf.getChannel().close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
}
if (ClosedChannelException.class.isAssignableFrom(cause.getClass())
|| abortOnReadCloseException(cause)
|| abortOnWriteCloseException(cause)) {
if (log.isDebugEnabled()) {
log.debug(cf.getCause() == null ? "" : cf.getCause().getMessage(), cf.getCause());
}
try {
cf.getChannel().close();
} catch (RuntimeException ex) {
log.debug(ex.getMessage(), ex);
}
return;
} else {
future.abort(cause);
}
return;
}
future.touch();
/**
* We need to make sure we aren't in the middle of an authorization process before publishing events
* as we will re-publish again the same event after the authorization, causing unpredictable behavior.
*/
Realm realm = future.getRequest().getRealm() != null ? future.getRequest().getRealm() : NettyAsyncHttpProvider.this.getConfig().getRealm();
boolean startPublishing = future.isInAuth()
|| realm == null
|| realm.getUsePreemptiveAuth() == true;
if (startPublishing && ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
if (notifyHeaders) {
ProgressAsyncHandler.class.cast(asyncHandler).onHeaderWriteCompleted();
} else {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteCompleted();
}
}
}
public void operationProgressed(ChannelFuture cf, long amount, long current, long total) {
future.touch();
if (ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteProgress(amount, current, total);
}
}
}
/**
* Because some implementation of the ThreadSchedulingService do not clean up cancel task until they try to run
* them, we wrap the task with the future so the when the NettyResponseFuture cancel the reaper future
* this wrapper will release the references to the channel and the nettyResponseFuture immediately. Otherwise,
* the memory referenced this way will only be released after the request timeout period which can be arbitrary long.
*/
private final class ReaperFuture implements Future, Runnable {
private Future scheduledFuture;
private NettyResponseFuture<?> nettyResponseFuture;
public ReaperFuture(NettyResponseFuture<?> nettyResponseFuture) {
this.nettyResponseFuture = nettyResponseFuture;
}
public void setScheduledFuture(Future scheduledFuture) {
this.scheduledFuture = scheduledFuture;
}
/**
* @Override
*/
public boolean cancel(boolean mayInterruptIfRunning) {
nettyResponseFuture = null;
return scheduledFuture.cancel(mayInterruptIfRunning);
}
/**
* @Override
*/
public Object get() throws InterruptedException, ExecutionException {
return scheduledFuture.get();
}
/**
* @Override
*/
public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return scheduledFuture.get(timeout, unit);
}
/**
* @Override
*/
public boolean isCancelled() {
return scheduledFuture.isCancelled();
}
/**
* @Override
*/
public boolean isDone() {
return scheduledFuture.isDone();
}
/**
* @Override
*/
public synchronized void run() {
if (isClose.get()) {
cancel(true);
return;
}
if (nettyResponseFuture != null && nettyResponseFuture.hasExpired()
&& !nettyResponseFuture.isDone() && !nettyResponseFuture.isCancelled()) {
log.debug("Request Timeout expired for {}\n", nettyResponseFuture);
int requestTimeout = config.getRequestTimeoutInMs();
PerRequestConfig p = nettyResponseFuture.getRequest().getPerRequestConfig();
if (p != null && p.getRequestTimeoutInMs() != -1) {
requestTimeout = p.getRequestTimeoutInMs();
}
abort(nettyResponseFuture, new TimeoutException(String.format("No response received after %s", requestTimeout)));
nettyResponseFuture = null;
}
if (nettyResponseFuture == null || nettyResponseFuture.isDone() || nettyResponseFuture.isCancelled()) {
cancel(true);
}
}
}
private abstract class AsyncCallable implements Callable<Object> {
private final NettyResponseFuture<?> future;
public AsyncCallable(NettyResponseFuture<?> future) {
this.future = future;
}
abstract public Object call() throws Exception;
public NettyResponseFuture<?> future() {
return future;
}
}
public static class ThreadLocalBoolean extends ThreadLocal<Boolean> {
private final boolean defaultValue;
public ThreadLocalBoolean() {
this(false);
}
public ThreadLocalBoolean(boolean defaultValue) {
this.defaultValue = defaultValue;
}
@Override
protected Boolean initialValue() {
return defaultValue ? Boolean.TRUE : Boolean.FALSE;
}
}
public static class OptimizedFileRegion implements FileRegion {
private final FileChannel file;
private final RandomAccessFile raf;
private final long position;
private final long count;
private long byteWritten;
public OptimizedFileRegion(RandomAccessFile raf, long position, long count) {
this.raf = raf;
this.file = raf.getChannel();
this.position = position;
this.count = count;
}
public long getPosition() {
return position;
}
public long getCount() {
return count;
}
public long transferTo(WritableByteChannel target, long position) throws IOException {
long count = this.count - position;
if (count < 0 || position < 0) {
throw new IllegalArgumentException(
"position out of range: " + position +
" (expected: 0 - " + (this.count - 1) + ")");
}
if (count == 0) {
return 0L;
}
long bw = file.transferTo(this.position + position, count, target);
byteWritten += bw;
if (byteWritten == raf.length()) {
releaseExternalResources();
}
return bw;
}
public void releaseExternalResources() {
try {
file.close();
} catch (IOException e) {
log.warn("Failed to close a file.", e);
}
try {
raf.close();
} catch (IOException e) {
log.warn("Failed to close a file.", e);
}
}
}
private static class NettyTransferAdapter extends TransferCompletionHandler.TransferAdapter {
private final ChannelBuffer content;
private final FileInputStream file;
private int byteRead = 0;
public NettyTransferAdapter(FluentCaseInsensitiveStringsMap headers, ChannelBuffer content, File file) throws IOException {
super(headers);
this.content = content;
if (file != null) {
this.file = new FileInputStream(file);
} else {
this.file = null;
}
}
@Override
public void getBytes(byte[] bytes) {
if (content.writableBytes() != 0) {
content.getBytes(byteRead, bytes);
byteRead += bytes.length;
} else if (file != null) {
try {
byteRead += file.read(bytes);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
protected AsyncHttpClientConfig getConfig() {
return config;
}
private static class NonConnectionsPool implements ConnectionsPool<String, Channel> {
public boolean offer(String uri, Channel connection) {
return false;
}
public Channel poll(String uri) {
return null;
}
public boolean removeAll(Channel connection) {
return false;
}
public boolean canCacheConnection() {
return true;
}
public void destroy() {
}
}
private static final boolean validateWebSocketRequest(Request request, AsyncHandler<?> asyncHandler) {
if (request.getMethod() != "GET" || !WebSocketUpgradeHandler.class.isAssignableFrom(asyncHandler.getClass())) {
return false;
}
return true;
}
private boolean redirect(Request request,
NettyResponseFuture<?> future,
HttpResponse response,
final ChannelHandlerContext ctx) throws Exception {
int statusCode = response.getStatus().getCode();
boolean redirectEnabled = request.isRedirectOverrideSet() ? request.isRedirectEnabled() : config.isRedirectEnabled();
if (redirectEnabled && (statusCode == 302
|| statusCode == 301
|| statusCode == 303
|| statusCode == 307)) {
if (future.incrementAndGetCurrentRedirectCount() < config.getMaxRedirects()) {
// We must allow 401 handling again.
future.getAndSetAuth(false);
String location = response.getHeader(HttpHeaders.Names.LOCATION);
URI uri = AsyncHttpProviderUtils.getRedirectUri(future.getURI(), location);
boolean stripQueryString = config.isRemoveQueryParamOnRedirect();
if (!uri.toString().equals(future.getURI().toString())) {
final RequestBuilder nBuilder = stripQueryString ?
new RequestBuilder(future.getRequest()).setQueryParameters(null)
: new RequestBuilder(future.getRequest());
if (!(statusCode < 302 || statusCode > 303)
&& !(statusCode == 302
&& config.isStrict302Handling())) {
nBuilder.setMethod("GET");
}
final URI initialConnectionUri = future.getURI();
final boolean initialConnectionKeepAlive = future.getKeepAlive();
future.setURI(uri);
String newUrl = uri.toString();
if (request.getUrl().startsWith(WEBSOCKET)) {
newUrl = newUrl.replace(HTTP, WEBSOCKET);
}
log.debug("Redirecting to {}", newUrl);
for (String cookieStr : future.getHttpResponse().getHeaders(HttpHeaders.Names.SET_COOKIE)) {
Cookie c = AsyncHttpProviderUtils.parseCookie(cookieStr);
nBuilder.addOrReplaceCookie(c);
}
for (String cookieStr : future.getHttpResponse().getHeaders(HttpHeaders.Names.SET_COOKIE2)) {
Cookie c = AsyncHttpProviderUtils.parseCookie(cookieStr);
nBuilder.addOrReplaceCookie(c);
}
final String connectionPoolKey = future.getConnectionPoolKeyStrategy().getKey(initialConnectionUri);
AsyncCallable ac = new AsyncCallable(future) {
public Object call() throws Exception {
if (initialConnectionKeepAlive && ctx.getChannel().isReadable() &&
connectionsPool.offer(connectionPoolKey, ctx.getChannel())) {
return null;
}
finishChannel(ctx);
return null;
}
};
if (response.isChunked()) {
// We must make sure there is no bytes left before executing the next request.
ctx.setAttachment(ac);
} else {
ac.call();
}
nextRequest(nBuilder.setUrl(newUrl).build(), future);
return true;
}
} else {
throw new MaxRedirectException("Maximum redirect reached: " + config.getMaxRedirects());
}
}
return false;
}
private final class HttpProtocol implements Protocol {
// @Override
public void handle(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
final NettyResponseFuture<?> future = (NettyResponseFuture<?>) ctx.getAttachment();
future.touch();
// The connect timeout occured.
if (future.isCancelled() || future.isDone()) {
finishChannel(ctx);
return;
}
HttpRequest nettyRequest = future.getNettyRequest();
AsyncHandler handler = future.getAsyncHandler();
Request request = future.getRequest();
ProxyServer proxyServer = future.getProxyServer();
HttpResponse response = null;
try {
if (e.getMessage() instanceof HttpResponse) {
response = (HttpResponse) e.getMessage();
log.debug("\n\nRequest {}\n\nResponse {}\n", nettyRequest, response);
// Required if there is some trailing headers.
future.setHttpResponse(response);
int statusCode = response.getStatus().getCode();
String ka = response.getHeader(HttpHeaders.Names.CONNECTION);
future.setKeepAlive(ka == null || ! ka.toLowerCase().equals("close"));
List<String> wwwAuth = getAuthorizationToken(response.getHeaders(), HttpHeaders.Names.WWW_AUTHENTICATE);
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
HttpResponseStatus status = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this);
HttpResponseHeaders responseHeaders = new ResponseHeaders(future.getURI(), response, NettyAsyncHttpProvider.this);
FilterContext fc = new FilterContext.FilterContextBuilder()
.asyncHandler(handler)
.request(request)
.responseStatus(status)
.responseHeaders(responseHeaders)
.build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
// The handler may have been wrapped.
handler = fc.getAsyncHandler();
future.setAsyncHandler(handler);
// The request has changed
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
Realm newRealm = null;
final FluentCaseInsensitiveStringsMap headers = request.getHeaders();
final RequestBuilder builder = new RequestBuilder(future.getRequest());
//if (realm != null && !future.getURI().getPath().equalsIgnoreCase(realm.getUri())) {
// builder.setUrl(future.getURI().toString());
//}
if (statusCode == 401
&& realm != null
&& wwwAuth.size() > 0
&& !future.getAndSetAuth(true)) {
future.setState(NettyResponseFuture.STATE.NEW);
// NTLM
if (!wwwAuth.contains("Kerberos") && (wwwAuth.contains("NTLM") || (wwwAuth.contains("Negotiate")))) {
newRealm = ntlmChallenge(wwwAuth, request, proxyServer, headers, realm, future);
// SPNEGO KERBEROS
} else if (wwwAuth.contains("Negotiate")) {
newRealm = kerberosChallenge(wwwAuth, request, proxyServer, headers, realm, future);
if (newRealm == null) return;
} else {
newRealm = new Realm.RealmBuilder().clone(realm).setScheme(realm.getAuthScheme())
.setUri(request.getURI().getPath())
.setMethodName(request.getMethod())
.setUsePreemptiveAuth(true)
.parseWWWAuthenticateHeader(wwwAuth.get(0))
.build();
}
final Realm nr = new Realm.RealmBuilder().clone(newRealm)
.setUri(URI.create(request.getUrl()).getPath()).build();
log.debug("Sending authentication to {}", request.getUrl());
AsyncCallable ac = new AsyncCallable(future) {
public Object call() throws Exception {
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
nextRequest(builder.setHeaders(headers).setRealm(nr).build(), future);
return null;
}
};
if (future.getKeepAlive() && response.isChunked()) {
// We must make sure there is no bytes left before executing the next request.
ctx.setAttachment(ac);
} else {
ac.call();
}
return;
}
if (statusCode == 100) {
future.getAndSetWriteHeaders(false);
future.getAndSetWriteBody(true);
writeRequest(ctx.getChannel(), config, future, nettyRequest);
return;
}
List<String> proxyAuth = getAuthorizationToken(response.getHeaders(), HttpHeaders.Names.PROXY_AUTHENTICATE);
if (statusCode == 407
&& realm != null
&& proxyAuth.size() > 0
&& !future.getAndSetAuth(true)) {
log.debug("Sending proxy authentication to {}", request.getUrl());
future.setState(NettyResponseFuture.STATE.NEW);
if (!proxyAuth.contains("Kerberos") && (proxyAuth.get(0).contains("NTLM") || (proxyAuth.contains("Negotiate")))) {
newRealm = ntlmProxyChallenge(proxyAuth, request, proxyServer, headers, realm, future);
// SPNEGO KERBEROS
} else if (proxyAuth.contains("Negotiate")) {
newRealm = kerberosChallenge(proxyAuth, request, proxyServer, headers, realm, future);
if (newRealm == null) return;
} else {
newRealm = future.getRequest().getRealm();
}
Request req = builder.setHeaders(headers).setRealm(newRealm).build();
future.setReuseChannel(true);
future.setConnectAllowed(true);
nextRequest(req, future);
return;
}
if (future.getNettyRequest().getMethod().equals(HttpMethod.CONNECT)
&& statusCode == 200) {
log.debug("Connected to {}:{}", proxyServer.getHost(), proxyServer.getPort());
if (future.getKeepAlive()) {
future.attachChannel(ctx.getChannel(), true);
}
try {
log.debug("Connecting to proxy {} for scheme {}", proxyServer, request.getUrl());
upgradeProtocol(ctx.getChannel().getPipeline(), request.getURI().getScheme());
} catch (Throwable ex) {
abort(future, ex);
}
Request req = builder.build();
future.setReuseChannel(true);
future.setConnectAllowed(false);
nextRequest(req, future);
return;
}
if (redirect(request, future, response, ctx)) return;
if (!future.getAndSetStatusReceived(true) && updateStatusAndInterrupt(handler, status)) {
finishUpdate(future, ctx, response.isChunked());
return;
} else if (updateHeadersAndInterrupt(handler, responseHeaders)) {
finishUpdate(future, ctx, response.isChunked());
return;
} else if (!response.isChunked()) {
if (response.getContent().readableBytes() != 0) {
updateBodyAndInterrupt(future, handler, new ResponseBodyPart(future.getURI(), response, NettyAsyncHttpProvider.this, true));
}
finishUpdate(future, ctx, false);
return;
}
if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
updateBodyAndInterrupt(future, handler, new ResponseBodyPart(future.getURI(), response, NettyAsyncHttpProvider.this, true));
markAsDone(future, ctx);
drainChannel(ctx, future, future.getKeepAlive(), future.getURI());
}
} else if (e.getMessage() instanceof HttpChunk) {
HttpChunk chunk = (HttpChunk) e.getMessage();
if (handler != null) {
if (chunk.isLast() || updateBodyAndInterrupt(future, handler,
new ResponseBodyPart(future.getURI(), null, NettyAsyncHttpProvider.this, chunk, chunk.isLast()))) {
if (chunk instanceof DefaultHttpChunkTrailer) {
updateHeadersAndInterrupt(handler, new ResponseHeaders(future.getURI(),
future.getHttpResponse(), NettyAsyncHttpProvider.this, (HttpChunkTrailer) chunk));
}
finishUpdate(future, ctx, !chunk.isLast());
}
}
}
} catch (Exception t) {
if (IOException.class.isAssignableFrom(t.getClass()) && config.getIOExceptionFilters().size() > 0) {
FilterContext<?> fc = new FilterContext.FilterContextBuilder().asyncHandler(future.getAsyncHandler())
.request(future.getRequest()).ioException(IOException.class.cast(t)).build();
fc = handleIoException(fc, future);
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
}
try {
abort(future, t);
} finally {
finishUpdate(future, ctx, false);
throw t;
}
}
}
// @Override
public void onError(ChannelHandlerContext ctx, ExceptionEvent e) {
}
// @Override
public void onClose(ChannelHandlerContext ctx, ChannelStateEvent e) {
}
}
private final class WebSocketProtocol implements Protocol {
private static final byte OPCODE_TEXT = 0x1;
private static final byte OPCODE_BINARY = 0x2;
private static final byte OPCODE_UNKNOWN = -1;
protected byte pendingOpcode = OPCODE_UNKNOWN;
// @Override
public void handle(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
NettyResponseFuture<?> future = NettyResponseFuture.class.cast(ctx.getAttachment());
WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(future.getAsyncHandler());
Request request = future.getRequest();
if (e.getMessage() instanceof HttpResponse) {
HttpResponse response = (HttpResponse) e.getMessage();
HttpResponseStatus s = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this);
HttpResponseHeaders responseHeaders = new ResponseHeaders(future.getURI(), response, NettyAsyncHttpProvider.this);
FilterContext fc = new FilterContext.FilterContextBuilder()
.asyncHandler(h)
.request(request)
.responseStatus(s)
.responseHeaders(responseHeaders)
.build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
try {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
} catch (FilterException efe) {
abort(future, efe);
}
}
// The handler may have been wrapped.
future.setAsyncHandler(fc.getAsyncHandler());
// The request has changed
if (fc.replayRequest()) {
replayRequest(future, fc, response, ctx);
return;
}
future.setHttpResponse(response);
if (redirect(request, future, response, ctx)) return;
final org.jboss.netty.handler.codec.http.HttpResponseStatus status =
new org.jboss.netty.handler.codec.http.HttpResponseStatus(101, "Web Socket Protocol Handshake");
final boolean validStatus = response.getStatus().equals(status);
final boolean validUpgrade = response.getHeader(HttpHeaders.Names.UPGRADE) != null;
String c = response.getHeader(HttpHeaders.Names.CONNECTION);
if (c == null) {
c = response.getHeader("connection");
}
final boolean validConnection = c == null ? false : c.equalsIgnoreCase(HttpHeaders.Values.UPGRADE);
s = new ResponseStatus(future.getURI(), response, NettyAsyncHttpProvider.this);
final boolean statusReceived = h.onStatusReceived(s) == STATE.UPGRADE;
if (!statusReceived) {
h.onClose(new NettyWebSocket(ctx.getChannel()), 1002, "Bad response status " + response.getStatus().getCode());
future.done(null);
return;
}
if (!validStatus || !validUpgrade || !validConnection) {
throw new IOException("Invalid handshake response");
}
String accept = response.getHeader("Sec-WebSocket-Accept");
String key = WebSocketUtil.getAcceptKey(future.getNettyRequest().getHeader(WEBSOCKET_KEY));
if (accept == null || !accept.equals(key)) {
throw new IOException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, key));
}
ctx.getPipeline().replace("ws-decoder", "ws-decoder", new WebSocket08FrameDecoder(false, false));
ctx.getPipeline().replace("ws-encoder", "ws-encoder", new WebSocket08FrameEncoder(true));
if (h.onHeadersReceived(responseHeaders) == STATE.CONTINUE) {
h.onSuccess(new NettyWebSocket(ctx.getChannel()));
}
future.done(null);
} else if (e.getMessage() instanceof WebSocketFrame) {
final WebSocketFrame frame = (WebSocketFrame) e.getMessage();
if(frame instanceof TextWebSocketFrame) {
pendingOpcode = OPCODE_TEXT;
}
else if(frame instanceof BinaryWebSocketFrame) {
pendingOpcode = OPCODE_BINARY;
}
HttpChunk webSocketChunk = new HttpChunk() {
private ChannelBuffer content;
// @Override
public boolean isLast() {
return false;
}
// @Override
public ChannelBuffer getContent() {
return content;
}
// @Override
public void setContent(ChannelBuffer content) {
this.content = content;
}
};
if (frame.getBinaryData() != null) {
webSocketChunk.setContent(ChannelBuffers.wrappedBuffer(frame.getBinaryData()));
ResponseBodyPart rp = new ResponseBodyPart(future.getURI(), null, NettyAsyncHttpProvider.this, webSocketChunk, true);
h.onBodyPartReceived(rp);
NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted());
if(pendingOpcode == OPCODE_BINARY) {
webSocket.onBinaryFragment(rp.getBodyPartBytes(),frame.isFinalFragment());
}
else {
webSocket.onTextFragment(frame.getBinaryData().toString(UTF8),frame.isFinalFragment());
}
if (CloseWebSocketFrame.class.isAssignableFrom(frame.getClass())) {
try {
webSocket.onClose(CloseWebSocketFrame.class.cast(frame).getStatusCode(), CloseWebSocketFrame.class.cast(frame).getReasonText());
} catch (Throwable t) {
// Swallow any exception that may comes from a Netty version released before 3.4.0
log.trace("", t);
}
}
}
} else {
log.error("Invalid attachment {}", ctx.getAttachment());
}
}
//@Override
public void onError(ChannelHandlerContext ctx, ExceptionEvent e) {
try {
log.warn("onError {}", e);
if (ctx.getAttachment() == null || !NettyResponseFuture.class.isAssignableFrom(ctx.getAttachment().getClass())) {
return;
}
NettyResponseFuture<?> nettyResponse = NettyResponseFuture.class.cast(ctx.getAttachment());
WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(nettyResponse.getAsyncHandler());
NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted());
webSocket.onError(e.getCause());
webSocket.close();
} catch (Throwable t) {
log.error("onError", t);
}
}
//@Override
public void onClose(ChannelHandlerContext ctx, ChannelStateEvent e) {
log.trace("onClose {}", e);
if (ctx.getAttachment() == null || !NettyResponseFuture.class.isAssignableFrom(ctx.getAttachment().getClass())) {
return;
}
try {
NettyResponseFuture<?> nettyResponse = NettyResponseFuture.class.cast(ctx.getAttachment());
WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(nettyResponse.getAsyncHandler());
NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted());
webSocket.close();
} catch (Throwable t) {
log.error("onError", t);
}
}
}
private static boolean isWebSocket(URI uri) {
return WEBSOCKET.equalsIgnoreCase(uri.getScheme()) || WEBSOCKET_SSL.equalsIgnoreCase(uri.getScheme());
}
private static boolean isSecure(String scheme) {
return HTTPS.equalsIgnoreCase(scheme) || WEBSOCKET_SSL.equalsIgnoreCase(scheme);
}
private static boolean isSecure(URI uri) {
return isSecure(uri.getScheme());
}
}
| true | true | private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri,
ChannelBuffer buffer,
ProxyServer proxyServer) throws IOException {
String host = AsyncHttpProviderUtils.getHost(uri);
boolean webSocket = isWebSocket(uri);
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else {
String path = null;
if (proxyServer != null)
path = uri.toString();
else if (uri.getRawQuery() != null)
path = uri.getRawPath() + "?" + uri.getRawQuery();
else
path = uri.getRawPath();
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path);
}
if (webSocket) {
nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
nettyRequest.addHeader("Origin", "http://" + uri.getHost() + ":"
+ (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
nettyRequest.addHeader(WEBSOCKET_KEY, WebSocketUtil.getKey());
nettyRequest.addHeader("Sec-WebSocket-Version", "13");
}
if (host != null) {
if (uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else if (request.getVirtualHost() != null) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
} else {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (isNonEmpty(auth) && auth.get(0).startsWith("NTLM")) {
nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
String domain = realm.getNtlmDomain();
if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
domain = proxyServer.getNtlmDomain();
}
String authHost = realm.getNtlmHost();
if (proxyServer != null && proxyServer.getHost() != null) {
host = proxyServer.getHost();
}
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (isNonEmpty(realm.getNonce())) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost);
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String server = proxyServer == null ? host : proxyServer.getHost();
try {
challengeHeader = getSpnegoEngine().generateToken(server);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
case NONE:
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
if (proxyServer != null) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", "keep-alive");
}
if (proxyServer.getPrincipal() != null) {
if (isNonEmpty(proxyServer.getNtlmDomain())) {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (!(isNonEmpty(auth) && auth.get(0).startsWith("NTLM"))) {
try {
String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(),
proxyServer.getHost());
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
}
} else {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") != null) {
nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else {
nettyRequest.setHeader("User-Agent",
AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class,
config));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (isNonEmpty(request.getCookies())) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
String reqType = request.getMethod();
if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getStringData().getBytes(bodyCharset)));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length));
} else if (isNonEmpty(request.getParams())) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (isSecure(uri)) {
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
}
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
| private static HttpRequest construct(AsyncHttpClientConfig config,
Request request,
HttpMethod m,
URI uri,
ChannelBuffer buffer,
ProxyServer proxyServer) throws IOException {
String host = AsyncHttpProviderUtils.getHost(uri);
boolean webSocket = isWebSocket(uri);
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
HttpRequest nettyRequest;
if (m.equals(HttpMethod.CONNECT)) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri));
} else {
String path = null;
if (proxyServer != null && !isSecure(uri))
path = uri.toString();
else if (uri.getRawQuery() != null)
path = uri.getRawPath() + "?" + uri.getRawQuery();
else
path = uri.getRawPath();
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, path);
}
if (webSocket) {
nettyRequest.addHeader(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
nettyRequest.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
nettyRequest.addHeader("Origin", "http://" + uri.getHost() + ":"
+ (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
nettyRequest.addHeader(WEBSOCKET_KEY, WebSocketUtil.getKey());
nettyRequest.addHeader("Sec-WebSocket-Version", "13");
}
if (host != null) {
if (uri.getPort() == -1) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else if (request.getVirtualHost() != null) {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host);
} else {
nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
}
} else {
host = "127.0.0.1";
}
if (!m.equals(HttpMethod.CONNECT)) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
nettyRequest.addHeader(name, value);
}
}
}
}
if (config.isCompressionEnabled()) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
}
} else {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (isNonEmpty(auth) && auth.get(0).startsWith("NTLM")) {
nettyRequest.addHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth()) {
String domain = realm.getNtlmDomain();
if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
domain = proxyServer.getNtlmDomain();
}
String authHost = realm.getNtlmHost();
if (proxyServer != null && proxyServer.getHost() != null) {
host = proxyServer.getHost();
}
switch (realm.getAuthScheme()) {
case BASIC:
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (isNonEmpty(realm.getNonce())) {
try {
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION,
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
try {
String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost);
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
break;
case KERBEROS:
case SPNEGO:
String challengeHeader = null;
String server = proxyServer == null ? host : proxyServer.getHost();
try {
challengeHeader = getSpnegoEngine().generateToken(server);
} catch (Throwable e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
nettyRequest.setHeader(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);
break;
case NONE:
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
}
if (proxyServer != null) {
if (!request.getHeaders().containsKey("Proxy-Connection")) {
nettyRequest.setHeader("Proxy-Connection", "keep-alive");
}
if (proxyServer.getPrincipal() != null) {
if (isNonEmpty(proxyServer.getNtlmDomain())) {
List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
if (!(isNonEmpty(auth) && auth.get(0).startsWith("NTLM"))) {
try {
String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(),
proxyServer.getHost());
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
} catch (NTLMEngineException e) {
IOException ie = new IOException();
ie.initCause(e);
throw ie;
}
}
} else {
nettyRequest.setHeader(HttpHeaders.Names.PROXY_AUTHORIZATION,
AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
nettyRequest.setHeader(HttpHeaders.Names.ACCEPT, "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") != null) {
nettyRequest.setHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent"));
} else if (config.getUserAgent() != null) {
nettyRequest.setHeader("User-Agent", config.getUserAgent());
} else {
nettyRequest.setHeader("User-Agent",
AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class,
config));
}
if (!m.equals(HttpMethod.CONNECT)) {
if (isNonEmpty(request.getCookies())) {
CookieEncoder httpCookieEncoder = new CookieEncoder(false);
Iterator<Cookie> ic = request.getCookies().iterator();
Cookie c;
org.jboss.netty.handler.codec.http.Cookie cookie;
while (ic.hasNext()) {
c = ic.next();
cookie = new DefaultCookie(c.getName(), c.getValue());
cookie.setPath(c.getPath());
cookie.setMaxAge(c.getMaxAge());
cookie.setDomain(c.getDomain());
httpCookieEncoder.addCookie(cookie);
}
nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
}
String reqType = request.getMethod();
if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) {
String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();
// We already have processed the body.
if (buffer != null && buffer.writerIndex() != 0) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex());
nettyRequest.setContent(buffer);
} else if (request.getByteData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getByteData()));
} else if (request.getStringData() != null) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(request.getStringData().getBytes(bodyCharset)));
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
int length = lengthWrapper[0];
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(bytes, 0, length));
} else if (isNonEmpty(request.getParams())) {
StringBuilder sb = new StringBuilder();
for (final Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
nettyRequest.setContent(ChannelBuffers.wrappedBuffer(sb.toString().getBytes(bodyCharset)));
if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
}
} else if (request.getParts() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));
/**
* TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements.
*/
if (isSecure(uri)) {
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(new ChannelBufferOutputStream(b));
nettyRequest.setContent(b);
}
} else if (request.getEntityWriter() != null) {
int lenght = computeAndSetContentLength(request, nettyRequest);
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex());
nettyRequest.setContent(b);
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, file.length());
}
}
}
return nettyRequest;
}
|
diff --git a/FRPapp/src/phillykeyspots/frpapp/DashboardActivity.java b/FRPapp/src/phillykeyspots/frpapp/DashboardActivity.java
index 1f28ef4..6ed8fe4 100644
--- a/FRPapp/src/phillykeyspots/frpapp/DashboardActivity.java
+++ b/FRPapp/src/phillykeyspots/frpapp/DashboardActivity.java
@@ -1,31 +1,33 @@
package phillykeyspots.frpapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
public class DashboardActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Fragment fragment;
switch(Integer.parseInt(getIntent().getExtras().get("ID").toString())){
case R.id.b_finder:
fragment = new FinderFragment();
break;
- /*case R.id.b_events:
+ case R.id.b_events:
+ fragment = new EventsFragment();
break;
case R.id.b_resources:
- break;*/
+ fragment = new ResourcesFragment();
+ break;
case R.id.b_joml:
fragment = new JomlFragment();
break;
default:
fragment = new FinderFragment();
}
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Fragment fragment;
switch(Integer.parseInt(getIntent().getExtras().get("ID").toString())){
case R.id.b_finder:
fragment = new FinderFragment();
break;
/*case R.id.b_events:
break;
case R.id.b_resources:
break;*/
case R.id.b_joml:
fragment = new JomlFragment();
break;
default:
fragment = new FinderFragment();
}
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fragment).commit();
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Fragment fragment;
switch(Integer.parseInt(getIntent().getExtras().get("ID").toString())){
case R.id.b_finder:
fragment = new FinderFragment();
break;
case R.id.b_events:
fragment = new EventsFragment();
break;
case R.id.b_resources:
fragment = new ResourcesFragment();
break;
case R.id.b_joml:
fragment = new JomlFragment();
break;
default:
fragment = new FinderFragment();
}
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fragment).commit();
}
|
diff --git a/src/zapfmaster2000-service/src/main/java/de/kile/zapfmaster2000/rest/api/installation/InstallationResource.java b/src/zapfmaster2000-service/src/main/java/de/kile/zapfmaster2000/rest/api/installation/InstallationResource.java
index ca40a05a..456c5a48 100644
--- a/src/zapfmaster2000-service/src/main/java/de/kile/zapfmaster2000/rest/api/installation/InstallationResource.java
+++ b/src/zapfmaster2000-service/src/main/java/de/kile/zapfmaster2000/rest/api/installation/InstallationResource.java
@@ -1,87 +1,87 @@
package de.kile.zapfmaster2000.rest.api.installation;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.hibernate.Session;
import org.hibernate.Transaction;
import de.kile.zapfmaster2000.rest.core.Zapfmaster2000Core;
import de.kile.zapfmaster2000.rest.model.zapfmaster2000.Admin;
import de.kile.zapfmaster2000.rest.model.zapfmaster2000.Zapfmaster2000Factory;
@Path("/install")
public class InstallationResource {
@GET
@Path("/status")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveStatus() {
StatusResponse response = new StatusResponse();
if (checkIsNewInstallation()) {
response.setStatus("new");
} else {
response.setStatus("installed");
}
return Response.ok(response).build();
}
@POST
@Path("/firstadmin")
@Produces(MediaType.APPLICATION_JSON)
- public Response createFirstAdmin(String name, String password) {
+ public Response createFirstAdmin(String adminName, String password) {
if (checkIsNewInstallation()) {
- createAdmin(name, password);
+ createAdmin(adminName, password);
String token = Zapfmaster2000Core.INSTANCE.getAuthService()
- .loginAdmin(name, password);
+ .loginAdmin(adminName, password);
if (token == null) {
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
} else {
return Response.ok(token).build();
}
} else {
return Response.status(Status.FORBIDDEN).build();
}
}
private void createAdmin(String name, String password) {
Admin admin = Zapfmaster2000Factory.eINSTANCE.createAdmin();
admin.setName(name);
admin.setPassword(password);
Session session = Zapfmaster2000Core.INSTANCE.getTransactionService()
.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
session.save(admin);
tx.commit();
}
private boolean checkIsNewInstallation() {
Session session = Zapfmaster2000Core.INSTANCE.getTransactionService()
.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
@SuppressWarnings("unchecked")
List<Long> result = session.createQuery("SELECT COUNT(*) FROM Admin")
.list();
boolean isNew = result.size() != 1 || result.get(0) == 0;
tx.commit();
return isNew;
}
}
| false | true | public Response createFirstAdmin(String name, String password) {
if (checkIsNewInstallation()) {
createAdmin(name, password);
String token = Zapfmaster2000Core.INSTANCE.getAuthService()
.loginAdmin(name, password);
if (token == null) {
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
} else {
return Response.ok(token).build();
}
} else {
return Response.status(Status.FORBIDDEN).build();
}
}
| public Response createFirstAdmin(String adminName, String password) {
if (checkIsNewInstallation()) {
createAdmin(adminName, password);
String token = Zapfmaster2000Core.INSTANCE.getAuthService()
.loginAdmin(adminName, password);
if (token == null) {
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
} else {
return Response.ok(token).build();
}
} else {
return Response.status(Status.FORBIDDEN).build();
}
}
|
diff --git a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/internal/core/services/osgi/OSGiContextStrategy.java b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/internal/core/services/osgi/OSGiContextStrategy.java
index f9c98bf3b..333eeefa4 100644
--- a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/internal/core/services/osgi/OSGiContextStrategy.java
+++ b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/internal/core/services/osgi/OSGiContextStrategy.java
@@ -1,179 +1,184 @@
/*******************************************************************************
* Copyright (c) 2009 IBM Corporation and others.
* 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.e4.internal.core.services.osgi;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
import org.eclipse.e4.core.services.IDisposable;
import org.eclipse.e4.core.services.context.IContextFunction;
import org.eclipse.e4.core.services.context.IEclipseContext;
import org.eclipse.e4.core.services.context.spi.ILookupStrategy;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
/**
* A context strategy that provides access to OSGi services.
* <p>
* OSGi services are looked up by service class name.
*/
public class OSGiContextStrategy implements ILookupStrategy, IDisposable, ServiceTrackerCustomizer {
class ServiceData {
// the service name
String name;
ServiceTracker tracker;
// the contexts using this service (IEclipseContext -> null)
final Map users = new WeakHashMap();
ServiceData(String name) {
this.name = name;
}
public void addContext(IEclipseContext originatingContext) {
users.put(originatingContext, null);
}
}
private final BundleContext bundleContext;
/**
* Map of String (service name) -> ServiceData
*/
private Map services = Collections.synchronizedMap(new HashMap());
public OSGiContextStrategy(BundleContext bc) {
super();
this.bundleContext = bc;
}
public Object addingService(ServiceReference reference) {
String name = serviceName(reference);
Object newValue = bundleContext.getService(reference);
if (newValue == null)
return null;
// for performance we store the concrete service object with each context that requested it
ServiceData data = (ServiceData) services.get(name);
// may have been cleaned up concurrently
if (data == null)
return null;
for (Iterator it = data.users.keySet().iterator(); it.hasNext();)
((IEclipseContext) it.next()).set(name, newValue);
return newValue;
}
/**
* Discards any services that are no longer used by any strongly reachable contexts.
*/
private void cleanReferences() {
synchronized (services) {
for (Iterator it = services.values().iterator(); it.hasNext();) {
ServiceData data = (ServiceData) it.next();
// if there are no more references, discard the service
if (data.users.isEmpty()) {
data.tracker.close();
it.remove();
}
}
}
}
public boolean containsKey(String name, IEclipseContext context) {
cleanReferences();
// first look for a registered IContextFunction matching the name
if (getContextFunction(name) != null)
return true;
// next, look for a matching service
return bundleContext.getServiceReference(name) != null;
}
public void dispose() {
synchronized (services) {
for (Iterator it = services.values().iterator(); it.hasNext();)
((ServiceData) it.next()).tracker.close();
services.clear();
}
}
public Object lookup(String name, IEclipseContext originatingContext) {
cleanReferences();
ServiceData data = (ServiceData) services.get(name);
if (data == null) {
// first look for a registered IContextFunction matching the name
ServiceReference ref = getContextFunction(name);
if (ref != null)
return bundleContext.getService(ref);
// create a tracker to retrieve the service with the given name
data = new ServiceData(name);
- data.tracker = new ServiceTracker(bundleContext, name, this);
+ try {
+ data.tracker = new ServiceTracker(bundleContext, name, this);
+ } catch (IllegalArgumentException iae) {
+ // we get these when the variables requested are not valid names
+ return null;
+ }
// add the context immediately so cleanReferences doesn't remove it
data.addContext(originatingContext);
services.put(name, data);
// just opening a tracker will cause values to be set by the tracker
// callback methods
data.tracker.open();
} else {
data.addContext(originatingContext);
}
return data.tracker.getService();
}
/**
* Returns an IContextFunction service that computes values for the given name, or
* <code>null</code> if there is no matching service.
*/
private ServiceReference getContextFunction(String name) {
try {
ServiceReference[] refs = bundleContext.getServiceReferences(
IContextFunction.SERVICE_NAME, "(" + IContextFunction.SERVICE_CONTEXT_KEY + '=' //$NON-NLS-1$
+ name + ')');
if (refs != null && refs.length > 0)
return refs[0];
} catch (InvalidSyntaxException e) {
// the name is not a valid service name, so just carry on
}
return null;
}
public void modifiedService(ServiceReference reference, Object service) {
String name = serviceName(reference);
ServiceData data = (ServiceData) services.get(name);
// may have been cleaned up concurrently
if (data == null)
return;
for (Iterator it = data.users.keySet().iterator(); it.hasNext();)
((IEclipseContext) it.next()).set(name, service);
}
public void removedService(ServiceReference reference, Object service) {
String name = serviceName(reference);
// must set to null rather than removing so injection continues to work
ServiceData data = (ServiceData) services.get(name);
// may have been cleaned up concurrently
if (data == null)
return;
for (Iterator it = data.users.keySet().iterator(); it.hasNext();)
((IEclipseContext) it.next()).set(name, null);
bundleContext.ungetService(reference);
}
/**
* Returns the service name for a service reference
*/
private String serviceName(ServiceReference reference) {
return ((String[]) reference.getProperty(Constants.OBJECTCLASS))[0];
}
}
| true | true | public Object lookup(String name, IEclipseContext originatingContext) {
cleanReferences();
ServiceData data = (ServiceData) services.get(name);
if (data == null) {
// first look for a registered IContextFunction matching the name
ServiceReference ref = getContextFunction(name);
if (ref != null)
return bundleContext.getService(ref);
// create a tracker to retrieve the service with the given name
data = new ServiceData(name);
data.tracker = new ServiceTracker(bundleContext, name, this);
// add the context immediately so cleanReferences doesn't remove it
data.addContext(originatingContext);
services.put(name, data);
// just opening a tracker will cause values to be set by the tracker
// callback methods
data.tracker.open();
} else {
data.addContext(originatingContext);
}
return data.tracker.getService();
}
| public Object lookup(String name, IEclipseContext originatingContext) {
cleanReferences();
ServiceData data = (ServiceData) services.get(name);
if (data == null) {
// first look for a registered IContextFunction matching the name
ServiceReference ref = getContextFunction(name);
if (ref != null)
return bundleContext.getService(ref);
// create a tracker to retrieve the service with the given name
data = new ServiceData(name);
try {
data.tracker = new ServiceTracker(bundleContext, name, this);
} catch (IllegalArgumentException iae) {
// we get these when the variables requested are not valid names
return null;
}
// add the context immediately so cleanReferences doesn't remove it
data.addContext(originatingContext);
services.put(name, data);
// just opening a tracker will cause values to be set by the tracker
// callback methods
data.tracker.open();
} else {
data.addContext(originatingContext);
}
return data.tracker.getService();
}
|
diff --git a/src/main/java/com/mojang/minecraft/model/CreeperModel.java b/src/main/java/com/mojang/minecraft/model/CreeperModel.java
index 5b6f109..81457b3 100644
--- a/src/main/java/com/mojang/minecraft/model/CreeperModel.java
+++ b/src/main/java/com/mojang/minecraft/model/CreeperModel.java
@@ -1,50 +1,52 @@
package com.mojang.minecraft.model;
import com.mojang.util.MathHelper;
public final class CreeperModel extends Model {
private ModelPart head = new ModelPart(0, 0);
private ModelPart unused;
private ModelPart body;
private ModelPart leg1;
private ModelPart leg2;
private ModelPart leg3;
private ModelPart leg4;
public CreeperModel() {
head.setBounds(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.0F);
+ head.setPosition(0.0F, 4.0F, 0.0F);
unused = new ModelPart(32, 0);
unused.setBounds(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.0F + 0.5F);
body = new ModelPart(16, 16);
body.setBounds(-4.0F, 0.0F, -2.0F, 8, 12, 4, 0.0F);
+ body.setPosition(0.0F, 4.0F, 0.0F);
leg1 = new ModelPart(0, 16);
leg1.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
- leg1.setPosition(-2.0F, 12.0F, 4.0F);
+ leg1.setPosition(-2.0F, 16.0F, 4.0F);
leg2 = new ModelPart(0, 16);
leg2.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
- leg2.setPosition(2.0F, 12.0F, 4.0F);
+ leg2.setPosition(2.0F, 16.0F, 4.0F);
leg3 = new ModelPart(0, 16);
leg3.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
- leg3.setPosition(-2.0F, 12.0F, -4.0F);
+ leg3.setPosition(-2.0F, 16.0F, -4.0F);
leg4 = new ModelPart(0, 16);
leg4.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
- leg4.setPosition(2.0F, 12.0F, -4.0F);
+ leg4.setPosition(2.0F, 16.0F, -4.0F);
}
@Override
public final void render(float var1, float var2, float var3, float var4, float var5, float var6) {
head.yaw = var4 / 57.295776F;
head.pitch = var5 / 57.295776F;
leg1.pitch = MathHelper.cos(var1 * 0.6662F) * 1.4F * var2;
leg2.pitch = MathHelper.cos(var1 * 0.6662F + 3.1415927F) * 1.4F * var2;
leg3.pitch = MathHelper.cos(var1 * 0.6662F + 3.1415927F) * 1.4F * var2;
leg4.pitch = MathHelper.cos(var1 * 0.6662F) * 1.4F * var2;
head.render(var6);
body.render(var6);
leg1.render(var6);
leg2.render(var6);
leg3.render(var6);
leg4.render(var6);
}
}
| false | true | public CreeperModel() {
head.setBounds(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.0F);
unused = new ModelPart(32, 0);
unused.setBounds(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.0F + 0.5F);
body = new ModelPart(16, 16);
body.setBounds(-4.0F, 0.0F, -2.0F, 8, 12, 4, 0.0F);
leg1 = new ModelPart(0, 16);
leg1.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
leg1.setPosition(-2.0F, 12.0F, 4.0F);
leg2 = new ModelPart(0, 16);
leg2.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
leg2.setPosition(2.0F, 12.0F, 4.0F);
leg3 = new ModelPart(0, 16);
leg3.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
leg3.setPosition(-2.0F, 12.0F, -4.0F);
leg4 = new ModelPart(0, 16);
leg4.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
leg4.setPosition(2.0F, 12.0F, -4.0F);
}
| public CreeperModel() {
head.setBounds(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.0F);
head.setPosition(0.0F, 4.0F, 0.0F);
unused = new ModelPart(32, 0);
unused.setBounds(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.0F + 0.5F);
body = new ModelPart(16, 16);
body.setBounds(-4.0F, 0.0F, -2.0F, 8, 12, 4, 0.0F);
body.setPosition(0.0F, 4.0F, 0.0F);
leg1 = new ModelPart(0, 16);
leg1.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
leg1.setPosition(-2.0F, 16.0F, 4.0F);
leg2 = new ModelPart(0, 16);
leg2.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
leg2.setPosition(2.0F, 16.0F, 4.0F);
leg3 = new ModelPart(0, 16);
leg3.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
leg3.setPosition(-2.0F, 16.0F, -4.0F);
leg4 = new ModelPart(0, 16);
leg4.setBounds(-2.0F, 0.0F, -2.0F, 4, 6, 4, 0.0F);
leg4.setPosition(2.0F, 16.0F, -4.0F);
}
|
diff --git a/src/webdebate-portlet/docroot/WEB-INF/src/com/arguments/Deployment.java b/src/webdebate-portlet/docroot/WEB-INF/src/com/arguments/Deployment.java
index 901cc72..45d9370 100644
--- a/src/webdebate-portlet/docroot/WEB-INF/src/com/arguments/Deployment.java
+++ b/src/webdebate-portlet/docroot/WEB-INF/src/com/arguments/Deployment.java
@@ -1,114 +1,114 @@
/**
*
*/
package com.arguments;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Properties;
import com.arguments.functional.datamodel.ArgumentsException;
/**
* @author mirleau
*
*/
public class Deployment
{
private static Deployment theInstance = new Deployment();
public final String dbUrl;
public final String dbName;
public final String dbDriver;
public final String dbUserName;
public final String dbPassword;
public final String foreignTestId = "0";
public final String foreignAdminId = "10001";
public final String webappPath;
public final String webinfPath;
public static Deployment i()
{
return theInstance;
}
public Deployment()
{
final URL myClassRoot = Deployment.class.getResource("/");
final String myClassRootPath = myClassRoot.getFile();
System.out.println("Class root path: " + myClassRootPath);
// From eclipse: /mnt/bigspace/opt/linux/i386/liferay/liferay-sdk/portlets/argumentation-portlet/docroot/WEB-INF/classes/
// From tomcat: /mnt/bigspace/opt/linux/i386/liferay/liferay-portal-6.1.0-ce-ga1.2/tomcat-7.0.23/webapps/argumentation-portlet/WEB-INF/classes/
//String myWebappToClassRootPath = "argumentation-portlet/docroot/WEB-INF/classes/";
//assertTrue(myClassRootPath.endsWith(myWebappToClassRootPath));
File myWebinfFile = new File(myClassRootPath).getParentFile();
File myWebappFile = new File(myClassRootPath).
getParentFile().getParentFile().getParentFile().getParentFile();
webappPath = myWebappFile.getAbsolutePath()+"/";
System.out.println("Webapp path: " + webappPath);
webinfPath = myWebinfFile.getAbsolutePath()+"/";
ArrayList<String> myPropertyLocations = new ArrayList<String>()
{{
add(webappPath + "webapps-conf/arguments.deployment.properties");
add(myClassRootPath + "com/arguments/testdeployment.properties");
}};
Properties myDeploymentProperties = new Properties();
try
{
InputStream myPropertiesStream = null;
String myLocation = null;
while(myPropertiesStream == null && !myPropertyLocations.isEmpty())
{
myLocation = myPropertyLocations.remove(0);
File myPropertiesFile = new File(myLocation);
if (!myPropertiesFile.exists())
{
System.out.println("Didn't find arguments properties at " + myLocation);
}
else
{
myPropertiesStream = new FileInputStream(myPropertiesFile);
}
}
- assertNotNull(myPropertiesStream);
+ assertNotNull("Didn't find deployment properties file.", myPropertiesStream);
System.out.println("Found aruments properties at " + myLocation);
myDeploymentProperties.load(myPropertiesStream);
} catch (IOException anException)
{
throw new ArgumentsException(anException);
}
dbUrl = myDeploymentProperties.getProperty("dbUrl");
dbName = myDeploymentProperties.getProperty("dbName");
dbDriver = myDeploymentProperties.getProperty("dbDriver");
dbUserName = myDeploymentProperties.getProperty("dbUserName");
dbPassword = myDeploymentProperties.getProperty("dbPassword");
assertNotNull(dbUrl);
}
static String getClassPath()
{
String myClassPath = System.getProperty("java.class.path");
return myClassPath.replace(":", "\n");
}
}
| true | true | public Deployment()
{
final URL myClassRoot = Deployment.class.getResource("/");
final String myClassRootPath = myClassRoot.getFile();
System.out.println("Class root path: " + myClassRootPath);
// From eclipse: /mnt/bigspace/opt/linux/i386/liferay/liferay-sdk/portlets/argumentation-portlet/docroot/WEB-INF/classes/
// From tomcat: /mnt/bigspace/opt/linux/i386/liferay/liferay-portal-6.1.0-ce-ga1.2/tomcat-7.0.23/webapps/argumentation-portlet/WEB-INF/classes/
//String myWebappToClassRootPath = "argumentation-portlet/docroot/WEB-INF/classes/";
//assertTrue(myClassRootPath.endsWith(myWebappToClassRootPath));
File myWebinfFile = new File(myClassRootPath).getParentFile();
File myWebappFile = new File(myClassRootPath).
getParentFile().getParentFile().getParentFile().getParentFile();
webappPath = myWebappFile.getAbsolutePath()+"/";
System.out.println("Webapp path: " + webappPath);
webinfPath = myWebinfFile.getAbsolutePath()+"/";
ArrayList<String> myPropertyLocations = new ArrayList<String>()
{{
add(webappPath + "webapps-conf/arguments.deployment.properties");
add(myClassRootPath + "com/arguments/testdeployment.properties");
}};
Properties myDeploymentProperties = new Properties();
try
{
InputStream myPropertiesStream = null;
String myLocation = null;
while(myPropertiesStream == null && !myPropertyLocations.isEmpty())
{
myLocation = myPropertyLocations.remove(0);
File myPropertiesFile = new File(myLocation);
if (!myPropertiesFile.exists())
{
System.out.println("Didn't find arguments properties at " + myLocation);
}
else
{
myPropertiesStream = new FileInputStream(myPropertiesFile);
}
}
assertNotNull(myPropertiesStream);
System.out.println("Found aruments properties at " + myLocation);
myDeploymentProperties.load(myPropertiesStream);
} catch (IOException anException)
{
throw new ArgumentsException(anException);
}
dbUrl = myDeploymentProperties.getProperty("dbUrl");
dbName = myDeploymentProperties.getProperty("dbName");
dbDriver = myDeploymentProperties.getProperty("dbDriver");
dbUserName = myDeploymentProperties.getProperty("dbUserName");
dbPassword = myDeploymentProperties.getProperty("dbPassword");
assertNotNull(dbUrl);
}
| public Deployment()
{
final URL myClassRoot = Deployment.class.getResource("/");
final String myClassRootPath = myClassRoot.getFile();
System.out.println("Class root path: " + myClassRootPath);
// From eclipse: /mnt/bigspace/opt/linux/i386/liferay/liferay-sdk/portlets/argumentation-portlet/docroot/WEB-INF/classes/
// From tomcat: /mnt/bigspace/opt/linux/i386/liferay/liferay-portal-6.1.0-ce-ga1.2/tomcat-7.0.23/webapps/argumentation-portlet/WEB-INF/classes/
//String myWebappToClassRootPath = "argumentation-portlet/docroot/WEB-INF/classes/";
//assertTrue(myClassRootPath.endsWith(myWebappToClassRootPath));
File myWebinfFile = new File(myClassRootPath).getParentFile();
File myWebappFile = new File(myClassRootPath).
getParentFile().getParentFile().getParentFile().getParentFile();
webappPath = myWebappFile.getAbsolutePath()+"/";
System.out.println("Webapp path: " + webappPath);
webinfPath = myWebinfFile.getAbsolutePath()+"/";
ArrayList<String> myPropertyLocations = new ArrayList<String>()
{{
add(webappPath + "webapps-conf/arguments.deployment.properties");
add(myClassRootPath + "com/arguments/testdeployment.properties");
}};
Properties myDeploymentProperties = new Properties();
try
{
InputStream myPropertiesStream = null;
String myLocation = null;
while(myPropertiesStream == null && !myPropertyLocations.isEmpty())
{
myLocation = myPropertyLocations.remove(0);
File myPropertiesFile = new File(myLocation);
if (!myPropertiesFile.exists())
{
System.out.println("Didn't find arguments properties at " + myLocation);
}
else
{
myPropertiesStream = new FileInputStream(myPropertiesFile);
}
}
assertNotNull("Didn't find deployment properties file.", myPropertiesStream);
System.out.println("Found aruments properties at " + myLocation);
myDeploymentProperties.load(myPropertiesStream);
} catch (IOException anException)
{
throw new ArgumentsException(anException);
}
dbUrl = myDeploymentProperties.getProperty("dbUrl");
dbName = myDeploymentProperties.getProperty("dbName");
dbDriver = myDeploymentProperties.getProperty("dbDriver");
dbUserName = myDeploymentProperties.getProperty("dbUserName");
dbPassword = myDeploymentProperties.getProperty("dbPassword");
assertNotNull(dbUrl);
}
|
diff --git a/collect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java b/collect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java
index 22dc96af6..2da70004e 100644
--- a/collect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java
+++ b/collect-flex/collect-flex-server/src/main/java/org/openforis/collect/remoting/service/DataService.java
@@ -1,643 +1,645 @@
/**
*
*/
package org.openforis.collect.remoting.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.openforis.collect.manager.RecordManager;
import org.openforis.collect.manager.SessionManager;
import org.openforis.collect.metamodel.proxy.CodeListItemProxy;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.User;
import org.openforis.collect.model.proxy.AttributeSymbol;
import org.openforis.collect.model.proxy.NodeProxy;
import org.openforis.collect.model.proxy.RecordProxy;
import org.openforis.collect.persistence.AccessDeniedException;
import org.openforis.collect.persistence.InvalidIdException;
import org.openforis.collect.persistence.MultipleEditException;
import org.openforis.collect.persistence.NonexistentIdException;
import org.openforis.collect.persistence.RecordLockedException;
import org.openforis.collect.remoting.service.UpdateRequest.Method;
import org.openforis.collect.session.SessionState;
import org.openforis.collect.session.SessionState.RecordState;
import org.openforis.idm.metamodel.AttributeDefinition;
import org.openforis.idm.metamodel.BooleanAttributeDefinition;
import org.openforis.idm.metamodel.CodeAttributeDefinition;
import org.openforis.idm.metamodel.CodeListItem;
import org.openforis.idm.metamodel.CoordinateAttributeDefinition;
import org.openforis.idm.metamodel.DateAttributeDefinition;
import org.openforis.idm.metamodel.EntityDefinition;
import org.openforis.idm.metamodel.ModelVersion;
import org.openforis.idm.metamodel.NodeDefinition;
import org.openforis.idm.metamodel.NumberAttributeDefinition;
import org.openforis.idm.metamodel.NumberAttributeDefinition.Type;
import org.openforis.idm.metamodel.RangeAttributeDefinition;
import org.openforis.idm.metamodel.Schema;
import org.openforis.idm.metamodel.Survey;
import org.openforis.idm.metamodel.TaxonAttributeDefinition;
import org.openforis.idm.metamodel.TimeAttributeDefinition;
import org.openforis.idm.model.Attribute;
import org.openforis.idm.model.Code;
import org.openforis.idm.model.CodeAttribute;
import org.openforis.idm.model.Entity;
import org.openforis.idm.model.Field;
import org.openforis.idm.model.Node;
import org.openforis.idm.model.Record;
import org.openforis.idm.model.expression.ExpressionFactory;
import org.openforis.idm.model.expression.ModelPathExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* @author M. Togna
* @author S. Ricci
*
*/
public class DataService {
@Autowired
private SessionManager sessionManager;
@Autowired
private RecordManager recordManager;
@Transactional
public RecordProxy loadRecord(int id) throws RecordLockedException, MultipleEditException, NonexistentIdException, AccessDeniedException {
Survey survey = getActiveSurvey();
User user = getUserInSession();
CollectRecord record = recordManager.checkout(survey, user, id);
Entity rootEntity = record.getRootEntity();
ModelVersion version = record.getVersion();
recordManager.addEmptyAttributes(rootEntity, version);
SessionState sessionState = sessionManager.getSessionState();
sessionState.setActiveRecord(record);
sessionState.setActiveRecordState(RecordState.SAVED);
return new RecordProxy(record);
}
/**
*
* @param rootEntityName
* @param offset
* @param toIndex
* @param orderByFieldName
* @param filter
*
* @return map with "count" and "records" items
*/
@Transactional
public Map<String, Object> getRecordSummaries(String rootEntityName, int offset, int maxNumberOfRows, String orderByFieldName, String filter) {
Map<String, Object> result = new HashMap<String, Object>();
SessionState sessionState = sessionManager.getSessionState();
Survey activeSurvey = sessionState.getActiveSurvey();
Schema schema = activeSurvey.getSchema();
EntityDefinition rootEntityDefinition = schema.getRootEntityDefinition(rootEntityName);
String rootEntityDefinitionName = rootEntityDefinition.getName();
int count = recordManager.getCountRecords(rootEntityDefinition);
List<CollectRecord> summaries = recordManager.getSummaries(activeSurvey, rootEntityDefinitionName, offset, maxNumberOfRows, orderByFieldName, filter);
List<RecordProxy> proxies = new ArrayList<RecordProxy>();
for (CollectRecord summary : summaries) {
proxies.add(new RecordProxy(summary));
}
result.put("count", count);
result.put("records", proxies);
return result;
}
@Transactional
public RecordProxy createRecord(String rootEntityName, String versionName) throws MultipleEditException, AccessDeniedException, RecordLockedException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
Survey activeSurvey = sessionState.getActiveSurvey();
ModelVersion version = activeSurvey.getVersion(versionName);
Schema schema = activeSurvey.getSchema();
EntityDefinition rootEntityDefinition = schema.getRootEntityDefinition(rootEntityName);
CollectRecord record = recordManager.create(activeSurvey, rootEntityDefinition, user, version.getName());
Entity rootEntity = record.getRootEntity();
recordManager.addEmptyAttributes(rootEntity, version);
sessionState.setActiveRecord((CollectRecord) record);
sessionState.setActiveRecordState(RecordState.NEW);
RecordProxy recordProxy = new RecordProxy(record);
return recordProxy;
}
@Transactional
public void deleteRecord(int id) throws RecordLockedException, AccessDeniedException, MultipleEditException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
recordManager.delete(id, user);
sessionManager.clearActiveRecord();
}
@Transactional
public void saveActiveRecord() {
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
record.setModifiedDate(new java.util.Date());
record.setModifiedBy(sessionState.getUser());
recordManager.save(record);
sessionState.setActiveRecordState(RecordState.SAVED);
}
@Transactional
public void deleteActiveRecord() throws RecordLockedException, AccessDeniedException, MultipleEditException {
SessionState sessionState = sessionManager.getSessionState();
User user = sessionState.getUser();
Record record = sessionState.getActiveRecord();
recordManager.delete(record.getId(), user);
sessionManager.clearActiveRecord();
}
public List<NodeProxy> updateActiveRecord(UpdateRequest request) {
List<Node<?>> updatedNodes = new ArrayList<Node<?>>();
List<Node<?>> removedNodes = new ArrayList<Node<?>>();
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
ModelVersion version = record.getVersion();
Integer parentEntityId = request.getParentEntityId();
Entity parentEntity = (Entity) record.getNodeByInternalId(parentEntityId);
Integer nodeId = request.getNodeId();
Integer fieldIndex = request.getFieldIndex();
String nodeName = request.getNodeName();
Node<?> node = null;
if(nodeId != null) {
node = record.getNodeByInternalId(nodeId);
}
NodeDefinition nodeDef = ((EntityDefinition) parentEntity.getDefinition()).getChildDefinition(nodeName);
String requestValue = request.getValue();
String remarks = request.getRemarks();
//parse request values into a list of attribute value objects (for example Code, Date, Time...)
Object value = null;
if(requestValue != null && nodeDef instanceof AttributeDefinition) {
value = parseFieldValue(parentEntity, (AttributeDefinition) nodeDef, requestValue, fieldIndex);
}
AttributeSymbol symbol = request.getSymbol();
if(symbol == null && AttributeSymbol.isShortKeyForBlank(requestValue)) {
symbol = AttributeSymbol.fromShortKey(requestValue);
}
Character symbolChar = symbol != null ? symbol.getCode(): null;
Method method = request.getMethod();
switch (method) {
case ADD:
updatedNodes = addNode(version, parentEntity, nodeDef, value, fieldIndex, symbol, remarks);
break;
case UPDATE:
- if(node instanceof CodeAttribute) {
+ if(nodeDef instanceof CodeAttributeDefinition) {
removedNodes = removeNodes(parentEntity, nodeName);
+ updatedNodes = addNode(version, parentEntity, nodeDef, value, fieldIndex, symbol, remarks);
+ } else {
+ updatedNodes = updateNode(parentEntity, node, fieldIndex, value, symbol, remarks);
}
- updatedNodes = updateNode(parentEntity, node, fieldIndex, value, symbol, remarks);
break;
case UPDATE_SYMBOL:
//update attribute value
if(nodeDef instanceof AttributeDefinition) {
Attribute<?, ?> a = (Attribute<?, ?>) node;
Field<?> field = a.getField(fieldIndex);
field.setSymbol(symbolChar);
field.setRemarks(remarks);
updatedNodes.add(a);
} else if(node instanceof Entity) {
//update only the symbol in entity's attributes
Entity entity = (Entity) node;
recordManager.addEmptyAttributes(entity, version);
List<NodeDefinition> childDefinitions = ((EntityDefinition) nodeDef).getChildDefinitions();
for (NodeDefinition def : childDefinitions) {
if(def instanceof AttributeDefinition) {
String name = def.getName();
Attribute<?, ?> a = (Attribute<?, ?>) entity.get(name, 0);
setSymbolInAllFields(a, symbol);
updatedNodes.add(a);
}
}
}
break;
case DELETE:
Node<?> deleted = recordManager.deleteNode(parentEntity, node);
removedNodes.add(deleted);
break;
}
//convert nodes to proxies
List<NodeProxy> result = NodeProxy.fromList((List<Node<?>>) updatedNodes);
List<NodeProxy> removed = NodeProxy.fromList((List<Node<?>>) removedNodes);
for (NodeProxy nodeProxy : removed) {
nodeProxy.setDeleted(true);
}
result.addAll(removed);
return result;
}
@SuppressWarnings("unchecked")
private List<Node<?>> updateNode(Entity parentEntity, Node<?> node, Integer fieldIndex,
Object value, AttributeSymbol symbol, String remarks) {
if(node instanceof Attribute) {
List<Node<?>> updatedNodes = new ArrayList<Node<?>>();
Attribute<?, Object> attribute = (Attribute<?, Object>) node;
CollectRecord activeRecord = getActiveRecord();
ModelVersion version = activeRecord.getVersion();
AttributeDefinition def = attribute.getDefinition();
if(def instanceof CodeAttributeDefinition) {
CodeAttributeDefinition codeDef = (CodeAttributeDefinition) def;
String codesString = value != null ? value.toString(): null;
List<Node<?>> list = insertCodeAttributes(version, parentEntity, codeDef, codesString, symbol, remarks);
updatedNodes.addAll(list);
} else {
if(fieldIndex != null) {
@SuppressWarnings("rawtypes")
Field field = attribute.getField(fieldIndex);
field.setRemarks(remarks);
field.setSymbol(symbol != null ? symbol.getCode(): null);
field.setValue(value);
} else {
attribute.setValue(value);
}
updatedNodes.add(attribute);
}
return updatedNodes;
} else {
throw new UnsupportedOperationException("Cannot update an entity");
}
}
private List<Node<?>> addNode(ModelVersion version, Entity parentEntity, NodeDefinition nodeDef, Object value, Integer fieldIndex,
AttributeSymbol symbol, String remarks) {
List<Node<?>> addedNodes = new ArrayList<Node<?>>();
if(nodeDef instanceof AttributeDefinition) {
AttributeDefinition def = (AttributeDefinition) nodeDef;
if(def instanceof CodeAttributeDefinition) {
CodeAttributeDefinition codeDef = (CodeAttributeDefinition) def;
String codesString = value != null ? value.toString(): null;
List<Node<?>> list = insertCodeAttributes(version, parentEntity, codeDef, codesString, symbol, remarks);
addedNodes.addAll(list);
} else {
Attribute<?,?> attribute = recordManager.addAttribute(parentEntity, def, null);
if(fieldIndex != null) {
@SuppressWarnings("unchecked")
Field<Object> field = (Field<Object>) attribute.getField(fieldIndex);
field.setRemarks(remarks);
field.setSymbol(symbol != null ? symbol.getCode(): null);
field.setValue(value);
}
addedNodes.add(attribute);
}
} else {
Entity e = recordManager.addEntity(parentEntity, nodeDef.getName(), version);
addedNodes.add(e);
}
return addedNodes;
}
private List<Node<?>> insertCodeAttributes(ModelVersion version, Entity parentEntity, CodeAttributeDefinition def, String codesString,
AttributeSymbol symbol, String remarks) {
List<Node<?>> addedNodes = new ArrayList<Node<?>>();
List<Code> codes = codesString != null ? parseCodes(parentEntity, def, codesString, version): null;
if(codes != null) {
for (Code c : codes) {
Attribute<?, ?> attribute = recordManager.addAttribute(parentEntity, def, c);
//set symbol and remarks in first field
Field<?> field = attribute.getField(0);
if(symbol != null) {
field.setSymbol(symbol.getCode());
}
field.setRemarks(remarks);
addedNodes.add(attribute);
}
} else {
Attribute<?,?> attribute = recordManager.addAttribute(parentEntity, def, null);
Field<?> field = attribute.getField(0);
field.setRemarks(remarks);
field.setSymbol(symbol != null ? symbol.getCode(): null);
addedNodes.add(attribute);
}
return addedNodes;
}
private List<Node<?>> removeNodes(Entity parentEntity, String nodeName) {
List<Node<?>> deletedNodes = new ArrayList<Node<?>>();
int count = parentEntity.getCount(nodeName);
for (int i = count - 1; i >= 0; i--) {
Node<?> removed = parentEntity.remove(nodeName, i);
deletedNodes.add(removed);
}
return deletedNodes;
}
private void setSymbolInAllFields(Attribute<?, ?> attribute, AttributeSymbol symbol) {
Character s = symbol != null ? symbol.getCode(): null;
int count = attribute.getFieldCount();
for (int i = 0; i < count; i++) {
Field<?> field = attribute.getField(i);
if(s == null || (symbol.isReasonBlank() && field.isEmpty())) {
field.setSymbol(s);
}
}
}
private Object parseFieldValue(Entity parentEntity, AttributeDefinition def, String value, Integer fieldIndex) {
Object result = null;
if(StringUtils.isBlank(value)) {
return null;
}
if(def instanceof BooleanAttributeDefinition) {
result = Boolean.parseBoolean(value);
} else if(def instanceof CodeAttributeDefinition) {
result = value;
} else if(def instanceof CoordinateAttributeDefinition) {
if(fieldIndex != null) {
if(fieldIndex == 2) {
//srsId
result = value;
} else {
Long val = Long.valueOf(value);
result = val;
}
}
} else if(def instanceof DateAttributeDefinition) {
Integer val = Integer.valueOf(value);
result = val;
} else if(def instanceof NumberAttributeDefinition) {
NumberAttributeDefinition numberDef = (NumberAttributeDefinition) def;
Type type = numberDef.getType();
Number number = null;
switch(type) {
case INTEGER:
number = Integer.valueOf(value);
break;
case REAL:
number = Double.valueOf(value);
break;
}
if(number != null) {
result = number;
}
} else if(def instanceof RangeAttributeDefinition) {
org.openforis.idm.metamodel.RangeAttributeDefinition.Type type = ((RangeAttributeDefinition) def).getType();
Number number = null;
switch(type) {
case INTEGER:
number = Integer.valueOf(value);
break;
case REAL:
number = Double.valueOf(value);
break;
}
if(number != null) {
result = number;
}
} else if(def instanceof TaxonAttributeDefinition) {
result = value;
} else if(def instanceof TimeAttributeDefinition) {
Integer val = Integer.valueOf(value);
result = val;
} else {
result = value;
}
return result;
}
@Transactional
public void promote(String recordId) throws InvalidIdException, MultipleEditException, NonexistentIdException, AccessDeniedException, RecordLockedException {
this.recordManager.promote(recordId);
}
@Transactional
public void demote(String recordId) throws InvalidIdException, MultipleEditException, NonexistentIdException, AccessDeniedException, RecordLockedException {
this.recordManager.demote(recordId);
}
public void updateNodeHierarchy(Node<? extends NodeDefinition> node, int newPosition) {
}
public List<String> find(String context, String query) {
return null;
}
/**
* remove the active record from the current session
* @throws RecordLockedException
* @throws AccessDeniedException
* @throws MultipleEditException
*/
public void clearActiveRecord() throws RecordLockedException, AccessDeniedException, MultipleEditException {
CollectRecord activeRecord = getActiveRecord();
User user = getUserInSession();
this.recordManager.unlock(activeRecord, user);
Integer recordId = activeRecord.getId();
SessionState sessionState = this.sessionManager.getSessionState();
if(RecordState.NEW == sessionState.getActiveRecordState()) {
this.recordManager.delete(recordId, user);
}
this.sessionManager.clearActiveRecord();
}
/**
* Gets the code list items assignable to the specified attribute and matching the specified codes.
*
* @param parentEntityId
* @param attrName
* @param codes
* @return
*/
public List<CodeListItemProxy> getCodeListItems(int parentEntityId, String attrName, String[] codes){
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attrName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItem> filteredItems = new ArrayList<CodeListItem>();
if(codes != null && codes.length > 0) {
//filter by specified codes
for (CodeListItem item : items) {
for (String code : codes) {
if(item.getCode().equals(code)) {
filteredItems.add(item);
}
}
}
}
List<CodeListItemProxy> result = CodeListItemProxy.fromList(filteredItems);
return result;
}
/**
* Gets the code list items assignable to the specified attribute.
*
* @param parentEntityId
* @param attrName
* @return
*/
public List<CodeListItemProxy> findAssignableCodeListItems(int parentEntityId, String attrName){
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attrName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItemProxy> result = CodeListItemProxy.fromList(items);
List<Node<?>> selectedCodes = parent.getAll(attrName);
CodeListItemProxy.setSelectedItems(result, selectedCodes);
return result;
}
/**
* Finds a list of code list items assignable to the specified attribute and matching the passed codes
*
* @param parentEntityId
* @param attributeName
* @param codes
* @return
*/
public List<CodeListItemProxy> findAssignableCodeListItems(int parentEntityId, String attributeName, String[] codes) {
CollectRecord record = getActiveRecord();
Entity parent = (Entity) record.getNodeByInternalId(parentEntityId);
CodeAttributeDefinition def = (CodeAttributeDefinition) parent.getDefinition().getChildDefinition(attributeName);
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
List<CodeListItemProxy> result = new ArrayList<CodeListItemProxy>();
for (String code : codes) {
CodeListItem item = findCodeListItem(items, code);
if(item != null) {
CodeListItemProxy proxy = new CodeListItemProxy(item);
result.add(proxy);
}
}
return result;
}
private User getUserInSession() {
SessionState sessionState = getSessionManager().getSessionState();
User user = sessionState.getUser();
return user;
}
private Survey getActiveSurvey() {
SessionState sessionState = getSessionManager().getSessionState();
Survey activeSurvey = sessionState.getActiveSurvey();
return activeSurvey;
}
protected CollectRecord getActiveRecord() {
SessionState sessionState = getSessionManager().getSessionState();
CollectRecord activeRecord = sessionState.getActiveRecord();
return activeRecord;
}
protected SessionManager getSessionManager() {
return sessionManager;
}
protected RecordManager getRecordManager() {
return recordManager;
}
/**
* Start of CodeList utility methods
*
* TODO move them to a better location
*/
private List<CodeListItem> getAssignableCodeListItems(Entity parent, CodeAttributeDefinition def) {
CollectRecord record = getActiveRecord();
ModelVersion version = record.getVersion();
List<CodeListItem> items = null;
if(StringUtils.isEmpty(def.getParentExpression())){
items = def.getList().getItems();
} else {
CodeAttribute parentCodeAttribute = getCodeParent(parent, def);
if(parentCodeAttribute!=null){
CodeListItem parentCodeListItem = parentCodeAttribute.getCodeListItem();
if(parentCodeListItem != null) {
//TODO exception if parent not specified
items = parentCodeListItem.getChildItems();
}
}
}
List<CodeListItem> result = new ArrayList<CodeListItem>();
if(items != null) {
for (CodeListItem item : items) {
if(version.isApplicable(item)) {
result.add(item);
}
}
}
return result;
}
private CodeAttribute getCodeParent(Entity context, CodeAttributeDefinition def) {
try {
String parentExpr = def.getParentExpression();
ExpressionFactory expressionFactory = context.getRecord().getContext().getExpressionFactory();
ModelPathExpression expression = expressionFactory.createModelPathExpression(parentExpr);
Node<?> parentNode = expression.evaluate(context, null);
if (parentNode != null && parentNode instanceof CodeAttribute) {
return (CodeAttribute) parentNode;
}
} catch (Exception e) {
// return null;
}
return null;
}
private CodeListItem findCodeListItem(List<CodeListItem> siblings, String code) {
String adaptedCode = code.trim();
adaptedCode = adaptedCode.toUpperCase();
//remove initial zeros
adaptedCode = adaptedCode.replaceFirst("^0+", "");
adaptedCode = Pattern.quote(adaptedCode);
for (CodeListItem item : siblings) {
String itemCode = item.getCode();
Pattern pattern = Pattern.compile("^[0]*" + adaptedCode + "$");
Matcher matcher = pattern.matcher(itemCode);
if(matcher.find()) {
return item;
}
}
return null;
}
private Code parseCode(String value, List<CodeListItem> codeList, ModelVersion version) {
Code code = null;
String[] strings = value.split(":");
String codeStr = null;
String qualifier = null;
switch(strings.length) {
case 2:
qualifier = strings[1].trim();
case 1:
codeStr = strings[0].trim();
break;
default:
//TODO throw error: invalid parameter
}
CodeListItem codeListItem = findCodeListItem(codeList, codeStr);
if(codeListItem != null) {
code = new Code(codeListItem.getCode(), qualifier);
}
if (code == null) {
code = new Code(codeStr, qualifier);
}
return code;
}
public List<Code> parseCodes(Entity parent, CodeAttributeDefinition def, String value, ModelVersion version) {
List<Code> result = new ArrayList<Code>();
List<CodeListItem> items = getAssignableCodeListItems(parent, def);
StringTokenizer st = new StringTokenizer(value, ",");
while (st.hasMoreTokens()) {
String token = st.nextToken();
Code code = parseCode(token, items, version);
if(code != null) {
result.add(code);
} else {
//TODO throw exception
}
}
return result;
}
}
| false | true | public List<NodeProxy> updateActiveRecord(UpdateRequest request) {
List<Node<?>> updatedNodes = new ArrayList<Node<?>>();
List<Node<?>> removedNodes = new ArrayList<Node<?>>();
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
ModelVersion version = record.getVersion();
Integer parentEntityId = request.getParentEntityId();
Entity parentEntity = (Entity) record.getNodeByInternalId(parentEntityId);
Integer nodeId = request.getNodeId();
Integer fieldIndex = request.getFieldIndex();
String nodeName = request.getNodeName();
Node<?> node = null;
if(nodeId != null) {
node = record.getNodeByInternalId(nodeId);
}
NodeDefinition nodeDef = ((EntityDefinition) parentEntity.getDefinition()).getChildDefinition(nodeName);
String requestValue = request.getValue();
String remarks = request.getRemarks();
//parse request values into a list of attribute value objects (for example Code, Date, Time...)
Object value = null;
if(requestValue != null && nodeDef instanceof AttributeDefinition) {
value = parseFieldValue(parentEntity, (AttributeDefinition) nodeDef, requestValue, fieldIndex);
}
AttributeSymbol symbol = request.getSymbol();
if(symbol == null && AttributeSymbol.isShortKeyForBlank(requestValue)) {
symbol = AttributeSymbol.fromShortKey(requestValue);
}
Character symbolChar = symbol != null ? symbol.getCode(): null;
Method method = request.getMethod();
switch (method) {
case ADD:
updatedNodes = addNode(version, parentEntity, nodeDef, value, fieldIndex, symbol, remarks);
break;
case UPDATE:
if(node instanceof CodeAttribute) {
removedNodes = removeNodes(parentEntity, nodeName);
}
updatedNodes = updateNode(parentEntity, node, fieldIndex, value, symbol, remarks);
break;
case UPDATE_SYMBOL:
//update attribute value
if(nodeDef instanceof AttributeDefinition) {
Attribute<?, ?> a = (Attribute<?, ?>) node;
Field<?> field = a.getField(fieldIndex);
field.setSymbol(symbolChar);
field.setRemarks(remarks);
updatedNodes.add(a);
} else if(node instanceof Entity) {
//update only the symbol in entity's attributes
Entity entity = (Entity) node;
recordManager.addEmptyAttributes(entity, version);
List<NodeDefinition> childDefinitions = ((EntityDefinition) nodeDef).getChildDefinitions();
for (NodeDefinition def : childDefinitions) {
if(def instanceof AttributeDefinition) {
String name = def.getName();
Attribute<?, ?> a = (Attribute<?, ?>) entity.get(name, 0);
setSymbolInAllFields(a, symbol);
updatedNodes.add(a);
}
}
}
break;
case DELETE:
Node<?> deleted = recordManager.deleteNode(parentEntity, node);
removedNodes.add(deleted);
break;
}
//convert nodes to proxies
List<NodeProxy> result = NodeProxy.fromList((List<Node<?>>) updatedNodes);
List<NodeProxy> removed = NodeProxy.fromList((List<Node<?>>) removedNodes);
for (NodeProxy nodeProxy : removed) {
nodeProxy.setDeleted(true);
}
result.addAll(removed);
return result;
}
| public List<NodeProxy> updateActiveRecord(UpdateRequest request) {
List<Node<?>> updatedNodes = new ArrayList<Node<?>>();
List<Node<?>> removedNodes = new ArrayList<Node<?>>();
SessionState sessionState = sessionManager.getSessionState();
CollectRecord record = sessionState.getActiveRecord();
ModelVersion version = record.getVersion();
Integer parentEntityId = request.getParentEntityId();
Entity parentEntity = (Entity) record.getNodeByInternalId(parentEntityId);
Integer nodeId = request.getNodeId();
Integer fieldIndex = request.getFieldIndex();
String nodeName = request.getNodeName();
Node<?> node = null;
if(nodeId != null) {
node = record.getNodeByInternalId(nodeId);
}
NodeDefinition nodeDef = ((EntityDefinition) parentEntity.getDefinition()).getChildDefinition(nodeName);
String requestValue = request.getValue();
String remarks = request.getRemarks();
//parse request values into a list of attribute value objects (for example Code, Date, Time...)
Object value = null;
if(requestValue != null && nodeDef instanceof AttributeDefinition) {
value = parseFieldValue(parentEntity, (AttributeDefinition) nodeDef, requestValue, fieldIndex);
}
AttributeSymbol symbol = request.getSymbol();
if(symbol == null && AttributeSymbol.isShortKeyForBlank(requestValue)) {
symbol = AttributeSymbol.fromShortKey(requestValue);
}
Character symbolChar = symbol != null ? symbol.getCode(): null;
Method method = request.getMethod();
switch (method) {
case ADD:
updatedNodes = addNode(version, parentEntity, nodeDef, value, fieldIndex, symbol, remarks);
break;
case UPDATE:
if(nodeDef instanceof CodeAttributeDefinition) {
removedNodes = removeNodes(parentEntity, nodeName);
updatedNodes = addNode(version, parentEntity, nodeDef, value, fieldIndex, symbol, remarks);
} else {
updatedNodes = updateNode(parentEntity, node, fieldIndex, value, symbol, remarks);
}
break;
case UPDATE_SYMBOL:
//update attribute value
if(nodeDef instanceof AttributeDefinition) {
Attribute<?, ?> a = (Attribute<?, ?>) node;
Field<?> field = a.getField(fieldIndex);
field.setSymbol(symbolChar);
field.setRemarks(remarks);
updatedNodes.add(a);
} else if(node instanceof Entity) {
//update only the symbol in entity's attributes
Entity entity = (Entity) node;
recordManager.addEmptyAttributes(entity, version);
List<NodeDefinition> childDefinitions = ((EntityDefinition) nodeDef).getChildDefinitions();
for (NodeDefinition def : childDefinitions) {
if(def instanceof AttributeDefinition) {
String name = def.getName();
Attribute<?, ?> a = (Attribute<?, ?>) entity.get(name, 0);
setSymbolInAllFields(a, symbol);
updatedNodes.add(a);
}
}
}
break;
case DELETE:
Node<?> deleted = recordManager.deleteNode(parentEntity, node);
removedNodes.add(deleted);
break;
}
//convert nodes to proxies
List<NodeProxy> result = NodeProxy.fromList((List<Node<?>>) updatedNodes);
List<NodeProxy> removed = NodeProxy.fromList((List<Node<?>>) removedNodes);
for (NodeProxy nodeProxy : removed) {
nodeProxy.setDeleted(true);
}
result.addAll(removed);
return result;
}
|
diff --git a/source/client/main/edu/wustl/cab2b/client/ui/mainframe/GlobalNavigationGlassPane.java b/source/client/main/edu/wustl/cab2b/client/ui/mainframe/GlobalNavigationGlassPane.java
index 1c49857e..fee5894d 100644
--- a/source/client/main/edu/wustl/cab2b/client/ui/mainframe/GlobalNavigationGlassPane.java
+++ b/source/client/main/edu/wustl/cab2b/client/ui/mainframe/GlobalNavigationGlassPane.java
@@ -1,248 +1,248 @@
package edu.wustl.cab2b.client.ui.mainframe;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import org.jdesktop.swingx.HorizontalLayout;
import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.JXPanel;
import edu.wustl.cab2b.client.ui.MainSearchPanel;
import edu.wustl.cab2b.client.ui.WindowUtilities;
import edu.wustl.cab2b.client.ui.controls.Cab2bButton;
import edu.wustl.cab2b.client.ui.controls.Cab2bHyperlink;
import edu.wustl.cab2b.client.ui.controls.Cab2bLabel;
import edu.wustl.cab2b.client.ui.controls.Cab2bPanel;
import edu.wustl.cab2b.client.ui.util.CommonUtils;
import edu.wustl.common.util.logger.Logger;
/**
* This class creates a glassPane over the icons and adds tab-buttons to the
* panel
*
* @author hrishikesh_rajpathak
*
*/
class GlobalNavigationGlassPane extends JComponent implements ActionListener {
Cab2bLabel loggedInUserLabel;
private ClassLoader loader = this.getClass().getClassLoader();
private URL[] tabsImagesUnPressed = { loader.getResource("home_tab.gif"), loader.getResource("searchdata_tab.gif"), loader.getResource("experiment_tab.gif") };
private URL[] tabsImagesPressed = { loader.getResource("home_MO_tab.gif"), loader.getResource("searchdata_MO_tab.gif"), loader.getResource("experiment_MO_tab.gif") };
private JButton[] tabButtons = new Cab2bButton[3];
public Color navigationButtonBgColorSelected = Color.WHITE;
private JXPanel tabsPanel;
public MainFrame mainFrame;
public JXFrame frame;
private JLabel middleLabel;
private JLabel rightLabel;
private JButton lastSelectedTab;
private static final long serialVersionUID = 1L;
public GlobalNavigationGlassPane(
JLabel leftLabel,
JLabel middleLabel,
JLabel rightLabel,
MainFrame mainFrame,
JXFrame frame) {
this.frame = mainFrame;
this.mainFrame = mainFrame;
this.middleLabel = middleLabel;
this.rightLabel = rightLabel;
initUI();
}
/**
* Initialize the UI
*/
private void initUI() {
middleLabel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Cab2bPanel topMiddlePanel = new Cab2bPanel();
topMiddlePanel.setPreferredSize(new Dimension(300, 40));
topMiddlePanel.setMinimumSize(new Dimension(300, 40));
topMiddlePanel.setMaximumSize(new Dimension(300, 40));
topMiddlePanel.setOpaque(false);
tabsPanel = new Cab2bPanel();
tabsPanel.setPreferredSize(new Dimension(300, 30));
tabsPanel.setMinimumSize(new Dimension(300, 30));
tabsPanel.setMaximumSize(new Dimension(300, 30));
tabsPanel.setOpaque(false);
tabsPanel.setLayout(new HorizontalLayout(10));
for (int i = 0; i < 3; i++) {
ImageIcon icon = new ImageIcon(tabsImagesUnPressed[i]);
tabButtons[i] = new Cab2bButton();
tabButtons[i].setPreferredSize(new Dimension(85, 22));
tabButtons[i].setIcon(icon);
tabButtons[i].setBorder(null);
tabButtons[i].addActionListener(this);
tabsPanel.add(tabButtons[i]);
}
ImageIcon icon = new ImageIcon(tabsImagesPressed[0]);
tabButtons[0].setIcon(icon);
gbc.gridx = 3;
gbc.gridy = 0;
gbc.gridwidth = 3;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.VERTICAL;
middleLabel.add(topMiddlePanel, gbc);
gbc.gridx = 3;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.VERTICAL;
middleLabel.add(tabsPanel, gbc);
rightLabel.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 2;
gbc.weightx = 1.5;
gbc.fill = GridBagConstraints.VERTICAL;
rightLabel.add(new JLabel(""), gbc);
Date date = new Date();
loggedInUserLabel = new Cab2bLabel("Robert Lloyd");
loggedInUserLabel.setFont(new Font("Arial", Font.BOLD, 12));
Cab2bLabel dateLabel = new Cab2bLabel(DateFormat.getDateInstance(DateFormat.LONG).format(date).toString());
dateLabel.setForeground(Color.WHITE);
Cab2bHyperlink logOutHyperLink = new Cab2bHyperlink();
- logOutHyperLink.setClickedHyperlinkColor(Color.GRAY);
+ logOutHyperLink.setClickedHyperlinkColor(Color.WHITE);
logOutHyperLink.setUnclickedHyperlinkColor(Color.WHITE);
logOutHyperLink.setText("Logout");
logOutHyperLink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked on logOut Link");
}
});
Cab2bHyperlink mySettingHyperlInk = new Cab2bHyperlink();
- mySettingHyperlInk.setClickedHyperlinkColor(Color.GRAY);
+ mySettingHyperlInk.setClickedHyperlinkColor(Color.WHITE);
mySettingHyperlInk.setUnclickedHyperlinkColor(Color.WHITE);
mySettingHyperlInk.setText("MySettings");
mySettingHyperlInk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked on My-Settings Link");
}
});
loggedInUserLabel.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
loggedInUserLabel.setForeground(Color.WHITE);
JLabel line = new JLabel("|");
line.setForeground(Color.WHITE);
Cab2bPanel linkPanel = new Cab2bPanel();
JLabel label = new JLabel(" ");
linkPanel.add("br", label);
linkPanel.add("tab ", loggedInUserLabel);
linkPanel.add("br ", label);
linkPanel.add("tab ", dateLabel);
linkPanel.add("br ", logOutHyperLink);
linkPanel.add(line);
linkPanel.add(mySettingHyperlInk);
linkPanel.setOpaque(false);
gbc.gridx = 2;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 2;
gbc.weightx = 0.1;
gbc.fill = GridBagConstraints.VERTICAL;
rightLabel.add(linkPanel, gbc);
lastSelectedTab = tabButtons[0];
this.repaint();
}
public void actionPerformed(ActionEvent e) {
Logger.out.debug("Global Nagigation Panel Button");
JButton button = (JButton) e.getSource();
if (button.equals(tabButtons[0])) {
tabButtons[0].setIcon(new ImageIcon(tabsImagesPressed[0]));
tabButtons[1].setIcon(new ImageIcon(tabsImagesUnPressed[1]));
tabButtons[2].setIcon(new ImageIcon(tabsImagesUnPressed[2]));
if (this.frame instanceof MainFrame) {
MainFrame mainframePanel = (MainFrame) this.frame;
mainframePanel.setHomeWelcomePanel();
Logger.out.debug("Global Nagigation Panel Home Button");
}
} else if (button.equals(tabButtons[1])) {
tabButtons[0].setIcon(new ImageIcon(tabsImagesUnPressed[0]));
tabButtons[1].setIcon(new ImageIcon(tabsImagesPressed[1]));
tabButtons[2].setIcon(new ImageIcon(tabsImagesUnPressed[2]));
GlobalNavigationPanel.mainSearchPanel = new MainSearchPanel();
Dimension relDimension = CommonUtils.getRelativeDimension(MainFrame.mainframeScreenDimesion, 0.90f,
0.85f);
GlobalNavigationPanel.mainSearchPanel.setPreferredSize(relDimension);
GlobalNavigationPanel.mainSearchPanel.setSize(relDimension);
// Update the variable for latest screen dimension from the
// toolkit, this is to handle the situations where
// application is started and then screen resolution is
// changed, but the variable stiil holds old resolution
// size.
MainFrame.mainframeScreenDimesion = Toolkit.getDefaultToolkit().getScreenSize();
Dimension dimension = MainFrame.mainframeScreenDimesion;
WindowUtilities.showInDialog(mainFrame, GlobalNavigationPanel.mainSearchPanel, "Search Data for Experiment",
new Dimension((int) (dimension.width * 0.90),
(int) (dimension.height * 0.85)), true, true);
MainSearchPanel.getDataList().clear();
GlobalNavigationPanel.mainSearchPanel = null;
// Set the Home tab as pressed and Search tab as unpressed
if(lastSelectedTab != null && lastSelectedTab.equals(tabButtons[0])) {
lastSelectedTab.setIcon(new ImageIcon(tabsImagesPressed[0]));
} else if(lastSelectedTab != null && lastSelectedTab.equals(tabButtons[2])) {
lastSelectedTab.setIcon(new ImageIcon(tabsImagesPressed[2]));
}
tabButtons[1].setIcon(new ImageIcon(tabsImagesUnPressed[1]));
} else if (button.equals(tabButtons[2])) {
tabButtons[0].setIcon(new ImageIcon(tabsImagesUnPressed[0]));
tabButtons[1].setIcon(new ImageIcon(tabsImagesUnPressed[1]));
tabButtons[2].setIcon(new ImageIcon(tabsImagesPressed[2]));
MainFrame mainframePanel = (MainFrame) this.frame;
mainframePanel.setOpenExperimentWelcomePanel();
}
lastSelectedTab = button;
this.updateUI();
this.repaint();
}
}
| false | true | private void initUI() {
middleLabel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Cab2bPanel topMiddlePanel = new Cab2bPanel();
topMiddlePanel.setPreferredSize(new Dimension(300, 40));
topMiddlePanel.setMinimumSize(new Dimension(300, 40));
topMiddlePanel.setMaximumSize(new Dimension(300, 40));
topMiddlePanel.setOpaque(false);
tabsPanel = new Cab2bPanel();
tabsPanel.setPreferredSize(new Dimension(300, 30));
tabsPanel.setMinimumSize(new Dimension(300, 30));
tabsPanel.setMaximumSize(new Dimension(300, 30));
tabsPanel.setOpaque(false);
tabsPanel.setLayout(new HorizontalLayout(10));
for (int i = 0; i < 3; i++) {
ImageIcon icon = new ImageIcon(tabsImagesUnPressed[i]);
tabButtons[i] = new Cab2bButton();
tabButtons[i].setPreferredSize(new Dimension(85, 22));
tabButtons[i].setIcon(icon);
tabButtons[i].setBorder(null);
tabButtons[i].addActionListener(this);
tabsPanel.add(tabButtons[i]);
}
ImageIcon icon = new ImageIcon(tabsImagesPressed[0]);
tabButtons[0].setIcon(icon);
gbc.gridx = 3;
gbc.gridy = 0;
gbc.gridwidth = 3;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.VERTICAL;
middleLabel.add(topMiddlePanel, gbc);
gbc.gridx = 3;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.VERTICAL;
middleLabel.add(tabsPanel, gbc);
rightLabel.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 2;
gbc.weightx = 1.5;
gbc.fill = GridBagConstraints.VERTICAL;
rightLabel.add(new JLabel(""), gbc);
Date date = new Date();
loggedInUserLabel = new Cab2bLabel("Robert Lloyd");
loggedInUserLabel.setFont(new Font("Arial", Font.BOLD, 12));
Cab2bLabel dateLabel = new Cab2bLabel(DateFormat.getDateInstance(DateFormat.LONG).format(date).toString());
dateLabel.setForeground(Color.WHITE);
Cab2bHyperlink logOutHyperLink = new Cab2bHyperlink();
logOutHyperLink.setClickedHyperlinkColor(Color.GRAY);
logOutHyperLink.setUnclickedHyperlinkColor(Color.WHITE);
logOutHyperLink.setText("Logout");
logOutHyperLink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked on logOut Link");
}
});
Cab2bHyperlink mySettingHyperlInk = new Cab2bHyperlink();
mySettingHyperlInk.setClickedHyperlinkColor(Color.GRAY);
mySettingHyperlInk.setUnclickedHyperlinkColor(Color.WHITE);
mySettingHyperlInk.setText("MySettings");
mySettingHyperlInk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked on My-Settings Link");
}
});
loggedInUserLabel.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
loggedInUserLabel.setForeground(Color.WHITE);
JLabel line = new JLabel("|");
line.setForeground(Color.WHITE);
Cab2bPanel linkPanel = new Cab2bPanel();
JLabel label = new JLabel(" ");
linkPanel.add("br", label);
linkPanel.add("tab ", loggedInUserLabel);
linkPanel.add("br ", label);
linkPanel.add("tab ", dateLabel);
linkPanel.add("br ", logOutHyperLink);
linkPanel.add(line);
linkPanel.add(mySettingHyperlInk);
linkPanel.setOpaque(false);
gbc.gridx = 2;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 2;
gbc.weightx = 0.1;
gbc.fill = GridBagConstraints.VERTICAL;
rightLabel.add(linkPanel, gbc);
lastSelectedTab = tabButtons[0];
this.repaint();
}
| private void initUI() {
middleLabel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Cab2bPanel topMiddlePanel = new Cab2bPanel();
topMiddlePanel.setPreferredSize(new Dimension(300, 40));
topMiddlePanel.setMinimumSize(new Dimension(300, 40));
topMiddlePanel.setMaximumSize(new Dimension(300, 40));
topMiddlePanel.setOpaque(false);
tabsPanel = new Cab2bPanel();
tabsPanel.setPreferredSize(new Dimension(300, 30));
tabsPanel.setMinimumSize(new Dimension(300, 30));
tabsPanel.setMaximumSize(new Dimension(300, 30));
tabsPanel.setOpaque(false);
tabsPanel.setLayout(new HorizontalLayout(10));
for (int i = 0; i < 3; i++) {
ImageIcon icon = new ImageIcon(tabsImagesUnPressed[i]);
tabButtons[i] = new Cab2bButton();
tabButtons[i].setPreferredSize(new Dimension(85, 22));
tabButtons[i].setIcon(icon);
tabButtons[i].setBorder(null);
tabButtons[i].addActionListener(this);
tabsPanel.add(tabButtons[i]);
}
ImageIcon icon = new ImageIcon(tabsImagesPressed[0]);
tabButtons[0].setIcon(icon);
gbc.gridx = 3;
gbc.gridy = 0;
gbc.gridwidth = 3;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.VERTICAL;
middleLabel.add(topMiddlePanel, gbc);
gbc.gridx = 3;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.VERTICAL;
middleLabel.add(tabsPanel, gbc);
rightLabel.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 2;
gbc.weightx = 1.5;
gbc.fill = GridBagConstraints.VERTICAL;
rightLabel.add(new JLabel(""), gbc);
Date date = new Date();
loggedInUserLabel = new Cab2bLabel("Robert Lloyd");
loggedInUserLabel.setFont(new Font("Arial", Font.BOLD, 12));
Cab2bLabel dateLabel = new Cab2bLabel(DateFormat.getDateInstance(DateFormat.LONG).format(date).toString());
dateLabel.setForeground(Color.WHITE);
Cab2bHyperlink logOutHyperLink = new Cab2bHyperlink();
logOutHyperLink.setClickedHyperlinkColor(Color.WHITE);
logOutHyperLink.setUnclickedHyperlinkColor(Color.WHITE);
logOutHyperLink.setText("Logout");
logOutHyperLink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked on logOut Link");
}
});
Cab2bHyperlink mySettingHyperlInk = new Cab2bHyperlink();
mySettingHyperlInk.setClickedHyperlinkColor(Color.WHITE);
mySettingHyperlInk.setUnclickedHyperlinkColor(Color.WHITE);
mySettingHyperlInk.setText("MySettings");
mySettingHyperlInk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked on My-Settings Link");
}
});
loggedInUserLabel.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
loggedInUserLabel.setForeground(Color.WHITE);
JLabel line = new JLabel("|");
line.setForeground(Color.WHITE);
Cab2bPanel linkPanel = new Cab2bPanel();
JLabel label = new JLabel(" ");
linkPanel.add("br", label);
linkPanel.add("tab ", loggedInUserLabel);
linkPanel.add("br ", label);
linkPanel.add("tab ", dateLabel);
linkPanel.add("br ", logOutHyperLink);
linkPanel.add(line);
linkPanel.add(mySettingHyperlInk);
linkPanel.setOpaque(false);
gbc.gridx = 2;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 2;
gbc.weightx = 0.1;
gbc.fill = GridBagConstraints.VERTICAL;
rightLabel.add(linkPanel, gbc);
lastSelectedTab = tabButtons[0];
this.repaint();
}
|
diff --git a/prov-interop/src/main/java/org/openprovenance/prov/interop/InteropFramework.java b/prov-interop/src/main/java/org/openprovenance/prov/interop/InteropFramework.java
index 419833c2..416f9949 100644
--- a/prov-interop/src/main/java/org/openprovenance/prov/interop/InteropFramework.java
+++ b/prov-interop/src/main/java/org/openprovenance/prov/interop/InteropFramework.java
@@ -1,597 +1,597 @@
package org.openprovenance.prov.interop;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Variant;
import javax.xml.bind.JAXBException;
import org.openprovenance.prov.xml.Document;
import org.openprovenance.prov.xml.ProvDeserialiser;
import org.openprovenance.prov.xml.ProvSerialiser;
import org.openprovenance.prov.xml.ProvFactory;
import org.openprovenance.prov.notation.Utility;
import org.antlr.runtime.tree.CommonTree;
import org.openrdf.rio.RDFFormat;
import org.openprovenance.prov.dot.ProvToDot;
import org.apache.log4j.Logger;
/**
* The interoperability framework for PROV.
*/
public class InteropFramework {
static Logger logger = Logger.getLogger(InteropFramework.class);
public static final String UNKNOWN = "unknown";
public static final String PC1_NS = "http://www.ipaw.info/pc1/";
public static final String PC1_PREFIX = "pc1";
public static final String PRIM_NS = "http://openprovenance.org/primitives#";
public static final String PRIM_PREFIX = "prim";
final Utility u = new Utility();
final ProvFactory pFactory = ProvFactory.getFactory();
final private String verbose;
final private String debug;
final private String logfile;
final private String infile;
final private String outfile;
final private String namespaces;
final private String title;
public final Hashtable<ProvFormat, String> extensionMap;
public final Hashtable<String, ProvFormat> extensionRevMap;
public final Hashtable<ProvFormat, String> mimeTypeMap;
public final Hashtable<String, ProvFormat> mimeTypeRevMap;
public final Hashtable<ProvFormat, ProvFormatType> provTypeMap;
public InteropFramework() {
this(null, null, null, null, null, null,null);
}
public InteropFramework(String verbose, String debug, String logfile,
String infile, String outfile, String namespaces, String title) {
this.verbose = verbose;
this.debug = debug;
this.logfile = logfile;
this.infile = infile;
this.outfile = outfile;
this.namespaces = namespaces;
this.title=title;
extensionMap = new Hashtable<InteropFramework.ProvFormat, String>();
extensionRevMap = new Hashtable<String, InteropFramework.ProvFormat>();
mimeTypeMap = new Hashtable<InteropFramework.ProvFormat, String>();
mimeTypeRevMap = new Hashtable<String, InteropFramework.ProvFormat>();
provTypeMap = new Hashtable<InteropFramework.ProvFormat, InteropFramework.ProvFormatType>();
initializeExtensionMap(extensionMap, extensionRevMap);
}
public void initializeExtensionMap(
Hashtable<ProvFormat, String> extensionMap,
Hashtable<String, InteropFramework.ProvFormat> extensionRevMap) {
for (ProvFormat f : ProvFormat.values()) {
switch (f) {
case DOT:
extensionMap.put(ProvFormat.DOT, "dot");
extensionRevMap.put("dot", ProvFormat.DOT);
extensionRevMap.put("gv", ProvFormat.DOT);
mimeTypeMap.put(ProvFormat.DOT, "text/vnd.graphviz");
mimeTypeRevMap.put("text/vnd.graphviz", ProvFormat.DOT);
provTypeMap.put(ProvFormat.DOT, ProvFormatType.OUTPUT);
break;
case JPEG:
extensionMap.put(ProvFormat.JPEG, "jpg");
extensionRevMap.put("jpeg", ProvFormat.JPEG);
extensionRevMap.put("jpg", ProvFormat.JPEG);
mimeTypeMap.put(ProvFormat.JPEG, "image/jpeg");
mimeTypeRevMap.put("image/jpeg", ProvFormat.JPEG);
provTypeMap.put(ProvFormat.JPEG, ProvFormatType.OUTPUT);
break;
case JSON:
extensionMap.put(ProvFormat.JSON, "json");
extensionRevMap.put("json", ProvFormat.JSON);
mimeTypeMap.put(ProvFormat.JSON, "application/json");
mimeTypeRevMap.put("application/json", ProvFormat.JSON);
provTypeMap.put(ProvFormat.JSON, ProvFormatType.INPUTOUTPUT);
break;
case PDF:
extensionMap.put(ProvFormat.PDF, "pdf");
extensionRevMap.put("pdf", ProvFormat.PDF);
mimeTypeMap.put(ProvFormat.PDF, "application/pdf");
mimeTypeRevMap.put("application/pdf", ProvFormat.PDF);
provTypeMap.put(ProvFormat.PDF, ProvFormatType.OUTPUT);
break;
case PROVN:
extensionMap.put(ProvFormat.PROVN, "provn");
extensionRevMap.put("provn", ProvFormat.PROVN);
extensionRevMap.put("pn", ProvFormat.PROVN);
extensionRevMap.put("asn", ProvFormat.PROVN);
extensionRevMap.put("prov-asn", ProvFormat.PROVN);
mimeTypeMap.put(ProvFormat.PROVN, "text/provenance-notation");
mimeTypeRevMap
.put("text/provenance-notation", ProvFormat.PROVN);
provTypeMap.put(ProvFormat.PROVN, ProvFormatType.INPUTOUTPUT);
break;
case RDFXML:
extensionMap.put(ProvFormat.RDFXML, "rdf");
extensionRevMap.put("rdf", ProvFormat.RDFXML);
mimeTypeMap.put(ProvFormat.RDFXML, "application/rdf+xml");
mimeTypeRevMap.put("application/rdf+xml", ProvFormat.RDFXML);
provTypeMap.put(ProvFormat.RDFXML, ProvFormatType.INPUTOUTPUT);
break;
case SVG:
extensionMap.put(ProvFormat.SVG, "svg");
extensionRevMap.put("svg", ProvFormat.SVG);
mimeTypeMap.put(ProvFormat.SVG, "image/svg+xml");
mimeTypeRevMap.put("image/svg+xml", ProvFormat.SVG);
provTypeMap.put(ProvFormat.SVG, ProvFormatType.OUTPUT);
break;
case TRIG:
extensionMap.put(ProvFormat.TRIG, "trig");
extensionRevMap.put("trig", ProvFormat.TRIG);
mimeTypeMap.put(ProvFormat.TRIG, "application/x-trig");
mimeTypeRevMap.put("application/x-trig", ProvFormat.TRIG);
provTypeMap.put(ProvFormat.TRIG, ProvFormatType.INPUTOUTPUT);
break;
case TURTLE:
extensionMap.put(ProvFormat.TURTLE, "ttl");
extensionRevMap.put("ttl", ProvFormat.TURTLE);
mimeTypeMap.put(ProvFormat.TURTLE, "text/turtle");
mimeTypeRevMap.put("text/turtle", ProvFormat.TURTLE);
provTypeMap.put(ProvFormat.TURTLE, ProvFormatType.INPUTOUTPUT);
break;
case XML:
extensionMap.put(ProvFormat.XML, "provx");
extensionRevMap.put("provx", ProvFormat.XML);
extensionRevMap.put("xml", ProvFormat.XML);
mimeTypeMap.put(ProvFormat.XML, "text/xml");
mimeTypeRevMap.put("text/xml", ProvFormat.XML);
provTypeMap.put(ProvFormat.XML, ProvFormatType.INPUTOUTPUT);
break;
default:
break;
}
}
}
public String getExtension(ProvFormat format) {
String extension = UNKNOWN;
if (format != null) {
extension = extensionMap.get(format);
}
return extension;
}
public String convertToMimeType(String type) {
ProvFormat format = extensionRevMap.get(type);
if (format == null)
return null;
return mimeTypeMap.get(format);
}
public void provn2html(String file, String file2)
throws java.io.IOException, JAXBException, Throwable {
Document doc = (Document) u.convertASNToJavaBean(file);
String s = u.convertBeanToHTML(doc);
u.writeTextToFile(s, file2);
}
public static final String RDF_TURTLE = "turtle";
public static final String RDF_XML = "rdf/xml";
public static final String RDF_TRIG = "trig";
public static final String RDF_N3 = "n3";
public RDFFormat convert(String type) {
if (RDF_TURTLE.equals(type))
return RDFFormat.TURTLE;
if (RDF_XML.equals(type))
return RDFFormat.RDFXML;
if (RDF_N3.equals(type))
return RDFFormat.N3;
if (RDF_TRIG.equals(type))
return RDFFormat.TRIG;
return null;
}
/** Reads a file into java bean. */
public Object loadProvGraph(String filename) throws java.io.IOException,
JAXBException, Throwable {
try {
return loadProvKnownGraph(filename);
} catch (Throwable e) {
e.printStackTrace();
return null;
// return loadProvUnknownGraph(filename);
}
}
public enum ProvFormat {
PROVN, XML, TURTLE, RDFXML, TRIG, JSON, DOT, JPEG, SVG, PDF
}
public enum ProvFormatType {
INPUT, OUTPUT, INPUTOUTPUT
}
public Boolean isInputFormat(ProvFormat format) {
ProvFormatType t = provTypeMap.get(format);
return (t.equals(ProvFormatType.INPUT) || t
.equals(ProvFormatType.INPUTOUTPUT));
}
public Boolean isOutputFormat(ProvFormat format) {
ProvFormatType t = provTypeMap.get(format);
return (t.equals(ProvFormatType.OUTPUT) || t
.equals(ProvFormatType.INPUTOUTPUT));
}
public ProvFormat getTypeForFile(String filename) {
int count = filename.lastIndexOf(".");
if (count == -1)
return null;
String extension = filename.substring(count + 1);
return extensionRevMap.get(extension);
}
public void writeDocument(String filename, Document doc) {
try {
ProvFormat format = getTypeForFile(filename);
if (format == null) {
System.err.println("Unknown output file format: " + filename);
return;
}
logger.debug("writing " + format);
logger.debug("writing " + filename);
setNamespaces(doc);
switch (format) {
case PROVN: {
u.writeDocument(doc, filename);
break;
}
case XML: {
ProvSerialiser serial = ProvSerialiser
.getThreadProvSerialiser();
logger.debug("namespaces " + doc.getNss());
serial.serialiseDocument(new File(filename), doc, true);
break;
}
case TURTLE: {
new org.openprovenance.prov.rdf.Utility().dumpRDF(pFactory,
doc, RDFFormat.TURTLE, filename);
break;
}
case RDFXML: {
new org.openprovenance.prov.rdf.Utility().dumpRDF(pFactory,
doc, RDFFormat.RDFXML, filename);
break;
}
case TRIG: {
new org.openprovenance.prov.rdf.Utility().dumpRDF(pFactory,
doc, RDFFormat.TRIG, filename);
break;
}
case JSON: {
new org.openprovenance.prov.json.Converter().writeDocument(doc,
filename);
break;
}
case PDF: {
String configFile = null; // TODO: get it as option
File tmp = File.createTempFile("viz-", ".dot");
String dotFileOut = tmp.getAbsolutePath(); // give it as option,
// if not available
// create tmp file
ProvToDot toDot = (configFile == null) ? new ProvToDot(
ProvToDot.Config.ROLE_NO_LABEL) : new ProvToDot(
configFile);
toDot.convert(doc, dotFileOut, filename,title);
break;
}
case DOT: {
String configFile = null; // TODO: get it as option
ProvToDot toDot = (configFile == null) ? new ProvToDot(
ProvToDot.Config.ROLE_NO_LABEL) : new ProvToDot(
configFile);
toDot.convert(doc, filename,title);
break;
}
case JPEG: {
String configFile = null; // give it as option
File tmp = File.createTempFile("viz-", ".dot");
String dotFileOut = tmp.getAbsolutePath(); // give it as option,
// if not available
// create tmp file
ProvToDot toDot;
if (configFile != null) {
toDot = new ProvToDot(configFile);
} else {
toDot = new ProvToDot(ProvToDot.Config.ROLE_NO_LABEL);
}
- toDot.convert(doc, dotFileOut, filename, "jpg");
+ toDot.convert(doc, dotFileOut, filename, "jpg", title);
tmp.delete();
break;
}
case SVG: {
String configFile = null; // give it as option
File tmp = File.createTempFile("viz-", ".dot");
String dotFileOut = tmp.getAbsolutePath(); // give it as option,
// if not available
// create tmp file
// ProvToDot toDot=new ProvToDot((configFile==null)?
// "../../ProvToolbox/prov-dot/src/main/resources/defaultConfigWithRoleNoLabel.xml"
// : configFile);
ProvToDot toDot;
if (configFile != null) {
toDot = new ProvToDot(configFile);
} else {
toDot = new ProvToDot(ProvToDot.Config.ROLE_NO_LABEL);
}
toDot.convert(doc, dotFileOut, filename, "svg", title);
tmp.delete();
break;
}
default:
break;
}
} catch (JAXBException e) {
if (verbose != null)
e.printStackTrace();
throw new InteropException(e);
} catch (Exception e) {
if (verbose != null)
e.printStackTrace();
throw new InteropException(e);
}
}
public void setNamespaces(Document doc) {
if (doc.getNss() == null)
doc.setNss(new Hashtable<String, String>());
}
public Object loadProvKnownGraph(String filename) {
try {
ProvFormat format = getTypeForFile(filename);
if (format == null) {
throw new InteropException("Unknown output file format: "
+ filename);
}
switch (format) {
case DOT:
case JPEG:
case SVG:
throw new UnsupportedOperationException(); // we don't load PROV
// from these
// formats
case JSON: {
return new org.openprovenance.prov.json.Converter()
.readDocument(filename);
}
case PROVN: {
Utility u = new Utility();
CommonTree tree = u.convertASNToTree(filename);
Object o = u.convertTreeToJavaBean(tree);
return o;
}
case RDFXML:
case TRIG:
case TURTLE: {
org.openprovenance.prov.rdf.Utility rdfU = new org.openprovenance.prov.rdf.Utility();
Document doc = rdfU.parseRDF(filename);
return doc;
}
case XML: {
File in = new File(filename);
ProvDeserialiser deserial = ProvDeserialiser
.getThreadProvDeserialiser();
Document c = deserial.deserialiseDocument(in);
return c;
}
default: {
System.out.println("Unknown format " + filename);
throw new UnsupportedOperationException();
}
}
} catch (IOException e) {
throw new InteropException(e);
} catch (Throwable e) {
e.printStackTrace();
throw new InteropException(e);
}
}
public Object loadProvUnknownGraph(String filename)
throws java.io.IOException, JAXBException, Throwable {
try {
Utility u = new Utility();
CommonTree tree = u.convertASNToTree(filename);
Object o = u.convertTreeToJavaBean(tree);
if (o != null) {
return o;
}
} catch (Throwable t1) {
// OK, we failed, let's try next format.
}
try {
File in = new File(filename);
ProvDeserialiser deserial = ProvDeserialiser
.getThreadProvDeserialiser();
Document c = deserial.deserialiseDocument(in);
if (c != null) {
return c;
}
} catch (Throwable t2) {
// OK, we failed, let's try next format.
}
try {
Object o = new org.openprovenance.prov.json.Converter()
.readDocument(filename);
if (o != null) {
return o;
}
} catch (RuntimeException e) {
// OK, we failed, let's try next format.
}
try {
org.openprovenance.prov.rdf.Utility rdfU = new org.openprovenance.prov.rdf.Utility();
Document doc = rdfU.parseRDF(filename);
if (doc != null) {
return doc;
}
} catch (RuntimeException e) {
// OK, we failed, let's try next format
}
System.out.println("Unparseable format " + filename);
throw new UnsupportedOperationException();
}
/* Support for content negotiation, jax-rs style. Create a list of media type supported by the framework. */
// http://docs.oracle.com/javaee/6/tutorial/doc/gkqbq.html
public List<Variant> getVariants() {
List<Variant> vs = new ArrayList<Variant>();
for (Map.Entry<String, ProvFormat> entry : mimeTypeRevMap
.entrySet()) {
if (isOutputFormat(entry.getValue())) {
String[] parts = entry.getKey().split("/");
MediaType m = new MediaType(parts[0], parts[1]);
vs.add(new Variant(m, (java.util.Locale) null, (String) null));
}
}
return vs;
}
public String buildAcceptHeader() {
StringBuffer mimetypes = new StringBuffer();
Enumeration<ProvFormat> e = mimeTypeMap.keys();
String sep = "";
while (e.hasMoreElements()) {
ProvFormat f = e.nextElement();
if (isInputFormat(f)) {
// careful - cant use .hasMoreElements as we are filtering
mimetypes.append(sep);
sep = ",";
mimetypes.append(mimeTypeMap.get(f));
}
}
mimetypes.append(sep);
mimetypes.append("*/*;q=0.1"); // be liberal
return mimetypes.toString();
}
public URLConnection connectWithRedirect(URL theURL) throws IOException {
URLConnection conn = null;
String accept_header = buildAcceptHeader();
int redirect_count = 0;
boolean done = false;
while (!done) {
if (theURL.getProtocol().equals("file")) {
return null;
}
Boolean isHttp = (theURL.getProtocol().equals("http") || theURL
.getProtocol().equals("https"));
logger.debug("Requesting: " + theURL.toString());
conn = theURL.openConnection();
if (isHttp) {
logger.debug("Accept: " + accept_header);
conn.setRequestProperty("Accept", accept_header);
}
conn.setConnectTimeout(60000);
conn.setReadTimeout(60000);
conn.connect();
done = true; // by default quit after one request
if (isHttp) {
logger.debug("Response: " + conn.getHeaderField(0));
int rc = ((HttpURLConnection) conn).getResponseCode();
if ((rc == HttpURLConnection.HTTP_MOVED_PERM)
|| (rc == HttpURLConnection.HTTP_MOVED_TEMP)
|| (rc == HttpURLConnection.HTTP_SEE_OTHER)
|| (rc == 307)) {
if (redirect_count > 10) {
return null; // Error: too many redirects
}
redirect_count++;
String loc = conn.getHeaderField("Location");
if (loc != null) {
theURL = new URL(loc);
done = false;
} else {
return null; // Bad redirect
}
} else if ((rc < 200) || (rc >= 300)) {
return null; // Unsuccessful
}
}
}
return conn;
}
public void run() {
if (infile == null)
return;
if (outfile == null)
return;
try {
Document doc = (Document) loadProvKnownGraph(infile);
// doc.setNss(new Hashtable<String, String>());
// doc.getNss().put("pc1",PC1_NS);
// doc.getNss().put("prim",PRIM_NS);
// doc.getNss().put("prov","http://www.w3.org/ns/prov#");
// doc.getNss().put("xsd","http://www.w3.org/2001/XMLSchema");
// doc.getNss().put("xsi","http://www.w3.org/2001/XMLSchema-instance");
// System.out.println("InteropFramework run() -> " + doc.getNss());
writeDocument(outfile, doc);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true | true | public void writeDocument(String filename, Document doc) {
try {
ProvFormat format = getTypeForFile(filename);
if (format == null) {
System.err.println("Unknown output file format: " + filename);
return;
}
logger.debug("writing " + format);
logger.debug("writing " + filename);
setNamespaces(doc);
switch (format) {
case PROVN: {
u.writeDocument(doc, filename);
break;
}
case XML: {
ProvSerialiser serial = ProvSerialiser
.getThreadProvSerialiser();
logger.debug("namespaces " + doc.getNss());
serial.serialiseDocument(new File(filename), doc, true);
break;
}
case TURTLE: {
new org.openprovenance.prov.rdf.Utility().dumpRDF(pFactory,
doc, RDFFormat.TURTLE, filename);
break;
}
case RDFXML: {
new org.openprovenance.prov.rdf.Utility().dumpRDF(pFactory,
doc, RDFFormat.RDFXML, filename);
break;
}
case TRIG: {
new org.openprovenance.prov.rdf.Utility().dumpRDF(pFactory,
doc, RDFFormat.TRIG, filename);
break;
}
case JSON: {
new org.openprovenance.prov.json.Converter().writeDocument(doc,
filename);
break;
}
case PDF: {
String configFile = null; // TODO: get it as option
File tmp = File.createTempFile("viz-", ".dot");
String dotFileOut = tmp.getAbsolutePath(); // give it as option,
// if not available
// create tmp file
ProvToDot toDot = (configFile == null) ? new ProvToDot(
ProvToDot.Config.ROLE_NO_LABEL) : new ProvToDot(
configFile);
toDot.convert(doc, dotFileOut, filename,title);
break;
}
case DOT: {
String configFile = null; // TODO: get it as option
ProvToDot toDot = (configFile == null) ? new ProvToDot(
ProvToDot.Config.ROLE_NO_LABEL) : new ProvToDot(
configFile);
toDot.convert(doc, filename,title);
break;
}
case JPEG: {
String configFile = null; // give it as option
File tmp = File.createTempFile("viz-", ".dot");
String dotFileOut = tmp.getAbsolutePath(); // give it as option,
// if not available
// create tmp file
ProvToDot toDot;
if (configFile != null) {
toDot = new ProvToDot(configFile);
} else {
toDot = new ProvToDot(ProvToDot.Config.ROLE_NO_LABEL);
}
toDot.convert(doc, dotFileOut, filename, "jpg");
tmp.delete();
break;
}
case SVG: {
String configFile = null; // give it as option
File tmp = File.createTempFile("viz-", ".dot");
String dotFileOut = tmp.getAbsolutePath(); // give it as option,
// if not available
// create tmp file
// ProvToDot toDot=new ProvToDot((configFile==null)?
// "../../ProvToolbox/prov-dot/src/main/resources/defaultConfigWithRoleNoLabel.xml"
// : configFile);
ProvToDot toDot;
if (configFile != null) {
toDot = new ProvToDot(configFile);
} else {
toDot = new ProvToDot(ProvToDot.Config.ROLE_NO_LABEL);
}
toDot.convert(doc, dotFileOut, filename, "svg", title);
tmp.delete();
break;
}
default:
break;
}
} catch (JAXBException e) {
if (verbose != null)
e.printStackTrace();
throw new InteropException(e);
} catch (Exception e) {
if (verbose != null)
e.printStackTrace();
throw new InteropException(e);
}
}
| public void writeDocument(String filename, Document doc) {
try {
ProvFormat format = getTypeForFile(filename);
if (format == null) {
System.err.println("Unknown output file format: " + filename);
return;
}
logger.debug("writing " + format);
logger.debug("writing " + filename);
setNamespaces(doc);
switch (format) {
case PROVN: {
u.writeDocument(doc, filename);
break;
}
case XML: {
ProvSerialiser serial = ProvSerialiser
.getThreadProvSerialiser();
logger.debug("namespaces " + doc.getNss());
serial.serialiseDocument(new File(filename), doc, true);
break;
}
case TURTLE: {
new org.openprovenance.prov.rdf.Utility().dumpRDF(pFactory,
doc, RDFFormat.TURTLE, filename);
break;
}
case RDFXML: {
new org.openprovenance.prov.rdf.Utility().dumpRDF(pFactory,
doc, RDFFormat.RDFXML, filename);
break;
}
case TRIG: {
new org.openprovenance.prov.rdf.Utility().dumpRDF(pFactory,
doc, RDFFormat.TRIG, filename);
break;
}
case JSON: {
new org.openprovenance.prov.json.Converter().writeDocument(doc,
filename);
break;
}
case PDF: {
String configFile = null; // TODO: get it as option
File tmp = File.createTempFile("viz-", ".dot");
String dotFileOut = tmp.getAbsolutePath(); // give it as option,
// if not available
// create tmp file
ProvToDot toDot = (configFile == null) ? new ProvToDot(
ProvToDot.Config.ROLE_NO_LABEL) : new ProvToDot(
configFile);
toDot.convert(doc, dotFileOut, filename,title);
break;
}
case DOT: {
String configFile = null; // TODO: get it as option
ProvToDot toDot = (configFile == null) ? new ProvToDot(
ProvToDot.Config.ROLE_NO_LABEL) : new ProvToDot(
configFile);
toDot.convert(doc, filename,title);
break;
}
case JPEG: {
String configFile = null; // give it as option
File tmp = File.createTempFile("viz-", ".dot");
String dotFileOut = tmp.getAbsolutePath(); // give it as option,
// if not available
// create tmp file
ProvToDot toDot;
if (configFile != null) {
toDot = new ProvToDot(configFile);
} else {
toDot = new ProvToDot(ProvToDot.Config.ROLE_NO_LABEL);
}
toDot.convert(doc, dotFileOut, filename, "jpg", title);
tmp.delete();
break;
}
case SVG: {
String configFile = null; // give it as option
File tmp = File.createTempFile("viz-", ".dot");
String dotFileOut = tmp.getAbsolutePath(); // give it as option,
// if not available
// create tmp file
// ProvToDot toDot=new ProvToDot((configFile==null)?
// "../../ProvToolbox/prov-dot/src/main/resources/defaultConfigWithRoleNoLabel.xml"
// : configFile);
ProvToDot toDot;
if (configFile != null) {
toDot = new ProvToDot(configFile);
} else {
toDot = new ProvToDot(ProvToDot.Config.ROLE_NO_LABEL);
}
toDot.convert(doc, dotFileOut, filename, "svg", title);
tmp.delete();
break;
}
default:
break;
}
} catch (JAXBException e) {
if (verbose != null)
e.printStackTrace();
throw new InteropException(e);
} catch (Exception e) {
if (verbose != null)
e.printStackTrace();
throw new InteropException(e);
}
}
|
diff --git a/src/web/org/codehaus/groovy/grails/web/metaclass/ControllerDynamicMethods.java b/src/web/org/codehaus/groovy/grails/web/metaclass/ControllerDynamicMethods.java
index e6f9b1530..0f8842e9f 100644
--- a/src/web/org/codehaus/groovy/grails/web/metaclass/ControllerDynamicMethods.java
+++ b/src/web/org/codehaus/groovy/grails/web/metaclass/ControllerDynamicMethods.java
@@ -1,107 +1,107 @@
/*
* Copyright 2004-2005 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.codehaus.groovy.grails.web.metaclass;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MissingPropertyException;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.metaclass.AbstractDynamicMethodInvocation;
import org.codehaus.groovy.grails.commons.metaclass.GenericDynamicProperty;
import org.codehaus.groovy.grails.commons.metaclass.GroovyDynamicMethodsInterceptor;
import org.codehaus.groovy.grails.scaffolding.GrailsScaffolder;
import org.codehaus.groovy.grails.web.servlet.GrailsHttpServletRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
/**
* Adds dynamic methods and properties for Grails Controllers
*
* @author Graeme Rocher
* @since Oct 24, 2005
*/
public class ControllerDynamicMethods extends
GroovyDynamicMethodsInterceptor {
public static final String REQUEST_PROPERTY = "request";
public static final String RESPONSE_PROPERTY = "response";
public static final String ERRORS_PROPERTY = "errors";
public static final String HAS_ERRORS_METHOD = "hasErrors";
public static final String MODEL_AND_VIEW_PROPERTY = "modelAndView";
protected GrailsControllerClass controllerClass;
protected GrailsScaffolder scaffolder;
private boolean scaffolding;
public ControllerDynamicMethods( GroovyObject controller,GrailsControllerHelper helper,HttpServletRequest request, HttpServletResponse response) throws IntrospectionException {
super(controller);
this.controllerClass = helper.getControllerClassByName(controller.getClass().getName());
// add dynamic properties
addDynamicProperty(new GetParamsDynamicProperty(request,response));
addDynamicProperty(new GetSessionDynamicProperty(request,response));
addDynamicProperty(new GenericDynamicProperty(REQUEST_PROPERTY, HttpServletRequest.class,new GrailsHttpServletRequest( request,controller),true) );
addDynamicProperty(new GenericDynamicProperty(RESPONSE_PROPERTY, HttpServletResponse.class,response,true) );
addDynamicProperty(new GenericDynamicProperty(ERRORS_PROPERTY, Errors.class, null, false));
- addDynamicProperty(new GenericDynamicProperty(MODEL_AND_VIEW, ModelAndView.class,null,false));
+ addDynamicProperty(new GenericDynamicProperty(MODEL_AND_VIEW_PROPERTY, ModelAndView.class,null,false));
// add dynamic methods
addDynamicMethodInvocation( new RedirectDynamicMethod(helper,request,response) );
addDynamicMethodInvocation( new ChainDynamicMethod(helper, request, response ) );
addDynamicMethodInvocation( new RenderDynamicMethod(helper,request,response));
addDynamicMethodInvocation( new RicoDynamicMethod(request,response));
addDynamicMethodInvocation( new BindDynamicMethod(request,response));
// the hasErrors() dynamic method that checks of there are any errors in the controller
addDynamicMethodInvocation( new AbstractDynamicMethodInvocation(HAS_ERRORS_METHOD) {
public Object invoke(Object target, Object[] arguments) {
GroovyObject controller = (GroovyObject)target;
Errors errors = (Errors)controller.getProperty(ERRORS_PROPERTY);
return new Boolean(errors.hasErrors());
}
});
this.scaffolding = this.controllerClass.isScaffolding();
// if the controller is scaffolding get the scaffolder, then loop through all the
// support actions by the scaffolder and register dynamic properties for those that don't exist
if(this.scaffolding) {
this.scaffolder = helper.getScaffolderForController(controllerClass.getFullName());
if(this.scaffolder == null) {
throw new IllegalStateException("Scaffolder is null when controller scaffold property is set to 'true'");
}
String[] scaffoldActions = this.scaffolder.getSupportedActionNames();
for (int i = 0; i < scaffoldActions.length; i++) {
try {
controller.getProperty(scaffoldActions[i]);
}
catch(MissingPropertyException mpe) {
addDynamicProperty(new GenericDynamicProperty( scaffoldActions[i],
Closure.class,
scaffolder.getAction(controller,scaffoldActions[i]),
true));
}
}
}
}
}
| true | true | public ControllerDynamicMethods( GroovyObject controller,GrailsControllerHelper helper,HttpServletRequest request, HttpServletResponse response) throws IntrospectionException {
super(controller);
this.controllerClass = helper.getControllerClassByName(controller.getClass().getName());
// add dynamic properties
addDynamicProperty(new GetParamsDynamicProperty(request,response));
addDynamicProperty(new GetSessionDynamicProperty(request,response));
addDynamicProperty(new GenericDynamicProperty(REQUEST_PROPERTY, HttpServletRequest.class,new GrailsHttpServletRequest( request,controller),true) );
addDynamicProperty(new GenericDynamicProperty(RESPONSE_PROPERTY, HttpServletResponse.class,response,true) );
addDynamicProperty(new GenericDynamicProperty(ERRORS_PROPERTY, Errors.class, null, false));
addDynamicProperty(new GenericDynamicProperty(MODEL_AND_VIEW, ModelAndView.class,null,false));
// add dynamic methods
addDynamicMethodInvocation( new RedirectDynamicMethod(helper,request,response) );
addDynamicMethodInvocation( new ChainDynamicMethod(helper, request, response ) );
addDynamicMethodInvocation( new RenderDynamicMethod(helper,request,response));
addDynamicMethodInvocation( new RicoDynamicMethod(request,response));
addDynamicMethodInvocation( new BindDynamicMethod(request,response));
// the hasErrors() dynamic method that checks of there are any errors in the controller
addDynamicMethodInvocation( new AbstractDynamicMethodInvocation(HAS_ERRORS_METHOD) {
public Object invoke(Object target, Object[] arguments) {
GroovyObject controller = (GroovyObject)target;
Errors errors = (Errors)controller.getProperty(ERRORS_PROPERTY);
return new Boolean(errors.hasErrors());
}
});
this.scaffolding = this.controllerClass.isScaffolding();
// if the controller is scaffolding get the scaffolder, then loop through all the
// support actions by the scaffolder and register dynamic properties for those that don't exist
if(this.scaffolding) {
this.scaffolder = helper.getScaffolderForController(controllerClass.getFullName());
if(this.scaffolder == null) {
throw new IllegalStateException("Scaffolder is null when controller scaffold property is set to 'true'");
}
String[] scaffoldActions = this.scaffolder.getSupportedActionNames();
for (int i = 0; i < scaffoldActions.length; i++) {
try {
controller.getProperty(scaffoldActions[i]);
}
catch(MissingPropertyException mpe) {
addDynamicProperty(new GenericDynamicProperty( scaffoldActions[i],
Closure.class,
scaffolder.getAction(controller,scaffoldActions[i]),
true));
}
}
}
}
| public ControllerDynamicMethods( GroovyObject controller,GrailsControllerHelper helper,HttpServletRequest request, HttpServletResponse response) throws IntrospectionException {
super(controller);
this.controllerClass = helper.getControllerClassByName(controller.getClass().getName());
// add dynamic properties
addDynamicProperty(new GetParamsDynamicProperty(request,response));
addDynamicProperty(new GetSessionDynamicProperty(request,response));
addDynamicProperty(new GenericDynamicProperty(REQUEST_PROPERTY, HttpServletRequest.class,new GrailsHttpServletRequest( request,controller),true) );
addDynamicProperty(new GenericDynamicProperty(RESPONSE_PROPERTY, HttpServletResponse.class,response,true) );
addDynamicProperty(new GenericDynamicProperty(ERRORS_PROPERTY, Errors.class, null, false));
addDynamicProperty(new GenericDynamicProperty(MODEL_AND_VIEW_PROPERTY, ModelAndView.class,null,false));
// add dynamic methods
addDynamicMethodInvocation( new RedirectDynamicMethod(helper,request,response) );
addDynamicMethodInvocation( new ChainDynamicMethod(helper, request, response ) );
addDynamicMethodInvocation( new RenderDynamicMethod(helper,request,response));
addDynamicMethodInvocation( new RicoDynamicMethod(request,response));
addDynamicMethodInvocation( new BindDynamicMethod(request,response));
// the hasErrors() dynamic method that checks of there are any errors in the controller
addDynamicMethodInvocation( new AbstractDynamicMethodInvocation(HAS_ERRORS_METHOD) {
public Object invoke(Object target, Object[] arguments) {
GroovyObject controller = (GroovyObject)target;
Errors errors = (Errors)controller.getProperty(ERRORS_PROPERTY);
return new Boolean(errors.hasErrors());
}
});
this.scaffolding = this.controllerClass.isScaffolding();
// if the controller is scaffolding get the scaffolder, then loop through all the
// support actions by the scaffolder and register dynamic properties for those that don't exist
if(this.scaffolding) {
this.scaffolder = helper.getScaffolderForController(controllerClass.getFullName());
if(this.scaffolder == null) {
throw new IllegalStateException("Scaffolder is null when controller scaffold property is set to 'true'");
}
String[] scaffoldActions = this.scaffolder.getSupportedActionNames();
for (int i = 0; i < scaffoldActions.length; i++) {
try {
controller.getProperty(scaffoldActions[i]);
}
catch(MissingPropertyException mpe) {
addDynamicProperty(new GenericDynamicProperty( scaffoldActions[i],
Closure.class,
scaffolder.getAction(controller,scaffoldActions[i]),
true));
}
}
}
}
|
diff --git a/src/da/alg1000/oblig3/DAALG1000Oblig3.java b/src/da/alg1000/oblig3/DAALG1000Oblig3.java
index f0e3e07..08219b4 100644
--- a/src/da/alg1000/oblig3/DAALG1000Oblig3.java
+++ b/src/da/alg1000/oblig3/DAALG1000Oblig3.java
@@ -1,60 +1,64 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package da.alg1000.oblig3;
import java.util.AbstractMap;
import java.util.Scanner;
/**
*
* @author Martin
*/
public class DAALG1000Oblig3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("Number-of-buckets> ");
hashTable<String, String> ht = new hashTable<>(Integer.parseInt(inp.nextLine()));
String key;
while (true) {
System.out.println();
System.out.println("0: Quit");
System.out.println("1: Store");
System.out.println("2: Retrieve");
System.out.println("3: Print table");
System.out.println("LF=" + ht.calculateLoadFactor());
System.out.println();
System.out.print("COMMAND> ");
- System.out.println();
switch (Integer.parseInt(inp.nextLine())) {
case 0:
+ exitManager eM=new exitManager(1);
return;
case 1:
System.out.print("Key> ");
key = inp.nextLine();
System.out.print("Value> ");
String value = inp.nextLine();
- ht.add(key, value);
+ if (!ht.contains(key)) {
+ ht.add(key, value);
+ } else {
+ ht.set(key, value);
+ }
break;
case 2:
System.out.print("Key> ");
key = inp.nextLine();
System.out.println(ht.get(key));
break;
case 3:
for (Object o : ht.toArray()) {
- System.out.println("\"" + ((AbstractMap.SimpleEntry<String,String>)o).getKey() + "\":\"" + ((AbstractMap.SimpleEntry<String,String>)o).getValue() + "\"");
+ System.out.println("\"" + ((AbstractMap.SimpleEntry<String, String>) o).getKey() + "\":\"" + ((AbstractMap.SimpleEntry<String, String>) o).getValue() + "\"");
}
break;
}
}
}
}
| false | true | public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("Number-of-buckets> ");
hashTable<String, String> ht = new hashTable<>(Integer.parseInt(inp.nextLine()));
String key;
while (true) {
System.out.println();
System.out.println("0: Quit");
System.out.println("1: Store");
System.out.println("2: Retrieve");
System.out.println("3: Print table");
System.out.println("LF=" + ht.calculateLoadFactor());
System.out.println();
System.out.print("COMMAND> ");
System.out.println();
switch (Integer.parseInt(inp.nextLine())) {
case 0:
return;
case 1:
System.out.print("Key> ");
key = inp.nextLine();
System.out.print("Value> ");
String value = inp.nextLine();
ht.add(key, value);
break;
case 2:
System.out.print("Key> ");
key = inp.nextLine();
System.out.println(ht.get(key));
break;
case 3:
for (Object o : ht.toArray()) {
System.out.println("\"" + ((AbstractMap.SimpleEntry<String,String>)o).getKey() + "\":\"" + ((AbstractMap.SimpleEntry<String,String>)o).getValue() + "\"");
}
break;
}
}
}
| public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("Number-of-buckets> ");
hashTable<String, String> ht = new hashTable<>(Integer.parseInt(inp.nextLine()));
String key;
while (true) {
System.out.println();
System.out.println("0: Quit");
System.out.println("1: Store");
System.out.println("2: Retrieve");
System.out.println("3: Print table");
System.out.println("LF=" + ht.calculateLoadFactor());
System.out.println();
System.out.print("COMMAND> ");
switch (Integer.parseInt(inp.nextLine())) {
case 0:
exitManager eM=new exitManager(1);
return;
case 1:
System.out.print("Key> ");
key = inp.nextLine();
System.out.print("Value> ");
String value = inp.nextLine();
if (!ht.contains(key)) {
ht.add(key, value);
} else {
ht.set(key, value);
}
break;
case 2:
System.out.print("Key> ");
key = inp.nextLine();
System.out.println(ht.get(key));
break;
case 3:
for (Object o : ht.toArray()) {
System.out.println("\"" + ((AbstractMap.SimpleEntry<String, String>) o).getKey() + "\":\"" + ((AbstractMap.SimpleEntry<String, String>) o).getValue() + "\"");
}
break;
}
}
}
|
diff --git a/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/impl/FileServiceImpl.java b/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/impl/FileServiceImpl.java
index 7535d4572..5b6035b98 100644
--- a/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/impl/FileServiceImpl.java
+++ b/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/impl/FileServiceImpl.java
@@ -1,257 +1,257 @@
package org.onebusaway.nyc.admin.service.impl;
import org.onebusaway.nyc.admin.service.FileService;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.annotation.PostConstruct;
/**
* Implements File operations over Amazon S3.
*
*/
public class FileServiceImpl implements FileService {
private static Logger _log = LoggerFactory.getLogger(FileServiceImpl.class);
private AWSCredentials _credentials;
private AmazonS3Client _s3;
@Autowired
private String _bucketName;
@Autowired
// the gtfs directory relative to the bundle directory; e.g. gtfs_latest
private String _gtfsPath;
@Autowired
// the stif directory relative to the bundle directory; e.g. stif_latest
private String _stifPath;
@Autowired
private String _buildPath;
@Override
public void setBucketName(String bucketName) {
this._bucketName = bucketName;
}
@Override
public void setGtfsPath(String gtfsPath) {
this._gtfsPath = gtfsPath;
}
@Override
public String getGtfsPath() {
return _gtfsPath;
}
@Override
public void setStifPath(String stifPath) {
this._stifPath = stifPath;
}
@Override
public String getStifPath() {
return _stifPath;
}
@Override
public void setBuildPath(String buildPath) {
this._buildPath = buildPath;
}
@Override
public String getBuildPath() {
return _buildPath;
}
@PostConstruct
@Override
public void setup() {
try {
_credentials = new PropertiesCredentials(
this.getClass().getResourceAsStream("AwsCredentials.properties"));
_s3 = new AmazonS3Client(_credentials);
} catch (IOException ioe) {
_log.error(ioe.toString());
throw new RuntimeException(ioe);
}
}
@Override
/**
* check to see if the given bundle directory exists in the configured bucket.
* Do not include leading slashes in the filename(key).
*/
public boolean bundleDirectoryExists(String filename) {
ListObjectsRequest request = new ListObjectsRequest(_bucketName, filename,
null, null, 1);
ObjectListing listing = _s3.listObjects(request);
return listing.getObjectSummaries().size() > 0;
}
@Override
public boolean createBundleDirectory(String filename) {
try {
/*
* a file needs to be written for a directory to exist create README file,
* which could optionally contain meta-data such as creator, production
* mode, etc.
*/
File tmpFile = File.createTempFile("README", "txt");
String contents = "Root of Bundle Build";
FileWriter fw = new FileWriter(tmpFile);
fw.append(contents);
fw.close();
PutObjectRequest request = new PutObjectRequest(_bucketName, filename
+ "/README.txt", tmpFile);
PutObjectResult result = _s3.putObject(request);
// now create tree structure
- // request = new PutObjectRequest(_bucketName, filename + "/" +
- // this.getGtfsPath(), null);
- // result = _s3.putObject(request);
- // request = new PutObjectRequest(_bucketName, filename + "/" +
- // this.getStifPath(), null);
- // result = _s3.putObject(request);
- // request = new PutObjectRequest(_bucketName, filename + "/" +
- // this.getBuildPath(), null);
- // result = _s3.putObject(request);
+ request = new PutObjectRequest(_bucketName, filename + "/" +
+ this.getGtfsPath() + "/README.txt", tmpFile);
+ result = _s3.putObject(request);
+ request = new PutObjectRequest(_bucketName, filename + "/" +
+ this.getStifPath() + "/README.txt", tmpFile);
+ result = _s3.putObject(request);
+ request = new PutObjectRequest(_bucketName, filename + "/" +
+ this.getBuildPath() + "/README.txt", tmpFile);
+ result = _s3.putObject(request);
return result != null;
} catch (Exception e) {
_log.error(e.toString(), e);
throw new RuntimeException(e);
}
}
@Override
/**
* Return tabular data (filename, flag, modified date) about bundle directories.
*/
public List<String[]> listBundleDirectories(int maxResults) {
List<String[]> rows = new ArrayList<String[]>();
HashMap<String, String> map = new HashMap<String, String>();
ListObjectsRequest request = new ListObjectsRequest(_bucketName, null, "/",
"", maxResults);
ObjectListing listing = null;
do {
if (listing == null) {
listing = _s3.listObjects(request);
} else {
listing = _s3.listNextBatchOfObjects(listing);
}
for (S3ObjectSummary summary : listing.getObjectSummaries()) {
String key = parseKey(summary.getKey());
if (!map.containsKey(key)) {
String[] columns = {
key, " ", "" + summary.getLastModified().getTime()};
rows.add(columns);
map.put(key, key);
}
}
} while (listing.isTruncated());
return rows;
}
@Override
/**
* Retrieve the specified key from S3 and store in the given directory.
*/
public String get(String key, String tmpDir) {
FileUtils fs = new FileUtils();
String filename = fs.parseFileName(key);
_log.info("downloading " + key);
GetObjectRequest request = new GetObjectRequest(this._bucketName, key);
S3Object file = _s3.getObject(request);
String pathAndFileName = tmpDir + File.separator + filename;
fs.copy(file.getObjectContent(), pathAndFileName);
return pathAndFileName;
}
@Override
/**
* push the contents of the directory to S3 at the given key location.
*/
public String put(String key, String file) {
if (new File(file).isDirectory()) {
File dir = new File(file);
for (File contents : dir.listFiles()) {
try {
put(key, contents.getName(), contents.getCanonicalPath());
} catch (IOException ioe) {
_log.error(ioe.toString(), ioe);
}
}
return null;
}
PutObjectRequest request = new PutObjectRequest(this._bucketName, key,
new File(file));
PutObjectResult result = _s3.putObject(request);
return result.getVersionId();
}
public String put(String prefix, String key, String file) {
if (new File(file).isDirectory()) {
File dir = new File(file);
for (File contents : dir.listFiles()) {
try {
put(prefix + "/" + key, contents.getName(),
contents.getCanonicalPath());
} catch (IOException ioe) {
_log.error(ioe.toString(), ioe);
}
}
return null;
}
String filename = prefix + "/" + key;
_log.info("uploading " + file + " to " + filename);
PutObjectRequest request = new PutObjectRequest(this._bucketName, filename,
new File(file));
PutObjectResult result = _s3.putObject(request);
return result.getVersionId();
}
@Override
/**
* list the files in the given directory.
*/
public List<String> list(String directory, int maxResults) {
ListObjectsRequest request = new ListObjectsRequest(_bucketName, directory,
null, null, maxResults);
ObjectListing listing = _s3.listObjects(request);
List<String> rows = new ArrayList<String>();
for (S3ObjectSummary summary : listing.getObjectSummaries()) {
// if its a directory at the root level
if (!summary.getKey().endsWith("/")) {
rows.add(summary.getKey());
}
}
return rows;
}
private String parseKey(String key) {
if (key == null) return null;
int pos = key.indexOf("/");
if (pos == -1) return key;
return key.substring(0, pos);
}
}
| true | true | public boolean createBundleDirectory(String filename) {
try {
/*
* a file needs to be written for a directory to exist create README file,
* which could optionally contain meta-data such as creator, production
* mode, etc.
*/
File tmpFile = File.createTempFile("README", "txt");
String contents = "Root of Bundle Build";
FileWriter fw = new FileWriter(tmpFile);
fw.append(contents);
fw.close();
PutObjectRequest request = new PutObjectRequest(_bucketName, filename
+ "/README.txt", tmpFile);
PutObjectResult result = _s3.putObject(request);
// now create tree structure
// request = new PutObjectRequest(_bucketName, filename + "/" +
// this.getGtfsPath(), null);
// result = _s3.putObject(request);
// request = new PutObjectRequest(_bucketName, filename + "/" +
// this.getStifPath(), null);
// result = _s3.putObject(request);
// request = new PutObjectRequest(_bucketName, filename + "/" +
// this.getBuildPath(), null);
// result = _s3.putObject(request);
return result != null;
} catch (Exception e) {
_log.error(e.toString(), e);
throw new RuntimeException(e);
}
}
| public boolean createBundleDirectory(String filename) {
try {
/*
* a file needs to be written for a directory to exist create README file,
* which could optionally contain meta-data such as creator, production
* mode, etc.
*/
File tmpFile = File.createTempFile("README", "txt");
String contents = "Root of Bundle Build";
FileWriter fw = new FileWriter(tmpFile);
fw.append(contents);
fw.close();
PutObjectRequest request = new PutObjectRequest(_bucketName, filename
+ "/README.txt", tmpFile);
PutObjectResult result = _s3.putObject(request);
// now create tree structure
request = new PutObjectRequest(_bucketName, filename + "/" +
this.getGtfsPath() + "/README.txt", tmpFile);
result = _s3.putObject(request);
request = new PutObjectRequest(_bucketName, filename + "/" +
this.getStifPath() + "/README.txt", tmpFile);
result = _s3.putObject(request);
request = new PutObjectRequest(_bucketName, filename + "/" +
this.getBuildPath() + "/README.txt", tmpFile);
result = _s3.putObject(request);
return result != null;
} catch (Exception e) {
_log.error(e.toString(), e);
throw new RuntimeException(e);
}
}
|
diff --git a/src/TestPackaging/TestScript.java b/src/TestPackaging/TestScript.java
index cedb6cd..ae6f507 100644
--- a/src/TestPackaging/TestScript.java
+++ b/src/TestPackaging/TestScript.java
@@ -1,136 +1,136 @@
package TestPackaging;
import TestPackaging.Conversions.PaintUtils.PaintUtils;
import org.powerbot.event.PaintListener;
import org.powerbot.script.AbstractScript;
import org.powerbot.script.Manifest;
import org.powerbot.script.methods.Environment;
import org.powerbot.script.methods.Game;
import org.powerbot.script.wrappers.*;
import org.powerbot.script.wrappers.Component;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
@Manifest(authors = { "Inf3cti0us -bro433-" }, name = "Name Sensor", description = "Sensors Your accounts name!", version = 0.2, topic = 2)
public class TestScript extends AbstractScript implements PaintListener {
//Old -> WidgetChild wUsername = new Widget(137).getChild(53);
final Component wUsername = ctx.widgets.get(137, 53);
/** Meh
WidgetChild slot1KeyBind = new Widget(640).getChild(70);
WidgetChild slot2KeyBind = new Widget(640).getChild(75);
WidgetChild slot3KeyBind = new Widget(640).getChild(80);
WidgetChild slot4KeyBind = new Widget(640).getChild(85);
WidgetChild slot5KeyBind = new Widget(640).getChild(90);
WidgetChild slot6KeyBind = new Widget(640).getChild(95);
WidgetChild slot7KeyBind = new Widget(640).getChild(100);
WidgetChild slot8KeyBind = new Widget(640).getChild(105);
WidgetChild slot9KeyBind = new Widget(640).getChild(110);
WidgetChild slot10KeyBind = new Widget(640).getChild(115);
WidgetChild slot11KeyBind = new Widget(640).getChild(120);
WidgetChild slot12KeyBind = new Widget(640).getChild(125);
*/
public BufferedImage sensoredUsername;
public BufferedImage dataBuffer;
boolean isSmeared = false;
Rectangle noUsername = new Rectangle(548, 424, 189, 31);
@Override
public void run() {
if(ctx.game.isLoggedIn()){ //Game.isLoggedIn()){
if(!isSmeared && wUsername.isVisible()){
createBlurredImage(5);
isSmeared = true;
}
while(isSmeared){
- sleep((int) 100L);
+ sleep((int) 100L); //TODO Find out what replaces this..
}
}
//return 43; //Best Number In the world..
}
public BufferedImage gfxToImage() {
Canvas meh = ctx.getClient().getCanvas();
int w = meh.getWidth();
int h = meh.getHeight();
BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
meh.paint(g2);
g2.dispose();
return image;
}
/**
*
* @param blurFactor How much blur is added to
*/
public void createBlurredImage(int blurFactor) {
//Capture Username
sensoredUsername = gfxToImage().getSubimage(
wUsername.getAbsoluteLocation().x,
wUsername.getAbsoluteLocation().y,
wUsername.getWidth()-15,
wUsername.getHeight());
/*
sensoredUsername = Environment.captureScreen().getSubimage(wUsername.getAbsoluteX(), wUsername.getAbsoluteY(),
wUsername.getWidth()-15, wUsername.getHeight());
*/
//
dataBuffer = new BufferedImage(sensoredUsername.getWidth(null),
sensoredUsername.getHeight(null),
BufferedImage.TYPE_INT_BGR);
//Getting the graphics
Graphics g = dataBuffer.getGraphics();
//Drawing the sensoredUsername to 500x300
g.drawImage(sensoredUsername, 500, 300, null); // g.drawImage(mshi, 455, 255, null);hh
//Declare the blurKernel
float[] blurKernel = {
1 / 9f, 1 / 9f, 1 / 9f,
1 / 9f, 1 / 9f, 1 / 9f,
1 / 9f, 1 / 9f, 1 / 9f
};
//Initialize the blur
BufferedImageOp blur = new ConvolveOp(new Kernel(3, 3, blurKernel)); //new Kernel 3,3,blurKernel
//Blur the username blurFactor times (lol)
for(int i=0; i < blurFactor; i++){
sensoredUsername = blur.filter(sensoredUsername, new BufferedImage(sensoredUsername.getWidth()-1,
sensoredUsername.getHeight()-1, sensoredUsername.getType()));
}
//Dispose of the graphics.. We are done blurring!
g.dispose();
}
@Override
public void repaint(Graphics graphics) {
Graphics2D g = (Graphics2D)graphics;
Font meh = g.getFont();
- if(Game.isLoggedIn() && wUsername!=null && wUsername.isOnScreen() && wUsername.visible()){
- g.drawImage(sensoredUsername, wUsername.getAbsoluteX()-2, wUsername.getAbsoluteY()+1,
+ if(ctx.game.isLoggedIn() && wUsername!=null && wUsername.isOnScreen() && wUsername.isVisible()){
+ g.drawImage(sensoredUsername, wUsername.getAbsoluteLocation().x-2, wUsername.getAbsoluteLocation().y+1,
wUsername.getWidth()-16, wUsername.getHeight()-4,null);
} else{
PaintUtils.drawStringCentered("No username to block!", meh, noUsername, Color.WHITE, g);
PaintUtils.drawGrid(g, 550, 257, 45, 20, 4, 12); //TODO Work on drawing a grid..
}
}
}
| false | true | public void run() {
if(ctx.game.isLoggedIn()){ //Game.isLoggedIn()){
if(!isSmeared && wUsername.isVisible()){
createBlurredImage(5);
isSmeared = true;
}
while(isSmeared){
sleep((int) 100L);
}
}
//return 43; //Best Number In the world..
}
public BufferedImage gfxToImage() {
Canvas meh = ctx.getClient().getCanvas();
int w = meh.getWidth();
int h = meh.getHeight();
BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
meh.paint(g2);
g2.dispose();
return image;
}
/**
*
* @param blurFactor How much blur is added to
*/
public void createBlurredImage(int blurFactor) {
//Capture Username
sensoredUsername = gfxToImage().getSubimage(
wUsername.getAbsoluteLocation().x,
wUsername.getAbsoluteLocation().y,
wUsername.getWidth()-15,
wUsername.getHeight());
/*
sensoredUsername = Environment.captureScreen().getSubimage(wUsername.getAbsoluteX(), wUsername.getAbsoluteY(),
wUsername.getWidth()-15, wUsername.getHeight());
*/
//
dataBuffer = new BufferedImage(sensoredUsername.getWidth(null),
sensoredUsername.getHeight(null),
BufferedImage.TYPE_INT_BGR);
//Getting the graphics
Graphics g = dataBuffer.getGraphics();
//Drawing the sensoredUsername to 500x300
g.drawImage(sensoredUsername, 500, 300, null); // g.drawImage(mshi, 455, 255, null);hh
//Declare the blurKernel
float[] blurKernel = {
1 / 9f, 1 / 9f, 1 / 9f,
1 / 9f, 1 / 9f, 1 / 9f,
1 / 9f, 1 / 9f, 1 / 9f
};
//Initialize the blur
BufferedImageOp blur = new ConvolveOp(new Kernel(3, 3, blurKernel)); //new Kernel 3,3,blurKernel
//Blur the username blurFactor times (lol)
for(int i=0; i < blurFactor; i++){
sensoredUsername = blur.filter(sensoredUsername, new BufferedImage(sensoredUsername.getWidth()-1,
sensoredUsername.getHeight()-1, sensoredUsername.getType()));
}
//Dispose of the graphics.. We are done blurring!
g.dispose();
}
@Override
public void repaint(Graphics graphics) {
Graphics2D g = (Graphics2D)graphics;
Font meh = g.getFont();
if(Game.isLoggedIn() && wUsername!=null && wUsername.isOnScreen() && wUsername.visible()){
g.drawImage(sensoredUsername, wUsername.getAbsoluteX()-2, wUsername.getAbsoluteY()+1,
wUsername.getWidth()-16, wUsername.getHeight()-4,null);
} else{
PaintUtils.drawStringCentered("No username to block!", meh, noUsername, Color.WHITE, g);
PaintUtils.drawGrid(g, 550, 257, 45, 20, 4, 12); //TODO Work on drawing a grid..
}
}
}
| public void run() {
if(ctx.game.isLoggedIn()){ //Game.isLoggedIn()){
if(!isSmeared && wUsername.isVisible()){
createBlurredImage(5);
isSmeared = true;
}
while(isSmeared){
sleep((int) 100L); //TODO Find out what replaces this..
}
}
//return 43; //Best Number In the world..
}
public BufferedImage gfxToImage() {
Canvas meh = ctx.getClient().getCanvas();
int w = meh.getWidth();
int h = meh.getHeight();
BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
meh.paint(g2);
g2.dispose();
return image;
}
/**
*
* @param blurFactor How much blur is added to
*/
public void createBlurredImage(int blurFactor) {
//Capture Username
sensoredUsername = gfxToImage().getSubimage(
wUsername.getAbsoluteLocation().x,
wUsername.getAbsoluteLocation().y,
wUsername.getWidth()-15,
wUsername.getHeight());
/*
sensoredUsername = Environment.captureScreen().getSubimage(wUsername.getAbsoluteX(), wUsername.getAbsoluteY(),
wUsername.getWidth()-15, wUsername.getHeight());
*/
//
dataBuffer = new BufferedImage(sensoredUsername.getWidth(null),
sensoredUsername.getHeight(null),
BufferedImage.TYPE_INT_BGR);
//Getting the graphics
Graphics g = dataBuffer.getGraphics();
//Drawing the sensoredUsername to 500x300
g.drawImage(sensoredUsername, 500, 300, null); // g.drawImage(mshi, 455, 255, null);hh
//Declare the blurKernel
float[] blurKernel = {
1 / 9f, 1 / 9f, 1 / 9f,
1 / 9f, 1 / 9f, 1 / 9f,
1 / 9f, 1 / 9f, 1 / 9f
};
//Initialize the blur
BufferedImageOp blur = new ConvolveOp(new Kernel(3, 3, blurKernel)); //new Kernel 3,3,blurKernel
//Blur the username blurFactor times (lol)
for(int i=0; i < blurFactor; i++){
sensoredUsername = blur.filter(sensoredUsername, new BufferedImage(sensoredUsername.getWidth()-1,
sensoredUsername.getHeight()-1, sensoredUsername.getType()));
}
//Dispose of the graphics.. We are done blurring!
g.dispose();
}
@Override
public void repaint(Graphics graphics) {
Graphics2D g = (Graphics2D)graphics;
Font meh = g.getFont();
if(ctx.game.isLoggedIn() && wUsername!=null && wUsername.isOnScreen() && wUsername.isVisible()){
g.drawImage(sensoredUsername, wUsername.getAbsoluteLocation().x-2, wUsername.getAbsoluteLocation().y+1,
wUsername.getWidth()-16, wUsername.getHeight()-4,null);
} else{
PaintUtils.drawStringCentered("No username to block!", meh, noUsername, Color.WHITE, g);
PaintUtils.drawGrid(g, 550, 257, 45, 20, 4, 12); //TODO Work on drawing a grid..
}
}
}
|
diff --git a/tools/ddms/libs/ddmuilib/src/com/android/ddmuilib/ScreenShotDialog.java b/tools/ddms/libs/ddmuilib/src/com/android/ddmuilib/ScreenShotDialog.java
index 88f1ad1e..b60c837f 100644
--- a/tools/ddms/libs/ddmuilib/src/com/android/ddmuilib/ScreenShotDialog.java
+++ b/tools/ddms/libs/ddmuilib/src/com/android/ddmuilib/ScreenShotDialog.java
@@ -1,285 +1,285 @@
/*
* Copyright (C) 2007 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.ddmuilib;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.Log;
import com.android.ddmlib.RawImage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import java.io.IOException;
/**
* Gather a screen shot from the device and save it to a file.
*/
public class ScreenShotDialog extends Dialog {
private Label mBusyLabel;
private Label mImageLabel;
private Button mSave;
private IDevice mDevice;
private RawImage mRawImage;
/**
* Create with default style.
*/
public ScreenShotDialog(Shell parent) {
this(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
}
/**
* Create with app-defined style.
*/
public ScreenShotDialog(Shell parent, int style) {
super(parent, style);
}
/**
* Prepare and display the dialog.
* @param device The {@link IDevice} from which to get the screenshot.
*/
public void open(IDevice device) {
mDevice = device;
Shell parent = getParent();
Shell shell = new Shell(parent, getStyle());
shell.setText("Device Screen Capture");
createContents(shell);
shell.pack();
shell.open();
updateDeviceImage(shell);
Display display = parent.getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
/*
* Create the screen capture dialog contents.
*/
private void createContents(final Shell shell) {
GridData data;
final int colCount = 4;
shell.setLayout(new GridLayout(colCount, true));
// "refresh" button
Button refresh = new Button(shell, SWT.PUSH);
refresh.setText("Refresh");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
refresh.setLayoutData(data);
refresh.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateDeviceImage(shell);
}
});
// "rotate" button
Button rotate = new Button(shell, SWT.PUSH);
rotate.setText("Rotate");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
rotate.setLayoutData(data);
rotate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (mRawImage != null) {
mRawImage = mRawImage.getRotated();
updateImageDisplay(shell);
}
}
});
// "save" button
mSave = new Button(shell, SWT.PUSH);
mSave.setText("Save");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
mSave.setLayoutData(data);
mSave.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveImage(shell);
}
});
// "done" button
Button done = new Button(shell, SWT.PUSH);
done.setText("Done");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
done.setLayoutData(data);
done.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.close();
}
});
// title/"capturing" label
mBusyLabel = new Label(shell, SWT.NONE);
mBusyLabel.setText("Preparing...");
data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
- data.horizontalSpan = 3;
+ data.horizontalSpan = colCount;
mBusyLabel.setLayoutData(data);
// space for the image
mImageLabel = new Label(shell, SWT.BORDER);
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
- data.horizontalSpan = 3;
+ data.horizontalSpan = colCount;
mImageLabel.setLayoutData(data);
Display display = shell.getDisplay();
mImageLabel.setImage(ImageHelper.createPlaceHolderArt(
display, 50, 50, display.getSystemColor(SWT.COLOR_BLUE)));
shell.setDefaultButton(done);
}
/**
* Captures a new image from the device, and display it.
*/
private void updateDeviceImage(Shell shell) {
mBusyLabel.setText("Capturing..."); // no effect
shell.setCursor(shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT));
mRawImage = getDeviceImage();
updateImageDisplay(shell);
}
/**
* Updates the display with {@link #mRawImage}.
* @param shell
*/
private void updateImageDisplay(Shell shell) {
Image image;
if (mRawImage == null) {
Display display = shell.getDisplay();
image = ImageHelper.createPlaceHolderArt(
display, 320, 240, display.getSystemColor(SWT.COLOR_BLUE));
mSave.setEnabled(false);
mBusyLabel.setText("Screen not available");
} else {
// convert raw data to an Image.
PaletteData palette = new PaletteData(
mRawImage.getRedMask(),
mRawImage.getGreenMask(),
mRawImage.getBlueMask());
ImageData imageData = new ImageData(mRawImage.width, mRawImage.height,
mRawImage.bpp, palette, 1, mRawImage.data);
image = new Image(getParent().getDisplay(), imageData);
mSave.setEnabled(true);
mBusyLabel.setText("Captured image:");
}
mImageLabel.setImage(image);
mImageLabel.pack();
shell.pack();
// there's no way to restore old cursor; assume it's ARROW
shell.setCursor(shell.getDisplay().getSystemCursor(SWT.CURSOR_ARROW));
}
/**
* Grabs an image from an ADB-connected device and returns it as a {@link RawImage}.
*/
private RawImage getDeviceImage() {
try {
return mDevice.getScreenshot();
}
catch (IOException ioe) {
Log.w("ddms", "Unable to get frame buffer: " + ioe.getMessage());
return null;
}
}
/*
* Prompt the user to save the image to disk.
*/
private void saveImage(Shell shell) {
FileDialog dlg = new FileDialog(shell, SWT.SAVE);
String fileName;
dlg.setText("Save image...");
dlg.setFileName("device.png");
dlg.setFilterPath(DdmUiPreferences.getStore().getString("lastImageSaveDir"));
dlg.setFilterNames(new String[] {
"PNG Files (*.png)"
});
dlg.setFilterExtensions(new String[] {
"*.png" //$NON-NLS-1$
});
fileName = dlg.open();
if (fileName != null) {
DdmUiPreferences.getStore().setValue("lastImageSaveDir", dlg.getFilterPath());
Log.d("ddms", "Saving image to " + fileName);
ImageData imageData = mImageLabel.getImage().getImageData();
try {
WritePng.savePng(fileName, imageData);
}
catch (IOException ioe) {
Log.w("ddms", "Unable to save " + fileName + ": " + ioe);
}
if (false) {
ImageLoader loader = new ImageLoader();
loader.data = new ImageData[] { imageData };
// PNG writing not available until 3.3? See bug at:
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=24697
// GIF writing only works for 8 bits
// JPEG uses lossy compression
// BMP has screwed-up colors
loader.save(fileName, SWT.IMAGE_JPEG);
}
}
}
}
| false | true | private void createContents(final Shell shell) {
GridData data;
final int colCount = 4;
shell.setLayout(new GridLayout(colCount, true));
// "refresh" button
Button refresh = new Button(shell, SWT.PUSH);
refresh.setText("Refresh");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
refresh.setLayoutData(data);
refresh.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateDeviceImage(shell);
}
});
// "rotate" button
Button rotate = new Button(shell, SWT.PUSH);
rotate.setText("Rotate");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
rotate.setLayoutData(data);
rotate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (mRawImage != null) {
mRawImage = mRawImage.getRotated();
updateImageDisplay(shell);
}
}
});
// "save" button
mSave = new Button(shell, SWT.PUSH);
mSave.setText("Save");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
mSave.setLayoutData(data);
mSave.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveImage(shell);
}
});
// "done" button
Button done = new Button(shell, SWT.PUSH);
done.setText("Done");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
done.setLayoutData(data);
done.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.close();
}
});
// title/"capturing" label
mBusyLabel = new Label(shell, SWT.NONE);
mBusyLabel.setText("Preparing...");
data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
data.horizontalSpan = 3;
mBusyLabel.setLayoutData(data);
// space for the image
mImageLabel = new Label(shell, SWT.BORDER);
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.horizontalSpan = 3;
mImageLabel.setLayoutData(data);
Display display = shell.getDisplay();
mImageLabel.setImage(ImageHelper.createPlaceHolderArt(
display, 50, 50, display.getSystemColor(SWT.COLOR_BLUE)));
shell.setDefaultButton(done);
}
| private void createContents(final Shell shell) {
GridData data;
final int colCount = 4;
shell.setLayout(new GridLayout(colCount, true));
// "refresh" button
Button refresh = new Button(shell, SWT.PUSH);
refresh.setText("Refresh");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
refresh.setLayoutData(data);
refresh.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateDeviceImage(shell);
}
});
// "rotate" button
Button rotate = new Button(shell, SWT.PUSH);
rotate.setText("Rotate");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
rotate.setLayoutData(data);
rotate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (mRawImage != null) {
mRawImage = mRawImage.getRotated();
updateImageDisplay(shell);
}
}
});
// "save" button
mSave = new Button(shell, SWT.PUSH);
mSave.setText("Save");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
mSave.setLayoutData(data);
mSave.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveImage(shell);
}
});
// "done" button
Button done = new Button(shell, SWT.PUSH);
done.setText("Done");
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.widthHint = 80;
done.setLayoutData(data);
done.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.close();
}
});
// title/"capturing" label
mBusyLabel = new Label(shell, SWT.NONE);
mBusyLabel.setText("Preparing...");
data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
data.horizontalSpan = colCount;
mBusyLabel.setLayoutData(data);
// space for the image
mImageLabel = new Label(shell, SWT.BORDER);
data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
data.horizontalSpan = colCount;
mImageLabel.setLayoutData(data);
Display display = shell.getDisplay();
mImageLabel.setImage(ImageHelper.createPlaceHolderArt(
display, 50, 50, display.getSystemColor(SWT.COLOR_BLUE)));
shell.setDefaultButton(done);
}
|
diff --git a/contentconnector-core/src/main/java/com/gentics/cr/plink/PlinkProcessor.java b/contentconnector-core/src/main/java/com/gentics/cr/plink/PlinkProcessor.java
index c652087e..1d597fbc 100644
--- a/contentconnector-core/src/main/java/com/gentics/cr/plink/PlinkProcessor.java
+++ b/contentconnector-core/src/main/java/com/gentics/cr/plink/PlinkProcessor.java
@@ -1,222 +1,222 @@
package com.gentics.cr.plink;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.jcs.JCS;
import org.apache.jcs.access.exception.CacheException;
import org.apache.log4j.Logger;
import com.gentics.api.lib.datasource.DatasourceNotAvailableException;
import com.gentics.api.lib.resolving.Resolvable;
import com.gentics.api.portalnode.connector.PLinkInformation;
import com.gentics.api.portalnode.connector.PortalConnectorFactory;
import com.gentics.cr.CRConfig;
import com.gentics.cr.CRConfigUtil;
import com.gentics.cr.CRRequest;
import com.gentics.cr.exceptions.CRException;
import com.gentics.cr.template.ITemplateManager;
/**
* CRPlinkProcessor should be initialized once and passed to CRPlinkReplacer on
* initalization. The Processor expects a plinkTemplate in the CRConfig.
*
*
* Last changed: $Date: 2010-01-25 12:05:57 +0100 (Mo, 25 Jän 2010) $
* @version $Revision: 406 $
* @author $Author: [email protected] $
*
*/
public class PlinkProcessor {
private CRConfig config;
Map<String,Resolvable> contextObjects;
private static Logger log = Logger.getLogger(PlinkProcessor.class);
private static JCS plinkCache;
private static String PLINK_CACHE_ACTIVATION_KEY="plinkcache";
private boolean plinkcache = true;
/**
* Create new instance of plink processor
* @param config
*/
public PlinkProcessor(CRConfig config) {
this.config = config;
contextObjects = new HashMap<String,Resolvable>();
if(config != null && config.getPortalNodeCompMode())
{
//Servlet will run in portal.node compatibility mode => no velocity available
log.warn("CRPlinkProcessor is running in Portal.Node 3 compatibility mode \n Therefore Velocity scripts will not work in the content.");
}
String s_plinkcache = null;
if(config != null) {
s_plinkcache = config.getString(PLINK_CACHE_ACTIVATION_KEY);
}
if(s_plinkcache!=null && !"".equals(s_plinkcache))
{
plinkcache = Boolean.parseBoolean(s_plinkcache);
}
if(plinkcache)
{
try {
String configName = "shared";
if(config != null){
configName=config.getName();
}
else{
log.error("Attention i'm using a shared plinkcache because i'm missing my config.");
}
plinkCache = JCS.getInstance("gentics-cr-" + configName + "-plinks");
log.debug("Initialized cache zone for \""+ configName + "-plinks\".");
} catch (CacheException e) {
log.warn("Could not initialize Cache for PlinkProcessor.");
}
}
else
{
plinkCache=null;
}
}
/**
* Deploy objects to the velocity context
* @param map
*/
public void deployObjects(Map<String,Resolvable> map)
{
Iterator<String> it = map.keySet().iterator();
while(it.hasNext())
{
String key = it.next();
this.contextObjects.put(key, map.get(key));
}
}
/**
* get a generated link according to the information in plinkinformation
* @param plink
* @param request
* @return
*/
public String getLink(PLinkInformation plink, CRRequest request) {
// starttime
long start = new Date().getTime();
String link = "";
String contentid = plink.getContentId();
- String cacheKey = contentid;
+ String cacheKey = contentid;
String type = "";
if (request.getRequest() != null && request.getRequest() instanceof HttpServletRequest) {
type = ((HttpServletRequest) request.getRequest()).getParameter("format");
String typeArg = ((HttpServletRequest) request.getRequest()).getParameter("type");
- if (!typeArg.equals("")) {
+ if (typeArg != null && !typeArg.equals("")) {
type = typeArg;
}
// reset to an empty string if php or null
// otherwise just use the given type for the cache-key
if (type == null || type.equals("php")) {
type = "";
}
// if the link refers to a binary-file, always use an empty type (this falls back to "php")
if (contentid.startsWith(config.getBinaryType() + ".")) {
type = "";
}
cacheKey += "-" + type;
}
// load link from cache
if (plinkCache != null) {
link = (String) plinkCache.get(cacheKey);
}
// no cache object so try to prepare a link
if (("".equals(link) || link == null )&& !config.getPortalNodeCompMode()) {
// Render Content with contentid as template name
Resolvable plinkObject;
try {
plinkObject = PortalConnectorFactory.getContentObject(contentid, this.config.getDatasource());
ITemplateManager myTemplateEngine = this.config.getTemplateManager();
// Put objects in the plink template
myTemplateEngine.put("plink", plinkObject);
//Deploy predefined Objects to the context
Iterator<String> it = this.contextObjects.keySet().iterator();
while(it.hasNext())
{
String key = it.next();
myTemplateEngine.put(key, this.contextObjects.get(key));
}
// as url is a special object put it also in the templates
if (this.config.getPathResolver() != null) {
String url = this.config.getPathResolver().getPath(
plinkObject);
if (url != null) {
myTemplateEngine.put("url", url);
}
}
link = myTemplateEngine.render("link", this.config.getPlinkTemplate());
} catch (DatasourceNotAvailableException e) {
CRException ex = new CRException(e);
log.error(ex.getMessage() + ex.getStringStackTrace());
} catch (CRException ex) {
log.error(ex.getMessage() + ex.getStringStackTrace());
}
// endtime
long end = new Date().getTime();
log.debug("plink generationtime for link " + contentid + ": "
+ (end - start));
}
// If velocity template parsing and caching does not work for any
// reason use a dynamic link
if ("".equals(link) || link == null) {
if("true".equals(this.config.get(CRConfig.ADVPLR_KEY))){
link = this.config.getPathResolver().getDynamicUrl(contentid, config, request);
}
else
{
link = this.config.getPathResolver().getDynamicUrl(contentid);
}
}
// add link to cache
try {
if (plinkCache != null) {
plinkCache.put(cacheKey, link);
}
} catch (CacheException e) {
log.warn("Could not add link to object " + contentid
+ " to cache");
}
return link;
}
}
| false | true | public String getLink(PLinkInformation plink, CRRequest request) {
// starttime
long start = new Date().getTime();
String link = "";
String contentid = plink.getContentId();
String cacheKey = contentid;
String type = "";
if (request.getRequest() != null && request.getRequest() instanceof HttpServletRequest) {
type = ((HttpServletRequest) request.getRequest()).getParameter("format");
String typeArg = ((HttpServletRequest) request.getRequest()).getParameter("type");
if (!typeArg.equals("")) {
type = typeArg;
}
// reset to an empty string if php or null
// otherwise just use the given type for the cache-key
if (type == null || type.equals("php")) {
type = "";
}
// if the link refers to a binary-file, always use an empty type (this falls back to "php")
if (contentid.startsWith(config.getBinaryType() + ".")) {
type = "";
}
cacheKey += "-" + type;
}
// load link from cache
if (plinkCache != null) {
link = (String) plinkCache.get(cacheKey);
}
// no cache object so try to prepare a link
if (("".equals(link) || link == null )&& !config.getPortalNodeCompMode()) {
// Render Content with contentid as template name
Resolvable plinkObject;
try {
plinkObject = PortalConnectorFactory.getContentObject(contentid, this.config.getDatasource());
ITemplateManager myTemplateEngine = this.config.getTemplateManager();
// Put objects in the plink template
myTemplateEngine.put("plink", plinkObject);
//Deploy predefined Objects to the context
Iterator<String> it = this.contextObjects.keySet().iterator();
while(it.hasNext())
{
String key = it.next();
myTemplateEngine.put(key, this.contextObjects.get(key));
}
// as url is a special object put it also in the templates
if (this.config.getPathResolver() != null) {
String url = this.config.getPathResolver().getPath(
plinkObject);
if (url != null) {
myTemplateEngine.put("url", url);
}
}
link = myTemplateEngine.render("link", this.config.getPlinkTemplate());
} catch (DatasourceNotAvailableException e) {
CRException ex = new CRException(e);
log.error(ex.getMessage() + ex.getStringStackTrace());
} catch (CRException ex) {
log.error(ex.getMessage() + ex.getStringStackTrace());
}
// endtime
long end = new Date().getTime();
log.debug("plink generationtime for link " + contentid + ": "
+ (end - start));
}
// If velocity template parsing and caching does not work for any
// reason use a dynamic link
if ("".equals(link) || link == null) {
if("true".equals(this.config.get(CRConfig.ADVPLR_KEY))){
link = this.config.getPathResolver().getDynamicUrl(contentid, config, request);
}
else
{
link = this.config.getPathResolver().getDynamicUrl(contentid);
}
}
// add link to cache
try {
if (plinkCache != null) {
plinkCache.put(cacheKey, link);
}
} catch (CacheException e) {
log.warn("Could not add link to object " + contentid
+ " to cache");
}
return link;
}
| public String getLink(PLinkInformation plink, CRRequest request) {
// starttime
long start = new Date().getTime();
String link = "";
String contentid = plink.getContentId();
String cacheKey = contentid;
String type = "";
if (request.getRequest() != null && request.getRequest() instanceof HttpServletRequest) {
type = ((HttpServletRequest) request.getRequest()).getParameter("format");
String typeArg = ((HttpServletRequest) request.getRequest()).getParameter("type");
if (typeArg != null && !typeArg.equals("")) {
type = typeArg;
}
// reset to an empty string if php or null
// otherwise just use the given type for the cache-key
if (type == null || type.equals("php")) {
type = "";
}
// if the link refers to a binary-file, always use an empty type (this falls back to "php")
if (contentid.startsWith(config.getBinaryType() + ".")) {
type = "";
}
cacheKey += "-" + type;
}
// load link from cache
if (plinkCache != null) {
link = (String) plinkCache.get(cacheKey);
}
// no cache object so try to prepare a link
if (("".equals(link) || link == null )&& !config.getPortalNodeCompMode()) {
// Render Content with contentid as template name
Resolvable plinkObject;
try {
plinkObject = PortalConnectorFactory.getContentObject(contentid, this.config.getDatasource());
ITemplateManager myTemplateEngine = this.config.getTemplateManager();
// Put objects in the plink template
myTemplateEngine.put("plink", plinkObject);
//Deploy predefined Objects to the context
Iterator<String> it = this.contextObjects.keySet().iterator();
while(it.hasNext())
{
String key = it.next();
myTemplateEngine.put(key, this.contextObjects.get(key));
}
// as url is a special object put it also in the templates
if (this.config.getPathResolver() != null) {
String url = this.config.getPathResolver().getPath(
plinkObject);
if (url != null) {
myTemplateEngine.put("url", url);
}
}
link = myTemplateEngine.render("link", this.config.getPlinkTemplate());
} catch (DatasourceNotAvailableException e) {
CRException ex = new CRException(e);
log.error(ex.getMessage() + ex.getStringStackTrace());
} catch (CRException ex) {
log.error(ex.getMessage() + ex.getStringStackTrace());
}
// endtime
long end = new Date().getTime();
log.debug("plink generationtime for link " + contentid + ": "
+ (end - start));
}
// If velocity template parsing and caching does not work for any
// reason use a dynamic link
if ("".equals(link) || link == null) {
if("true".equals(this.config.get(CRConfig.ADVPLR_KEY))){
link = this.config.getPathResolver().getDynamicUrl(contentid, config, request);
}
else
{
link = this.config.getPathResolver().getDynamicUrl(contentid);
}
}
// add link to cache
try {
if (plinkCache != null) {
plinkCache.put(cacheKey, link);
}
} catch (CacheException e) {
log.warn("Could not add link to object " + contentid
+ " to cache");
}
return link;
}
|
diff --git a/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java b/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
index dd495c1..046a4cf 100644
--- a/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
+++ b/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
@@ -1,333 +1,349 @@
/*
* Copyright 2010 The myBatis Team
*
* 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.mybatis.spring;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* {@link org.springframework.beans.factory.FactoryBean} that creates an MyBatis
* {@link org.apache.ibatis.session.SqlSessionFactory}. This is the usual way to set up a shared
* MyBatis SqlSessionFactory in a Spring application context; the SqlSessionFactory can then be
* passed to MyBatis-based DAOs via dependency injection.
*
* Either {@link org.springframework.jdbc.datasource.DataSourceTransactionManager} or
* {@link org.springframework.transaction.jta.JtaTransactionManager} can be used for transaction
* demarcation in combination with a SqlSessionFactory. JTA should be used for transactions
* which span multiple databases or when container managed transactions (CMT) are being used.
*
* Allows for specifying a DataSource at the SqlSessionFactory level. This is preferable to per-DAO
* DataSource references, as it allows for lazy loading and avoids repeated DataSource references in
* every DAO.
*
* @see #setConfigLocation
* @see #setDataSource
* @see org.mybatis.spring.SqlSessionTemplate#setSqlSessionFactory
* @see org.mybatis.spring.SqlSessionTemplate#setDataSource
* @version $Id$
*/
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean {
protected final Log logger = LogFactory.getLog(getClass());
private Resource configLocation;
private Resource[] mapperLocations;
private DataSource dataSource;
private Class<? extends TransactionFactory> transactionFactoryClass = SpringManagedTransactionFactory.class;
private Properties transactionFactoryProperties;
private Properties configurationProperties;
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
private SqlSessionFactory sqlSessionFactory;
private String environment = SqlSessionFactoryBean.class.getSimpleName();
public SqlSessionFactoryBean() {}
/**
* Set the location of the MyBatis SqlSessionFactory config file. A typical value is
* "WEB-INF/mybatis-configuration.xml".
*/
public void setConfigLocation(Resource configLocation) {
this.configLocation = configLocation;
}
/**
* Set locations of MyBatis mapper files that are going to be merged into the SqlSessionFactory
* configuration at runtime.
*
* This is an alternative to specifying "<sqlmapper>" entries in an MyBatis config file.
* This property being based on Spring's resource abstraction also allows for specifying
* resource patterns here: e.g. "/sqlmap/*-mapper.xml".
*/
public void setMapperLocations(Resource[] mapperLocations) {
this.mapperLocations = mapperLocations;
}
/**
* Set optional properties to be passed into the SqlSession configuration, as alternative to a
* <code><properties></code> tag in the configuration xml file. This will be used to
* resolve placeholders in the config file.
*
* @see org.apache.ibatis.session.Configuration#getVariables
*/
public void setConfigurationProperties(Properties sqlSessionFactoryProperties) {
this.configurationProperties = sqlSessionFactoryProperties;
}
/**
* Set the JDBC DataSource that this instance should manage transactions for. The DataSource
* should match the one used by the SqlSessionFactory: for example, you could specify the same
* JNDI DataSource for both.
*
* A transactional JDBC Connection for this DataSource will be provided to application code
* accessing this DataSource directly via DataSourceUtils or DataSourceTransactionManager.
*
* The DataSource specified here should be the target DataSource to manage transactions for, not
* a TransactionAwareDataSourceProxy. Only data access code may work with
* TransactionAwareDataSourceProxy, while the transaction manager needs to work on the
* underlying target DataSource. If there's nevertheless a TransactionAwareDataSourceProxy
* passed in, it will be unwrapped to extract its target DataSource.
*
* @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
* @see org.springframework.jdbc.datasource.DataSourceUtils
* @see org.springframework.jdbc.datasource.DataSourceTransactionManager
*/
public void setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
// If we got a TransactionAwareDataSourceProxy, we need to perform
// transactions for its underlying target DataSource, else data
// access code won't see properly exposed transactions (i.e.
// transactions for the target DataSource).
this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
} else {
this.dataSource = dataSource;
}
}
/**
* Sets the SqlSessionFactoryBuilder to use when creating the SqlSessionFactory.
*
* This is mainly meant for testing so that mock SqlSessionFactory classes can be injected. By
* default, SqlSessionFactoryBuilder creates <code>DefaultSqlSessionFactory<code> instances.
*
* @see org.apache.ibatis.session.SqlSessionFactoryBuilder
*/
public void setSqlSessionFactoryBuilder(SqlSessionFactoryBuilder sqlSessionFactoryBuilder) {
this.sqlSessionFactoryBuilder = sqlSessionFactoryBuilder;
}
/**
* Set the MyBatis TransactionFactory class to use. Default is
* <code>SpringManagedTransactionFactory</code>.
*
* The default SpringManagedTransactionFactory should be appropriate for all cases: be it Spring
* transaction management, EJB CMT or plain JTA. If there is no active transaction, SqlSession
* operations will execute SQL statements non-transactionally.
*
* <b>It is strongly recommended to use the default TransactionFactory.</b> If not used, any
* attempt at getting an SqlSession through Spring's MyBatis framework will throw an exception if
* a transaction is active.
*
* @see #setDataSource
* @see #setTransactionFactoryProperties(java.util.Properties)
* @see org.apache.ibatis.transaction.TransactionFactory
* @see org.mybatis.spring.transaction.SpringManagedTransactionFactory
* @see org.apache.ibatis.transaction.Transaction
* @see org.mybatis.spring.SqlSessionUtils#getSqlSession(SqlSessionFactory,
* DataSource, org.apache.ibatis.session.ExecutorType)
* @param <TF> the MyBatis TransactionFactory type
* @param transactionFactoryClass the MyBatis TransactionFactory class to use
*/
public <TF extends TransactionFactory> void setTransactionFactoryClass(Class<TF> transactionFactoryClass) {
this.transactionFactoryClass = transactionFactoryClass;
}
/**
* Set properties to be passed to the TransactionFactory instance used by this
* SqlSessionFactory.
*
* The default SpringManagedTransactionFactory does not have any user configurable properties.
*
* @see org.apache.ibatis.transaction.TransactionFactory#setProperties(java.util.Properties)
* @see org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory
* @see org.apache.ibatis.transaction.managed.ManagedTransactionFactory
*/
public void setTransactionFactoryProperties(Properties transactionFactoryProperties) {
this.transactionFactoryProperties = transactionFactoryProperties;
}
/**
* <b>NOTE:</b> This class <em>overrides</em> any Environment you have set in the MyBatis config
* file. This is used only as a placeholder name. The default value is
* <code>SqlSessionFactoryBean.class.getSimpleName()</code>.
*
* @param environment the environment name
*/
public void setEnvironment(String environment) {
this.environment = environment;
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(dataSource, "Property 'dataSource' is required");
Assert.notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
Assert.notNull(transactionFactoryClass, "Property 'transactionFactoryClass' is required");
sqlSessionFactory = buildSqlSessionFactory();
}
/**
* Build a SqlSessionFactory instance.
*
* The default implementation uses the standard MyBatis {@link XMLConfigBuilder} API to build a
* SqlSessionFactory instance based on an Reader.
*
* @see org.apache.ibatis.builder.xml.XMLConfigBuilder#parse()
*
* @return SqlSessionFactory
*
* @throws IOException if loading the config file failed
* @throws IllegalAccessException
* @throws InstantiationException
*/
protected SqlSessionFactory buildSqlSessionFactory() throws IOException, IllegalAccessException,
InstantiationException {
XMLConfigBuilder xmlConfigBuilder;
Configuration configuration;
if (configLocation != null) {
+ Reader reader = null;
try {
- Reader reader = new InputStreamReader(configLocation.getInputStream());
+ reader = new InputStreamReader(configLocation.getInputStream());
// Null environment causes the configuration to use the default.
// This will be overwritten below regardless.
xmlConfigBuilder = new XMLConfigBuilder(reader, null, configurationProperties);
configuration = xmlConfigBuilder.parse();
} catch (IOException ex) {
throw new NestedIOException("Failed to parse config resource: " + configLocation, ex);
+ } finally {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException ignored) {
+ }
+ }
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed configuration file: '" + configLocation + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
}
TransactionFactory transactionFactory = this.transactionFactoryClass.newInstance(); // expose IllegalAccessException, InstantiationException
transactionFactory.setProperties(transactionFactoryProperties);
Environment environment = new Environment(this.environment, transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(mapperLocations)) {
Map<String, XNode> sqlFragments = new HashMap<String, XNode>();
+ Reader reader = null;
for (Resource mapperLocation : mapperLocations) {
if (mapperLocation == null) {
continue;
}
// MyBatis holds a Map using "resource" name as a key.
// If a mapper file is loaded, it searches for a mapper interface type.
// If the type is found then it tries to load the mapper file again looking for this:
//
// String xmlResource = type.getName().replace('.', '/') + ".xml";
//
// So if a mapper interface exists, resource cannot be an absolute path.
// Otherwise MyBatis will throw an exception because
// it will load both a mapper interface and the mapper xml file,
// and throw an exception telling that a mapperStatement cannot be loaded twice.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ClassPathResource.class.cast(mapperLocation).getPath();
} else {
// this won't work if there is also a mapper interface in classpath
path = mapperLocation.getURI().getPath();
}
try {
- Reader reader = new InputStreamReader(mapperLocation.getInputStream());
+ reader = new InputStreamReader(mapperLocation.getInputStream());
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(reader, configuration, path, sqlFragments);
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
+ } finally {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException ignored) {
+ }
+ }
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else if (logger.isDebugEnabled()) {
logger.debug("Property 'mapperLocations' was not specified, only MyBatis mapper files specified in the config xml were loaded");
}
return sqlSessionFactoryBuilder.build(configuration);
}
public SqlSessionFactory getObject() throws Exception {
if (sqlSessionFactory == null) {
afterPropertiesSet();
}
return sqlSessionFactory;
}
public Class<? extends SqlSessionFactory> getObjectType() {
return sqlSessionFactory == null ? SqlSessionFactory.class : sqlSessionFactory.getClass();
}
public boolean isSingleton() {
return true;
}
}
| false | true | protected SqlSessionFactory buildSqlSessionFactory() throws IOException, IllegalAccessException,
InstantiationException {
XMLConfigBuilder xmlConfigBuilder;
Configuration configuration;
if (configLocation != null) {
try {
Reader reader = new InputStreamReader(configLocation.getInputStream());
// Null environment causes the configuration to use the default.
// This will be overwritten below regardless.
xmlConfigBuilder = new XMLConfigBuilder(reader, null, configurationProperties);
configuration = xmlConfigBuilder.parse();
} catch (IOException ex) {
throw new NestedIOException("Failed to parse config resource: " + configLocation, ex);
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed configuration file: '" + configLocation + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
}
TransactionFactory transactionFactory = this.transactionFactoryClass.newInstance(); // expose IllegalAccessException, InstantiationException
transactionFactory.setProperties(transactionFactoryProperties);
Environment environment = new Environment(this.environment, transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(mapperLocations)) {
Map<String, XNode> sqlFragments = new HashMap<String, XNode>();
for (Resource mapperLocation : mapperLocations) {
if (mapperLocation == null) {
continue;
}
// MyBatis holds a Map using "resource" name as a key.
// If a mapper file is loaded, it searches for a mapper interface type.
// If the type is found then it tries to load the mapper file again looking for this:
//
// String xmlResource = type.getName().replace('.', '/') + ".xml";
//
// So if a mapper interface exists, resource cannot be an absolute path.
// Otherwise MyBatis will throw an exception because
// it will load both a mapper interface and the mapper xml file,
// and throw an exception telling that a mapperStatement cannot be loaded twice.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ClassPathResource.class.cast(mapperLocation).getPath();
} else {
// this won't work if there is also a mapper interface in classpath
path = mapperLocation.getURI().getPath();
}
try {
Reader reader = new InputStreamReader(mapperLocation.getInputStream());
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(reader, configuration, path, sqlFragments);
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else if (logger.isDebugEnabled()) {
logger.debug("Property 'mapperLocations' was not specified, only MyBatis mapper files specified in the config xml were loaded");
}
return sqlSessionFactoryBuilder.build(configuration);
}
| protected SqlSessionFactory buildSqlSessionFactory() throws IOException, IllegalAccessException,
InstantiationException {
XMLConfigBuilder xmlConfigBuilder;
Configuration configuration;
if (configLocation != null) {
Reader reader = null;
try {
reader = new InputStreamReader(configLocation.getInputStream());
// Null environment causes the configuration to use the default.
// This will be overwritten below regardless.
xmlConfigBuilder = new XMLConfigBuilder(reader, null, configurationProperties);
configuration = xmlConfigBuilder.parse();
} catch (IOException ex) {
throw new NestedIOException("Failed to parse config resource: " + configLocation, ex);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed configuration file: '" + configLocation + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
}
TransactionFactory transactionFactory = this.transactionFactoryClass.newInstance(); // expose IllegalAccessException, InstantiationException
transactionFactory.setProperties(transactionFactoryProperties);
Environment environment = new Environment(this.environment, transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(mapperLocations)) {
Map<String, XNode> sqlFragments = new HashMap<String, XNode>();
Reader reader = null;
for (Resource mapperLocation : mapperLocations) {
if (mapperLocation == null) {
continue;
}
// MyBatis holds a Map using "resource" name as a key.
// If a mapper file is loaded, it searches for a mapper interface type.
// If the type is found then it tries to load the mapper file again looking for this:
//
// String xmlResource = type.getName().replace('.', '/') + ".xml";
//
// So if a mapper interface exists, resource cannot be an absolute path.
// Otherwise MyBatis will throw an exception because
// it will load both a mapper interface and the mapper xml file,
// and throw an exception telling that a mapperStatement cannot be loaded twice.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ClassPathResource.class.cast(mapperLocation).getPath();
} else {
// this won't work if there is also a mapper interface in classpath
path = mapperLocation.getURI().getPath();
}
try {
reader = new InputStreamReader(mapperLocation.getInputStream());
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(reader, configuration, path, sqlFragments);
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else if (logger.isDebugEnabled()) {
logger.debug("Property 'mapperLocations' was not specified, only MyBatis mapper files specified in the config xml were loaded");
}
return sqlSessionFactoryBuilder.build(configuration);
}
|
diff --git a/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/api/notify/PropertiesEditingSemanticLister.java b/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/api/notify/PropertiesEditingSemanticLister.java
index 99346ae37..76fd3aedf 100644
--- a/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/api/notify/PropertiesEditingSemanticLister.java
+++ b/plugins/org.eclipse.emf.eef.runtime/src/org/eclipse/emf/eef/runtime/api/notify/PropertiesEditingSemanticLister.java
@@ -1,83 +1,83 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 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.emf.eef.runtime.api.notify;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
/**
* @author <a href="mailto:[email protected]">Goulwen Le Fur</a>
*/
@Deprecated
public abstract class PropertiesEditingSemanticLister extends EContentAdapter {
private IPropertiesEditionComponent component;
private IPropertiesEditionPart part;
/**
* @param component
*/
public PropertiesEditingSemanticLister(IPropertiesEditionComponent component) {
this.component = component;
}
/**
* @return the part
*/
public IPropertiesEditionPart getPart() {
return part;
}
/**
* @param part
* the part to set
*/
public void setPart(IPropertiesEditionPart part) {
this.part = part;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.util.EContentAdapter#notifyChanged(org.eclipse.emf.common.notify.Notification)
*/
@Override
public void notifyChanged(final Notification notification) {
if (part == null)
component.dispose();
else {
Runnable updateRunnable = new Runnable() {
public void run() {
runUpdateRunnable(notification);
}
};
if (null == Display.getCurrent()) {
- PlatformUI.getWorkbench().getDisplay().syncExec(updateRunnable);
+ PlatformUI.getWorkbench().getDisplay().asyncExec(updateRunnable);
} else {
updateRunnable.run();
}
}
}
/**
* Performs update in the views
*
* @param notification
* the model notification
*/
public abstract void runUpdateRunnable(Notification notification);
}
| true | true | public void notifyChanged(final Notification notification) {
if (part == null)
component.dispose();
else {
Runnable updateRunnable = new Runnable() {
public void run() {
runUpdateRunnable(notification);
}
};
if (null == Display.getCurrent()) {
PlatformUI.getWorkbench().getDisplay().syncExec(updateRunnable);
} else {
updateRunnable.run();
}
}
}
| public void notifyChanged(final Notification notification) {
if (part == null)
component.dispose();
else {
Runnable updateRunnable = new Runnable() {
public void run() {
runUpdateRunnable(notification);
}
};
if (null == Display.getCurrent()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(updateRunnable);
} else {
updateRunnable.run();
}
}
}
|
diff --git a/org.coreasm.engine/src/org/coreasm/engine/informationHandler/AbstractDispatcher.java b/org.coreasm.engine/src/org/coreasm/engine/informationHandler/AbstractDispatcher.java
index 9efbb64..631536c 100644
--- a/org.coreasm.engine/src/org/coreasm/engine/informationHandler/AbstractDispatcher.java
+++ b/org.coreasm.engine/src/org/coreasm/engine/informationHandler/AbstractDispatcher.java
@@ -1,130 +1,130 @@
/**
*
*/
package org.coreasm.engine.informationHandler;
import java.util.HashMap;
import java.util.LinkedList;
/**
* @author Marcel Dausend
*
*/
abstract class AbstractDispatcher {
static class Action {
static final String CREATION = "CREATION";
static final String CLEAR = "CLEAR";
}
public enum DistributionMode {
COMMIT, AUTOCOMMIT;
};
/** thread specific information */
private LinkedList<DispatcherContext> newActions;
private DistributionMode distributionMode;
HashMap<String, IInformationDispatchObserver> observers = new HashMap<String, IInformationDispatchObserver>();
/**
* creates an Dispatcher with <code>DistributionMode.AUTOCOMMIT</code>
*/
public AbstractDispatcher() {
newActions = new LinkedList<DispatcherContext>();
distributionMode = DistributionMode.AUTOCOMMIT;
}
public AbstractDispatcher(DistributionMode mode) {
newActions = new LinkedList<DispatcherContext>();
distributionMode = mode;
}
/**
* add an observer to the list of observers
*
* @param iStorageAndDispatchObserver
*
* \todo introduce priorities
*/
protected void addSuperObserver(IInformationDispatchObserver iStorageAndDispatchObserver) {
if (! this.observers.containsKey(iStorageAndDispatchObserver.getClass().getCanonicalName()))
this.observers.put(iStorageAndDispatchObserver.getClass().getCanonicalName(), iStorageAndDispatchObserver);
}
/**
* remove an observer from the list of observers
*
* @param iStorageAndDispatchObserver
*/
protected void deleteSuperObserver(IInformationDispatchObserver iStorageAndDispatchObserver) {
if (this.observers.containsKey(iStorageAndDispatchObserver.getClass().getCanonicalName()))
this.observers.remove(iStorageAndDispatchObserver.getClass().getCanonicalName());
}
/**
* remove all observers
*/
protected void deleteSuperObervers() {
this.observers.clear();
}
public synchronized void createInformation(InformationObject info) {
//Instantiate new DispatcherContext with given information object
DispatcherContext newInfoDispObject = new DispatcherContext(info, Action.CREATION);
//add new DisplayContext to list of actions
this.newActions.add(newInfoDispObject);
if (this.getDistributionMode().equals(DistributionMode.AUTOCOMMIT)) {
this.notifyObservers();
} else if (this.getDistributionMode().equals(DistributionMode.COMMIT)) {
//wait for call of the commit method;
}
}
public synchronized void clearInformation() {
//Instantiate new DispatcherContext with a null-Object as information object
DispatcherContext newInfoDispObject = new DispatcherContext(null, Action.CLEAR);
newActions.add(newInfoDispObject);
if (this.getDistributionMode().equals(DistributionMode.AUTOCOMMIT)) {
notifyObservers();
} else if (this.getDistributionMode().equals(DistributionMode.COMMIT)) {
//already added to added into new actions
}
}
public synchronized void commit() {
if (this.getDistributionMode().equals(DistributionMode.COMMIT))
this.notifyObservers();
}
public synchronized void setDistributionMode(DistributionMode distMode) {
this.distributionMode = distMode;
}
public synchronized DistributionMode getDistributionMode() {
return this.distributionMode;
}
/**
* call both interface functions of IStorageAndDispatchObserver foreach
* InformationDispatch belonging to the current thread. Add or remove each
* InformationObject from the information list of StorageAndDispatch. Clear
* the newActions entry from the newActions HashMap.
*/
private synchronized void notifyObservers() {
if (!this.newActions.isEmpty()) {
for (DispatcherContext dispInfo : this.newActions) {
for (IInformationDispatchObserver obs : observers.values()) {
if (dispInfo.getAction().equals(Action.CREATION)) {
obs.informationCreated(dispInfo.getInformation());
} else if (dispInfo.getAction().equals(Action.CLEAR)) {
obs.clearInformation();
}
}
- this.newActions.remove(dispInfo);
}
+ this.newActions.clear();
}
}
}
| false | true | private synchronized void notifyObservers() {
if (!this.newActions.isEmpty()) {
for (DispatcherContext dispInfo : this.newActions) {
for (IInformationDispatchObserver obs : observers.values()) {
if (dispInfo.getAction().equals(Action.CREATION)) {
obs.informationCreated(dispInfo.getInformation());
} else if (dispInfo.getAction().equals(Action.CLEAR)) {
obs.clearInformation();
}
}
this.newActions.remove(dispInfo);
}
}
}
| private synchronized void notifyObservers() {
if (!this.newActions.isEmpty()) {
for (DispatcherContext dispInfo : this.newActions) {
for (IInformationDispatchObserver obs : observers.values()) {
if (dispInfo.getAction().equals(Action.CREATION)) {
obs.informationCreated(dispInfo.getInformation());
} else if (dispInfo.getAction().equals(Action.CLEAR)) {
obs.clearInformation();
}
}
}
this.newActions.clear();
}
}
|
diff --git a/cat-consumer-advanced/src/test/java/com/dianping/cat/consumer/advanced/MetricAnalyzerTest.java b/cat-consumer-advanced/src/test/java/com/dianping/cat/consumer/advanced/MetricAnalyzerTest.java
index 1fd386346..a6a510047 100644
--- a/cat-consumer-advanced/src/test/java/com/dianping/cat/consumer/advanced/MetricAnalyzerTest.java
+++ b/cat-consumer-advanced/src/test/java/com/dianping/cat/consumer/advanced/MetricAnalyzerTest.java
@@ -1,33 +1,33 @@
package com.dianping.cat.consumer.advanced;
import junit.framework.Assert;
import org.junit.Test;
public class MetricAnalyzerTest {
@Test
public void test() {
MetricAnalyzer analyzer = new MetricAnalyzer();
String data = "aaa=1.1&a=1.1&abc=2.2&c=1.2&aaaa=11.1&abbbb=1.1&ssabc=2.2&sc=1.2";
long t = System.currentTimeMillis();
- for (int i = 0; i < 10000000; i++) {
+ for (int i = 0; i < 1000; i++) {
analyzer.parseValue("abc", data);
}
System.out.println(System.currentTimeMillis() - t);
- Assert.assertEquals(analyzer.parseValue("aaa", "aaa=1.1"), 1.1);
- Assert.assertEquals(analyzer.parseValue("aaa", data), 1.1);
- Assert.assertEquals(analyzer.parseValue("a", data), 1.1);
- Assert.assertEquals(analyzer.parseValue("abc", data), 2.2);
- Assert.assertEquals(analyzer.parseValue("c", data), 1.2);
- Assert.assertEquals(analyzer.parseValue("aaaa", data), 11.1);
- Assert.assertEquals(analyzer.parseValue("abbbb", data), 1.1);
- Assert.assertEquals(analyzer.parseValue("ssabc", data), 2.2);
- Assert.assertEquals(analyzer.parseValue("sc", data), 1.2);
+ Assert.assertEquals(analyzer.parseValue("aaa", "aaa=1.1"), "1.1");
+ Assert.assertEquals(analyzer.parseValue("aaa", data), "1.1");
+ Assert.assertEquals(analyzer.parseValue("a", data), "1.1");
+ Assert.assertEquals(analyzer.parseValue("abc", data), "2.2");
+ Assert.assertEquals(analyzer.parseValue("c", data), "1.2");
+ Assert.assertEquals(analyzer.parseValue("aaaa", data), "11.1");
+ Assert.assertEquals(analyzer.parseValue("abbbb", data), "1.1");
+ Assert.assertEquals(analyzer.parseValue("ssabc", data), "2.2");
+ Assert.assertEquals(analyzer.parseValue("sc", data), "1.2");
}
}
| false | true | public void test() {
MetricAnalyzer analyzer = new MetricAnalyzer();
String data = "aaa=1.1&a=1.1&abc=2.2&c=1.2&aaaa=11.1&abbbb=1.1&ssabc=2.2&sc=1.2";
long t = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
analyzer.parseValue("abc", data);
}
System.out.println(System.currentTimeMillis() - t);
Assert.assertEquals(analyzer.parseValue("aaa", "aaa=1.1"), 1.1);
Assert.assertEquals(analyzer.parseValue("aaa", data), 1.1);
Assert.assertEquals(analyzer.parseValue("a", data), 1.1);
Assert.assertEquals(analyzer.parseValue("abc", data), 2.2);
Assert.assertEquals(analyzer.parseValue("c", data), 1.2);
Assert.assertEquals(analyzer.parseValue("aaaa", data), 11.1);
Assert.assertEquals(analyzer.parseValue("abbbb", data), 1.1);
Assert.assertEquals(analyzer.parseValue("ssabc", data), 2.2);
Assert.assertEquals(analyzer.parseValue("sc", data), 1.2);
}
| public void test() {
MetricAnalyzer analyzer = new MetricAnalyzer();
String data = "aaa=1.1&a=1.1&abc=2.2&c=1.2&aaaa=11.1&abbbb=1.1&ssabc=2.2&sc=1.2";
long t = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
analyzer.parseValue("abc", data);
}
System.out.println(System.currentTimeMillis() - t);
Assert.assertEquals(analyzer.parseValue("aaa", "aaa=1.1"), "1.1");
Assert.assertEquals(analyzer.parseValue("aaa", data), "1.1");
Assert.assertEquals(analyzer.parseValue("a", data), "1.1");
Assert.assertEquals(analyzer.parseValue("abc", data), "2.2");
Assert.assertEquals(analyzer.parseValue("c", data), "1.2");
Assert.assertEquals(analyzer.parseValue("aaaa", data), "11.1");
Assert.assertEquals(analyzer.parseValue("abbbb", data), "1.1");
Assert.assertEquals(analyzer.parseValue("ssabc", data), "2.2");
Assert.assertEquals(analyzer.parseValue("sc", data), "1.2");
}
|
diff --git a/src/org/eclipse/jface/dialogs/InputDialog.java b/src/org/eclipse/jface/dialogs/InputDialog.java
index dabafc84..f9de32f2 100644
--- a/src/org/eclipse/jface/dialogs/InputDialog.java
+++ b/src/org/eclipse/jface/dialogs/InputDialog.java
@@ -1,229 +1,230 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.dialogs;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.*;
/**
* A simple input dialog for soliciting an input string
* from the user.
* <p>
* This concete dialog class can be instantiated as is,
* or further subclassed as required.
* </p>
*/
public class InputDialog extends Dialog {
/**
* The title of the dialog.
*/
private String title;
/**
* The message to display, or <code>null</code> if none.
*/
private String message;
/**
* The input value; the empty string by default.
*/
private String value= "";//$NON-NLS-1$
/**
* The input validator, or <code>null</code> if none.
*/
private IInputValidator validator;
/**
* Ok button widget.
*/
private Button okButton;
/**
* Input text widget.
*/
private Text text;
/**
* Error message label widget.
*/
private Label errorMessageLabel;
/**
* Creates an input dialog with OK and Cancel buttons.
* Note that the dialog will have no visual representation (no widgets)
* until it is told to open.
* <p>
* Note that the <code>open</code> method blocks for input dialogs.
* </p>
*
* @param parentShell the parent shell
* @param dialogTitle the dialog title, or <code>null</code> if none
* @param dialogMessage the dialog message, or <code>null</code> if none
* @param initialValue the initial input value, or <code>null</code> if none
* (equivalent to the empty string)
* @param validator an input validator, or <code>null</code> if none
*/
public InputDialog(Shell parentShell, String dialogTitle, String dialogMessage, String initialValue, IInputValidator validator) {
super(parentShell);
this.title = dialogTitle;
message = dialogMessage;
if (initialValue == null)
value = "";//$NON-NLS-1$
else
value = initialValue;
this.validator = validator;
}
/* (non-Javadoc)
* Method declared on Dialog.
*/
protected void buttonPressed(int buttonId) {
if (buttonId == IDialogConstants.OK_ID) {
value= text.getText();
} else {
value= null;
}
super.buttonPressed(buttonId);
}
/* (non-Javadoc)
* Method declared in Window.
*/
protected void configureShell(Shell shell) {
super.configureShell(shell);
if (title != null)
shell.setText(title);
}
/* (non-Javadoc)
* Method declared on Dialog.
*/
protected void createButtonsForButtonBar(Composite parent) {
// create OK and Cancel buttons by default
okButton = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
//do this here because setting the text will set enablement on the ok button
text.setFocus();
if (value != null) {
text.setText(value);
text.selectAll();
}
}
/* (non-Javadoc)
* Method declared on Dialog.
*/
protected Control createDialogArea(Composite parent) {
// create composite
Composite composite = (Composite)super.createDialogArea(parent);
// create message
if (message != null) {
Label label = new Label(composite, SWT.WRAP);
label.setText(message);
GridData data = new GridData(
GridData.GRAB_HORIZONTAL |
GridData.GRAB_VERTICAL |
GridData.HORIZONTAL_ALIGN_FILL |
GridData.VERTICAL_ALIGN_CENTER);
data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);;
label.setLayoutData(data);
label.setFont(parent.getFont());
}
text= new Text(composite, SWT.SINGLE | SWT.BORDER);
text.setLayoutData(new GridData(
GridData.GRAB_HORIZONTAL |
GridData.HORIZONTAL_ALIGN_FILL));
text.addModifyListener(
new ModifyListener() {
public void modifyText(ModifyEvent e) {
validateInput();
}
}
);
+ text.setFont(parent.getFont());
errorMessageLabel = new Label(composite, SWT.NONE);
errorMessageLabel.setLayoutData(new GridData(
GridData.GRAB_HORIZONTAL |
GridData.HORIZONTAL_ALIGN_FILL));
errorMessageLabel.setFont(parent.getFont());
return composite;
}
/**
* Returns the error message label.
*
* @return the error message label
*/
protected Label getErrorMessageLabel() {
return errorMessageLabel;
}
/**
* Returns the ok button.
*
* @return the ok button
*/
protected Button getOkButton() {
return okButton;
}
/**
* Returns the text area.
*
* @return the text area
*/
protected Text getText() {
return text;
}
/**
* Returns the validator.
*
* @return the validator
*/
protected IInputValidator getValidator() {
return validator;
}
/**
* Returns the string typed into this input dialog.
*
* @return the input string
*/
public String getValue() {
return value;
}
/**
* Validates the input.
* <p>
* The default implementation of this framework method
* delegates the request to the supplied input validator object;
* if it finds the input invalid, the error message is displayed
* in the dialog's message line.
* This hook method is called whenever the text changes in the
* input field.
* </p>
*/
protected void validateInput() {
String errorMessage = null;
if (validator != null) {
errorMessage = validator.isValid(text.getText());
}
// Bug 16256: important not to treat "" (blank error) the same as null (no error)
errorMessageLabel.setText(errorMessage == null ? "" : errorMessage); //$NON-NLS-1$
okButton.setEnabled(errorMessage == null);
errorMessageLabel.getParent().update();
}
}
| true | true | protected Control createDialogArea(Composite parent) {
// create composite
Composite composite = (Composite)super.createDialogArea(parent);
// create message
if (message != null) {
Label label = new Label(composite, SWT.WRAP);
label.setText(message);
GridData data = new GridData(
GridData.GRAB_HORIZONTAL |
GridData.GRAB_VERTICAL |
GridData.HORIZONTAL_ALIGN_FILL |
GridData.VERTICAL_ALIGN_CENTER);
data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);;
label.setLayoutData(data);
label.setFont(parent.getFont());
}
text= new Text(composite, SWT.SINGLE | SWT.BORDER);
text.setLayoutData(new GridData(
GridData.GRAB_HORIZONTAL |
GridData.HORIZONTAL_ALIGN_FILL));
text.addModifyListener(
new ModifyListener() {
public void modifyText(ModifyEvent e) {
validateInput();
}
}
);
errorMessageLabel = new Label(composite, SWT.NONE);
errorMessageLabel.setLayoutData(new GridData(
GridData.GRAB_HORIZONTAL |
GridData.HORIZONTAL_ALIGN_FILL));
errorMessageLabel.setFont(parent.getFont());
return composite;
}
| protected Control createDialogArea(Composite parent) {
// create composite
Composite composite = (Composite)super.createDialogArea(parent);
// create message
if (message != null) {
Label label = new Label(composite, SWT.WRAP);
label.setText(message);
GridData data = new GridData(
GridData.GRAB_HORIZONTAL |
GridData.GRAB_VERTICAL |
GridData.HORIZONTAL_ALIGN_FILL |
GridData.VERTICAL_ALIGN_CENTER);
data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);;
label.setLayoutData(data);
label.setFont(parent.getFont());
}
text= new Text(composite, SWT.SINGLE | SWT.BORDER);
text.setLayoutData(new GridData(
GridData.GRAB_HORIZONTAL |
GridData.HORIZONTAL_ALIGN_FILL));
text.addModifyListener(
new ModifyListener() {
public void modifyText(ModifyEvent e) {
validateInput();
}
}
);
text.setFont(parent.getFont());
errorMessageLabel = new Label(composite, SWT.NONE);
errorMessageLabel.setLayoutData(new GridData(
GridData.GRAB_HORIZONTAL |
GridData.HORIZONTAL_ALIGN_FILL));
errorMessageLabel.setFont(parent.getFont());
return composite;
}
|
diff --git a/src/com/FedoraPlanet/Viewer/PlanetFedoraViewer.java b/src/com/FedoraPlanet/Viewer/PlanetFedoraViewer.java
index 6b6991f..7ec199d 100644
--- a/src/com/FedoraPlanet/Viewer/PlanetFedoraViewer.java
+++ b/src/com/FedoraPlanet/Viewer/PlanetFedoraViewer.java
@@ -1,37 +1,37 @@
/*
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 com.FedoraPlanet.Viewer;
import android.app.Activity;
import android.os.Bundle;
import org.apache.cordova.*;
public class PlanetFedoraViewer extends DroidGap
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
+ super.setIntegerProperty("loadUrlTimeoutValue", 60000);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index.html", 60000);
- super.setIntegerProperty("loadUrlTimeoutValue", 60000);
}
}
| false | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index.html", 60000);
super.setIntegerProperty("loadUrlTimeoutValue", 60000);
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("loadUrlTimeoutValue", 60000);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index.html", 60000);
}
|
diff --git a/src/main/java/com/lyndir/lhunath/snaplog/webapp/servlet/ImageServlet.java b/src/main/java/com/lyndir/lhunath/snaplog/webapp/servlet/ImageServlet.java
index 2b685ef..728a1b1 100644
--- a/src/main/java/com/lyndir/lhunath/snaplog/webapp/servlet/ImageServlet.java
+++ b/src/main/java/com/lyndir/lhunath/snaplog/webapp/servlet/ImageServlet.java
@@ -1,138 +1,139 @@
/*
* Copyright 2010, Maarten Billemont
*
* 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.lyndir.lhunath.snaplog.webapp.servlet;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import com.google.inject.Inject;
import com.lyndir.lhunath.lib.system.logging.Logger;
import com.lyndir.lhunath.snaplog.data.media.Album;
import com.lyndir.lhunath.snaplog.data.media.Media;
import com.lyndir.lhunath.snaplog.data.media.Media.Quality;
import com.lyndir.lhunath.snaplog.data.security.PermissionDeniedException;
import com.lyndir.lhunath.snaplog.data.security.SecurityToken;
import com.lyndir.lhunath.snaplog.data.user.User;
import com.lyndir.lhunath.snaplog.model.AlbumService;
import com.lyndir.lhunath.snaplog.model.UserService;
import com.lyndir.lhunath.snaplog.util.URLUtils;
import com.lyndir.lhunath.snaplog.webapp.SnaplogSession;
/**
* <h2>{@link ImageServlet}<br>
* <sub>[in short] (TODO).</sub></h2>
*
* <p>
* <i>Jan 19, 2010</i>
* </p>
*
* @author lhunath
*/
public class ImageServlet extends HttpServlet {
final Logger logger = Logger.get( ImageServlet.class );
/**
* Context-relative path of this servlet.
*/
public static final String PATH = "/img";
private static final String PARAM_USER = "u";
private static final String PARAM_ALBUM = "a";
private static final String PARAM_MEDIA = "m";
private static final String PARAM_QUALITY = "q";
private final UserService userService;
private final AlbumService albumService;
/**
* @param userService See {@link UserService}
* @param albumService See {@link AlbumService}
*/
@Inject
public ImageServlet(final UserService userService, final AlbumService albumService) {
this.userService = userService;
this.albumService = albumService;
}
/**
* Obtain a context-relative path to the {@link ImageServlet} such that it will render the given media at the given
* quality.
*
* @param media The media that should be shown at the given URL.
* @param quality The quality to show the media at.
*
* @return A context-relative URL.
*/
public static String getContextRelativePathFor(final Media media, final Quality quality) {
checkNotNull( media, "Given media must not be null." );
checkNotNull( quality, "Given quality must not be null." );
Album album = media.getAlbum();
User user = album.getOwnerProfile().getUser();
StringBuilder path = new StringBuilder( PATH ).append( '?' );
path.append( PARAM_USER ).append( '=' ).append( URLUtils.encode( user.getUserName() ) ).append( '&' );
path.append( PARAM_ALBUM ).append( '=' ).append( URLUtils.encode( album.getName() ) ).append( '&' );
path.append( PARAM_MEDIA ).append( '=' ).append( URLUtils.encode( media.getName() ) ).append( '&' );
path.append( PARAM_QUALITY ).append( '=' ).append( URLUtils.encode( quality.getName() ) ).append( '&' );
return path.substring( 0, path.length() - 1 );
}
/**
* {@inheritDoc}
*/
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
try {
String userName = req.getParameter( PARAM_USER );
String albumName = req.getParameter( PARAM_ALBUM );
String mediaName = req.getParameter( PARAM_MEDIA );
String qualityName = req.getParameter( PARAM_QUALITY );
SecurityToken token = SnaplogSession.get().newToken();
logger.dbg( "Getting image for media: %s, in album: %s, of user: %s, at quality: %s", //
mediaName, albumName, userName, qualityName );
User user = checkNotNull( userService.findUserWithUserName( userName ), //
"No user named: %s.", userName );
Album album = checkNotNull( albumService.findAlbumWithName( token, user, albumName ), //
"User: %s, has no album named: %s.", user, albumName );
Media media = checkNotNull( albumService.findMediaWithName( token, album, mediaName ), //
"Album: %s, has no media named: %s.", album, mediaName );
- Quality quality = checkNotNull( Quality.findQualityWithName( qualityName ) );
+ Quality quality = checkNotNull( Quality.findQualityWithName( qualityName ), //
+ "No quality named: %s.", qualityName );
logger.dbg( "Resolved image request for: %s, in: %s, of: %s, at: %s", //
media, album, user, quality );
resp.sendRedirect( albumService.getResourceURL( token, media, quality ).toExternalForm() );
}
catch (PermissionDeniedException e) {
resp.sendError( HttpServletResponse.SC_FORBIDDEN, e.getLocalizedMessage() );
}
}
}
| true | true | protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
try {
String userName = req.getParameter( PARAM_USER );
String albumName = req.getParameter( PARAM_ALBUM );
String mediaName = req.getParameter( PARAM_MEDIA );
String qualityName = req.getParameter( PARAM_QUALITY );
SecurityToken token = SnaplogSession.get().newToken();
logger.dbg( "Getting image for media: %s, in album: %s, of user: %s, at quality: %s", //
mediaName, albumName, userName, qualityName );
User user = checkNotNull( userService.findUserWithUserName( userName ), //
"No user named: %s.", userName );
Album album = checkNotNull( albumService.findAlbumWithName( token, user, albumName ), //
"User: %s, has no album named: %s.", user, albumName );
Media media = checkNotNull( albumService.findMediaWithName( token, album, mediaName ), //
"Album: %s, has no media named: %s.", album, mediaName );
Quality quality = checkNotNull( Quality.findQualityWithName( qualityName ) );
logger.dbg( "Resolved image request for: %s, in: %s, of: %s, at: %s", //
media, album, user, quality );
resp.sendRedirect( albumService.getResourceURL( token, media, quality ).toExternalForm() );
}
catch (PermissionDeniedException e) {
resp.sendError( HttpServletResponse.SC_FORBIDDEN, e.getLocalizedMessage() );
}
}
| protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
try {
String userName = req.getParameter( PARAM_USER );
String albumName = req.getParameter( PARAM_ALBUM );
String mediaName = req.getParameter( PARAM_MEDIA );
String qualityName = req.getParameter( PARAM_QUALITY );
SecurityToken token = SnaplogSession.get().newToken();
logger.dbg( "Getting image for media: %s, in album: %s, of user: %s, at quality: %s", //
mediaName, albumName, userName, qualityName );
User user = checkNotNull( userService.findUserWithUserName( userName ), //
"No user named: %s.", userName );
Album album = checkNotNull( albumService.findAlbumWithName( token, user, albumName ), //
"User: %s, has no album named: %s.", user, albumName );
Media media = checkNotNull( albumService.findMediaWithName( token, album, mediaName ), //
"Album: %s, has no media named: %s.", album, mediaName );
Quality quality = checkNotNull( Quality.findQualityWithName( qualityName ), //
"No quality named: %s.", qualityName );
logger.dbg( "Resolved image request for: %s, in: %s, of: %s, at: %s", //
media, album, user, quality );
resp.sendRedirect( albumService.getResourceURL( token, media, quality ).toExternalForm() );
}
catch (PermissionDeniedException e) {
resp.sendError( HttpServletResponse.SC_FORBIDDEN, e.getLocalizedMessage() );
}
}
|
diff --git a/trunk/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java b/trunk/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java
index f1c9e9ab..61b0309b 100644
--- a/trunk/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java
+++ b/trunk/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java
@@ -1,32 +1,32 @@
package org.sakaiproject.springframework.orm.hibernate.dialect.db2;
import org.hibernate.dialect.DB2Dialect;
import java.sql.Types;
/**
* Created by IntelliJ IDEA.
* User: jbush
* Date: May 23, 2007
* Time: 4:20:48 PM
* To change this template use File | Settings | File Templates.
*/
public class DB2Dialect9 extends DB2Dialect {
public DB2Dialect9() {
super();
registerColumnType( Types.VARBINARY, "LONG VARCHAR FOR BIT DATA" );
registerColumnType( Types.VARCHAR, "clob(1000000000)" );
registerColumnType( Types.VARCHAR, 1000000000, "clob($l)" );
- registerColumnType( Types.VARCHAR, 32704, "varchar($l)" );
+ registerColumnType( Types.VARCHAR, 3999, "varchar($l)" );
//according to the db2 docs the max for clob and blob should be 2147438647, but this isn't working for me
// possibly something to do with how my database is configured ?
registerColumnType( Types.CLOB, "clob(1000000000)" );
registerColumnType( Types.CLOB, 1000000000, "clob($l)" );
registerColumnType( Types.BLOB, "blob(1000000000)" );
registerColumnType( Types.BLOB, 1000000000, "blob($l)" );
}
}
| true | true | public DB2Dialect9() {
super();
registerColumnType( Types.VARBINARY, "LONG VARCHAR FOR BIT DATA" );
registerColumnType( Types.VARCHAR, "clob(1000000000)" );
registerColumnType( Types.VARCHAR, 1000000000, "clob($l)" );
registerColumnType( Types.VARCHAR, 32704, "varchar($l)" );
//according to the db2 docs the max for clob and blob should be 2147438647, but this isn't working for me
// possibly something to do with how my database is configured ?
registerColumnType( Types.CLOB, "clob(1000000000)" );
registerColumnType( Types.CLOB, 1000000000, "clob($l)" );
registerColumnType( Types.BLOB, "blob(1000000000)" );
registerColumnType( Types.BLOB, 1000000000, "blob($l)" );
}
| public DB2Dialect9() {
super();
registerColumnType( Types.VARBINARY, "LONG VARCHAR FOR BIT DATA" );
registerColumnType( Types.VARCHAR, "clob(1000000000)" );
registerColumnType( Types.VARCHAR, 1000000000, "clob($l)" );
registerColumnType( Types.VARCHAR, 3999, "varchar($l)" );
//according to the db2 docs the max for clob and blob should be 2147438647, but this isn't working for me
// possibly something to do with how my database is configured ?
registerColumnType( Types.CLOB, "clob(1000000000)" );
registerColumnType( Types.CLOB, 1000000000, "clob($l)" );
registerColumnType( Types.BLOB, "blob(1000000000)" );
registerColumnType( Types.BLOB, 1000000000, "blob($l)" );
}
|
diff --git a/src/main/java/edu/sc/seis/TauP/TauP_Wavefront.java b/src/main/java/edu/sc/seis/TauP/TauP_Wavefront.java
index dc4a69e..df072fa 100644
--- a/src/main/java/edu/sc/seis/TauP/TauP_Wavefront.java
+++ b/src/main/java/edu/sc/seis/TauP/TauP_Wavefront.java
@@ -1,321 +1,321 @@
package edu.sc.seis.TauP;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OptionalDataException;
import java.io.PrintWriter;
import java.io.StreamCorruptedException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class TauP_Wavefront extends TauP_Path {
int numRays = 30;
float timeStep = 100;
boolean separateFilesByTime = false;
boolean negDistance = false;
Map<SeismicPhase, Map<Float, List<TimeDist>>> result;
@Override
public void calculate(double degrees) throws TauModelException {
depthCorrect(getSourceDepth());
recalcPhases();
// ignore degrees as we need a suite of distances
result = calcIsochron();
}
@Override
public void printUsage() {
printStdUsage();
System.out.println("--rays num -- number of raypaths/distances to sample.");
System.out.println("--timestep num -- steps in time (seconds) for output.");
System.out.println("--timefiles -- outputs each time into a separate .ps file within the gmt script.");
System.out.println("--negdist -- outputs negative distance as well so wavefronts are in both halves.");
printStdUsageTail();
}
@Override
public void printScriptBeginning(PrintWriter out) throws IOException {
if (!gmtScript) {
return;
}
if (outFile == null) {
outFile = "taup_wavefront.gmt";
psFile = "taup_wavefront.ps";
}
super.printScriptBeginning(out);
}
@Override
public void printResult(PrintWriter out) throws IOException {
String byTimePsFile = psFile;
double radiusOfEarth = tModDepth.getRadiusOfEarth();
HashSet<Float> keySet = new HashSet<Float>();
for (SeismicPhase phase : result.keySet()) {
Map<Float, List<TimeDist>> phaseResult = result.get(phase);
keySet.addAll(phaseResult.keySet());
}
List<Float> keys = new ArrayList<Float>();
keys.addAll(keySet);
Collections.sort(keys);
Float lastTime = keys.get(keys.size() - 1);
int numDigits = 1;
String formatStr = "0";
while (Math.pow(10, numDigits) < lastTime) {
numDigits++;
formatStr += "0";
}
if (lastTime < 1) {
formatStr += ".0";
int fracDigits = 0;
while (Math.pow(10, fracDigits) > lastTime) {
fracDigits--;
formatStr += "0";
}
}
DecimalFormat format = new DecimalFormat(formatStr);
PrintWriter timeOut = out;
for (Float time : keys) {
if (separateFilesByTime) {
String psFileBase = psFile;
- if (psFile.endsWith(".ps")) {
+ if (gmtScript && psFile.endsWith(".ps")) {
psFileBase = psFile.substring(0, psFile.length() - 3);
}
String timeExt = "_" + format.format(time);
byTimePsFile = psFileBase + timeExt + ".ps";
String timeOutName = outFile+timeExt;
if (outFile.endsWith(".gmt")) {
- timeOutName = outFile.substring(0, psFile.length() - 3)+timeExt + ".gmt";
+ timeOutName = outFile.substring(0, outFile.length() - 4)+timeExt + ".gmt";
}
if (timeOut != null && timeOut != out) {timeOut.close();}
timeOut = new PrintWriter(new BufferedWriter(new FileWriter(timeOutName)));
- printScriptBeginning(timeOut, byTimePsFile);
+ if (gmtScript) {printScriptBeginning(timeOut, byTimePsFile);}
}
if (gmtScript) {
timeOut.println("# timestep = " + time);
timeOut.println("psxy -P -R -K -O -Wblue -JP -m -A >> " + byTimePsFile + " <<END");
}
for (SeismicPhase phase : result.keySet()) {
Map<Float, List<TimeDist>> phaseResult = result.get(phase);
List<TimeDist> wavefront = phaseResult.get(time);
if (wavefront == null || wavefront.size() == 0) {
continue;
}
timeOut.println("> " + phase.getName() + " at " + time + " seconds");
Collections.sort(wavefront, new Comparator<TimeDist>() {
// @Override
public int compare(TimeDist arg0, TimeDist arg1) {
return new Double(arg0.getP()).compareTo(arg1.getP());
}
});
for (TimeDist td : wavefront) {
timeOut.println(Outputs.formatDistance(td.getDistDeg()) + " "
+ Outputs.formatDepth(radiusOfEarth - td.getDepth()) + " " + Outputs.formatTime(time) + " "
+ Outputs.formatRayParam(td.getP()));
}
if (isNegDistance()) {
timeOut.write("> " + phase.getName() + " at " + time + " seconds (neg distance)\n");
for (TimeDist td : wavefront) {
timeOut.println(Outputs.formatDistance(-1*td.getDistDeg()) + " "
+ Outputs.formatDepth(radiusOfEarth - td.getDepth()) + " " + Outputs.formatTime(time) + " "
+ Outputs.formatRayParam(td.getP()));
}
}
}
if (gmtScript) {
timeOut.println("END");
if (separateFilesByTime) {
timeOut.println("psxy -P -R -O -JP -m -A >> " + byTimePsFile + " <<END");
timeOut.println("END");
}
}
}
if (gmtScript && out != timeOut) {
out.println("psxy -P -R -O -JP -m -A >> " + byTimePsFile + " <<END");
out.println("END");
}
timeOut.flush();
out.flush();
}
public Map<SeismicPhase, Map<Float, List<TimeDist>>> calcIsochron() {
Map<SeismicPhase, Map<Float, List<TimeDist>>> resultOut = new HashMap<SeismicPhase, Map<Float, List<TimeDist>>>();
SeismicPhase phase;
clearArrivals();
for (int phaseNum = 0; phaseNum < phases.size(); phaseNum++) {
phase = phases.get(phaseNum);
if (verbose) {
System.out.println("Work on " + phase.getName());
}
double minDist = phase.getMinDistanceDeg();
double maxDist = phase.getMaxDistanceDeg();
double deltaDist = (maxDist - minDist) / (numRays - 1);
degrees = minDist;
List<Arrival> allArrival = new ArrayList<Arrival>();
for (int r = 0; r < getNumRays(); r++) {
degrees = minDist + r * deltaDist;
List<Arrival> phaseArrivals = phase.calcTime(degrees);
allArrival.addAll(phaseArrivals);
}
Map<Float, List<TimeDist>> out = new HashMap<Float, List<TimeDist>>();
resultOut.put(phase, out);
boolean done = false;
float timeVal = 0;
while (!done) {
done = true;
timeVal += timeStep;
if (verbose) {
System.out.println("Time " + timeVal + " for " + phase.getName() + " " + allArrival.size());
}
for (Arrival arrival : allArrival) {
TimeDist[] path = arrival.getPath();
for (int i = 0; i < path.length; i++) {
if (path[i].getTime() <= timeVal && i < path.length - 1 && timeVal < path[i + 1].getTime()) {
TimeDist interp = interp(path[i], path[i + 1], timeVal);
List<TimeDist> tdList = out.get(timeVal);
if (tdList == null) {
tdList = new ArrayList<TimeDist>();
out.put(timeVal, tdList);
}
tdList.add(interp);
done = false;
break;
}
}
}
}
}
return resultOut;
}
TimeDist interp(TimeDist x, TimeDist y, float t) {
// this is probably wrong...
return new TimeDist(x.getP(),
t,
Theta.linInterp(x.getTime(), y.getTime(), x.getDistRadian(), y.getDistRadian(), t),
Theta.linInterp(x.getTime(), y.getTime(), x.getDepth(), y.getDepth(), t));
}
public void setNumRays(int numRays) {
this.numRays = numRays;
}
public int getNumRays() {
return numRays;
}
public float getTimeStep() {
return timeStep;
}
public void setTimeStep(float timeStep) {
this.timeStep = timeStep;
}
public boolean isSeparateFilesByTime() {
return separateFilesByTime;
}
public void setSeparateFilesByTime(boolean separateFilesByTime) {
this.separateFilesByTime = separateFilesByTime;
}
public boolean isNegDistance() {
return negDistance;
}
public void setNegDistance(boolean negDistance) {
this.negDistance = negDistance;
}
public String[] parseCmdLineArgs(String[] args) throws IOException {
int i = 0;
String[] leftOverArgs;
int numNoComprendoArgs = 0;
leftOverArgs = super.parseCmdLineArgs(args);
String[] noComprendoArgs = new String[leftOverArgs.length];
while (i < leftOverArgs.length) {
if (dashEquals("gmt", leftOverArgs[i])) {
gmtScript = true;
} else if (dashEquals("timefiles", leftOverArgs[i])) {
separateFilesByTime = true;
} else if (dashEquals("negdist", leftOverArgs[i])) {
negDistance = true;
} else if (dashEquals("rays", leftOverArgs[i]) && i < leftOverArgs.length - 1) {
setNumRays(Integer.parseInt(leftOverArgs[i + 1]));
i++;
} else if (dashEquals("timestep", leftOverArgs[i]) && i < leftOverArgs.length - 1) {
setTimeStep(Float.parseFloat(leftOverArgs[i + 1]));
i++;
} else if (dashEquals("mapwidth", leftOverArgs[i]) && i < leftOverArgs.length - 1) {
setMapWidth(Float.parseFloat(leftOverArgs[i + 1]));
i++;
} else if (dashEquals("help", leftOverArgs[i])) {
noComprendoArgs[numNoComprendoArgs++] = leftOverArgs[i];
} else {
noComprendoArgs[numNoComprendoArgs++] = leftOverArgs[i];
}
i++;
}
if (numNoComprendoArgs > 0) {
String[] temp = new String[numNoComprendoArgs];
System.arraycopy(noComprendoArgs, 0, temp, 0, numNoComprendoArgs);
return temp;
} else {
return new String[0];
}
}
/**
* Allows TauP_Isochron to run as an application. Creates an instance of
* TauP_Isochron. .
*/
public static void main(String[] args) throws FileNotFoundException, IOException, StreamCorruptedException,
ClassNotFoundException, OptionalDataException {
boolean doInteractive = true;
try {
TauP_Wavefront tauP_wavefront = new TauP_Wavefront();
tauP_wavefront.outFile = "taup_wavefront.gmt";
String[] noComprendoArgs = tauP_wavefront.parseCmdLineArgs(args);
printNoComprendoArgs(noComprendoArgs);
for (int i = 0; i < args.length; i++) {
if (dashEquals("h", args[i])) {
doInteractive = false;
}
}
if (tauP_wavefront.DEBUG) {
System.out.println("Done reading " + tauP_wavefront.modelName);
}
tauP_wavefront.init();
if (doInteractive) {
tauP_wavefront.start();
} else {
/* enough info given on cmd line, so just do one calc. */
tauP_wavefront.depthCorrect(Double.valueOf(tauP_wavefront.toolProps.getProperty("taup.source.depth",
"0.0")).doubleValue());
tauP_wavefront.calculate(tauP_wavefront.degrees);
tauP_wavefront.printResult(tauP_wavefront.getWriter());
}
tauP_wavefront.destroy();
} catch(TauModelException e) {
System.out.println("Caught TauModelException: " + e.getMessage());
e.printStackTrace();
} catch(TauPException e) {
System.out.println("Caught TauPException: " + e.getMessage());
e.printStackTrace();
}
}
}
| false | true | public void printResult(PrintWriter out) throws IOException {
String byTimePsFile = psFile;
double radiusOfEarth = tModDepth.getRadiusOfEarth();
HashSet<Float> keySet = new HashSet<Float>();
for (SeismicPhase phase : result.keySet()) {
Map<Float, List<TimeDist>> phaseResult = result.get(phase);
keySet.addAll(phaseResult.keySet());
}
List<Float> keys = new ArrayList<Float>();
keys.addAll(keySet);
Collections.sort(keys);
Float lastTime = keys.get(keys.size() - 1);
int numDigits = 1;
String formatStr = "0";
while (Math.pow(10, numDigits) < lastTime) {
numDigits++;
formatStr += "0";
}
if (lastTime < 1) {
formatStr += ".0";
int fracDigits = 0;
while (Math.pow(10, fracDigits) > lastTime) {
fracDigits--;
formatStr += "0";
}
}
DecimalFormat format = new DecimalFormat(formatStr);
PrintWriter timeOut = out;
for (Float time : keys) {
if (separateFilesByTime) {
String psFileBase = psFile;
if (psFile.endsWith(".ps")) {
psFileBase = psFile.substring(0, psFile.length() - 3);
}
String timeExt = "_" + format.format(time);
byTimePsFile = psFileBase + timeExt + ".ps";
String timeOutName = outFile+timeExt;
if (outFile.endsWith(".gmt")) {
timeOutName = outFile.substring(0, psFile.length() - 3)+timeExt + ".gmt";
}
if (timeOut != null && timeOut != out) {timeOut.close();}
timeOut = new PrintWriter(new BufferedWriter(new FileWriter(timeOutName)));
printScriptBeginning(timeOut, byTimePsFile);
}
if (gmtScript) {
timeOut.println("# timestep = " + time);
timeOut.println("psxy -P -R -K -O -Wblue -JP -m -A >> " + byTimePsFile + " <<END");
}
for (SeismicPhase phase : result.keySet()) {
Map<Float, List<TimeDist>> phaseResult = result.get(phase);
List<TimeDist> wavefront = phaseResult.get(time);
if (wavefront == null || wavefront.size() == 0) {
continue;
}
timeOut.println("> " + phase.getName() + " at " + time + " seconds");
Collections.sort(wavefront, new Comparator<TimeDist>() {
// @Override
public int compare(TimeDist arg0, TimeDist arg1) {
return new Double(arg0.getP()).compareTo(arg1.getP());
}
});
for (TimeDist td : wavefront) {
timeOut.println(Outputs.formatDistance(td.getDistDeg()) + " "
+ Outputs.formatDepth(radiusOfEarth - td.getDepth()) + " " + Outputs.formatTime(time) + " "
+ Outputs.formatRayParam(td.getP()));
}
if (isNegDistance()) {
timeOut.write("> " + phase.getName() + " at " + time + " seconds (neg distance)\n");
for (TimeDist td : wavefront) {
timeOut.println(Outputs.formatDistance(-1*td.getDistDeg()) + " "
+ Outputs.formatDepth(radiusOfEarth - td.getDepth()) + " " + Outputs.formatTime(time) + " "
+ Outputs.formatRayParam(td.getP()));
}
}
}
if (gmtScript) {
timeOut.println("END");
if (separateFilesByTime) {
timeOut.println("psxy -P -R -O -JP -m -A >> " + byTimePsFile + " <<END");
timeOut.println("END");
}
}
}
if (gmtScript && out != timeOut) {
out.println("psxy -P -R -O -JP -m -A >> " + byTimePsFile + " <<END");
out.println("END");
}
timeOut.flush();
out.flush();
}
| public void printResult(PrintWriter out) throws IOException {
String byTimePsFile = psFile;
double radiusOfEarth = tModDepth.getRadiusOfEarth();
HashSet<Float> keySet = new HashSet<Float>();
for (SeismicPhase phase : result.keySet()) {
Map<Float, List<TimeDist>> phaseResult = result.get(phase);
keySet.addAll(phaseResult.keySet());
}
List<Float> keys = new ArrayList<Float>();
keys.addAll(keySet);
Collections.sort(keys);
Float lastTime = keys.get(keys.size() - 1);
int numDigits = 1;
String formatStr = "0";
while (Math.pow(10, numDigits) < lastTime) {
numDigits++;
formatStr += "0";
}
if (lastTime < 1) {
formatStr += ".0";
int fracDigits = 0;
while (Math.pow(10, fracDigits) > lastTime) {
fracDigits--;
formatStr += "0";
}
}
DecimalFormat format = new DecimalFormat(formatStr);
PrintWriter timeOut = out;
for (Float time : keys) {
if (separateFilesByTime) {
String psFileBase = psFile;
if (gmtScript && psFile.endsWith(".ps")) {
psFileBase = psFile.substring(0, psFile.length() - 3);
}
String timeExt = "_" + format.format(time);
byTimePsFile = psFileBase + timeExt + ".ps";
String timeOutName = outFile+timeExt;
if (outFile.endsWith(".gmt")) {
timeOutName = outFile.substring(0, outFile.length() - 4)+timeExt + ".gmt";
}
if (timeOut != null && timeOut != out) {timeOut.close();}
timeOut = new PrintWriter(new BufferedWriter(new FileWriter(timeOutName)));
if (gmtScript) {printScriptBeginning(timeOut, byTimePsFile);}
}
if (gmtScript) {
timeOut.println("# timestep = " + time);
timeOut.println("psxy -P -R -K -O -Wblue -JP -m -A >> " + byTimePsFile + " <<END");
}
for (SeismicPhase phase : result.keySet()) {
Map<Float, List<TimeDist>> phaseResult = result.get(phase);
List<TimeDist> wavefront = phaseResult.get(time);
if (wavefront == null || wavefront.size() == 0) {
continue;
}
timeOut.println("> " + phase.getName() + " at " + time + " seconds");
Collections.sort(wavefront, new Comparator<TimeDist>() {
// @Override
public int compare(TimeDist arg0, TimeDist arg1) {
return new Double(arg0.getP()).compareTo(arg1.getP());
}
});
for (TimeDist td : wavefront) {
timeOut.println(Outputs.formatDistance(td.getDistDeg()) + " "
+ Outputs.formatDepth(radiusOfEarth - td.getDepth()) + " " + Outputs.formatTime(time) + " "
+ Outputs.formatRayParam(td.getP()));
}
if (isNegDistance()) {
timeOut.write("> " + phase.getName() + " at " + time + " seconds (neg distance)\n");
for (TimeDist td : wavefront) {
timeOut.println(Outputs.formatDistance(-1*td.getDistDeg()) + " "
+ Outputs.formatDepth(radiusOfEarth - td.getDepth()) + " " + Outputs.formatTime(time) + " "
+ Outputs.formatRayParam(td.getP()));
}
}
}
if (gmtScript) {
timeOut.println("END");
if (separateFilesByTime) {
timeOut.println("psxy -P -R -O -JP -m -A >> " + byTimePsFile + " <<END");
timeOut.println("END");
}
}
}
if (gmtScript && out != timeOut) {
out.println("psxy -P -R -O -JP -m -A >> " + byTimePsFile + " <<END");
out.println("END");
}
timeOut.flush();
out.flush();
}
|
diff --git a/src/main/java/plugins/WebOfTrust/pages/ShowIdentityController.java b/src/main/java/plugins/WebOfTrust/pages/ShowIdentityController.java
index acfcc53..b34c851 100644
--- a/src/main/java/plugins/WebOfTrust/pages/ShowIdentityController.java
+++ b/src/main/java/plugins/WebOfTrust/pages/ShowIdentityController.java
@@ -1,385 +1,386 @@
package plugins.WebOfTrust.pages;
import java.io.IOException;
import java.net.URI;
import java.util.SortedSet;
import java.util.TreeSet;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.ReadableIndex;
import plugins.WebOfTrust.WebOfTrust;
import plugins.WebOfTrust.datamodel.IContext;
import plugins.WebOfTrust.datamodel.IEdge;
import plugins.WebOfTrust.datamodel.IVertex;
import plugins.WebOfTrust.datamodel.Rel;
import plugins.WebOfTrust.fcp.SetTrust;
import freenet.client.HighLevelSimpleClient;
import freenet.clients.http.LinkEnabledCallback;
import freenet.clients.http.PageNode;
import freenet.clients.http.Toadlet;
import freenet.clients.http.ToadletContext;
import freenet.clients.http.ToadletContextClosedException;
import freenet.support.HTMLNode;
import freenet.support.api.HTTPRequest;
public class ShowIdentityController extends Toadlet implements LinkEnabledCallback {
private final String path;
private final GraphDatabaseService db;
// TODO: reference for ReadableIndex also not
// changeable during the whole lifetime?
private ReadableIndex<Node> nodeIndex;
public ShowIdentityController(HighLevelSimpleClient client, String URLPath, GraphDatabaseService db) {
super(client);
this.db = db;
this.path = URLPath;
// TODO: can the nodeIndex be referenced like WebOfTrust.nodeIndex?
nodeIndex = db.index().getNodeAutoIndexer().getAutoIndex();
}
public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if(WebOfTrust.allowFullAccessOnly && !ctx.isAllowedFullAccess()) {
writeReply(ctx, 403, "text/plain", "forbidden", "Your host is not allowed to access this page.");
return;
}
PageNode mPageNode = ctx.getPageMaker().getPageNode("LCWoT - Identity details", true, true, ctx);
mPageNode.addCustomStyleSheet(WebOfTrust.basePath + "/WebOfTrust.css");
HTMLNode contentDiv = new HTMLNode("div");
contentDiv.addAttribute("id", "WebOfTrust");
try {
//get the query param
// FIXME: maybe better to use
// ^ request.getPartAsStringFailsafe(name, maxlength)
final String id = request.getParam("id");
// get the identity vertex & properties
final Node identity = nodeIndex.get(IVertex.ID, id).getSingle();
final boolean is_own_identity = identity.hasProperty(IVertex.OWN_IDENTITY);
final SortedSet<String> sortedKeys = new TreeSet<String>();
for(String key : identity.getPropertyKeys()) sortedKeys.add(key);
// FIXME: just for testing.
// <br /> should be div margin/padding or something i guess
// if ^ stylesheet is correctly set up the <b> tags can become h1 and h2 again.
contentDiv.addChild("br");
contentDiv.addChild("b", "Here are the details of the identity");
contentDiv.addChild("br");
contentDiv.addChild("br");
HTMLNode form = new HTMLNode("form");
form.addAttribute("action", "#");
form.addAttribute("method", "post");
HTMLNode input = new HTMLNode("input");
input.addAttribute("type", "hidden");
input.addAttribute("name", "action");
input.addAttribute("value", "modify_properties");
form.addChild(input);
input = new HTMLNode("input");
input.addAttribute("type", "hidden");
input.addAttribute("name", "identity");
input.addAttribute("value", id);
form.addChild(input);
HTMLNode table = new HTMLNode("table");
HTMLNode tr = new HTMLNode("tr");
tr.addChild("th", "Name");
tr.addChild("th", "Value");
table.addChild(tr);
// generic properties associated with this identity in the graph store
int property_index = 0;
for(String key : sortedKeys) {
Object value = identity.getProperty(key);
if (is_own_identity) {
table.addChild(getKeyPairRow(key, value.toString(), property_index));
}
else {
tr = new HTMLNode("tr");
tr.addChild("td", key);
tr.addChild("td", value.toString());
table.addChild(tr);
}
property_index += 1;
}
if (is_own_identity) {
// extra empty property value pair
table.addChild(getKeyPairRow("", "", property_index));
form.addChild(table);
// submit button
input = new HTMLNode("input");
input.addAttribute("type", "submit");
input.addAttribute("value", "Modify properties");
form.addChild(input);
} else {
form.addChild(table);
}
contentDiv.addChild(form);
// display available contexts
HTMLNode contextDiv = new HTMLNode("div");
contextDiv.addChild("br");
contextDiv.addChild("b", "Contexts");
contextDiv.addChild("br");
contextDiv.addChild("br");
HTMLNode list = new HTMLNode("ul");
for(Relationship rel : identity.getRelationships(Direction.OUTGOING, Rel.HAS_CONTEXT)) {
list.addChild("li", (String) rel.getEndNode().getProperty(IContext.NAME));
}
contentDiv.addChild(contextDiv.addChild(list));
// allow specifying an updated trust value
contentDiv.addChild("br");
contentDiv.addChild("b", "Local trust assignments to this identity:");
contentDiv.addChild("br");
contentDiv.addChild("br");
for(Node own_vertex : nodeIndex.get(IVertex.OWN_IDENTITY, true)) {
byte current_trust_value = 0;
String current_comment = "";
for(Relationship edge : own_vertex.getRelationships(Direction.OUTGOING, Rel.TRUSTS)) {
if (edge.getEndNode().equals(identity)) {
current_trust_value = (Byte) edge.getProperty(IEdge.SCORE);
current_comment = (String) edge.getProperty(IEdge.COMMENT);
// TODO: add a break; here? not exactly sure what the goal of this is.
}
}
form = new HTMLNode("form");
form.addAttribute("method", "post");
// TODO: why not use # here like above?
form.addAttribute("action", WebOfTrust.basePath+"/ShowIdentity?id="+id);
form.addAttribute("method", "post");
HTMLNode fieldset = new HTMLNode("fieldset");
fieldset.addChild("legend", (String) own_vertex.getProperty(IVertex.NAME));
fieldset.addChild(getInput("hidden", "action", "set_trust"));
fieldset.addChild(getInput("hidden", "identity_id", id));
fieldset.addChild(getInput("hidden", "own_identity_id", (String) own_vertex.getProperty(IVertex.ID)));
fieldset.addChild("span", "Trust: ");
fieldset.addChild(getInput("number", "trust_value", Byte.toString(current_trust_value)));
fieldset.addChild("span", "Comment: ");
fieldset.addChild(getInput("text", "trust_comment", current_comment));
fieldset.addChild(getInput("submit", "", "Update"));
form.addChild(fieldset);
contentDiv.addChild(form);
}
// explicit trust relations assigned by this identity
contentDiv.addChild("br");
contentDiv.addChild("b", "Explicit trust relations exposed by this identity:");
contentDiv.addChild("br");
contentDiv.addChild("br");
table = new HTMLNode("table");
tr = new HTMLNode("tr");
tr.addChild("th", "nr.");
tr.addChild("th", "identity");
tr.addChild("th", "Trust");
tr.addChild("th", "Comment");
tr.addChild("th", "action");
table.addChild(tr);
int i = 1;
HTMLNode link;
for(Relationship edge : identity.getRelationships(Direction.OUTGOING, Rel.TRUSTS)) {
if (edge.hasProperty(IEdge.SCORE) && edge.hasProperty(IEdge.COMMENT)) {
byte trustValue = (Byte) edge.getProperty(IEdge.SCORE);
String trustComment = (String) edge.getProperty(IEdge.COMMENT);
String peerName;
Node peer_identity = edge.getEndNode();
if (peer_identity.hasProperty(IVertex.NAME)) {
peerName = (String) peer_identity.getProperty(IVertex.NAME);
} else {
peerName = "(Not yet downloaded)";
}
String peerID = (String) peer_identity.getProperty(IVertex.ID);
link = new HTMLNode("a", peerName+" ("+peerID+")");
link.addAttribute("href", WebOfTrust.basePath+"/ShowIdentity?id="+peerID);
link.addAttribute("name", Integer.toString(i));
tr = new HTMLNode("tr");
tr.addChild("td", Integer.toString(i));
tr.addChild(new HTMLNode("td").addChild(link));
tr.addChild("td", Integer.toString(trustValue));
tr.addChild("td", trustComment);
if (identity.hasProperty(IVertex.OWN_IDENTITY)) {
// identity we are displaying is a local one, thus display additional options!
form = new HTMLNode("form");
form.addAttribute("action", WebOfTrust.basePath+"/ShowIdentity?id="+id + "#"+(i-1));
form.addAttribute("method", "post");
form.addChild(getInput("submit", "", "Remove"));
form.addChild(getInput("hidden", "action", "remove_edge"));
form.addChild(getInput("hidden", "edge_id", Long.toString(edge.getId())));
tr.addChild(new HTMLNode("td").addChild(form));
} else {
tr.addChild("td");
}
table.addChild(tr);
i += 1;
}
}
contentDiv.addChild(table);
// explicit trust relations given by others
contentDiv.addChild("br");
contentDiv.addChild("b", "Explicit trust relations given by others to this identity:");
contentDiv.addChild("br");
contentDiv.addChild("br");
table = new HTMLNode("table");
tr = new HTMLNode("tr");
tr.addChild("th", "nr.");
tr.addChild("th", "identity");
tr.addChild("th", "Trust");
tr.addChild("th", "Comment");
table.addChild(tr);
i = 1;
for(Relationship edge : identity.getRelationships(Direction.INCOMING, Rel.TRUSTS)) {
Node peer_identity = edge.getStartNode();
byte trustValue = (Byte) edge.getProperty(IEdge.SCORE);
String trustComment = (String) edge.getProperty(IEdge.COMMENT);
String peerName;
try {
peerName = (String) peer_identity.getProperty(IVertex.NAME);
} catch(org.neo4j.graphdb.NotFoundException e) {
peerName = "... not retrieved yet ...";
}
String peerID = (String) peer_identity.getProperty(IVertex.ID);
+ tr = new HTMLNode("tr");
link = new HTMLNode("a", peerName+" ("+peerID+")");
link.addAttribute("href", WebOfTrust.basePath+"/ShowIdentity?id="+peerID);
tr.addChild("td", Integer.toString(i));
tr.addChild(new HTMLNode("td").addChild(link));
tr.addChild("td", Byte.toString(trustValue));
tr.addChild("td", trustComment);
table.addChild(tr);
i += 1;
}
contentDiv.addChild(table);
mPageNode.content.addChild(contentDiv);
// finally send the request
writeReply(ctx, 200, "text/html", "OK", mPageNode.outer.generate());
}
catch(Exception ex) {
// FIXME: catch only specific exceptions
ex.printStackTrace();
writeReply(ctx, 200, "text/plain", "error retrieve identity", "Cannot display identity, maybe it hasn't been retrieved from Freenet yet.");
} finally {
// uh? why do we need this?
}
}
private HTMLNode getKeyPairRow(String key, String value, int property_index) {
HTMLNode tr = new HTMLNode("tr");
// user modifiable key
HTMLNode input = new HTMLNode("input");
input.addAttribute("type", "text");
input.addAttribute("name", "propertyName"+property_index);
input.addAttribute("value", key);
tr.addChild(new HTMLNode("td").addChild(input));
// user modifiable value
input = new HTMLNode("input");
input.addAttribute("type", "text");
input.addAttribute("name", "propertyValue"+property_index);
input.addAttribute("value", value);
input.addAttribute("size", "100");
tr.addChild(new HTMLNode("td").addChild(input));
// invisible old key
input = new HTMLNode("input");
input.addAttribute("type", "hidden");
input.addAttribute("name", "oldPropertyName"+property_index);
input.addAttribute("value", key);
tr.addChild(input);
// invisible old value
input = new HTMLNode("input");
input.addAttribute("type", "hidden");
input.addAttribute("name", "oldPropertyValue"+property_index);
input.addAttribute("value", value);
tr.addChild(input);
return tr;
}
private HTMLNode getInput(String type, String name, String value) {
HTMLNode input = new HTMLNode("input");
input.addAttribute("type", type);
input.addAttribute("name", name);
input.addAttribute("value", value);
return input;
}
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if(WebOfTrust.allowFullAccessOnly && !ctx.isAllowedFullAccess()) {
writeReply(ctx, 403, "text/plain", "forbidden", "Your host is not allowed to access this page.");
return;
}
final String action = request.getPartAsStringFailsafe("action", 1000);
Transaction tx = db.beginTx();
try {
if (action.equals("remove_edge")) {
final long edge_id = Long.parseLong(request.getPartAsStringFailsafe("edge_id", 1000));
db.getRelationshipById(edge_id).delete();
} else if (action.equals("set_trust")) {
setTrust(request);
} else if (action.equals("modify_properties")) {
modifyProperties(request);
}
tx.success();
} finally {
tx.finish();
}
// finally treat the request like any GET request
handleMethodGET(uri, request, ctx);
}
private void modifyProperties(HTTPRequest request) {
final String id = request.getPartAsStringFailsafe("identity", 1000);
final Node id_vertex = nodeIndex.get(IVertex.ID, id).getSingle();
int i = 0;
while(request.isPartSet("oldPropertyName"+i)) {
String oldPropertyName = request.getPartAsStringFailsafe("oldPropertyName"+i, 10000);
String oldPropertyValue = request.getPartAsStringFailsafe("oldPropertyValue"+i, 10000);
String propertyName = request.getPartAsStringFailsafe("propertyName"+i, 10000);
String propertyValue = request.getPartAsStringFailsafe("propertyValue"+i, 10000);
id_vertex.removeProperty(oldPropertyName);
if (!propertyName.trim().equals("")) {
id_vertex.setProperty(propertyName, propertyValue);
}
i += 1;
}
}
protected void setTrust(HTTPRequest request) {
String own_identity = request.getPartAsStringFailsafe("own_identity_id", 1000);
String identity = request.getPartAsStringFailsafe("identity_id", 1000);
String trustValue = request.getPartAsStringFailsafe("trust_value", 1000);
String trustComment = request.getPartAsStringFailsafe("trust_comment", 1000);
SetTrust.setTrust(db, nodeIndex, own_identity, identity, trustValue, trustComment);
}
@Override
public boolean isEnabled(ToadletContext ctx) {
// TODO: wait for database initialization?
// return WebOfTrust.ReadyToRock;
return true;
}
@Override
public String path() {
return path;
}
}
| true | true | public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if(WebOfTrust.allowFullAccessOnly && !ctx.isAllowedFullAccess()) {
writeReply(ctx, 403, "text/plain", "forbidden", "Your host is not allowed to access this page.");
return;
}
PageNode mPageNode = ctx.getPageMaker().getPageNode("LCWoT - Identity details", true, true, ctx);
mPageNode.addCustomStyleSheet(WebOfTrust.basePath + "/WebOfTrust.css");
HTMLNode contentDiv = new HTMLNode("div");
contentDiv.addAttribute("id", "WebOfTrust");
try {
//get the query param
// FIXME: maybe better to use
// ^ request.getPartAsStringFailsafe(name, maxlength)
final String id = request.getParam("id");
// get the identity vertex & properties
final Node identity = nodeIndex.get(IVertex.ID, id).getSingle();
final boolean is_own_identity = identity.hasProperty(IVertex.OWN_IDENTITY);
final SortedSet<String> sortedKeys = new TreeSet<String>();
for(String key : identity.getPropertyKeys()) sortedKeys.add(key);
// FIXME: just for testing.
// <br /> should be div margin/padding or something i guess
// if ^ stylesheet is correctly set up the <b> tags can become h1 and h2 again.
contentDiv.addChild("br");
contentDiv.addChild("b", "Here are the details of the identity");
contentDiv.addChild("br");
contentDiv.addChild("br");
HTMLNode form = new HTMLNode("form");
form.addAttribute("action", "#");
form.addAttribute("method", "post");
HTMLNode input = new HTMLNode("input");
input.addAttribute("type", "hidden");
input.addAttribute("name", "action");
input.addAttribute("value", "modify_properties");
form.addChild(input);
input = new HTMLNode("input");
input.addAttribute("type", "hidden");
input.addAttribute("name", "identity");
input.addAttribute("value", id);
form.addChild(input);
HTMLNode table = new HTMLNode("table");
HTMLNode tr = new HTMLNode("tr");
tr.addChild("th", "Name");
tr.addChild("th", "Value");
table.addChild(tr);
// generic properties associated with this identity in the graph store
int property_index = 0;
for(String key : sortedKeys) {
Object value = identity.getProperty(key);
if (is_own_identity) {
table.addChild(getKeyPairRow(key, value.toString(), property_index));
}
else {
tr = new HTMLNode("tr");
tr.addChild("td", key);
tr.addChild("td", value.toString());
table.addChild(tr);
}
property_index += 1;
}
if (is_own_identity) {
// extra empty property value pair
table.addChild(getKeyPairRow("", "", property_index));
form.addChild(table);
// submit button
input = new HTMLNode("input");
input.addAttribute("type", "submit");
input.addAttribute("value", "Modify properties");
form.addChild(input);
} else {
form.addChild(table);
}
contentDiv.addChild(form);
// display available contexts
HTMLNode contextDiv = new HTMLNode("div");
contextDiv.addChild("br");
contextDiv.addChild("b", "Contexts");
contextDiv.addChild("br");
contextDiv.addChild("br");
HTMLNode list = new HTMLNode("ul");
for(Relationship rel : identity.getRelationships(Direction.OUTGOING, Rel.HAS_CONTEXT)) {
list.addChild("li", (String) rel.getEndNode().getProperty(IContext.NAME));
}
contentDiv.addChild(contextDiv.addChild(list));
// allow specifying an updated trust value
contentDiv.addChild("br");
contentDiv.addChild("b", "Local trust assignments to this identity:");
contentDiv.addChild("br");
contentDiv.addChild("br");
for(Node own_vertex : nodeIndex.get(IVertex.OWN_IDENTITY, true)) {
byte current_trust_value = 0;
String current_comment = "";
for(Relationship edge : own_vertex.getRelationships(Direction.OUTGOING, Rel.TRUSTS)) {
if (edge.getEndNode().equals(identity)) {
current_trust_value = (Byte) edge.getProperty(IEdge.SCORE);
current_comment = (String) edge.getProperty(IEdge.COMMENT);
// TODO: add a break; here? not exactly sure what the goal of this is.
}
}
form = new HTMLNode("form");
form.addAttribute("method", "post");
// TODO: why not use # here like above?
form.addAttribute("action", WebOfTrust.basePath+"/ShowIdentity?id="+id);
form.addAttribute("method", "post");
HTMLNode fieldset = new HTMLNode("fieldset");
fieldset.addChild("legend", (String) own_vertex.getProperty(IVertex.NAME));
fieldset.addChild(getInput("hidden", "action", "set_trust"));
fieldset.addChild(getInput("hidden", "identity_id", id));
fieldset.addChild(getInput("hidden", "own_identity_id", (String) own_vertex.getProperty(IVertex.ID)));
fieldset.addChild("span", "Trust: ");
fieldset.addChild(getInput("number", "trust_value", Byte.toString(current_trust_value)));
fieldset.addChild("span", "Comment: ");
fieldset.addChild(getInput("text", "trust_comment", current_comment));
fieldset.addChild(getInput("submit", "", "Update"));
form.addChild(fieldset);
contentDiv.addChild(form);
}
// explicit trust relations assigned by this identity
contentDiv.addChild("br");
contentDiv.addChild("b", "Explicit trust relations exposed by this identity:");
contentDiv.addChild("br");
contentDiv.addChild("br");
table = new HTMLNode("table");
tr = new HTMLNode("tr");
tr.addChild("th", "nr.");
tr.addChild("th", "identity");
tr.addChild("th", "Trust");
tr.addChild("th", "Comment");
tr.addChild("th", "action");
table.addChild(tr);
int i = 1;
HTMLNode link;
for(Relationship edge : identity.getRelationships(Direction.OUTGOING, Rel.TRUSTS)) {
if (edge.hasProperty(IEdge.SCORE) && edge.hasProperty(IEdge.COMMENT)) {
byte trustValue = (Byte) edge.getProperty(IEdge.SCORE);
String trustComment = (String) edge.getProperty(IEdge.COMMENT);
String peerName;
Node peer_identity = edge.getEndNode();
if (peer_identity.hasProperty(IVertex.NAME)) {
peerName = (String) peer_identity.getProperty(IVertex.NAME);
} else {
peerName = "(Not yet downloaded)";
}
String peerID = (String) peer_identity.getProperty(IVertex.ID);
link = new HTMLNode("a", peerName+" ("+peerID+")");
link.addAttribute("href", WebOfTrust.basePath+"/ShowIdentity?id="+peerID);
link.addAttribute("name", Integer.toString(i));
tr = new HTMLNode("tr");
tr.addChild("td", Integer.toString(i));
tr.addChild(new HTMLNode("td").addChild(link));
tr.addChild("td", Integer.toString(trustValue));
tr.addChild("td", trustComment);
if (identity.hasProperty(IVertex.OWN_IDENTITY)) {
// identity we are displaying is a local one, thus display additional options!
form = new HTMLNode("form");
form.addAttribute("action", WebOfTrust.basePath+"/ShowIdentity?id="+id + "#"+(i-1));
form.addAttribute("method", "post");
form.addChild(getInput("submit", "", "Remove"));
form.addChild(getInput("hidden", "action", "remove_edge"));
form.addChild(getInput("hidden", "edge_id", Long.toString(edge.getId())));
tr.addChild(new HTMLNode("td").addChild(form));
} else {
tr.addChild("td");
}
table.addChild(tr);
i += 1;
}
}
contentDiv.addChild(table);
// explicit trust relations given by others
contentDiv.addChild("br");
contentDiv.addChild("b", "Explicit trust relations given by others to this identity:");
contentDiv.addChild("br");
contentDiv.addChild("br");
table = new HTMLNode("table");
tr = new HTMLNode("tr");
tr.addChild("th", "nr.");
tr.addChild("th", "identity");
tr.addChild("th", "Trust");
tr.addChild("th", "Comment");
table.addChild(tr);
i = 1;
for(Relationship edge : identity.getRelationships(Direction.INCOMING, Rel.TRUSTS)) {
Node peer_identity = edge.getStartNode();
byte trustValue = (Byte) edge.getProperty(IEdge.SCORE);
String trustComment = (String) edge.getProperty(IEdge.COMMENT);
String peerName;
try {
peerName = (String) peer_identity.getProperty(IVertex.NAME);
} catch(org.neo4j.graphdb.NotFoundException e) {
peerName = "... not retrieved yet ...";
}
String peerID = (String) peer_identity.getProperty(IVertex.ID);
link = new HTMLNode("a", peerName+" ("+peerID+")");
link.addAttribute("href", WebOfTrust.basePath+"/ShowIdentity?id="+peerID);
tr.addChild("td", Integer.toString(i));
tr.addChild(new HTMLNode("td").addChild(link));
tr.addChild("td", Byte.toString(trustValue));
tr.addChild("td", trustComment);
table.addChild(tr);
i += 1;
}
contentDiv.addChild(table);
mPageNode.content.addChild(contentDiv);
// finally send the request
writeReply(ctx, 200, "text/html", "OK", mPageNode.outer.generate());
}
catch(Exception ex) {
// FIXME: catch only specific exceptions
ex.printStackTrace();
writeReply(ctx, 200, "text/plain", "error retrieve identity", "Cannot display identity, maybe it hasn't been retrieved from Freenet yet.");
} finally {
// uh? why do we need this?
}
}
| public void handleMethodGET(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException {
if(WebOfTrust.allowFullAccessOnly && !ctx.isAllowedFullAccess()) {
writeReply(ctx, 403, "text/plain", "forbidden", "Your host is not allowed to access this page.");
return;
}
PageNode mPageNode = ctx.getPageMaker().getPageNode("LCWoT - Identity details", true, true, ctx);
mPageNode.addCustomStyleSheet(WebOfTrust.basePath + "/WebOfTrust.css");
HTMLNode contentDiv = new HTMLNode("div");
contentDiv.addAttribute("id", "WebOfTrust");
try {
//get the query param
// FIXME: maybe better to use
// ^ request.getPartAsStringFailsafe(name, maxlength)
final String id = request.getParam("id");
// get the identity vertex & properties
final Node identity = nodeIndex.get(IVertex.ID, id).getSingle();
final boolean is_own_identity = identity.hasProperty(IVertex.OWN_IDENTITY);
final SortedSet<String> sortedKeys = new TreeSet<String>();
for(String key : identity.getPropertyKeys()) sortedKeys.add(key);
// FIXME: just for testing.
// <br /> should be div margin/padding or something i guess
// if ^ stylesheet is correctly set up the <b> tags can become h1 and h2 again.
contentDiv.addChild("br");
contentDiv.addChild("b", "Here are the details of the identity");
contentDiv.addChild("br");
contentDiv.addChild("br");
HTMLNode form = new HTMLNode("form");
form.addAttribute("action", "#");
form.addAttribute("method", "post");
HTMLNode input = new HTMLNode("input");
input.addAttribute("type", "hidden");
input.addAttribute("name", "action");
input.addAttribute("value", "modify_properties");
form.addChild(input);
input = new HTMLNode("input");
input.addAttribute("type", "hidden");
input.addAttribute("name", "identity");
input.addAttribute("value", id);
form.addChild(input);
HTMLNode table = new HTMLNode("table");
HTMLNode tr = new HTMLNode("tr");
tr.addChild("th", "Name");
tr.addChild("th", "Value");
table.addChild(tr);
// generic properties associated with this identity in the graph store
int property_index = 0;
for(String key : sortedKeys) {
Object value = identity.getProperty(key);
if (is_own_identity) {
table.addChild(getKeyPairRow(key, value.toString(), property_index));
}
else {
tr = new HTMLNode("tr");
tr.addChild("td", key);
tr.addChild("td", value.toString());
table.addChild(tr);
}
property_index += 1;
}
if (is_own_identity) {
// extra empty property value pair
table.addChild(getKeyPairRow("", "", property_index));
form.addChild(table);
// submit button
input = new HTMLNode("input");
input.addAttribute("type", "submit");
input.addAttribute("value", "Modify properties");
form.addChild(input);
} else {
form.addChild(table);
}
contentDiv.addChild(form);
// display available contexts
HTMLNode contextDiv = new HTMLNode("div");
contextDiv.addChild("br");
contextDiv.addChild("b", "Contexts");
contextDiv.addChild("br");
contextDiv.addChild("br");
HTMLNode list = new HTMLNode("ul");
for(Relationship rel : identity.getRelationships(Direction.OUTGOING, Rel.HAS_CONTEXT)) {
list.addChild("li", (String) rel.getEndNode().getProperty(IContext.NAME));
}
contentDiv.addChild(contextDiv.addChild(list));
// allow specifying an updated trust value
contentDiv.addChild("br");
contentDiv.addChild("b", "Local trust assignments to this identity:");
contentDiv.addChild("br");
contentDiv.addChild("br");
for(Node own_vertex : nodeIndex.get(IVertex.OWN_IDENTITY, true)) {
byte current_trust_value = 0;
String current_comment = "";
for(Relationship edge : own_vertex.getRelationships(Direction.OUTGOING, Rel.TRUSTS)) {
if (edge.getEndNode().equals(identity)) {
current_trust_value = (Byte) edge.getProperty(IEdge.SCORE);
current_comment = (String) edge.getProperty(IEdge.COMMENT);
// TODO: add a break; here? not exactly sure what the goal of this is.
}
}
form = new HTMLNode("form");
form.addAttribute("method", "post");
// TODO: why not use # here like above?
form.addAttribute("action", WebOfTrust.basePath+"/ShowIdentity?id="+id);
form.addAttribute("method", "post");
HTMLNode fieldset = new HTMLNode("fieldset");
fieldset.addChild("legend", (String) own_vertex.getProperty(IVertex.NAME));
fieldset.addChild(getInput("hidden", "action", "set_trust"));
fieldset.addChild(getInput("hidden", "identity_id", id));
fieldset.addChild(getInput("hidden", "own_identity_id", (String) own_vertex.getProperty(IVertex.ID)));
fieldset.addChild("span", "Trust: ");
fieldset.addChild(getInput("number", "trust_value", Byte.toString(current_trust_value)));
fieldset.addChild("span", "Comment: ");
fieldset.addChild(getInput("text", "trust_comment", current_comment));
fieldset.addChild(getInput("submit", "", "Update"));
form.addChild(fieldset);
contentDiv.addChild(form);
}
// explicit trust relations assigned by this identity
contentDiv.addChild("br");
contentDiv.addChild("b", "Explicit trust relations exposed by this identity:");
contentDiv.addChild("br");
contentDiv.addChild("br");
table = new HTMLNode("table");
tr = new HTMLNode("tr");
tr.addChild("th", "nr.");
tr.addChild("th", "identity");
tr.addChild("th", "Trust");
tr.addChild("th", "Comment");
tr.addChild("th", "action");
table.addChild(tr);
int i = 1;
HTMLNode link;
for(Relationship edge : identity.getRelationships(Direction.OUTGOING, Rel.TRUSTS)) {
if (edge.hasProperty(IEdge.SCORE) && edge.hasProperty(IEdge.COMMENT)) {
byte trustValue = (Byte) edge.getProperty(IEdge.SCORE);
String trustComment = (String) edge.getProperty(IEdge.COMMENT);
String peerName;
Node peer_identity = edge.getEndNode();
if (peer_identity.hasProperty(IVertex.NAME)) {
peerName = (String) peer_identity.getProperty(IVertex.NAME);
} else {
peerName = "(Not yet downloaded)";
}
String peerID = (String) peer_identity.getProperty(IVertex.ID);
link = new HTMLNode("a", peerName+" ("+peerID+")");
link.addAttribute("href", WebOfTrust.basePath+"/ShowIdentity?id="+peerID);
link.addAttribute("name", Integer.toString(i));
tr = new HTMLNode("tr");
tr.addChild("td", Integer.toString(i));
tr.addChild(new HTMLNode("td").addChild(link));
tr.addChild("td", Integer.toString(trustValue));
tr.addChild("td", trustComment);
if (identity.hasProperty(IVertex.OWN_IDENTITY)) {
// identity we are displaying is a local one, thus display additional options!
form = new HTMLNode("form");
form.addAttribute("action", WebOfTrust.basePath+"/ShowIdentity?id="+id + "#"+(i-1));
form.addAttribute("method", "post");
form.addChild(getInput("submit", "", "Remove"));
form.addChild(getInput("hidden", "action", "remove_edge"));
form.addChild(getInput("hidden", "edge_id", Long.toString(edge.getId())));
tr.addChild(new HTMLNode("td").addChild(form));
} else {
tr.addChild("td");
}
table.addChild(tr);
i += 1;
}
}
contentDiv.addChild(table);
// explicit trust relations given by others
contentDiv.addChild("br");
contentDiv.addChild("b", "Explicit trust relations given by others to this identity:");
contentDiv.addChild("br");
contentDiv.addChild("br");
table = new HTMLNode("table");
tr = new HTMLNode("tr");
tr.addChild("th", "nr.");
tr.addChild("th", "identity");
tr.addChild("th", "Trust");
tr.addChild("th", "Comment");
table.addChild(tr);
i = 1;
for(Relationship edge : identity.getRelationships(Direction.INCOMING, Rel.TRUSTS)) {
Node peer_identity = edge.getStartNode();
byte trustValue = (Byte) edge.getProperty(IEdge.SCORE);
String trustComment = (String) edge.getProperty(IEdge.COMMENT);
String peerName;
try {
peerName = (String) peer_identity.getProperty(IVertex.NAME);
} catch(org.neo4j.graphdb.NotFoundException e) {
peerName = "... not retrieved yet ...";
}
String peerID = (String) peer_identity.getProperty(IVertex.ID);
tr = new HTMLNode("tr");
link = new HTMLNode("a", peerName+" ("+peerID+")");
link.addAttribute("href", WebOfTrust.basePath+"/ShowIdentity?id="+peerID);
tr.addChild("td", Integer.toString(i));
tr.addChild(new HTMLNode("td").addChild(link));
tr.addChild("td", Byte.toString(trustValue));
tr.addChild("td", trustComment);
table.addChild(tr);
i += 1;
}
contentDiv.addChild(table);
mPageNode.content.addChild(contentDiv);
// finally send the request
writeReply(ctx, 200, "text/html", "OK", mPageNode.outer.generate());
}
catch(Exception ex) {
// FIXME: catch only specific exceptions
ex.printStackTrace();
writeReply(ctx, 200, "text/plain", "error retrieve identity", "Cannot display identity, maybe it hasn't been retrieved from Freenet yet.");
} finally {
// uh? why do we need this?
}
}
|
diff --git a/openFaces/source/org/openfaces/taglib/internal/filter/ExpressionFilterTag.java b/openFaces/source/org/openfaces/taglib/internal/filter/ExpressionFilterTag.java
index 567dc6a37..309c454ac 100644
--- a/openFaces/source/org/openfaces/taglib/internal/filter/ExpressionFilterTag.java
+++ b/openFaces/source/org/openfaces/taglib/internal/filter/ExpressionFilterTag.java
@@ -1,78 +1,79 @@
/*
* Copyright (c) 1998-2009 TeamDev Ltd. All Rights Reserved.
* Use is subject to license terms.
*/
package org.openfaces.taglib.internal.filter;
import org.openfaces.component.filter.ExpressionFilter;
import org.openfaces.component.filter.FilterCondition;
import org.openfaces.component.filter.ExpressionFilterCriterion;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
/**
* @author Dmitry Pikhulya
*/
public abstract class ExpressionFilterTag extends FilterTag {
@Override
public void setComponentProperties(FacesContext context, UIComponent component) {
super.setComponentProperties(context, component);
ExpressionFilter filter = (ExpressionFilter) component;
String expression = getPropertyValue("expression");
if (getExpressionCreator().isValueReference("expression", expression))
filter.setExpression(createValueExpression(context, "expression", expression));
else
filter.setExpression(expression);
String value = getPropertyValue("value");
if (!setPropertyAsBinding(component, "value", value)) {
setValueAsCondition(filter, value);
}
setPropertyBinding(component, "options");
setConverterProperty(context, component, "converter");
+ setBooleanProperty(component, "caseSensitive");
setStringProperty(component, "allRecordsText");
setStringProperty(component, "emptyRecordsText");
setStringProperty(component, "nonEmptyRecordsText");
setStringProperty(component, "promptText");
setStringProperty(component, "promptTextStyle");
setStringProperty(component, "promptTextClass");
setStringProperty(component, "title");
setStringProperty(component, "accesskey");
setStringProperty(component, "tabindex");
setIntProperty(component, "autoFilterDelay");
}
private void setValueAsCondition(ExpressionFilter filter, String value) {
String[] parts = value.split(" ");
String conditionName = parts[parts.length - 1];
FilterCondition condition = null;
String possibleConditionsStr = "";
for (FilterCondition c : FilterCondition.values()) {
if (c == FilterCondition.EMPTY || c == FilterCondition.BETWEEN)
continue; // these are not applicable for one-property filters (which are ancesotrs of ExpressionFilter)
if (possibleConditionsStr.length() > 0)
possibleConditionsStr += ", ";
String n = c.getName();
possibleConditionsStr += n;
if (conditionName.equals(n))
condition = c;
}
if (parts.length > 2 || condition == null)
throw new FacesException("Improper 'criterion' attribute value: \"" + value + "\". It should be of \"<condition>\" or \"not <condition>\", where <condition> is one of: " + possibleConditionsStr +"; but it was: " + value);
boolean inverse = false;
if (parts.length == 2) {
if (!parts[0].equals("not"))
throw new FacesException("Improper 'criterion' attribute value: \"" + value + "\". It should be of \"<condition>\" or \"not <condition>\", where <condition> is one of: " + possibleConditionsStr +"; but it was: " + value);
inverse = true;
}
filter.setValue(new ExpressionFilterCriterion(condition, inverse));
}
}
| true | true | public void setComponentProperties(FacesContext context, UIComponent component) {
super.setComponentProperties(context, component);
ExpressionFilter filter = (ExpressionFilter) component;
String expression = getPropertyValue("expression");
if (getExpressionCreator().isValueReference("expression", expression))
filter.setExpression(createValueExpression(context, "expression", expression));
else
filter.setExpression(expression);
String value = getPropertyValue("value");
if (!setPropertyAsBinding(component, "value", value)) {
setValueAsCondition(filter, value);
}
setPropertyBinding(component, "options");
setConverterProperty(context, component, "converter");
setStringProperty(component, "allRecordsText");
setStringProperty(component, "emptyRecordsText");
setStringProperty(component, "nonEmptyRecordsText");
setStringProperty(component, "promptText");
setStringProperty(component, "promptTextStyle");
setStringProperty(component, "promptTextClass");
setStringProperty(component, "title");
setStringProperty(component, "accesskey");
setStringProperty(component, "tabindex");
setIntProperty(component, "autoFilterDelay");
}
| public void setComponentProperties(FacesContext context, UIComponent component) {
super.setComponentProperties(context, component);
ExpressionFilter filter = (ExpressionFilter) component;
String expression = getPropertyValue("expression");
if (getExpressionCreator().isValueReference("expression", expression))
filter.setExpression(createValueExpression(context, "expression", expression));
else
filter.setExpression(expression);
String value = getPropertyValue("value");
if (!setPropertyAsBinding(component, "value", value)) {
setValueAsCondition(filter, value);
}
setPropertyBinding(component, "options");
setConverterProperty(context, component, "converter");
setBooleanProperty(component, "caseSensitive");
setStringProperty(component, "allRecordsText");
setStringProperty(component, "emptyRecordsText");
setStringProperty(component, "nonEmptyRecordsText");
setStringProperty(component, "promptText");
setStringProperty(component, "promptTextStyle");
setStringProperty(component, "promptTextClass");
setStringProperty(component, "title");
setStringProperty(component, "accesskey");
setStringProperty(component, "tabindex");
setIntProperty(component, "autoFilterDelay");
}
|
diff --git a/workspace/enwida/src/main/java/de/enwida/web/dao/implementation/AspectDaoImpl.java b/workspace/enwida/src/main/java/de/enwida/web/dao/implementation/AspectDaoImpl.java
index 7df061a3..c5d5f0a9 100644
--- a/workspace/enwida/src/main/java/de/enwida/web/dao/implementation/AspectDaoImpl.java
+++ b/workspace/enwida/src/main/java/de/enwida/web/dao/implementation/AspectDaoImpl.java
@@ -1,60 +1,61 @@
package de.enwida.web.dao.implementation;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import de.enwida.transport.Aspect;
import de.enwida.web.dao.interfaces.IAspectsDao;
import de.enwida.web.model.AspectRight;
public class AspectDaoImpl implements IAspectsDao {
@Autowired
private DriverManagerDataSource datasource;
public List<Aspect> getAspects(int chartId) {
// TODO Auto-generated method stub
return Collections.emptyList();
}
public List<AspectRight> getAllAspects(long roleID) {
String sql = "select * FROM users.rights";
Connection conn = null;
ArrayList<AspectRight> rights = new ArrayList<AspectRight>();
try {
conn = datasource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
AspectRight right = new AspectRight();
right.setRightID(rs.getLong("right_id"));
+ right.setAspectName(rs.getString("aspect_id"));
right.setRoleID(rs.getLong("role_id"));
right.setResolution(rs.getString("resolution"));
right.setProduct(rs.getString("product"));
right.setTso(rs.getString("tso"));
right.setEnabled(rs.getBoolean("enabled"));
rights.add(right);
}
rs.close();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
return rights;
}
}
| true | true | public List<AspectRight> getAllAspects(long roleID) {
String sql = "select * FROM users.rights";
Connection conn = null;
ArrayList<AspectRight> rights = new ArrayList<AspectRight>();
try {
conn = datasource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
AspectRight right = new AspectRight();
right.setRightID(rs.getLong("right_id"));
right.setRoleID(rs.getLong("role_id"));
right.setResolution(rs.getString("resolution"));
right.setProduct(rs.getString("product"));
right.setTso(rs.getString("tso"));
right.setEnabled(rs.getBoolean("enabled"));
rights.add(right);
}
rs.close();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
return rights;
}
| public List<AspectRight> getAllAspects(long roleID) {
String sql = "select * FROM users.rights";
Connection conn = null;
ArrayList<AspectRight> rights = new ArrayList<AspectRight>();
try {
conn = datasource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
AspectRight right = new AspectRight();
right.setRightID(rs.getLong("right_id"));
right.setAspectName(rs.getString("aspect_id"));
right.setRoleID(rs.getLong("role_id"));
right.setResolution(rs.getString("resolution"));
right.setProduct(rs.getString("product"));
right.setTso(rs.getString("tso"));
right.setEnabled(rs.getBoolean("enabled"));
rights.add(right);
}
rs.close();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
return rights;
}
|
diff --git a/src/com/fluendo/plugin/HTTPSrc.java b/src/com/fluendo/plugin/HTTPSrc.java
index a0a8cc6..3e81e43 100644
--- a/src/com/fluendo/plugin/HTTPSrc.java
+++ b/src/com/fluendo/plugin/HTTPSrc.java
@@ -1,265 +1,265 @@
/* Copyright (C) <2004> Wim Taymans <[email protected]>
*
* 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., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package com.fluendo.plugin;
import java.io.*;
import java.net.*;
import com.fluendo.jst.*;
import com.fluendo.utils.*;
public class HTTPSrc extends Element
{
private String userId;
private String password;
private String urlString;
private InputStream input;
private long contentLength;
private String mime;
private Caps outCaps;
private boolean discont;
private URL documentBase;
private static final int DEFAULT_READSIZE = 4096;
private int readSize = DEFAULT_READSIZE;
private Pad srcpad = new Pad(Pad.SRC, "src") {
private boolean doSeek (Event event) {
boolean result;
int format;
long position;
format = event.parseSeekFormat();
position = event.parseSeekPosition();
if (format == Format.PERCENT) {
position = position * contentLength / Format.PERCENT_MAX;
}
else if (format != Format.BYTES) {
Debug.log (Debug.WARNING, "can only seek in bytes");
return false;
}
pushEvent (Event.newFlushStart());
synchronized (streamLock) {
Debug.log(Debug.INFO, "synced "+this);
try {
input = getInputStream (position);
result = true;
}
catch (Exception e) {
e.printStackTrace ();
result = false;
}
pushEvent (Event.newFlushStop());
pushEvent (Event.newNewsegment(false, Format.BYTES, position, contentLength, position));
if (result) {
postMessage (Message.newStreamStatus (this, true, Pad.OK, "restart after seek"));
result = startTask();
}
}
return result;
}
protected boolean eventFunc (Event event)
{
boolean res;
switch (event.getType()) {
case Event.SEEK:
res = doSeek(event);
break;
default:
res = super.eventFunc (event);
break;
}
return res;
}
protected void taskFunc()
{
int ret;
Buffer data = Buffer.create();
data.ensureSize (readSize);
data.offset = 0;
try {
data.length = input.read (data.data, 0, readSize);
}
catch (Exception e) {
e.printStackTrace();
data.length = 0;
}
if (data.length <= 0) {
/* EOS */
data.free();
Debug.log(Debug.INFO, this+" reached EOS");
pushEvent (Event.newEOS());
postMessage (Message.newStreamStatus (this, false, Pad.UNEXPECTED, "reached EOS"));
pauseTask();
}
else {
if (srcpad.getCaps() == null) {
String typeMime;
typeMime = ElementFactory.typeFindMime (data.data, data.offset, data.length);
if (typeMime != null) {
if (!typeMime.equals (mime)) {
Debug.log(Debug.WARNING, "server contentType: "+mime+" disagrees with our typeFind: "
+typeMime);
}
Debug.log(Debug.INFO, "using typefind contentType: "+typeMime);
mime = typeMime;
}
else {
Debug.log(Debug.INFO, "typefind failed, using server contentType: "+mime);
}
outCaps = new Caps (mime);
srcpad.setCaps (outCaps);
}
data.caps = outCaps;
data.setFlag (com.fluendo.jst.Buffer.FLAG_DISCONT, discont);
discont = false;
if ((ret = push(data)) != OK) {
if (isFlowFatal(ret) || ret == Pad.NOT_LINKED) {
postMessage (Message.newError (this, "error: "+getFlowName (ret)));
+ pushEvent (Event.newEOS());
}
postMessage (Message.newStreamStatus (this, false, ret, "reason: "+getFlowName (ret)));
pauseTask();
- pushEvent (Event.newEOS());
}
}
}
protected boolean activateFunc (int mode)
{
boolean res = true;
switch (mode) {
case MODE_NONE:
postMessage (Message.newStreamStatus (this, false, Pad.WRONG_STATE, "stopping"));
res = stopTask();
input = null;
outCaps = null;
mime = null;
break;
case MODE_PUSH:
try {
input = getInputStream(0);
if (input == null)
res = false;
}
catch (Exception e) {
res = false;
}
if (res) {
postMessage (Message.newStreamStatus (this, true, Pad.OK, "activating"));
res = startTask();
}
break;
default:
res = false;
break;
}
return res;
}
};
private InputStream getInputStream (long offset) throws Exception
{
InputStream dis = null;
try {
URL url;
postMessage(Message.newResource (this, "Opening "+urlString));
Debug.log(Debug.INFO, "reading from url "+urlString);
if (documentBase != null)
url = new URL(documentBase, urlString);
else
url = new URL(urlString);
Debug.log(Debug.INFO, "trying to open "+url);
URLConnection uc = url.openConnection();
if (userId != null && password != null) {
String userPassword = userId + ":" + password;
String encoding = Base64Converter.encode (userPassword.getBytes());
uc.setRequestProperty ("Authorization", "Basic " + encoding);
}
uc.setRequestProperty ("Range", "bytes=" + offset+"-");
/* FIXME, do typefind ? */
dis = uc.getInputStream();
contentLength = uc.getHeaderFieldInt ("Content-Length", 0) + offset;
mime = uc.getContentType();
discont = true;
Debug.log(Debug.INFO, "opened "+url);
Debug.log(Debug.INFO, "contentLength: "+contentLength);
Debug.log(Debug.INFO, "server contentType: "+mime);
}
catch (SecurityException e) {
e.printStackTrace();
postMessage(Message.newError (this, "Not allowed "+urlString+"..."));
}
catch (Exception e) {
e.printStackTrace();
postMessage(Message.newError (this, "Failed opening "+urlString+"..."));
}
return dis;
}
public String getFactoryName () {
return "httpsrc";
}
public HTTPSrc () {
super ();
addPad (srcpad);
}
public synchronized boolean setProperty(String name, java.lang.Object value) {
boolean res = true;
if (name.equals("url")) {
urlString = String.valueOf(value);
}
else if (name.equals("documentBase")) {
documentBase = (URL)value;
}
else if (name.equals("userId")) {
userId = String.valueOf(value);
}
else if (name.equals("password")) {
password = String.valueOf(value);
}
else if (name.equals("readSize")) {
readSize = Integer.parseInt((String)value);
}
else {
res = false;
}
return res;
}
}
| false | true | protected void taskFunc()
{
int ret;
Buffer data = Buffer.create();
data.ensureSize (readSize);
data.offset = 0;
try {
data.length = input.read (data.data, 0, readSize);
}
catch (Exception e) {
e.printStackTrace();
data.length = 0;
}
if (data.length <= 0) {
/* EOS */
data.free();
Debug.log(Debug.INFO, this+" reached EOS");
pushEvent (Event.newEOS());
postMessage (Message.newStreamStatus (this, false, Pad.UNEXPECTED, "reached EOS"));
pauseTask();
}
else {
if (srcpad.getCaps() == null) {
String typeMime;
typeMime = ElementFactory.typeFindMime (data.data, data.offset, data.length);
if (typeMime != null) {
if (!typeMime.equals (mime)) {
Debug.log(Debug.WARNING, "server contentType: "+mime+" disagrees with our typeFind: "
+typeMime);
}
Debug.log(Debug.INFO, "using typefind contentType: "+typeMime);
mime = typeMime;
}
else {
Debug.log(Debug.INFO, "typefind failed, using server contentType: "+mime);
}
outCaps = new Caps (mime);
srcpad.setCaps (outCaps);
}
data.caps = outCaps;
data.setFlag (com.fluendo.jst.Buffer.FLAG_DISCONT, discont);
discont = false;
if ((ret = push(data)) != OK) {
if (isFlowFatal(ret) || ret == Pad.NOT_LINKED) {
postMessage (Message.newError (this, "error: "+getFlowName (ret)));
}
postMessage (Message.newStreamStatus (this, false, ret, "reason: "+getFlowName (ret)));
pauseTask();
pushEvent (Event.newEOS());
}
}
}
| protected void taskFunc()
{
int ret;
Buffer data = Buffer.create();
data.ensureSize (readSize);
data.offset = 0;
try {
data.length = input.read (data.data, 0, readSize);
}
catch (Exception e) {
e.printStackTrace();
data.length = 0;
}
if (data.length <= 0) {
/* EOS */
data.free();
Debug.log(Debug.INFO, this+" reached EOS");
pushEvent (Event.newEOS());
postMessage (Message.newStreamStatus (this, false, Pad.UNEXPECTED, "reached EOS"));
pauseTask();
}
else {
if (srcpad.getCaps() == null) {
String typeMime;
typeMime = ElementFactory.typeFindMime (data.data, data.offset, data.length);
if (typeMime != null) {
if (!typeMime.equals (mime)) {
Debug.log(Debug.WARNING, "server contentType: "+mime+" disagrees with our typeFind: "
+typeMime);
}
Debug.log(Debug.INFO, "using typefind contentType: "+typeMime);
mime = typeMime;
}
else {
Debug.log(Debug.INFO, "typefind failed, using server contentType: "+mime);
}
outCaps = new Caps (mime);
srcpad.setCaps (outCaps);
}
data.caps = outCaps;
data.setFlag (com.fluendo.jst.Buffer.FLAG_DISCONT, discont);
discont = false;
if ((ret = push(data)) != OK) {
if (isFlowFatal(ret) || ret == Pad.NOT_LINKED) {
postMessage (Message.newError (this, "error: "+getFlowName (ret)));
pushEvent (Event.newEOS());
}
postMessage (Message.newStreamStatus (this, false, ret, "reason: "+getFlowName (ret)));
pauseTask();
}
}
}
|
diff --git a/maven-scm-api/src/main/java/org/apache/maven/scm/util/AbstractConsumer.java b/maven-scm-api/src/main/java/org/apache/maven/scm/util/AbstractConsumer.java
index 7697f4d1..28915553 100644
--- a/maven-scm-api/src/main/java/org/apache/maven/scm/util/AbstractConsumer.java
+++ b/maven-scm-api/src/main/java/org/apache/maven/scm/util/AbstractConsumer.java
@@ -1,127 +1,127 @@
package org.apache.maven.scm.util;
/*
* 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.maven.scm.log.ScmLogger;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.StreamConsumer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* @author <a href="mailto:[email protected]">Emmanuel Venisse</a>
* @version $Id$
*/
public abstract class AbstractConsumer
implements StreamConsumer
{
private ScmLogger logger;
/**
* AbstractConsumer constructor.
*
* @param logger The logger to use in the consumer
*/
public AbstractConsumer( ScmLogger logger )
{
setLogger( logger );
}
public ScmLogger getLogger()
{
return logger;
}
public void setLogger( ScmLogger logger )
{
this.logger = logger;
}
/**
* Converts the date timestamp from the output into a date object.
*
* @return A date representing the timestamp of the log entry.
*/
protected Date parseDate( String date, String userPattern, String defaultPattern )
{
return parseDate( date, userPattern, defaultPattern, null );
}
/**
* Converts the date timestamp from the output into a date object.
*
* @return A date representing the timestamp of the log entry.
*/
protected Date parseDate( String date, String userPattern, String defaultPattern, Locale locale )
{
DateFormat format;
String patternUsed = null;
if ( StringUtils.isNotEmpty( userPattern ) )
{
format = new SimpleDateFormat( userPattern );
patternUsed = userPattern;
}
else
{
if ( StringUtils.isNotEmpty( defaultPattern ) )
{
if ( locale != null )
{
format = new SimpleDateFormat( defaultPattern, locale );
}
else
{
format = new SimpleDateFormat( defaultPattern );
}
patternUsed = defaultPattern;
}
else
{
// Use the English short date pattern if no pattern is specified
format = DateFormat.getDateInstance( DateFormat.SHORT, Locale.ENGLISH );
patternUsed = " DateFormat.SHORT ";
}
}
try
{
return format.parse( date );
}
catch ( ParseException e )
{
- if ( getLogger() != null && getLogger().isErrorEnabled() )
+ if ( getLogger() != null && getLogger().isWarnEnabled() )
{
- getLogger().error(
+ getLogger().warn(
"skip ParseException: " + e.getMessage() + " during parsing date " + date
+ " with pattern " + patternUsed + " with Locale "
+ ( locale == null ? Locale.ENGLISH : locale ), e );
}
return null;
}
}
}
| false | true | protected Date parseDate( String date, String userPattern, String defaultPattern, Locale locale )
{
DateFormat format;
String patternUsed = null;
if ( StringUtils.isNotEmpty( userPattern ) )
{
format = new SimpleDateFormat( userPattern );
patternUsed = userPattern;
}
else
{
if ( StringUtils.isNotEmpty( defaultPattern ) )
{
if ( locale != null )
{
format = new SimpleDateFormat( defaultPattern, locale );
}
else
{
format = new SimpleDateFormat( defaultPattern );
}
patternUsed = defaultPattern;
}
else
{
// Use the English short date pattern if no pattern is specified
format = DateFormat.getDateInstance( DateFormat.SHORT, Locale.ENGLISH );
patternUsed = " DateFormat.SHORT ";
}
}
try
{
return format.parse( date );
}
catch ( ParseException e )
{
if ( getLogger() != null && getLogger().isErrorEnabled() )
{
getLogger().error(
"skip ParseException: " + e.getMessage() + " during parsing date " + date
+ " with pattern " + patternUsed + " with Locale "
+ ( locale == null ? Locale.ENGLISH : locale ), e );
}
return null;
}
}
| protected Date parseDate( String date, String userPattern, String defaultPattern, Locale locale )
{
DateFormat format;
String patternUsed = null;
if ( StringUtils.isNotEmpty( userPattern ) )
{
format = new SimpleDateFormat( userPattern );
patternUsed = userPattern;
}
else
{
if ( StringUtils.isNotEmpty( defaultPattern ) )
{
if ( locale != null )
{
format = new SimpleDateFormat( defaultPattern, locale );
}
else
{
format = new SimpleDateFormat( defaultPattern );
}
patternUsed = defaultPattern;
}
else
{
// Use the English short date pattern if no pattern is specified
format = DateFormat.getDateInstance( DateFormat.SHORT, Locale.ENGLISH );
patternUsed = " DateFormat.SHORT ";
}
}
try
{
return format.parse( date );
}
catch ( ParseException e )
{
if ( getLogger() != null && getLogger().isWarnEnabled() )
{
getLogger().warn(
"skip ParseException: " + e.getMessage() + " during parsing date " + date
+ " with pattern " + patternUsed + " with Locale "
+ ( locale == null ? Locale.ENGLISH : locale ), e );
}
return null;
}
}
|
diff --git a/src/com/github/igotyou/FactoryMod/listeners/BlockListener.java b/src/com/github/igotyou/FactoryMod/listeners/BlockListener.java
index c47b5a7..072c6db 100644
--- a/src/com/github/igotyou/FactoryMod/listeners/BlockListener.java
+++ b/src/com/github/igotyou/FactoryMod/listeners/BlockListener.java
@@ -1,370 +1,365 @@
package com.github.igotyou.FactoryMod.listeners;
import static com.untamedears.citadel.Utility.isReinforced;
import static com.untamedears.citadel.Utility.getReinforcement;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import com.github.igotyou.FactoryMod.FactoryModPlugin;
import com.github.igotyou.FactoryMod.Factorys.ProductionFactory;
import com.github.igotyou.FactoryMod.managers.FactoryModManager;
import com.github.igotyou.FactoryMod.managers.ProductionManager;
import com.github.igotyou.FactoryMod.utility.InteractionResponse;
import com.github.igotyou.FactoryMod.utility.InteractionResponse.InteractionResult;
import com.github.igotyou.FactoryMod.utility.InventoryMethods;
import com.untamedears.citadel.entity.PlayerReinforcement;
public class BlockListener implements Listener
{
private FactoryModManager factoryMan;
//this is a lazy fix...
private ProductionManager productionMan;
/**
* Constructor
*/
public BlockListener(FactoryModManager factoryManager, ProductionManager productionManager)
{
this.factoryMan = factoryManager;
this.productionMan = productionManager;
}
/**
* Called when a block is broken
* If the block that is destroyed is part of a factory, call the required methods.
*/
@EventHandler
public void blockBreakEvent(BlockBreakEvent e)
{
Block block = e.getBlock();
//Is the block part of a factory?
if (factoryMan.factoryExistsAt(block.getLocation()))
{
//Is the factory a production factory?
if (productionMan.factoryExistsAt(block.getLocation()))
{
ProductionFactory factory = (ProductionFactory) productionMan.getFactory(block.getLocation());
e.setCancelled(true);
//if the blocks is not reinforced destroy it
if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(block)) || !FactoryModPlugin.CITADEL_ENABLED)
{
factory.destroy(block.getLocation());
productionMan.removeFactory(factory);
}
}
}
}
/**
* Called when a entity explodes(creeper,tnt etc.)
* Nearly the same as blockBreakEvent
*/
@EventHandler
public void explosionListener(EntityExplodeEvent e)
{
List<Block> blocks = e.blockList();
for (Block block : blocks)
{
if (factoryMan.factoryExistsAt(block.getLocation()))
{
if (productionMan.factoryExistsAt(block.getLocation()))
{
ProductionFactory factory = (ProductionFactory) productionMan.getFactory(block.getLocation());
e.setCancelled(true);
if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(block)) || !FactoryModPlugin.CITADEL_ENABLED)
{
factory.destroy(block.getLocation());
productionMan.removeFactory(factory);
}
}
}
}
}
/**
* Called when a block burns
* Nearly the same as blockBreakEvent
*/
@EventHandler
public void burnListener(BlockBurnEvent e)
{
Block block = e.getBlock();
if (factoryMan.factoryExistsAt(block.getLocation()))
{
if (productionMan.factoryExistsAt(block.getLocation()))
{
ProductionFactory factory = (ProductionFactory) productionMan.getFactory(block.getLocation());
e.setCancelled(true);
if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(block)) || !FactoryModPlugin.CITADEL_ENABLED)
{
factory.destroy(block.getLocation());
productionMan.removeFactory(factory);
}
}
}
}
/**
* Called when a player left or right clicks.
* Takes care of cycling recipes turning factory's on and off, etc.
*/
@EventHandler
public void playerInteractionEvent(PlayerInteractEvent e)
{
Block clicked = e.getClickedBlock();
Player player = e.getPlayer();
//if the player left clicked a block
if (e.getAction().equals(Action.LEFT_CLICK_BLOCK))
{
//If the player was holding a item matching the interaction material
if (player.getItemInHand().getType() == FactoryModPlugin.FACTORY_INTERACTION_MATERIAL)
{
//If the material which was clicked is the central block material
if (clicked.getType() == FactoryModPlugin.CENTRAL_BLOCK_MATERIAL)
{
//is there a factory at the clicked location?
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
- PlayerReinforcement reinforcment = (PlayerReinforcement) getReinforcement(clicked);
//if the player is allowed to interact with that block.
- if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) || !FactoryModPlugin.CITADEL_ENABLED ||
- (reinforcment.isAccessible(player)))
+ if ((!FactoryModPlugin.CITADEL_ENABLED || FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) ||
+ (((PlayerReinforcement) getReinforcement(clicked)).isAccessible(player)))
{
//if there is a production Factory at the clicked location
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
//toggle the recipe, and print the returned message.
InteractionResponse.messagePlayerResult(player, production.toggleRecipes());
}
}
//if the player does NOT have acssess to the block that was clicked
else
{
//return a error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
//if no factory exists at the clicked location
else
{
- PlayerReinforcement reinforcment = (PlayerReinforcement) getReinforcement(clicked);
//if the player is allowed to interact with that block.
- if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) || !FactoryModPlugin.CITADEL_ENABLED ||
- (reinforcment.isAccessible(player)))
+ if ((!FactoryModPlugin.CITADEL_ENABLED || FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) ||
+ (((PlayerReinforcement) getReinforcement(clicked)).isAccessible(player)))
{
createFactory(clicked.getLocation(), player);
}
//if the player does NOT have acssess to the block that was clicked
else
{
//return a error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
//if the clicked block is a furnace
else if (clicked.getType() == Material.FURNACE || clicked.getType() == Material.BURNING_FURNACE)
{
//if there is a factory at that location
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
- PlayerReinforcement reinforcment = (PlayerReinforcement) getReinforcement(clicked);
//if the player is allowed to interact with that block.
- if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) || !FactoryModPlugin.CITADEL_ENABLED ||
- (reinforcment.isAccessible(player)))
+ if ((!FactoryModPlugin.CITADEL_ENABLED || FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) ||
+ (((PlayerReinforcement) getReinforcement(clicked)).isAccessible(player)))
{
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
//toggle the power, and print the returned message
InteractionResponse.messagePlayerResult(player, production.togglePower());
}
}
//if the player is NOT allowed to interact with the clicked block.
else
{
//return error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
//if the block clicked is a chest
else if (clicked.getType() == Material.CHEST)
{
//is there a factory there?
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
- PlayerReinforcement reinforcment = (PlayerReinforcement) getReinforcement(clicked);
//if the player is allowed to interact with that block?
- if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) || !FactoryModPlugin.CITADEL_ENABLED ||
- (reinforcment.isAccessible(player)))
+ if ((!FactoryModPlugin.CITADEL_ENABLED || FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) ||
+ (((PlayerReinforcement) getReinforcement(clicked)).isAccessible(player)))
{
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
int procentDone = Math.round(production.getProductionTimer()*100/production.getCurrentRecipe().getProductionTime());
//if the clicked factory is turned on, print information
if (production.getActive() == true)
{
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "----------Factory Information---------"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Type : " + production.getProductionFactoryProperties().getName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Status : On"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe : " + production.getCurrentRecipe().getRecipeName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe output: " + production.getCurrentRecipe().getBatchAmount() + " " + production.getCurrentRecipe().getOutput().getData().toString() + InventoryMethods.getEnchantmentsMessage(production.getCurrentRecipe().getEnchantments())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe input: " + InventoryMethods.getMaterialsNeededMessage(production.getCurrentRecipe().getInput())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe fuel requirement: " + production.getCurrentRecipe().getProductionTime()/production.getProductionFactoryProperties().getEnergyTime()*production.getProductionFactoryProperties().getEnergyMaterial().getAmount() + " " + production.getProductionFactoryProperties().getEnergyMaterial().getData().toString()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe production time: " + production.getCurrentRecipe().getProductionTime() + " seconds("+ production.getCurrentRecipe().getProductionTime()*FactoryModPlugin.TICKS_PER_SECOND + " ticks)"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Progress: " + procentDone + "%"));
}
//if the factory is turned off, print information
else
{
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "----------Factory Information---------"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Type : " + production.getProductionFactoryProperties().getName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Status: Off"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe: " + production.getCurrentRecipe().getRecipeName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe output: " + production.getCurrentRecipe().getBatchAmount() + " " + production.getCurrentRecipe().getOutput().getData().toString() + InventoryMethods.getEnchantmentsMessage(production.getCurrentRecipe().getEnchantments())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe input: " + InventoryMethods.getMaterialsNeededMessage(production.getCurrentRecipe().getInput())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe fuel requirement: " + production.getCurrentRecipe().getProductionTime()/production.getProductionFactoryProperties().getEnergyTime()*production.getProductionFactoryProperties().getEnergyMaterial().getAmount() + " " + production.getProductionFactoryProperties().getEnergyMaterial().getData().toString()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe production time: " + production.getCurrentRecipe().getProductionTime() + " seconds("+ production.getCurrentRecipe().getProductionTime()*FactoryModPlugin.TICKS_PER_SECOND + " ticks)"));
}
}
}
//if the player is NOT allowed to interact with the clicked block
else
{
//return error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
}
}
//if the player right clicked a block
else if(e.getAction() == Action.RIGHT_CLICK_BLOCK)
{
//if the player right clicked a chest
if (clicked.getType() == Material.CHEST)
{
//is the chest part of a factory?
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
- PlayerReinforcement reinforcment = (PlayerReinforcement) getReinforcement(clicked);
//if the player is allowed to interact with that block.
- if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) || !FactoryModPlugin.CITADEL_ENABLED ||
- (reinforcment.isAccessible(player)))
+ if ((!FactoryModPlugin.CITADEL_ENABLED || FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) ||
+ (((PlayerReinforcement) getReinforcement(clicked)).isAccessible(player)))
{
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
//is the factory turned on?
if (production.getActive() == true)
{
//return error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You can't access the chest while the factory is active! Turn it off first!" ));
e.setCancelled(true);
}
}
}
//if the player is NOT allowed to interact with the block
else
{
//No need to get 2 messages, citadel already does 1. e InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
}
}
private Location westLoc(Location loc)
{
Location newLoc = loc.clone();
newLoc.add(-1, 0, 0);
return newLoc;
}
private Location eastLoc(Location loc)
{
Location newLoc = loc.clone();
newLoc.add(1, 0, 0);
return newLoc;
}
private Location northLoc(Location loc)
{
Location newLoc = loc.clone();
newLoc.add(0, 0, -1);
return newLoc;
}
private Location southLoc(Location loc)
{
Location newLoc = loc.clone();
newLoc.add(0, 0, 1);
return newLoc;
}
private void createFactory(Location loc, Player player)
{
Location northLocation = northLoc(loc);
Location southLocation = southLoc(loc);
Location eastLocation = eastLoc(loc);
Location westLocation = westLoc(loc);
Block northBlock = northLocation.getBlock();
Block southBlock = southLocation.getBlock();
Block eastBlock = eastLocation.getBlock();
Block westBlock = westLocation.getBlock();
Material northType = northBlock.getType();
Material southType = southBlock.getType();
Material eastType = eastBlock.getType();
Material westType = westBlock.getType();
if(northType.getId()== 61 || northType.getId()== 62)
{
if(southType.getId()== 54)
{
InteractionResponse.messagePlayerResult(player, productionMan.createFactory(loc, southLocation, northLocation));
}
}
if(westType.getId()== 61 || westType.getId() == 62)
{
if(eastType.getId()== 54)
{
InteractionResponse.messagePlayerResult(player, productionMan.createFactory(loc, eastLocation, westLocation));
}
}
if(southType.getId()== 61 || southType.getId()== 62)
{
if(northType.getId()== 54)
{
InteractionResponse.messagePlayerResult(player, productionMan.createFactory(loc, northLocation, southLocation));
}
}
if(eastType.getId()== 61 || eastType.getId()== 62)
{
if(westType.getId()== 54)
{
InteractionResponse.messagePlayerResult(player, productionMan.createFactory(loc, westLocation, eastLocation));
}
}
}
}
| false | true | public void playerInteractionEvent(PlayerInteractEvent e)
{
Block clicked = e.getClickedBlock();
Player player = e.getPlayer();
//if the player left clicked a block
if (e.getAction().equals(Action.LEFT_CLICK_BLOCK))
{
//If the player was holding a item matching the interaction material
if (player.getItemInHand().getType() == FactoryModPlugin.FACTORY_INTERACTION_MATERIAL)
{
//If the material which was clicked is the central block material
if (clicked.getType() == FactoryModPlugin.CENTRAL_BLOCK_MATERIAL)
{
//is there a factory at the clicked location?
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
PlayerReinforcement reinforcment = (PlayerReinforcement) getReinforcement(clicked);
//if the player is allowed to interact with that block.
if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) || !FactoryModPlugin.CITADEL_ENABLED ||
(reinforcment.isAccessible(player)))
{
//if there is a production Factory at the clicked location
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
//toggle the recipe, and print the returned message.
InteractionResponse.messagePlayerResult(player, production.toggleRecipes());
}
}
//if the player does NOT have acssess to the block that was clicked
else
{
//return a error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
//if no factory exists at the clicked location
else
{
PlayerReinforcement reinforcment = (PlayerReinforcement) getReinforcement(clicked);
//if the player is allowed to interact with that block.
if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) || !FactoryModPlugin.CITADEL_ENABLED ||
(reinforcment.isAccessible(player)))
{
createFactory(clicked.getLocation(), player);
}
//if the player does NOT have acssess to the block that was clicked
else
{
//return a error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
//if the clicked block is a furnace
else if (clicked.getType() == Material.FURNACE || clicked.getType() == Material.BURNING_FURNACE)
{
//if there is a factory at that location
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
PlayerReinforcement reinforcment = (PlayerReinforcement) getReinforcement(clicked);
//if the player is allowed to interact with that block.
if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) || !FactoryModPlugin.CITADEL_ENABLED ||
(reinforcment.isAccessible(player)))
{
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
//toggle the power, and print the returned message
InteractionResponse.messagePlayerResult(player, production.togglePower());
}
}
//if the player is NOT allowed to interact with the clicked block.
else
{
//return error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
//if the block clicked is a chest
else if (clicked.getType() == Material.CHEST)
{
//is there a factory there?
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
PlayerReinforcement reinforcment = (PlayerReinforcement) getReinforcement(clicked);
//if the player is allowed to interact with that block?
if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) || !FactoryModPlugin.CITADEL_ENABLED ||
(reinforcment.isAccessible(player)))
{
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
int procentDone = Math.round(production.getProductionTimer()*100/production.getCurrentRecipe().getProductionTime());
//if the clicked factory is turned on, print information
if (production.getActive() == true)
{
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "----------Factory Information---------"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Type : " + production.getProductionFactoryProperties().getName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Status : On"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe : " + production.getCurrentRecipe().getRecipeName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe output: " + production.getCurrentRecipe().getBatchAmount() + " " + production.getCurrentRecipe().getOutput().getData().toString() + InventoryMethods.getEnchantmentsMessage(production.getCurrentRecipe().getEnchantments())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe input: " + InventoryMethods.getMaterialsNeededMessage(production.getCurrentRecipe().getInput())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe fuel requirement: " + production.getCurrentRecipe().getProductionTime()/production.getProductionFactoryProperties().getEnergyTime()*production.getProductionFactoryProperties().getEnergyMaterial().getAmount() + " " + production.getProductionFactoryProperties().getEnergyMaterial().getData().toString()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe production time: " + production.getCurrentRecipe().getProductionTime() + " seconds("+ production.getCurrentRecipe().getProductionTime()*FactoryModPlugin.TICKS_PER_SECOND + " ticks)"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Progress: " + procentDone + "%"));
}
//if the factory is turned off, print information
else
{
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "----------Factory Information---------"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Type : " + production.getProductionFactoryProperties().getName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Status: Off"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe: " + production.getCurrentRecipe().getRecipeName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe output: " + production.getCurrentRecipe().getBatchAmount() + " " + production.getCurrentRecipe().getOutput().getData().toString() + InventoryMethods.getEnchantmentsMessage(production.getCurrentRecipe().getEnchantments())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe input: " + InventoryMethods.getMaterialsNeededMessage(production.getCurrentRecipe().getInput())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe fuel requirement: " + production.getCurrentRecipe().getProductionTime()/production.getProductionFactoryProperties().getEnergyTime()*production.getProductionFactoryProperties().getEnergyMaterial().getAmount() + " " + production.getProductionFactoryProperties().getEnergyMaterial().getData().toString()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe production time: " + production.getCurrentRecipe().getProductionTime() + " seconds("+ production.getCurrentRecipe().getProductionTime()*FactoryModPlugin.TICKS_PER_SECOND + " ticks)"));
}
}
}
//if the player is NOT allowed to interact with the clicked block
else
{
//return error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
}
}
//if the player right clicked a block
else if(e.getAction() == Action.RIGHT_CLICK_BLOCK)
{
//if the player right clicked a chest
if (clicked.getType() == Material.CHEST)
{
//is the chest part of a factory?
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
PlayerReinforcement reinforcment = (PlayerReinforcement) getReinforcement(clicked);
//if the player is allowed to interact with that block.
if ((FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) || !FactoryModPlugin.CITADEL_ENABLED ||
(reinforcment.isAccessible(player)))
{
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
//is the factory turned on?
if (production.getActive() == true)
{
//return error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You can't access the chest while the factory is active! Turn it off first!" ));
e.setCancelled(true);
}
}
}
//if the player is NOT allowed to interact with the block
else
{
//No need to get 2 messages, citadel already does 1. e InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
}
}
| public void playerInteractionEvent(PlayerInteractEvent e)
{
Block clicked = e.getClickedBlock();
Player player = e.getPlayer();
//if the player left clicked a block
if (e.getAction().equals(Action.LEFT_CLICK_BLOCK))
{
//If the player was holding a item matching the interaction material
if (player.getItemInHand().getType() == FactoryModPlugin.FACTORY_INTERACTION_MATERIAL)
{
//If the material which was clicked is the central block material
if (clicked.getType() == FactoryModPlugin.CENTRAL_BLOCK_MATERIAL)
{
//is there a factory at the clicked location?
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
//if the player is allowed to interact with that block.
if ((!FactoryModPlugin.CITADEL_ENABLED || FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) ||
(((PlayerReinforcement) getReinforcement(clicked)).isAccessible(player)))
{
//if there is a production Factory at the clicked location
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
//toggle the recipe, and print the returned message.
InteractionResponse.messagePlayerResult(player, production.toggleRecipes());
}
}
//if the player does NOT have acssess to the block that was clicked
else
{
//return a error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
//if no factory exists at the clicked location
else
{
//if the player is allowed to interact with that block.
if ((!FactoryModPlugin.CITADEL_ENABLED || FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) ||
(((PlayerReinforcement) getReinforcement(clicked)).isAccessible(player)))
{
createFactory(clicked.getLocation(), player);
}
//if the player does NOT have acssess to the block that was clicked
else
{
//return a error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
//if the clicked block is a furnace
else if (clicked.getType() == Material.FURNACE || clicked.getType() == Material.BURNING_FURNACE)
{
//if there is a factory at that location
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
//if the player is allowed to interact with that block.
if ((!FactoryModPlugin.CITADEL_ENABLED || FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) ||
(((PlayerReinforcement) getReinforcement(clicked)).isAccessible(player)))
{
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
//toggle the power, and print the returned message
InteractionResponse.messagePlayerResult(player, production.togglePower());
}
}
//if the player is NOT allowed to interact with the clicked block.
else
{
//return error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
//if the block clicked is a chest
else if (clicked.getType() == Material.CHEST)
{
//is there a factory there?
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
//if the player is allowed to interact with that block?
if ((!FactoryModPlugin.CITADEL_ENABLED || FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) ||
(((PlayerReinforcement) getReinforcement(clicked)).isAccessible(player)))
{
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
int procentDone = Math.round(production.getProductionTimer()*100/production.getCurrentRecipe().getProductionTime());
//if the clicked factory is turned on, print information
if (production.getActive() == true)
{
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "----------Factory Information---------"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Type : " + production.getProductionFactoryProperties().getName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Status : On"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe : " + production.getCurrentRecipe().getRecipeName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe output: " + production.getCurrentRecipe().getBatchAmount() + " " + production.getCurrentRecipe().getOutput().getData().toString() + InventoryMethods.getEnchantmentsMessage(production.getCurrentRecipe().getEnchantments())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe input: " + InventoryMethods.getMaterialsNeededMessage(production.getCurrentRecipe().getInput())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe fuel requirement: " + production.getCurrentRecipe().getProductionTime()/production.getProductionFactoryProperties().getEnergyTime()*production.getProductionFactoryProperties().getEnergyMaterial().getAmount() + " " + production.getProductionFactoryProperties().getEnergyMaterial().getData().toString()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe production time: " + production.getCurrentRecipe().getProductionTime() + " seconds("+ production.getCurrentRecipe().getProductionTime()*FactoryModPlugin.TICKS_PER_SECOND + " ticks)"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Progress: " + procentDone + "%"));
}
//if the factory is turned off, print information
else
{
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "----------Factory Information---------"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Type : " + production.getProductionFactoryProperties().getName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Status: Off"));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe: " + production.getCurrentRecipe().getRecipeName()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe output: " + production.getCurrentRecipe().getBatchAmount() + " " + production.getCurrentRecipe().getOutput().getData().toString() + InventoryMethods.getEnchantmentsMessage(production.getCurrentRecipe().getEnchantments())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe input: " + InventoryMethods.getMaterialsNeededMessage(production.getCurrentRecipe().getInput())));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe fuel requirement: " + production.getCurrentRecipe().getProductionTime()/production.getProductionFactoryProperties().getEnergyTime()*production.getProductionFactoryProperties().getEnergyMaterial().getAmount() + " " + production.getProductionFactoryProperties().getEnergyMaterial().getData().toString()));
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.SUCCESS, "Recipe production time: " + production.getCurrentRecipe().getProductionTime() + " seconds("+ production.getCurrentRecipe().getProductionTime()*FactoryModPlugin.TICKS_PER_SECOND + " ticks)"));
}
}
}
//if the player is NOT allowed to interact with the clicked block
else
{
//return error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
}
}
//if the player right clicked a block
else if(e.getAction() == Action.RIGHT_CLICK_BLOCK)
{
//if the player right clicked a chest
if (clicked.getType() == Material.CHEST)
{
//is the chest part of a factory?
if (factoryMan.factoryExistsAt(clicked.getLocation()))
{
//if the player is allowed to interact with that block.
if ((!FactoryModPlugin.CITADEL_ENABLED || FactoryModPlugin.CITADEL_ENABLED && !isReinforced(clicked)) ||
(((PlayerReinforcement) getReinforcement(clicked)).isAccessible(player)))
{
if (productionMan.factoryExistsAt(clicked.getLocation()))
{
ProductionFactory production = (ProductionFactory) productionMan.getFactory(clicked.getLocation());
//is the factory turned on?
if (production.getActive() == true)
{
//return error message
InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You can't access the chest while the factory is active! Turn it off first!" ));
e.setCancelled(true);
}
}
}
//if the player is NOT allowed to interact with the block
else
{
//No need to get 2 messages, citadel already does 1. e InteractionResponse.messagePlayerResult(player, new InteractionResponse(InteractionResult.FAILURE,"You do not have permission to use that block!" ));
}
}
}
}
}
|
diff --git a/org/xbill/DNS/utils/hexdump.java b/org/xbill/DNS/utils/hexdump.java
index b85e732..0f5a9dc 100644
--- a/org/xbill/DNS/utils/hexdump.java
+++ b/org/xbill/DNS/utils/hexdump.java
@@ -1,54 +1,55 @@
// Copyright (c) 1999 Brian Wellington ([email protected])
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS.utils;
import java.io.*;
/**
* A routine to produce a nice looking hex dump
*
* @author Brian Wellington
*/
public class hexdump {
public static String
dump(String description, byte [] b, int offset, int length) {
StringBuffer sb = new StringBuffer();
sb.append(length);
- sb.append(" bytes");
+ sb.append("b");
if (description != null) {
sb.append(" (");
sb.append(description);
sb.append(')');
}
sb.append(':');
int prefixlen = sb.toString().length();
prefixlen = (prefixlen + 8) & ~ 7;
sb.append('\t');
int perline = (80 - prefixlen) / 3;
for (int i = 0; i < length; i++) {
if (i != 0 && i % perline == 0) {
+ sb.append('\n');
for (int j = 0; j < prefixlen; j+=8)
- sb.append("\n\t");
+ sb.append('\t');
}
int value = (int)(b[i + offset]) & 0xFF;
if (value < 16)
sb.append('0');
sb.append(Integer.toHexString(value));
sb.append(' ');
}
sb.append('\n');
return sb.toString();
}
public static String
dump(String s, byte [] b) {
return dump(s, b, 0, b.length);
}
}
| false | true | public static String
dump(String description, byte [] b, int offset, int length) {
StringBuffer sb = new StringBuffer();
sb.append(length);
sb.append(" bytes");
if (description != null) {
sb.append(" (");
sb.append(description);
sb.append(')');
}
sb.append(':');
int prefixlen = sb.toString().length();
prefixlen = (prefixlen + 8) & ~ 7;
sb.append('\t');
int perline = (80 - prefixlen) / 3;
for (int i = 0; i < length; i++) {
if (i != 0 && i % perline == 0) {
for (int j = 0; j < prefixlen; j+=8)
sb.append("\n\t");
}
int value = (int)(b[i + offset]) & 0xFF;
if (value < 16)
sb.append('0');
sb.append(Integer.toHexString(value));
sb.append(' ');
}
sb.append('\n');
return sb.toString();
}
| public static String
dump(String description, byte [] b, int offset, int length) {
StringBuffer sb = new StringBuffer();
sb.append(length);
sb.append("b");
if (description != null) {
sb.append(" (");
sb.append(description);
sb.append(')');
}
sb.append(':');
int prefixlen = sb.toString().length();
prefixlen = (prefixlen + 8) & ~ 7;
sb.append('\t');
int perline = (80 - prefixlen) / 3;
for (int i = 0; i < length; i++) {
if (i != 0 && i % perline == 0) {
sb.append('\n');
for (int j = 0; j < prefixlen; j+=8)
sb.append('\t');
}
int value = (int)(b[i + offset]) & 0xFF;
if (value < 16)
sb.append('0');
sb.append(Integer.toHexString(value));
sb.append(' ');
}
sb.append('\n');
return sb.toString();
}
|
diff --git a/core/src/main/java/org/infinispan/marshall/exts/EnumSetExternalizer.java b/core/src/main/java/org/infinispan/marshall/exts/EnumSetExternalizer.java
index 73dc648a97..4d0c571fa4 100644
--- a/core/src/main/java/org/infinispan/marshall/exts/EnumSetExternalizer.java
+++ b/core/src/main/java/org/infinispan/marshall/exts/EnumSetExternalizer.java
@@ -1,131 +1,133 @@
package org.infinispan.marshall.exts;
import net.jcip.annotations.Immutable;
import org.infinispan.commons.io.UnsignedNumeric;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.commons.marshall.MarshallUtil;
import org.infinispan.commons.util.Util;
import org.infinispan.marshall.core.Ids;
import org.jboss.marshalling.util.IdentityIntMap;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.AbstractSet;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
/**
* {@link EnumSet} externalizer.
*
* @author Galder Zamarreño
* @since 6.0
*/
@Immutable
public class EnumSetExternalizer extends AbstractExternalizer<Set> {
private static final int UNKNOWN_ENUM_SET = 0;
private static final int ENUM_SET = 1;
private static final int REGULAR_ENUM_SET = 2;
private static final int JUMBO_ENUM_SET = 3;
private static final int MINI_ENUM_SET = 4; // IBM class
private static final int HUGE_ENUM_SET = 5; // IBM class
private final IdentityIntMap<Class<?>> numbers = new IdentityIntMap<Class<?>>(3);
public EnumSetExternalizer() {
numbers.put(EnumSet.class, ENUM_SET);
addEnumSetClass(getRegularEnumSetClass(), REGULAR_ENUM_SET);
addEnumSetClass(getJumboEnumSetClass(), JUMBO_ENUM_SET);
addEnumSetClass(getMiniEnumSetClass(), MINI_ENUM_SET);
addEnumSetClass(getHugeEnumSetClass(), HUGE_ENUM_SET);
}
private void addEnumSetClass(Class<EnumSet> clazz, int index) {
if (clazz != null)
numbers.put(clazz, index);
}
@Override
public void writeObject(ObjectOutput output, Set set) throws IOException {
int number = numbers.get(set.getClass(), UNKNOWN_ENUM_SET);
if (number == UNKNOWN_ENUM_SET) {
// Fallback on standard object write
output.writeObject(set);
} else {
output.writeByte(number);
MarshallUtil.marshallCollection(set, output);
}
}
@Override
public Set readObject(ObjectInput input) throws IOException, ClassNotFoundException {
int magicNumber = input.readUnsignedByte();
if (magicNumber == UNKNOWN_ENUM_SET)
return (Set) input.readObject();
AbstractSet<Enum> enumSet = null;
int size = UnsignedNumeric.readUnsignedInt(input);
for (int i = 0; i < size; i++) {
switch (magicNumber) {
case ENUM_SET:
case REGULAR_ENUM_SET:
case JUMBO_ENUM_SET:
+ case MINI_ENUM_SET:
+ case HUGE_ENUM_SET:
if (i == 0)
enumSet = EnumSet.of((Enum) input.readObject());
else
enumSet.add((Enum) input.readObject());
break;
}
}
return enumSet;
}
@Override
public Integer getId() {
return Ids.ENUM_SET_ID;
}
@Override
public Set<Class<? extends Set>> getTypeClasses() {
Set<Class<? extends Set>> set = new HashSet<Class<? extends Set>>();
set.add(EnumSet.class);
addEnumSetType(getRegularEnumSetClass(), set);
addEnumSetType(getJumboEnumSetClass(), set);
addEnumSetType(getMiniEnumSetClass(), set);
addEnumSetType(getHugeEnumSetClass(), set);
return set;
}
private void addEnumSetType(Class<? extends Set> clazz, Set<Class<? extends Set>> typeSet) {
if (clazz != null)
typeSet.add(clazz);
}
private Class<EnumSet> getJumboEnumSetClass() {
return getEnumSetClass("java.util.JumboEnumSet");
}
private Class<EnumSet> getRegularEnumSetClass() {
return getEnumSetClass("java.util.RegularEnumSet");
}
private Class<EnumSet> getMiniEnumSetClass() {
return getEnumSetClass("java.util.MiniEnumSet");
}
private Class<EnumSet> getHugeEnumSetClass() {
return getEnumSetClass("java.util.HugeEnumSet");
}
private Class<EnumSet> getEnumSetClass(String className) {
try {
return Util.loadClassStrict(className, EnumSet.class.getClassLoader());
} catch (ClassNotFoundException e) {
return null; // Ignore
}
}
}
| true | true | public Set readObject(ObjectInput input) throws IOException, ClassNotFoundException {
int magicNumber = input.readUnsignedByte();
if (magicNumber == UNKNOWN_ENUM_SET)
return (Set) input.readObject();
AbstractSet<Enum> enumSet = null;
int size = UnsignedNumeric.readUnsignedInt(input);
for (int i = 0; i < size; i++) {
switch (magicNumber) {
case ENUM_SET:
case REGULAR_ENUM_SET:
case JUMBO_ENUM_SET:
if (i == 0)
enumSet = EnumSet.of((Enum) input.readObject());
else
enumSet.add((Enum) input.readObject());
break;
}
}
return enumSet;
}
| public Set readObject(ObjectInput input) throws IOException, ClassNotFoundException {
int magicNumber = input.readUnsignedByte();
if (magicNumber == UNKNOWN_ENUM_SET)
return (Set) input.readObject();
AbstractSet<Enum> enumSet = null;
int size = UnsignedNumeric.readUnsignedInt(input);
for (int i = 0; i < size; i++) {
switch (magicNumber) {
case ENUM_SET:
case REGULAR_ENUM_SET:
case JUMBO_ENUM_SET:
case MINI_ENUM_SET:
case HUGE_ENUM_SET:
if (i == 0)
enumSet = EnumSet.of((Enum) input.readObject());
else
enumSet.add((Enum) input.readObject());
break;
}
}
return enumSet;
}
|
diff --git a/ufd/GreatestCommonDivisorModular.java b/ufd/GreatestCommonDivisorModular.java
index b9c7bbc4..12147e63 100644
--- a/ufd/GreatestCommonDivisorModular.java
+++ b/ufd/GreatestCommonDivisorModular.java
@@ -1,286 +1,290 @@
/*
* $Id$
*/
package edu.jas.ufd;
import org.apache.log4j.Logger;
import edu.jas.structure.GcdRingElem;
import edu.jas.arith.BigInteger;
import edu.jas.arith.ModInteger;
import edu.jas.arith.PrimeList;
import edu.jas.poly.GenPolynomial;
import edu.jas.poly.GenPolynomialRing;
import edu.jas.poly.ExpVector;
import edu.jas.poly.PolyUtil;
/**
* Greatest common divisor algorithms with primitive polynomial remainder sequence.
* @author Heinz Kredel
*/
public class GreatestCommonDivisorModular //<C extends GcdRingElem<C> >
extends GreatestCommonDivisorAbstract<BigInteger> {
private static final Logger logger = Logger.getLogger(GreatestCommonDivisorModular.class);
private boolean debug = logger.isDebugEnabled();
protected final
GreatestCommonDivisorAbstract<ModInteger> mufd =
new GreatestCommonDivisorSimple<ModInteger>();
protected final
GreatestCommonDivisorAbstract<BigInteger> iufd =
new GreatestCommonDivisorSubres<BigInteger>();
/**
* Univariate GenPolynomial greatest comon divisor.
* Delegate to subresultant baseGcd, should not be needed.
* @param P univariate GenPolynomial.
* @param S univariate GenPolynomial.
* @return gcd(P,S).
*/
public GenPolynomial<BigInteger> baseGcd( GenPolynomial<BigInteger> P,
GenPolynomial<BigInteger> S ) {
return iufd.baseGcd(P,S);
}
/**
* Univariate GenPolynomial recursive greatest comon divisor.
* Delegate to subresultant recursiveGcd, should not be needed.
* @param P univariate recursive GenPolynomial.
* @param S univariate recursive GenPolynomial.
* @return gcd(P,S).
*/
public GenPolynomial<GenPolynomial<BigInteger>>
recursiveGcd( GenPolynomial<GenPolynomial<BigInteger>> P,
GenPolynomial<GenPolynomial<BigInteger>> S ) {
return iufd.recursiveGcd(P,S);
}
/**
* GenPolynomial greatest comon divisor, modular algorithm.
* @param P univariate GenPolynomial.
* @param S univariate GenPolynomial.
* @return gcd(P,S).
*/
public GenPolynomial<BigInteger> gcd( GenPolynomial<BigInteger> P,
GenPolynomial<BigInteger> S ) {
if ( S == null || S.isZERO() ) {
return P;
}
if ( P == null || P.isZERO() ) {
return S;
}
GenPolynomialRing<BigInteger> fac = P.ring;
if ( fac.nvar <= 1 ) {
//System.out.println("P = " + P);
//System.out.println("S = " + S);
GenPolynomial<BigInteger> T = baseGcd(P,S);
//System.out.println("T = " + T);
if ( false || debug ) {
GenPolynomial<BigInteger> X;
X = basePseudoRemainder(P,T);
System.out.println("X1 =" + X);
if ( !X.isZERO() ) {
throw new RuntimeException(this.getClass().getName()
+ " X != null");
}
X = basePseudoRemainder(S,T);
System.out.println("X2 =" + X);
if ( !X.isZERO() ) {
throw new RuntimeException(this.getClass().getName()
+ " X != null");
}
}
return T;
}
long e = P.degree(0);
long f = S.degree(0);
System.out.println("e = " + e);
System.out.println("f = " + f);
GenPolynomial<BigInteger> q;
GenPolynomial<BigInteger> r;
if ( f > e ) {
r = P;
q = S;
long g = f;
f = e;
e = g;
} else {
q = P;
r = S;
}
r = r.abs();
q = q.abs();
// compute contents and primitive parts
- GenPolynomial<BigInteger> a = content( r );
- GenPolynomial<BigInteger> b = content( q );
+ BigInteger a = baseContent( r );
+ BigInteger b = baseContent( q );
// gcd of coefficient contents
- GenPolynomial<BigInteger> c = gcd(a,b); // indirection
+ BigInteger c = gcd(a,b); // indirection
System.out.println("a = " + a);
System.out.println("b = " + b);
- //fix r = divide(r,a); // indirection
- //fix q = divide(q,b); // indirection
+ r = divide(r,a); // indirection
+ q = divide(q,b); // indirection
System.out.println("r = " + r);
System.out.println("q = " + q);
System.out.println("c = " + c);
if ( r.isONE() ) {
return r.multiply(c);
}
if ( q.isONE() ) {
return q.multiply(c);
}
// compute normalization factor
BigInteger ac = r.leadingBaseCoefficient();
BigInteger bc = q.leadingBaseCoefficient();
BigInteger cc = gcd(ac,bc); // indirection
System.out.println("ac = " + ac);
System.out.println("bc = " + bc);
System.out.println("cc = " + cc);
// compute norms
BigInteger an = r.maxNorm();
BigInteger bn = q.maxNorm();
BigInteger n = ( an.compareTo(bn) < 0 ? bn : an );
n = n.multiply( cc ).multiply( n.fromInteger(2) );
System.out.println("an = " + an);
System.out.println("bn = " + bn);
System.out.println("n = " + n);
// compute degree vectors
ExpVector rdegv = r.degreeVector();
ExpVector rdegv1 = rdegv.subst( 0, rdegv.getVal(0) + 1 );
ExpVector qdegv = q.degreeVector();
System.out.println("rdegv = " + rdegv);
System.out.println("rdegv1 = " + rdegv1);
System.out.println("qdegv = " + qdegv);
//compute factor coefficient bounds
BigInteger af = an.multiply( PolyUtil.factorBound( rdegv ) );
BigInteger bf = bn.multiply( PolyUtil.factorBound( qdegv ) );
BigInteger cf = ( af.compareTo(bf) < 0 ? bf : af );
cf = cf.multiply( cc.multiply( cc.fromInteger(8) ) );
System.out.println("af = " + af);
System.out.println("bf = " + bf);
System.out.println("cf = " + cf);
//initialize prime list and degree vector
PrimeList primes = new PrimeList();
- int pn = 3; //primes.size();
+ int pn = 10; //primes.size();
ModInteger cofac;
ModInteger cofacM = null;
GenPolynomial<ModInteger> qm;
GenPolynomial<ModInteger> rm;
GenPolynomialRing<ModInteger> mfac;
GenPolynomialRing<ModInteger> rfac = null;
int i = 0;
BigInteger M = null;
GenPolynomial<ModInteger> cp = null;
GenPolynomial<ModInteger> cm = null;
for ( java.math.BigInteger p : primes ) {
if ( ++i >= pn ) {
+ System.out.println("prime list exhausted");
+ return iufd.gcd(P,S);
//throw new RuntimeException("prime list exhausted");
- break;
+ //break;
}
cofac = new ModInteger( p, true );
System.out.println("cofac = " + cofac.getModul());
ModInteger nf = cofac.fromInteger( cc.getVal() );
System.out.println("nf = " + nf);
if ( nf.isZERO() ) {
continue;
}
mfac = new GenPolynomialRing<ModInteger>(cofac,fac.nvar,fac.tord,fac.getVars());
System.out.println("mfac = " + mfac);
qm = PolyUtil.<ModInteger>fromIntegerCoefficients(mfac,q);
System.out.println("qm = " + qm);
if ( !qm.degreeVector().equals( qdegv ) ) {
continue;
}
rm = PolyUtil.<ModInteger>fromIntegerCoefficients(mfac,r);
System.out.println("rm = " + rm);
if ( !rm.degreeVector().equals( rdegv ) ) {
continue;
}
// compute modular gcd
cm = mufd.gcd(rm,qm);
System.out.println("cm = " + cm);
if ( debug ) {
System.out.println("rm/cm = " + mufd.basePseudoRemainder(rm,cm));
System.out.println("qm/cm = " + mufd.basePseudoRemainder(qm,cm));
}
// test for constant g.c.d
if ( cm.isConstant() ) {
return fac.getONE();
}
cm = cm.multiply(nf);
System.out.println("cm = " + cm);
ExpVector mdegv = cm.degreeVector();
System.out.println("mdegv = " + mdegv);
if ( rdegv1.equals(mdegv) ) {
System.out.println("TL = 0");
// TL = 0
} else { // TL = 3
+ boolean ok = false;
if ( ExpVector.EVMT(rdegv1,mdegv) ) { // TL = 2
System.out.println("TL = 2");
M = null;
+ ok = true;
}
if ( ExpVector.EVMT(mdegv,rdegv1) ) { // TL = 1
- // cannot happen
System.out.println("TL = 1");
+ continue;
+ }
+ System.out.println("TL = 3");
+ if ( !ok ) {
M = null;
continue;
}
- //System.out.println("TL = 3");
- //M = null;
- //continue;
}
rdegv1 = mdegv;
if ( M == null ) {
M = new BigInteger(p);
cofacM = cofac;
rfac = mfac;
cp = cm;
rdegv1 = ExpVector.EVGCD(rdegv1,mdegv);
} else {
// apply chinese remainder algorithm
ModInteger mi = cofac.fromInteger( M.getVal() );
mi = mi.inverse(); // mod p
System.out.println("mi = " + mi);
M = M.multiply( new BigInteger(p) );
System.out.println("M = " + M);
cofacM = new ModInteger( M.getVal() );
rfac = new GenPolynomialRing<ModInteger>(cofacM,fac.nvar,fac.tord,fac.getVars());
cp = PolyUtil.chineseRemainder(rfac,cp,mi,cm);
}
System.out.println("cp = " + cp);
// test for completion
if ( n.compareTo(M) <= 0 ) {
System.out.println("done on M = " + M);
break;
}
// must use integer.sumNorm
java.math.BigInteger cmn = cp.sumNorm().getVal();
cmn = cmn.shiftLeft(2);
System.out.println("cmn = " + cmn);
if ( cmn.compareTo( M.getVal() ) <= 0 ) {
System.out.println("done on cmn = " + cmn);
//break;
}
}
// remove normalization
q = PolyUtil.integerFromModularCoefficients(fac,cp);
System.out.println("q = " + q);
q = basePrimitivePart( q ); // should be monic
System.out.println("q = " + q);
- return q.abs(); //fix .multiply( c );
+ return q.abs().multiply( c );
}
}
| false | true | public GenPolynomial<BigInteger> gcd( GenPolynomial<BigInteger> P,
GenPolynomial<BigInteger> S ) {
if ( S == null || S.isZERO() ) {
return P;
}
if ( P == null || P.isZERO() ) {
return S;
}
GenPolynomialRing<BigInteger> fac = P.ring;
if ( fac.nvar <= 1 ) {
//System.out.println("P = " + P);
//System.out.println("S = " + S);
GenPolynomial<BigInteger> T = baseGcd(P,S);
//System.out.println("T = " + T);
if ( false || debug ) {
GenPolynomial<BigInteger> X;
X = basePseudoRemainder(P,T);
System.out.println("X1 =" + X);
if ( !X.isZERO() ) {
throw new RuntimeException(this.getClass().getName()
+ " X != null");
}
X = basePseudoRemainder(S,T);
System.out.println("X2 =" + X);
if ( !X.isZERO() ) {
throw new RuntimeException(this.getClass().getName()
+ " X != null");
}
}
return T;
}
long e = P.degree(0);
long f = S.degree(0);
System.out.println("e = " + e);
System.out.println("f = " + f);
GenPolynomial<BigInteger> q;
GenPolynomial<BigInteger> r;
if ( f > e ) {
r = P;
q = S;
long g = f;
f = e;
e = g;
} else {
q = P;
r = S;
}
r = r.abs();
q = q.abs();
// compute contents and primitive parts
GenPolynomial<BigInteger> a = content( r );
GenPolynomial<BigInteger> b = content( q );
// gcd of coefficient contents
GenPolynomial<BigInteger> c = gcd(a,b); // indirection
System.out.println("a = " + a);
System.out.println("b = " + b);
//fix r = divide(r,a); // indirection
//fix q = divide(q,b); // indirection
System.out.println("r = " + r);
System.out.println("q = " + q);
System.out.println("c = " + c);
if ( r.isONE() ) {
return r.multiply(c);
}
if ( q.isONE() ) {
return q.multiply(c);
}
// compute normalization factor
BigInteger ac = r.leadingBaseCoefficient();
BigInteger bc = q.leadingBaseCoefficient();
BigInteger cc = gcd(ac,bc); // indirection
System.out.println("ac = " + ac);
System.out.println("bc = " + bc);
System.out.println("cc = " + cc);
// compute norms
BigInteger an = r.maxNorm();
BigInteger bn = q.maxNorm();
BigInteger n = ( an.compareTo(bn) < 0 ? bn : an );
n = n.multiply( cc ).multiply( n.fromInteger(2) );
System.out.println("an = " + an);
System.out.println("bn = " + bn);
System.out.println("n = " + n);
// compute degree vectors
ExpVector rdegv = r.degreeVector();
ExpVector rdegv1 = rdegv.subst( 0, rdegv.getVal(0) + 1 );
ExpVector qdegv = q.degreeVector();
System.out.println("rdegv = " + rdegv);
System.out.println("rdegv1 = " + rdegv1);
System.out.println("qdegv = " + qdegv);
//compute factor coefficient bounds
BigInteger af = an.multiply( PolyUtil.factorBound( rdegv ) );
BigInteger bf = bn.multiply( PolyUtil.factorBound( qdegv ) );
BigInteger cf = ( af.compareTo(bf) < 0 ? bf : af );
cf = cf.multiply( cc.multiply( cc.fromInteger(8) ) );
System.out.println("af = " + af);
System.out.println("bf = " + bf);
System.out.println("cf = " + cf);
//initialize prime list and degree vector
PrimeList primes = new PrimeList();
int pn = 3; //primes.size();
ModInteger cofac;
ModInteger cofacM = null;
GenPolynomial<ModInteger> qm;
GenPolynomial<ModInteger> rm;
GenPolynomialRing<ModInteger> mfac;
GenPolynomialRing<ModInteger> rfac = null;
int i = 0;
BigInteger M = null;
GenPolynomial<ModInteger> cp = null;
GenPolynomial<ModInteger> cm = null;
for ( java.math.BigInteger p : primes ) {
if ( ++i >= pn ) {
//throw new RuntimeException("prime list exhausted");
break;
}
cofac = new ModInteger( p, true );
System.out.println("cofac = " + cofac.getModul());
ModInteger nf = cofac.fromInteger( cc.getVal() );
System.out.println("nf = " + nf);
if ( nf.isZERO() ) {
continue;
}
mfac = new GenPolynomialRing<ModInteger>(cofac,fac.nvar,fac.tord,fac.getVars());
System.out.println("mfac = " + mfac);
qm = PolyUtil.<ModInteger>fromIntegerCoefficients(mfac,q);
System.out.println("qm = " + qm);
if ( !qm.degreeVector().equals( qdegv ) ) {
continue;
}
rm = PolyUtil.<ModInteger>fromIntegerCoefficients(mfac,r);
System.out.println("rm = " + rm);
if ( !rm.degreeVector().equals( rdegv ) ) {
continue;
}
// compute modular gcd
cm = mufd.gcd(rm,qm);
System.out.println("cm = " + cm);
if ( debug ) {
System.out.println("rm/cm = " + mufd.basePseudoRemainder(rm,cm));
System.out.println("qm/cm = " + mufd.basePseudoRemainder(qm,cm));
}
// test for constant g.c.d
if ( cm.isConstant() ) {
return fac.getONE();
}
cm = cm.multiply(nf);
System.out.println("cm = " + cm);
ExpVector mdegv = cm.degreeVector();
System.out.println("mdegv = " + mdegv);
if ( rdegv1.equals(mdegv) ) {
System.out.println("TL = 0");
// TL = 0
} else { // TL = 3
if ( ExpVector.EVMT(rdegv1,mdegv) ) { // TL = 2
System.out.println("TL = 2");
M = null;
}
if ( ExpVector.EVMT(mdegv,rdegv1) ) { // TL = 1
// cannot happen
System.out.println("TL = 1");
M = null;
continue;
}
//System.out.println("TL = 3");
//M = null;
//continue;
}
rdegv1 = mdegv;
if ( M == null ) {
M = new BigInteger(p);
cofacM = cofac;
rfac = mfac;
cp = cm;
rdegv1 = ExpVector.EVGCD(rdegv1,mdegv);
} else {
// apply chinese remainder algorithm
ModInteger mi = cofac.fromInteger( M.getVal() );
mi = mi.inverse(); // mod p
System.out.println("mi = " + mi);
M = M.multiply( new BigInteger(p) );
System.out.println("M = " + M);
cofacM = new ModInteger( M.getVal() );
rfac = new GenPolynomialRing<ModInteger>(cofacM,fac.nvar,fac.tord,fac.getVars());
cp = PolyUtil.chineseRemainder(rfac,cp,mi,cm);
}
System.out.println("cp = " + cp);
// test for completion
if ( n.compareTo(M) <= 0 ) {
System.out.println("done on M = " + M);
break;
}
// must use integer.sumNorm
java.math.BigInteger cmn = cp.sumNorm().getVal();
cmn = cmn.shiftLeft(2);
System.out.println("cmn = " + cmn);
if ( cmn.compareTo( M.getVal() ) <= 0 ) {
System.out.println("done on cmn = " + cmn);
//break;
}
}
// remove normalization
q = PolyUtil.integerFromModularCoefficients(fac,cp);
System.out.println("q = " + q);
q = basePrimitivePart( q ); // should be monic
System.out.println("q = " + q);
return q.abs(); //fix .multiply( c );
}
| public GenPolynomial<BigInteger> gcd( GenPolynomial<BigInteger> P,
GenPolynomial<BigInteger> S ) {
if ( S == null || S.isZERO() ) {
return P;
}
if ( P == null || P.isZERO() ) {
return S;
}
GenPolynomialRing<BigInteger> fac = P.ring;
if ( fac.nvar <= 1 ) {
//System.out.println("P = " + P);
//System.out.println("S = " + S);
GenPolynomial<BigInteger> T = baseGcd(P,S);
//System.out.println("T = " + T);
if ( false || debug ) {
GenPolynomial<BigInteger> X;
X = basePseudoRemainder(P,T);
System.out.println("X1 =" + X);
if ( !X.isZERO() ) {
throw new RuntimeException(this.getClass().getName()
+ " X != null");
}
X = basePseudoRemainder(S,T);
System.out.println("X2 =" + X);
if ( !X.isZERO() ) {
throw new RuntimeException(this.getClass().getName()
+ " X != null");
}
}
return T;
}
long e = P.degree(0);
long f = S.degree(0);
System.out.println("e = " + e);
System.out.println("f = " + f);
GenPolynomial<BigInteger> q;
GenPolynomial<BigInteger> r;
if ( f > e ) {
r = P;
q = S;
long g = f;
f = e;
e = g;
} else {
q = P;
r = S;
}
r = r.abs();
q = q.abs();
// compute contents and primitive parts
BigInteger a = baseContent( r );
BigInteger b = baseContent( q );
// gcd of coefficient contents
BigInteger c = gcd(a,b); // indirection
System.out.println("a = " + a);
System.out.println("b = " + b);
r = divide(r,a); // indirection
q = divide(q,b); // indirection
System.out.println("r = " + r);
System.out.println("q = " + q);
System.out.println("c = " + c);
if ( r.isONE() ) {
return r.multiply(c);
}
if ( q.isONE() ) {
return q.multiply(c);
}
// compute normalization factor
BigInteger ac = r.leadingBaseCoefficient();
BigInteger bc = q.leadingBaseCoefficient();
BigInteger cc = gcd(ac,bc); // indirection
System.out.println("ac = " + ac);
System.out.println("bc = " + bc);
System.out.println("cc = " + cc);
// compute norms
BigInteger an = r.maxNorm();
BigInteger bn = q.maxNorm();
BigInteger n = ( an.compareTo(bn) < 0 ? bn : an );
n = n.multiply( cc ).multiply( n.fromInteger(2) );
System.out.println("an = " + an);
System.out.println("bn = " + bn);
System.out.println("n = " + n);
// compute degree vectors
ExpVector rdegv = r.degreeVector();
ExpVector rdegv1 = rdegv.subst( 0, rdegv.getVal(0) + 1 );
ExpVector qdegv = q.degreeVector();
System.out.println("rdegv = " + rdegv);
System.out.println("rdegv1 = " + rdegv1);
System.out.println("qdegv = " + qdegv);
//compute factor coefficient bounds
BigInteger af = an.multiply( PolyUtil.factorBound( rdegv ) );
BigInteger bf = bn.multiply( PolyUtil.factorBound( qdegv ) );
BigInteger cf = ( af.compareTo(bf) < 0 ? bf : af );
cf = cf.multiply( cc.multiply( cc.fromInteger(8) ) );
System.out.println("af = " + af);
System.out.println("bf = " + bf);
System.out.println("cf = " + cf);
//initialize prime list and degree vector
PrimeList primes = new PrimeList();
int pn = 10; //primes.size();
ModInteger cofac;
ModInteger cofacM = null;
GenPolynomial<ModInteger> qm;
GenPolynomial<ModInteger> rm;
GenPolynomialRing<ModInteger> mfac;
GenPolynomialRing<ModInteger> rfac = null;
int i = 0;
BigInteger M = null;
GenPolynomial<ModInteger> cp = null;
GenPolynomial<ModInteger> cm = null;
for ( java.math.BigInteger p : primes ) {
if ( ++i >= pn ) {
System.out.println("prime list exhausted");
return iufd.gcd(P,S);
//throw new RuntimeException("prime list exhausted");
//break;
}
cofac = new ModInteger( p, true );
System.out.println("cofac = " + cofac.getModul());
ModInteger nf = cofac.fromInteger( cc.getVal() );
System.out.println("nf = " + nf);
if ( nf.isZERO() ) {
continue;
}
mfac = new GenPolynomialRing<ModInteger>(cofac,fac.nvar,fac.tord,fac.getVars());
System.out.println("mfac = " + mfac);
qm = PolyUtil.<ModInteger>fromIntegerCoefficients(mfac,q);
System.out.println("qm = " + qm);
if ( !qm.degreeVector().equals( qdegv ) ) {
continue;
}
rm = PolyUtil.<ModInteger>fromIntegerCoefficients(mfac,r);
System.out.println("rm = " + rm);
if ( !rm.degreeVector().equals( rdegv ) ) {
continue;
}
// compute modular gcd
cm = mufd.gcd(rm,qm);
System.out.println("cm = " + cm);
if ( debug ) {
System.out.println("rm/cm = " + mufd.basePseudoRemainder(rm,cm));
System.out.println("qm/cm = " + mufd.basePseudoRemainder(qm,cm));
}
// test for constant g.c.d
if ( cm.isConstant() ) {
return fac.getONE();
}
cm = cm.multiply(nf);
System.out.println("cm = " + cm);
ExpVector mdegv = cm.degreeVector();
System.out.println("mdegv = " + mdegv);
if ( rdegv1.equals(mdegv) ) {
System.out.println("TL = 0");
// TL = 0
} else { // TL = 3
boolean ok = false;
if ( ExpVector.EVMT(rdegv1,mdegv) ) { // TL = 2
System.out.println("TL = 2");
M = null;
ok = true;
}
if ( ExpVector.EVMT(mdegv,rdegv1) ) { // TL = 1
System.out.println("TL = 1");
continue;
}
System.out.println("TL = 3");
if ( !ok ) {
M = null;
continue;
}
}
rdegv1 = mdegv;
if ( M == null ) {
M = new BigInteger(p);
cofacM = cofac;
rfac = mfac;
cp = cm;
rdegv1 = ExpVector.EVGCD(rdegv1,mdegv);
} else {
// apply chinese remainder algorithm
ModInteger mi = cofac.fromInteger( M.getVal() );
mi = mi.inverse(); // mod p
System.out.println("mi = " + mi);
M = M.multiply( new BigInteger(p) );
System.out.println("M = " + M);
cofacM = new ModInteger( M.getVal() );
rfac = new GenPolynomialRing<ModInteger>(cofacM,fac.nvar,fac.tord,fac.getVars());
cp = PolyUtil.chineseRemainder(rfac,cp,mi,cm);
}
System.out.println("cp = " + cp);
// test for completion
if ( n.compareTo(M) <= 0 ) {
System.out.println("done on M = " + M);
break;
}
// must use integer.sumNorm
java.math.BigInteger cmn = cp.sumNorm().getVal();
cmn = cmn.shiftLeft(2);
System.out.println("cmn = " + cmn);
if ( cmn.compareTo( M.getVal() ) <= 0 ) {
System.out.println("done on cmn = " + cmn);
//break;
}
}
// remove normalization
q = PolyUtil.integerFromModularCoefficients(fac,cp);
System.out.println("q = " + q);
q = basePrimitivePart( q ); // should be monic
System.out.println("q = " + q);
return q.abs().multiply( c );
}
|
diff --git a/htroot/Banner.java b/htroot/Banner.java
index 4576d25d4..27b95ca15 100644
--- a/htroot/Banner.java
+++ b/htroot/Banner.java
@@ -1,116 +1,116 @@
// Banner.java
// -----------------------
// part of YaCy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
//
// This File is contributed by Marc Nause
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.visualization.RasterPlotter;
import de.anomic.search.Switchboard;
import de.anomic.search.SwitchboardConstants;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.graphics.NetworkGraph;
/** draw a banner with information about the peer */
public class Banner {
public static RasterPlotter respond(final RequestHeader header, final serverObjects post, final serverSwitch env) throws IOException {
final Switchboard sb = (Switchboard) env;
final String IMAGE = "htroot/env/grafics/yacy.gif";
int width = 468;
int height = 60;
- String bgcolor = "ddeeee";
+ String bgcolor = "e7effc";
String textcolor = "000000";
- String bordercolor = "aaaaaa";
+ String bordercolor = "5090d0";
if (post != null) {
bgcolor = post.get("bgcolor", bgcolor);
textcolor = post.get("textcolor", textcolor);
bordercolor = post.get("bordercolor", bordercolor);
width = post.getInt("width", width);
height = post.getInt("heigth", height);
}
String name = "";
long links = 0;
long words = 0;
int myppm = 0;
double myqph = 0;
String type = "";
final String network = env.getConfig(SwitchboardConstants.NETWORK_NAME, "unspecified").toUpperCase();
final int peers = sb.peers.sizeConnected() + 1; // the '+ 1': the own peer is not included in sizeConnected()
long nlinks = sb.peers.countActiveURL();
long nwords = sb.peers.countActiveRWI();
final double nqpm = sb.peers.countActiveQPM();
long nppm = sb.peers.countActivePPM();
double nqph = 0;
final yacySeed seed = sb.peers.mySeed();
if (seed != null){
name = seed.get(yacySeed.NAME, "-").toUpperCase();
links = seed.getLinkCount();
words = seed.getWordCount();
myppm = seed.getPPM();
myqph = 60d * seed.getQPM();
if (sb.peers.mySeed().isVirgin()) {
type = "VIRGIN";
nqph = Math.round(6000d * nqpm) / 100d;
} else if(sb.peers.mySeed().isJunior()) {
type = "JUNIOR";
nqph = Math.round(6000d * nqpm) / 100d;
} else if(sb.peers.mySeed().isSenior()) {
type = "SENIOR";
nlinks = nlinks + links;
nwords = nwords + words;
nqph = Math.round(6000d * nqpm + 100d * myqph) / 100d;
nppm = nppm + myppm;
} else if(sb.peers.mySeed().isPrincipal()) {
type = "PRINCIPAL";
nlinks = nlinks + links;
nwords = nwords + words;
nqph = Math.round(6000d * nqpm + 100d * myqph) / 100d;
nppm = nppm + myppm;
}
}
if (!NetworkGraph.logoIsLoaded()) {
ImageIO.setUseCache(false); // do not write a cache to disc; keep in RAM
final BufferedImage logo = ImageIO.read(new File(IMAGE));
return NetworkGraph.getBannerPicture(1000, width, height, bgcolor, textcolor, bordercolor, name, links, words, type, myppm, network, peers, nlinks, nwords, nqph, nppm, logo);
}
return NetworkGraph.getBannerPicture(1000, width, height, bgcolor, textcolor, bordercolor, name, links, words, type, myppm, network, peers, nlinks, nwords, nqph, nppm);
}
}
| false | true | public static RasterPlotter respond(final RequestHeader header, final serverObjects post, final serverSwitch env) throws IOException {
final Switchboard sb = (Switchboard) env;
final String IMAGE = "htroot/env/grafics/yacy.gif";
int width = 468;
int height = 60;
String bgcolor = "ddeeee";
String textcolor = "000000";
String bordercolor = "aaaaaa";
if (post != null) {
bgcolor = post.get("bgcolor", bgcolor);
textcolor = post.get("textcolor", textcolor);
bordercolor = post.get("bordercolor", bordercolor);
width = post.getInt("width", width);
height = post.getInt("heigth", height);
}
String name = "";
long links = 0;
long words = 0;
int myppm = 0;
double myqph = 0;
String type = "";
final String network = env.getConfig(SwitchboardConstants.NETWORK_NAME, "unspecified").toUpperCase();
final int peers = sb.peers.sizeConnected() + 1; // the '+ 1': the own peer is not included in sizeConnected()
long nlinks = sb.peers.countActiveURL();
long nwords = sb.peers.countActiveRWI();
final double nqpm = sb.peers.countActiveQPM();
long nppm = sb.peers.countActivePPM();
double nqph = 0;
final yacySeed seed = sb.peers.mySeed();
if (seed != null){
name = seed.get(yacySeed.NAME, "-").toUpperCase();
links = seed.getLinkCount();
words = seed.getWordCount();
myppm = seed.getPPM();
myqph = 60d * seed.getQPM();
if (sb.peers.mySeed().isVirgin()) {
type = "VIRGIN";
nqph = Math.round(6000d * nqpm) / 100d;
} else if(sb.peers.mySeed().isJunior()) {
type = "JUNIOR";
nqph = Math.round(6000d * nqpm) / 100d;
} else if(sb.peers.mySeed().isSenior()) {
type = "SENIOR";
nlinks = nlinks + links;
nwords = nwords + words;
nqph = Math.round(6000d * nqpm + 100d * myqph) / 100d;
nppm = nppm + myppm;
} else if(sb.peers.mySeed().isPrincipal()) {
type = "PRINCIPAL";
nlinks = nlinks + links;
nwords = nwords + words;
nqph = Math.round(6000d * nqpm + 100d * myqph) / 100d;
nppm = nppm + myppm;
}
}
if (!NetworkGraph.logoIsLoaded()) {
ImageIO.setUseCache(false); // do not write a cache to disc; keep in RAM
final BufferedImage logo = ImageIO.read(new File(IMAGE));
return NetworkGraph.getBannerPicture(1000, width, height, bgcolor, textcolor, bordercolor, name, links, words, type, myppm, network, peers, nlinks, nwords, nqph, nppm, logo);
}
return NetworkGraph.getBannerPicture(1000, width, height, bgcolor, textcolor, bordercolor, name, links, words, type, myppm, network, peers, nlinks, nwords, nqph, nppm);
}
| public static RasterPlotter respond(final RequestHeader header, final serverObjects post, final serverSwitch env) throws IOException {
final Switchboard sb = (Switchboard) env;
final String IMAGE = "htroot/env/grafics/yacy.gif";
int width = 468;
int height = 60;
String bgcolor = "e7effc";
String textcolor = "000000";
String bordercolor = "5090d0";
if (post != null) {
bgcolor = post.get("bgcolor", bgcolor);
textcolor = post.get("textcolor", textcolor);
bordercolor = post.get("bordercolor", bordercolor);
width = post.getInt("width", width);
height = post.getInt("heigth", height);
}
String name = "";
long links = 0;
long words = 0;
int myppm = 0;
double myqph = 0;
String type = "";
final String network = env.getConfig(SwitchboardConstants.NETWORK_NAME, "unspecified").toUpperCase();
final int peers = sb.peers.sizeConnected() + 1; // the '+ 1': the own peer is not included in sizeConnected()
long nlinks = sb.peers.countActiveURL();
long nwords = sb.peers.countActiveRWI();
final double nqpm = sb.peers.countActiveQPM();
long nppm = sb.peers.countActivePPM();
double nqph = 0;
final yacySeed seed = sb.peers.mySeed();
if (seed != null){
name = seed.get(yacySeed.NAME, "-").toUpperCase();
links = seed.getLinkCount();
words = seed.getWordCount();
myppm = seed.getPPM();
myqph = 60d * seed.getQPM();
if (sb.peers.mySeed().isVirgin()) {
type = "VIRGIN";
nqph = Math.round(6000d * nqpm) / 100d;
} else if(sb.peers.mySeed().isJunior()) {
type = "JUNIOR";
nqph = Math.round(6000d * nqpm) / 100d;
} else if(sb.peers.mySeed().isSenior()) {
type = "SENIOR";
nlinks = nlinks + links;
nwords = nwords + words;
nqph = Math.round(6000d * nqpm + 100d * myqph) / 100d;
nppm = nppm + myppm;
} else if(sb.peers.mySeed().isPrincipal()) {
type = "PRINCIPAL";
nlinks = nlinks + links;
nwords = nwords + words;
nqph = Math.round(6000d * nqpm + 100d * myqph) / 100d;
nppm = nppm + myppm;
}
}
if (!NetworkGraph.logoIsLoaded()) {
ImageIO.setUseCache(false); // do not write a cache to disc; keep in RAM
final BufferedImage logo = ImageIO.read(new File(IMAGE));
return NetworkGraph.getBannerPicture(1000, width, height, bgcolor, textcolor, bordercolor, name, links, words, type, myppm, network, peers, nlinks, nwords, nqph, nppm, logo);
}
return NetworkGraph.getBannerPicture(1000, width, height, bgcolor, textcolor, bordercolor, name, links, words, type, myppm, network, peers, nlinks, nwords, nqph, nppm);
}
|
diff --git a/modules/plugin/arcsde/sde-dummy/src/main/java/com/esri/sde/sdk/client/SeRasterColumn.java b/modules/plugin/arcsde/sde-dummy/src/main/java/com/esri/sde/sdk/client/SeRasterColumn.java
index 180b6c236..ec52e118c 100644
--- a/modules/plugin/arcsde/sde-dummy/src/main/java/com/esri/sde/sdk/client/SeRasterColumn.java
+++ b/modules/plugin/arcsde/sde-dummy/src/main/java/com/esri/sde/sdk/client/SeRasterColumn.java
@@ -1,27 +1,27 @@
package com.esri.sde.sdk.client;
public class SeRasterColumn {
public SeRasterColumn(SeConnection conn, SeObjectId id) throws SeException {}
public SeRasterColumn(SeConnection conn) throws SeException {}
public SeCoordinateReference getCoordRef() { return null; }
public String getName() { return null; }
public String getQualifiedTableName() { return null; }
public void setTableName(String name) {}
public void setDescription(String desc) {}
public void setRasterColumnName(String rColName) {}
public void setCoordRef(SeCoordinateReference coordref) {}
public void setConfigurationKeyword(String s) {}
public void create() {}
public String getTableName() {
return null;
}
- public Integer getID() throws SeException{
+ public SeObjectId getID() throws SeException{
// TODO Auto-generated method stub
return null;
}
}
| true | true | public Integer getID() throws SeException{
// TODO Auto-generated method stub
return null;
}
| public SeObjectId getID() throws SeException{
// TODO Auto-generated method stub
return null;
}
|
diff --git a/ini/trakem2/display/Display.java b/ini/trakem2/display/Display.java
index 133f4ba5..1bb6add8 100644
--- a/ini/trakem2/display/Display.java
+++ b/ini/trakem2/display/Display.java
@@ -1,5569 +1,5578 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005-2009 Albert Cardona and Rodney Douglas.
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 (http://www.gnu.org/licenses/gpl.txt )
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
**/
package ini.trakem2.display;
import ij.*;
import ij.gui.*;
import ij.io.OpenDialog;
import ij.io.DirectoryChooser;
import ij.measure.Calibration;
import ini.trakem2.Project;
import ini.trakem2.ControlWindow;
import ini.trakem2.persistence.DBObject;
import ini.trakem2.persistence.Loader;
import ini.trakem2.utils.IJError;
import ini.trakem2.imaging.PatchStack;
import ini.trakem2.imaging.Blending;
import ini.trakem2.imaging.Segmentation;
import ini.trakem2.utils.ProjectToolbar;
import ini.trakem2.utils.Utils;
import ini.trakem2.utils.DNDInsertImage;
import ini.trakem2.utils.Search;
import ini.trakem2.utils.Bureaucrat;
import ini.trakem2.utils.Worker;
import ini.trakem2.utils.Dispatcher;
import ini.trakem2.utils.Lock;
import ini.trakem2.utils.M;
import ini.trakem2.utils.OptionPanel;
import ini.trakem2.tree.*;
import ini.trakem2.display.graphics.*;
import ini.trakem2.imaging.StitchingTEM;
import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.event.*;
import mpicbg.trakem2.align.AlignLayersTask;
import mpicbg.trakem2.align.AlignTask;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Line2D;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.io.Writer;
import java.io.File;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
import lenscorrection.DistortionCorrectionTask;
import mpicbg.models.PointMatch;
import mpicbg.trakem2.transform.AffineModel3D;
/** A Display is a class to show a Layer and enable mouse and keyboard manipulation of all its components. */
public final class Display extends DBObject implements ActionListener, IJEventListener {
/** The Layer this Display is showing. */
private Layer layer;
private Displayable active = null;
/** All selected Displayable objects, including the active one. */
final private Selection selection = new Selection(this);
private JFrame frame;
private JTabbedPane tabs;
private Hashtable<Class,JScrollPane> ht_tabs;
private JScrollPane scroll_patches;
private JPanel panel_patches;
private JScrollPane scroll_profiles;
private JPanel panel_profiles;
private JScrollPane scroll_zdispl;
private JPanel panel_zdispl;
private JScrollPane scroll_channels;
private JPanel panel_channels;
private JScrollPane scroll_labels;
private JPanel panel_labels;
private JPanel panel_layers;
private JScrollPane scroll_layers;
private Hashtable<Layer,LayerPanel> layer_panels = new Hashtable<Layer,LayerPanel>();
private OptionPanel tool_options;
private JScrollPane scroll_options;
static protected int scrollbar_width = 0;
private JEditorPane annot_editor;
private JLabel annot_label;
private JPanel annot_panel;
static private HashMap<Displayable,Document> annot_docs = new HashMap<Displayable,Document>();
private JSlider transp_slider;
private DisplayNavigator navigator;
private JScrollBar scroller;
private DisplayCanvas canvas; // WARNING this is an AWT component, since it extends ImageCanvas
private JPanel canvas_panel; // and this is a workaround, to better (perhaps) integrate the awt canvas inside a JSplitPane
private JSplitPane split;
private JPopupMenu popup = null;
private ToolbarPanel toolbar_panel = null;
/** Contains the packed alphas of every channel. */
private int c_alphas = 0xffffffff; // all 100 % visible
private Channel[] channels;
private Hashtable<Displayable,DisplayablePanel> ht_panels = new Hashtable<Displayable,DisplayablePanel>();
/** Handle drop events, to insert image files. */
private DNDInsertImage dnd;
private boolean size_adjusted = false;
private int scroll_step = 1;
/** Keep track of all existing Display objects. */
static private Vector<Display> al_displays = new Vector<Display>();
/** The currently focused Display, if any. */
static private Display front = null;
/** Displays to open when all objects have been reloaded from the database. */
static private final Hashtable ht_later = new Hashtable();
/** A thread to handle user actions, for example an event sent from a popup menu. */
protected final Dispatcher dispatcher = new Dispatcher("Display GUI Updater");
static private WindowAdapter window_listener = new WindowAdapter() {
/** Unregister the closed Display. */
public void windowClosing(WindowEvent we) {
final Object source = we.getSource();
for (Iterator it = al_displays.iterator(); it.hasNext(); ) {
Display d = (Display)it.next();
if (source == d.frame) {
it.remove();
if (d == front) front = null;
d.remove(false); //calls destroy
break;
}
}
}
/** Set the source Display as front. */
public void windowActivated(WindowEvent we) {
// find which was it to make it be the front
ImageJ ij = IJ.getInstance();
if (null != ij && ij.quitting()) return;
final Object source = we.getSource();
for (final Display d : al_displays) {
if (source == d.frame) {
front = d;
// set toolbar
ProjectToolbar.setProjectToolbar();
// now, select the layer in the LayerTree
front.getProject().select(front.layer);
// finally, set the virtual ImagePlus that ImageJ will see
d.setTempCurrentImage();
// copied from ij.gui.ImageWindow, with modifications
if (IJ.isMacintosh() && IJ.getInstance()!=null) {
IJ.wait(10); // may be needed for Java 1.4 on OS X
d.frame.setMenuBar(Menus.getMenuBar());
}
return;
}
}
// else, restore the ImageJ toolbar for non-project images
//if (!source.equals(IJ.getInstance())) {
// ProjectToolbar.setImageJToolbar();
//}
}
/** Restore the ImageJ toolbar */
public void windowDeactivated(WindowEvent we) {
// Can't, the user can never click the ProjectToolbar then. This has to be done in a different way, for example checking who is the WindowManager.getCurrentImage (and maybe setting a dummy image into it) //ProjectToolbar.setImageJToolbar();
}
/** Call a pack() when the window is maximized to fit the canvas correctly. */
public void windowStateChanged(WindowEvent we) {
final Object source = we.getSource();
for (final Display d : al_displays) {
if (source != d.frame) continue;
d.pack();
break;
}
}
};
static public final Vector<Display> getDisplays() {
return (Vector<Display>)al_displays.clone();
}
static private MouseListener frame_mouse_listener = new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
Object source = me.getSource();
for (final Display d : al_displays) {
if (d.frame == source) {
if (d.size_adjusted) {
d.pack();
d.size_adjusted = false;
Utils.log2("mouse released on JFrame");
}
break;
}
}
}
};
private int last_frame_state = frame.NORMAL;
// THIS WHOLE SYSTEM OF LISTENERS IS BROKEN:
// * when zooming in, the window growths in width a few pixels.
// * when enlarging the window quickly, the canvas is not resized as large as it should.
// -- the whole problem: swing threading, which I am not handling properly. It's hard.
static private ComponentListener component_listener = new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
final Display d = getDisplaySource(ce);
if (null != d) {
d.size_adjusted = true; // works in combination with mouseReleased to call pack(), avoiding infinite loops.
d.adjustCanvas();
d.navigator.repaint(false); // upate srcRect red frame position/size
int frame_state = d.frame.getExtendedState();
if (frame_state != d.last_frame_state) { // this setup avoids infinite loops (for pack() calls componentResized as well
d.last_frame_state = frame_state;
if (d.frame.ICONIFIED != frame_state) d.pack();
}
}
}
public void componentMoved(ComponentEvent ce) {
Display d = getDisplaySource(ce);
if (null != d) d.updateInDatabase("position");
}
private Display getDisplaySource(ComponentEvent ce) {
final Object source = ce.getSource();
for (final Display d : al_displays) {
if (source == d.frame) {
return d;
}
}
return null;
}
};
static private ChangeListener tabs_listener = new ChangeListener() {
/** Listen to tab changes. */
public void stateChanged(final ChangeEvent ce) {
final Object source = ce.getSource();
for (final Display d : al_displays) {
if (source == d.tabs) {
d.dispatcher.exec(new Runnable() { public void run() {
// creating tabs fires the event!!!
if (null == d.frame || null == d.canvas) return;
final Container tab = (Container)d.tabs.getSelectedComponent();
if (tab == d.scroll_channels) {
// find active channel if any
for (int i=0; i<d.channels.length; i++) {
if (d.channels[i].isActive()) {
d.transp_slider.setValue((int)(d.channels[i].getAlpha() * 100));
break;
}
}
} else {
// recreate contents
/*
int count = tab.getComponentCount();
if (0 == count || (1 == count && tab.getComponent(0).getClass().equals(JLabel.class))) {
*/ // ALWAYS, because it could be the case that the user changes layer while on one specific tab, and then clicks on the other tab which may not be empty and shows totally the wrong contents (i.e. for another layer)
ArrayList al = null;
JPanel p = null;
if (tab == d.scroll_zdispl) {
al = d.layer.getParent().getZDisplayables();
p = d.panel_zdispl;
} else if (tab == d.scroll_patches) {
al = d.layer.getDisplayables(Patch.class);
p = d.panel_patches;
} else if (tab == d.scroll_labels) {
al = d.layer.getDisplayables(DLabel.class);
p = d.panel_labels;
} else if (tab == d.scroll_profiles) {
al = d.layer.getDisplayables(Profile.class);
p = d.panel_profiles;
} else if (tab == d.scroll_layers) {
// nothing to do
return;
} else if (tab == d.scroll_options) {
// Choose accordint to tool
d.updateToolTab();
return;
}
d.updateTab(p, al);
//Utils.updateComponent(d.tabs.getSelectedComponent());
//Utils.log2("updated tab: " + p + " with " + al.size() + " objects.");
//}
if (null != d.active) {
// set the transp slider to the alpha value of the active Displayable if any
d.transp_slider.setValue((int)(d.active.getAlpha() * 100));
DisplayablePanel dp = d.ht_panels.get(d.active);
if (null != dp) dp.setActive(true);
}
}
}});
break;
}
}
}
};
private final ScrollLayerListener scroller_listener = new ScrollLayerListener();
private class ScrollLayerListener implements AdjustmentListener {
public void adjustmentValueChanged(final AdjustmentEvent ae) {
final int index = scroller.getValue();
slt.set(layer.getParent().getLayer(index));
}
}
private final SetLayerThread slt = new SetLayerThread();
private class SetLayerThread extends Thread {
private boolean go = true;
private Layer layer;
private final Lock lock = new Lock();
SetLayerThread() {
super("SetLayerThread");
setPriority(Thread.NORM_PRIORITY);
setDaemon(true);
start();
}
public final void set(final Layer layer) {
synchronized (lock) {
this.layer = layer;
}
synchronized (this) {
notify();
}
}
// Does not use the thread, rather just sets it within the context of the calling thread (would be the same as making the caller thread wait.)
final void setAndWait(final Layer layer) {
if (null != layer) {
Display.this.setLayer(layer);
Display.this.updateInDatabase("layer_id");
createColumnScreenshots();
}
}
public void run() {
while (go) {
while (null == this.layer) {
synchronized (this) {
try { wait(); } catch (InterruptedException ie) {}
}
}
Layer layer = null;
synchronized (lock) {
layer = this.layer;
this.layer = null;
}
//
if (!go) return; // after nullifying layer
//
setAndWait(layer);
}
}
public void quit() {
go = false;
}
}
static final public void clearColumnScreenshots(final LayerSet ls) {
for (final Display d : al_displays) {
if (d.layer.getParent() == ls) d.clearColumnScreenshots();
}
}
final public void clearColumnScreenshots() {
getLayerSet().clearScreenshots();
}
/** Only for DefaultMode. */
final private void createColumnScreenshots() {
final int n;
try {
if (mode.getClass() == DefaultMode.class) {
int ahead = project.getProperty("look_ahead_cache", 0);
if (ahead < 0) ahead = 0;
if (0 == ahead) return;
n = ahead;
} else return;
} catch (Exception e) {
IJError.print(e);
return;
}
project.getLoader().doLater(new Callable() {
public Object call() {
final Layer current = Display.this.layer;
// 1 - Create DisplayCanvas.Screenshot instances for the next 5 and previous 5 layers
final ArrayList<DisplayCanvas.Screenshot> s = new ArrayList<DisplayCanvas.Screenshot>();
Layer now = current;
Layer prev = now.getParent().previous(now);
int i = 0;
Layer next = now.getParent().next(now);
while (now != next && i < n) {
s.add(canvas.createScreenshot(next));
now = next;
next = now.getParent().next(now);
i++;
}
now = current;
i = 0;
while (now != prev && i < n) {
s.add(0, canvas.createScreenshot(prev));
now = prev;
prev = now.getParent().previous(now);
i++;
}
// Store them all into the LayerSet offscreens hashmap, but trigger image creation in parallel threads.
for (final DisplayCanvas.Screenshot sc : s) {
if (!current.getParent().containsScreenshot(sc)) {
sc.init();
current.getParent().storeScreenshot(sc);
project.getLoader().doLater(new Callable() {
public Object call() {
sc.createImage();
return null;
}
});
}
}
current.getParent().trimScreenshots();
return null;
}
});
}
/** Creates a new Display with adjusted magnification to fit in the screen. */
static public void createDisplay(final Project project, final Layer layer) {
SwingUtilities.invokeLater(new Runnable() { public void run() {
Display display = new Display(project, layer);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle srcRect = new Rectangle(0, 0, (int)layer.getLayerWidth(), (int)layer.getLayerHeight());
double mag = screen.width / layer.getLayerWidth();
if (mag * layer.getLayerHeight() > screen.height) mag = screen.height / layer.getLayerHeight();
mag = display.canvas.getLowerZoomLevel2(mag);
if (mag > 1.0) mag = 1.0;
//display.getCanvas().setup(mag, srcRect); // would call pack() at the wrong time!
// ... so instead: manually
display.getCanvas().setMagnification(mag);
display.getCanvas().setSrcRect(srcRect.x, srcRect.y, srcRect.width, srcRect.height);
display.getCanvas().setDrawingSize((int)Math.ceil(srcRect.width * mag), (int)Math.ceil(srcRect.height * mag));
//
display.updateFrameTitle(layer);
ij.gui.GUI.center(display.frame);
display.frame.pack();
}});
}
/** A new Display from scratch, to show the given Layer. */
public Display(Project project, final Layer layer) {
super(project);
front = this;
makeGUI(layer, null);
IJ.addEventListener(this);
setLayer(layer);
this.layer = layer; // after, or it doesn't update properly
al_displays.add(this);
addToDatabase();
}
/** For reconstruction purposes. The Display will be stored in the ht_later.*/
public Display(Project project, long id, Layer layer, Object[] props) {
super(project, id);
synchronized (ht_later) {
Display.ht_later.put(this, props);
}
this.layer = layer;
IJ.addEventListener(this);
}
/** Open a new Display centered around the given Displayable. */
public Display(Project project, Layer layer, Displayable displ) {
super(project);
front = this;
active = displ;
makeGUI(layer, null);
IJ.addEventListener(this);
setLayer(layer);
this.layer = layer; // after set layer!
al_displays.add(this);
addToDatabase();
}
/** Reconstruct a Display from an XML entry, to be opened when everything is ready. */
public Display(Project project, long id, Layer layer, HashMap ht_attributes) {
super(project, id);
if (null == layer) {
Utils.log2("Display: need a non-null Layer for id=" + id);
return;
}
Rectangle srcRect = new Rectangle(0, 0, (int)layer.getLayerWidth(), (int)layer.getLayerHeight());
double magnification = 0.25;
Point p = new Point(0, 0);
int c_alphas = 0xffffffff;
int c_alphas_state = 0xffffffff;
for (Iterator it = ht_attributes.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Map.Entry)it.next();
String key = (String)entry.getKey();
String data = (String)entry.getValue();
if (key.equals("srcrect_x")) { // reflection! Reflection!
srcRect.x = Integer.parseInt(data);
} else if (key.equals("srcrect_y")) {
srcRect.y = Integer.parseInt(data);
} else if (key.equals("srcrect_width")) {
srcRect.width = Integer.parseInt(data);
} else if (key.equals("srcrect_height")) {
srcRect.height = Integer.parseInt(data);
} else if (key.equals("magnification")) {
magnification = Double.parseDouble(data);
} else if (key.equals("x")) {
p.x = Integer.parseInt(data);
} else if (key.equals("y")) {
p.y = Integer.parseInt(data);
} else if (key.equals("c_alphas")) {
try {
c_alphas = Integer.parseInt(data);
} catch (Exception ex) {
c_alphas = 0xffffffff;
}
} else if (key.equals("c_alphas_state")) {
try {
c_alphas_state = Integer.parseInt(data);
} catch (Exception ex) {
IJError.print(ex);
c_alphas_state = 0xffffffff;
}
} else if (key.equals("scroll_step")) {
try {
setScrollStep(Integer.parseInt(data));
} catch (Exception ex) {
IJError.print(ex);
setScrollStep(1);
}
}
// TODO the above is insecure, in that data is not fully checked to be within bounds.
}
Object[] props = new Object[]{p, new Double(magnification), srcRect, new Long(layer.getId()), new Integer(c_alphas), new Integer(c_alphas_state)};
synchronized (ht_later) {
Display.ht_later.put(this, props);
}
this.layer = layer;
IJ.addEventListener(this);
}
/** After reloading a project from the database, open the Displays that the project had. */
static public Bureaucrat openLater() {
final Hashtable ht_later_local;
synchronized (ht_later) {
if (0 == ht_later.size()) return null;
ht_later_local = new Hashtable(ht_later);
ht_later.keySet().removeAll(ht_later_local.keySet());
}
final Worker worker = new Worker.Task("Opening displays") {
public void exec() {
try {
Thread.sleep(300); // waiting for Swing
for (Enumeration e = ht_later_local.keys(); e.hasMoreElements(); ) {
final Display d = (Display)e.nextElement();
front = d; // must be set before repainting any ZDisplayable!
Object[] props = (Object[])ht_later_local.get(d);
if (ControlWindow.isGUIEnabled()) d.makeGUI(d.layer, props);
d.setLayerLater(d.layer, d.layer.get(((Long)props[3]).longValue())); //important to do it after makeGUI
if (!ControlWindow.isGUIEnabled()) continue;
al_displays.add(d);
d.updateFrameTitle(d.layer);
// force a repaint if a prePaint was done TODO this should be properly managed with repaints using always the invokeLater, but then it's DOG SLOW
if (d.canvas.getMagnification() > 0.499) {
SwingUtilities.invokeLater(new Runnable() { public void run() {
d.repaint(d.layer);
d.project.getLoader().setChanged(false);
Utils.log2("A set to false");
}});
}
d.project.getLoader().setChanged(false);
Utils.log2("B set to false");
}
if (null != front) front.getProject().select(front.layer);
} catch (Throwable t) {
IJError.print(t);
}
}
};
return Bureaucrat.createAndStart(worker, ((Display)ht_later_local.keySet().iterator().next()).getProject()); // gets the project from the first Display
}
private void makeGUI(final Layer layer, final Object[] props) {
// gather properties
Point p = null;
double mag = 1.0D;
Rectangle srcRect = null;
if (null != props) {
p = (Point)props[0];
mag = ((Double)props[1]).doubleValue();
srcRect = (Rectangle)props[2];
}
// transparency slider
this.transp_slider = new JSlider(javax.swing.SwingConstants.HORIZONTAL, 0, 100, 100);
this.transp_slider.setBackground(Color.white);
this.transp_slider.setMinimumSize(new Dimension(250, 20));
this.transp_slider.setMaximumSize(new Dimension(250, 20));
this.transp_slider.setPreferredSize(new Dimension(250, 20));
TransparencySliderListener tsl = new TransparencySliderListener();
this.transp_slider.addChangeListener(tsl);
this.transp_slider.addMouseListener(tsl);
for (final KeyListener kl : this.transp_slider.getKeyListeners()) {
this.transp_slider.removeKeyListener(kl);
}
// Tabbed pane on the left
this.tabs = new JTabbedPane();
this.tabs.setMinimumSize(new Dimension(250, 300));
this.tabs.setBackground(Color.white);
this.tabs.addChangeListener(tabs_listener);
// Tab 1: Patches
this.panel_patches = makeTabPanel();
this.scroll_patches = makeScrollPane(panel_patches);
this.addTab("Patches", scroll_patches);
// Tab 2: Profiles
this.panel_profiles = makeTabPanel();
this.scroll_profiles = makeScrollPane(panel_profiles);
this.addTab("Profiles", scroll_profiles);
// Tab 3: pipes
this.panel_zdispl = makeTabPanel();
this.scroll_zdispl = makeScrollPane(panel_zdispl);
this.addTab("Z space", scroll_zdispl);
// Tab 4: channels
this.panel_channels = makeTabPanel();
this.scroll_channels = makeScrollPane(panel_channels);
this.channels = new Channel[4];
this.channels[0] = new Channel(this, Channel.MONO);
this.channels[1] = new Channel(this, Channel.RED);
this.channels[2] = new Channel(this, Channel.GREEN);
this.channels[3] = new Channel(this, Channel.BLUE);
//this.panel_channels.add(this.channels[0]);
this.panel_channels.add(this.channels[1]);
this.panel_channels.add(this.channels[2]);
this.panel_channels.add(this.channels[3]);
this.addTab("Opacity", scroll_channels);
// Tab 5: labels
this.panel_labels = makeTabPanel();
this.scroll_labels = makeScrollPane(panel_labels);
this.addTab("Labels", scroll_labels);
// Tab 6: layers
this.panel_layers = makeTabPanel();
this.scroll_layers = makeScrollPane(panel_layers);
recreateLayerPanels(layer);
this.scroll_layers.addMouseWheelListener(canvas);
this.addTab("Layers", scroll_layers);
// Tab 7: tool options
this.tool_options = new OptionPanel(); // empty
this.scroll_options = makeScrollPane(this.tool_options);
this.addTab("Tool options", this.scroll_options);
// Tab 8: annotations
this.annot_editor = new JEditorPane();
this.annot_editor.setEnabled(false); // by default, nothing is selected
this.annot_editor.setMinimumSize(new Dimension(200, 50));
this.annot_label = new JLabel("(No selected object)");
this.annot_panel = makeAnnotationsPanel(this.annot_editor, this.annot_label);
this.addTab("Annotations", this.annot_panel);
this.ht_tabs = new Hashtable<Class,JScrollPane>();
this.ht_tabs.put(Patch.class, scroll_patches);
this.ht_tabs.put(Profile.class, scroll_profiles);
this.ht_tabs.put(ZDisplayable.class, scroll_zdispl);
this.ht_tabs.put(AreaList.class, scroll_zdispl);
this.ht_tabs.put(Pipe.class, scroll_zdispl);
this.ht_tabs.put(Polyline.class, scroll_zdispl);
this.ht_tabs.put(Treeline.class, scroll_zdispl);
this.ht_tabs.put(AreaTree.class, scroll_zdispl);
this.ht_tabs.put(Connector.class, scroll_zdispl);
this.ht_tabs.put(Ball.class, scroll_zdispl);
this.ht_tabs.put(Dissector.class, scroll_zdispl);
this.ht_tabs.put(DLabel.class, scroll_labels);
this.ht_tabs.put(Stack.class, scroll_zdispl);
// channels not included
// layers not included
// tools not included
// annotations not included
// Navigator
this.navigator = new DisplayNavigator(this, layer.getLayerWidth(), layer.getLayerHeight());
// Layer scroller (to scroll slices)
int extent = (int)(250.0 / layer.getParent().size());
if (extent < 10) extent = 10;
this.scroller = new JScrollBar(JScrollBar.HORIZONTAL);
updateLayerScroller(layer);
this.scroller.addAdjustmentListener(scroller_listener);
// Toolbar
// Left panel, contains the transp slider, the tabbed pane, the navigation panel and the layer scroller
JPanel left = new JPanel();
left.setBackground(Color.white);
BoxLayout left_layout = new BoxLayout(left, BoxLayout.Y_AXIS);
left.setLayout(left_layout);
toolbar_panel = new ToolbarPanel();
left.add(toolbar_panel);
left.add(transp_slider);
left.add(tabs);
left.add(navigator);
left.add(scroller);
// Canvas
this.canvas = new DisplayCanvas(this, (int)Math.ceil(layer.getLayerWidth()), (int)Math.ceil(layer.getLayerHeight()));
this.canvas_panel = new JPanel();
GridBagLayout gb = new GridBagLayout();
this.canvas_panel.setLayout(gb);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.NORTHWEST;
gb.setConstraints(this.canvas_panel, c);
gb.setConstraints(this.canvas, c);
// prevent new Displays from screweing up if input is globally disabled
if (!project.isInputEnabled()) this.canvas.setReceivesInput(false);
this.canvas_panel.add(canvas);
this.navigator.addMouseWheelListener(canvas);
this.transp_slider.addKeyListener(canvas);
// Split pane to contain everything
this.split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, canvas_panel);
this.split.setOneTouchExpandable(true); // NOT present in all L&F (?)
this.split.setBackground(Color.white);
// fix
gb.setConstraints(split.getRightComponent(), c);
// JFrame to show the split pane
this.frame = ControlWindow.createJFrame(layer.toString());
this.frame.setBackground(Color.white);
this.frame.getContentPane().setBackground(Color.white);
if (IJ.isMacintosh() && IJ.getInstance()!=null) {
IJ.wait(10); // may be needed for Java 1.4 on OS X
this.frame.setMenuBar(ij.Menus.getMenuBar());
}
this.frame.addWindowListener(window_listener);
this.frame.addComponentListener(component_listener);
this.frame.getContentPane().add(split);
this.frame.addMouseListener(frame_mouse_listener);
//doesn't exist//this.frame.setMinimumSize(new Dimension(270, 600));
if (null != props) {
// restore canvas
canvas.setup(mag, srcRect);
// restore visibility of each channel
int cs = ((Integer)props[5]).intValue(); // aka c_alphas_state
int[] sel = new int[4];
sel[0] = ((cs&0xff000000)>>24);
sel[1] = ((cs&0xff0000)>>16);
sel[2] = ((cs&0xff00)>>8);
sel[3] = (cs&0xff);
// restore channel alphas
this.c_alphas = ((Integer)props[4]).intValue();
channels[0].setAlpha( (float)((c_alphas&0xff000000)>>24) / 255.0f , 0 != sel[0]);
channels[1].setAlpha( (float)((c_alphas&0xff0000)>>16) / 255.0f , 0 != sel[1]);
channels[2].setAlpha( (float)((c_alphas&0xff00)>>8) / 255.0f , 0 != sel[2]);
channels[3].setAlpha( (float) (c_alphas&0xff) / 255.0f , 0 != sel[3]);
// restore visibility in the working c_alphas
this.c_alphas = ((0 != sel[0] ? (int)(255 * channels[0].getAlpha()) : 0)<<24) + ((0 != sel[1] ? (int)(255 * channels[1].getAlpha()) : 0)<<16) + ((0 != sel[2] ? (int)(255 * channels[2].getAlpha()) : 0)<<8) + (0 != sel[3] ? (int)(255 * channels[3].getAlpha()) : 0);
}
if (null != active && null != layer) {
Rectangle r = active.getBoundingBox();
r.x -= r.width/2;
r.y -= r.height/2;
r.width += r.width;
r.height += r.height;
if (r.x < 0) r.x = 0;
if (r.y < 0) r.y = 0;
if (r.width > layer.getLayerWidth()) r.width = (int)layer.getLayerWidth();
if (r.height> layer.getLayerHeight())r.height= (int)layer.getLayerHeight();
double magn = layer.getLayerWidth() / (double)r.width;
canvas.setup(magn, r);
}
// add keyListener to the whole frame
this.tabs.addKeyListener(canvas);
this.canvas_panel.addKeyListener(canvas);
this.frame.addKeyListener(canvas);
this.frame.pack();
ij.gui.GUI.center(this.frame);
this.frame.setVisible(true);
ProjectToolbar.setProjectToolbar(); // doesn't get it through events
final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
if (null != props) {
// fix positioning outside the screen (dual to single monitor)
if (p.x >= 0 && p.x < screen.width - 50 && p.y >= 0 && p.y <= screen.height - 50) this.frame.setLocation(p);
else frame.setLocation(0, 0);
}
// fix excessive size
final Rectangle box = this.frame.getBounds();
int x = box.x;
int y = box.y;
int width = box.width;
int height = box.height;
if (box.width > screen.width) { x = 0; width = screen.width; }
if (box.height > screen.height) { y = 0; height = screen.height; }
if (x != box.x || y != box.y) {
this.frame.setLocation(x, y + (0 == y ? 30 : 0)); // added insets for bad window managers
updateInDatabase("position");
}
if (width != box.width || height != box.height) {
this.frame.setSize(new Dimension(width -10, height -30)); // added insets for bad window managers
}
if (null == props) {
// try to optimize canvas dimensions and magn
double magn = layer.getLayerHeight() / screen.height;
if (magn > 1.0) magn = 1.0;
long size = 0;
// limit magnification if appropriate
for (Iterator it = layer.getDisplayables(Patch.class).iterator(); it.hasNext(); ) {
final Patch pa = (Patch)it.next();
final Rectangle ba = pa.getBoundingBox();
size += (long)(ba.width * ba.height);
}
if (size > 10000000) canvas.setInitialMagnification(0.25); // 10 Mb
else {
this.frame.setSize(new Dimension((int)(screen.width * 0.66), (int)(screen.height * 0.66)));
}
}
updateTab(panel_patches, layer.getDisplayables(Patch.class));
Utils.updateComponent(tabs); // otherwise fails in FreeBSD java 1.4.2 when reconstructing
// Set the calibration of the FakeImagePlus to that of the LayerSet
((FakeImagePlus)canvas.getFakeImagePlus()).setCalibrationSuper(layer.getParent().getCalibrationCopy());
updateFrameTitle(layer);
// Set the FakeImagePlus as the current image
setTempCurrentImage();
// create a drag and drop listener
dnd = new DNDInsertImage(this);
// start a repainting thread
if (null != props) {
canvas.repaint(true); // repaint() is unreliable
}
// Set the minimum size of the tabbed pane on the left, so it can be completely collapsed now that it has been properly displayed. This is a patch to the lack of respect for the setDividerLocation method.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
tabs.setMinimumSize(new Dimension(0, 100));
Display.scrollbar_width = Display.this.scroll_patches.getVerticalScrollBar().getPreferredSize().width; // using scroll_patches since it's the one selected by default and thus visible and painted
ControlWindow.setLookAndFeel();
}
});
}
static public void repaintToolbar() {
for (final Display d : al_displays) {
d.toolbar_panel.repaint();
}
}
private class ToolbarPanel extends JPanel implements MouseListener {
Method drawButton;
Field lineType;
Field SIZE;
Field OFFSET;
Toolbar toolbar = Toolbar.getInstance();
int size;
int offset;
ToolbarPanel() {
setBackground(Color.white);
addMouseListener(this);
try {
drawButton = Toolbar.class.getDeclaredMethod("drawButton", Graphics.class, Integer.TYPE);
drawButton.setAccessible(true);
lineType = Toolbar.class.getDeclaredField("lineType");
lineType.setAccessible(true);
SIZE = Toolbar.class.getDeclaredField("SIZE");
SIZE.setAccessible(true);
OFFSET = Toolbar.class.getDeclaredField("OFFSET");
OFFSET.setAccessible(true);
size = ((Integer)SIZE.get(null)).intValue();
offset = ((Integer)OFFSET.get(null)).intValue();
} catch (Exception e) {
IJError.print(e);
}
// Magic cocktail:
Dimension dim = new Dimension(250, size+size);
setPreferredSize(dim);
setMinimumSize(dim);
setMaximumSize(dim);
}
public void update(Graphics g) { paint(g); }
public void paint(Graphics g) {
try {
int i = 0;
for (; i<Toolbar.LINE; i++) {
drawButton.invoke(toolbar, g, i);
}
drawButton.invoke(toolbar, g, lineType.get(toolbar));
for (; i<=Toolbar.TEXT; i++) {
drawButton.invoke(toolbar, g, i);
}
drawButton.invoke(toolbar, g, Toolbar.ANGLE);
// newline
AffineTransform aff = new AffineTransform();
aff.translate(-size*Toolbar.TEXT, size-1);
((Graphics2D)g).setTransform(aff);
for (; i<18; i++) {
drawButton.invoke(toolbar, g, i);
}
} catch (Exception e) {
IJError.print(e);
}
}
// Fails: "origin not in parent's hierarchy" ... right.
private void showPopup(String name, int x, int y) {
try {
Field f = Toolbar.getInstance().getClass().getDeclaredField(name);
f.setAccessible(true);
PopupMenu p = (PopupMenu) f.get(Toolbar.getInstance());
p.show(this, x, y);
} catch (Throwable t) {
IJError.print(t);
}
}
public void mousePressed(MouseEvent me) {
int x = me.getX();
int y = me.getY();
if (y > size) {
if (x > size * 7) return; // off limits
x += size * 9;
y -= size;
} else {
if (x > size * 9) return; // off limits
}
/*
if (Utils.isPopupTrigger(me)) {
if (x >= size && x <= size * 2 && y >= 0 && y <= size) {
showPopup("ovalPopup", x, y);
return;
} else if (x >= size * 4 && x <= size * 5 && y >= 0 && y <= size) {
showPopup("linePopup", x, y);
return;
}
}
*/
Toolbar.getInstance().mousePressed(new MouseEvent(toolbar, me.getID(), System.currentTimeMillis(), me.getModifiers(), x, y, me.getClickCount(), me.isPopupTrigger()));
repaint();
Display.this.toolChanged(ProjectToolbar.getToolId()); // should fire on its own but it does not (?) TODO
}
public void mouseReleased(MouseEvent me) {}
public void mouseClicked(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
}
private JPanel makeTabPanel() {
JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(layout);
return panel;
}
private JScrollPane makeScrollPane(Component c) {
JScrollPane jsp = new JScrollPane(c);
jsp.setBackground(Color.white); // no effect
jsp.getViewport().setBackground(Color.white); // no effect
// adjust scrolling to use one DisplayablePanel as the minimal unit
jsp.getVerticalScrollBar().setBlockIncrement(DisplayablePanel.HEIGHT); // clicking within the track
jsp.getVerticalScrollBar().setUnitIncrement(DisplayablePanel.HEIGHT); // clicking on an arrow
jsp.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setPreferredSize(new Dimension(250, 300));
jsp.setMinimumSize(new Dimension(250, 300));
return jsp;
}
private JPanel makeAnnotationsPanel(JEditorPane ep, JLabel label) {
JPanel p = new JPanel();
GridBagLayout gb = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
p.setLayout(gb);
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
c.ipadx = 5;
c.ipady = 5;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
c.weighty = 0;
JLabel title = new JLabel("Annotate:");
gb.setConstraints(title, c);
p.add(title);
c.gridy++;
gb.setConstraints(label, c);
p.add(label);
c.weighty = 1;
c.gridy++;
c.fill = GridBagConstraints.BOTH;
c.ipadx = 0;
c.ipady = 0;
JScrollPane sp = new JScrollPane(ep, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sp.setPreferredSize(new Dimension(250, 300));
sp.setMinimumSize(new Dimension(250, 300));
gb.setConstraints(sp, c);
p.add(sp);
return p;
}
public JPanel getCanvasPanel() {
return canvas_panel;
}
public DisplayCanvas getCanvas() {
return canvas;
}
public synchronized void setLayer(final Layer layer) {
if (!mode.canChangeLayer()) {
scroller.setValue(Display.this.layer.getParent().getLayerIndex(Display.this.layer.getId()));
return;
}
if (null == layer || layer == this.layer) return;
translateLayerColors(this.layer, layer);
if (tabs.getSelectedComponent() == scroll_layers) {
SwingUtilities.invokeLater(new Runnable() { public void run() {
scrollToShow(scroll_layers, layer_panels.get(layer));
}});
}
final boolean set_zdispl = null == Display.this.layer || layer.getParent() != Display.this.layer.getParent();
this.layer = layer;
scroller.setValue(layer.getParent().getLayerIndex(layer.getId()));
// update the current Layer pointer in ZDisplayable objects
for (Iterator it = layer.getParent().getZDisplayables().iterator(); it.hasNext(); ) {
((ZDisplayable)it.next()).setLayer(layer); // the active layer
}
updateVisibleTab(set_zdispl);
updateFrameTitle(layer); // to show the new 'z'
// select the Layer in the LayerTree
project.select(Display.this.layer); // does so in a separate thread
// update active Displayable:
// deselect all except ZDisplayables
final ArrayList<Displayable> sel = selection.getSelected();
final Displayable last_active = Display.this.active;
int sel_next = -1;
for (final Iterator<Displayable> it = sel.iterator(); it.hasNext(); ) {
final Displayable d = it.next();
if (!(d instanceof ZDisplayable)) {
it.remove();
selection.remove(d);
if (d == last_active && sel.size() > 0) {
// select the last one of the remaining, if any
sel_next = sel.size()-1;
}
}
}
if (-1 != sel_next && sel.size() > 0) select(sel.get(sel_next), true);
// repaint everything
navigator.repaint(true);
canvas.repaint(true);
// repaint tabs (hard as hell)
Utils.updateComponent(tabs);
// @#$%^! The above works half the times, so explicit repaint as well:
Component c = tabs.getSelectedComponent();
if (null == c) {
c = scroll_patches;
tabs.setSelectedComponent(scroll_patches);
}
Utils.updateComponent(c);
// update the coloring in the ProjectTree
project.getProjectTree().updateUILater();
setTempCurrentImage();
}
static public void updateVisibleTabs() {
for (final Display d : al_displays) {
d.updateVisibleTab(true);
}
}
static public void updateVisibleTabs(final Project p) {
for (final Display d : al_displays) {
if (d.project == p) d.updateVisibleTab(true);
}
}
/** Recreate the tab that is being shown. */
public void updateVisibleTab(boolean set_zdispl) {
// update only the visible tab
switch (tabs.getSelectedIndex()) {
case 0:
ht_panels.clear();
updateTab(panel_patches, layer.getDisplayables(Patch.class));
break;
case 1:
ht_panels.clear();
updateTab(panel_profiles, layer.getDisplayables(Profile.class));
break;
case 2:
if (set_zdispl) {
ht_panels.clear();
updateTab(panel_zdispl, layer.getParent().getZDisplayables());
}
break;
// case 3: channel opacities
case 4:
ht_panels.clear();
updateTab(panel_labels, layer.getDisplayables(DLabel.class));
break;
// case 5: layer panels
}
}
private void setLayerLater(final Layer layer, final Displayable active) {
if (null == layer) return;
this.layer = layer;
if (!ControlWindow.isGUIEnabled()) return;
SwingUtilities.invokeLater(new Runnable() { public void run() {
// empty the tabs, except channels and pipes
clearTab(panel_profiles);
clearTab(panel_patches);
clearTab(panel_labels);
// distribute Displayable to the tabs. Ignore LayerSet instances.
if (null == ht_panels) ht_panels = new Hashtable<Displayable,DisplayablePanel>();
else ht_panels.clear();
for (final Displayable d : layer.getParent().getZDisplayables()) {
d.setLayer(layer);
}
updateTab(panel_patches, layer.getDisplayables(Patch.class));
navigator.repaint(true); // was not done when adding
Utils.updateComponent(tabs.getSelectedComponent());
//
setActive(active);
}});
// swing issues:
/*
new Thread() {
public void run() {
setPriority(Thread.NORM_PRIORITY);
try { Thread.sleep(1000); } catch (Exception e) {}
setActive(active);
}
}.start();
*/
}
/** Remove all components from the tab. */
private void clearTab(final Container c) {
c.removeAll();
// magic cocktail:
if (tabs.getSelectedComponent() == c) {
Utils.updateComponent(c);
}
}
/** A class to listen to the transparency_slider of the DisplayablesSelectorWindow. */
private class TransparencySliderListener extends MouseAdapter implements ChangeListener {
public void stateChanged(ChangeEvent ce) {
//change the transparency value of the current active displayable
float new_value = (float)((JSlider)ce.getSource()).getValue();
setTransparency(new_value / 100.0f);
}
public void mousePressed(MouseEvent me) {
if (tabs.getSelectedComponent() != scroll_channels && !selection.isEmpty()) selection.addDataEditStep(new String[]{"alpha"});
}
public void mouseReleased(MouseEvent me) {
// update navigator window
navigator.repaint(true);
if (tabs.getSelectedComponent() != scroll_channels && !selection.isEmpty()) selection.addDataEditStep(new String[]{"alpha"});
}
}
/** Context-sensitive: to a Displayable, or to a channel. */
private void setTransparency(final float value) {
Component scroll = tabs.getSelectedComponent();
if (scroll == scroll_channels) {
for (int i=0; i<4; i++) {
if (channels[i].getBackground() == Color.cyan) {
channels[i].setAlpha(value); // will call back and repaint the Display
return;
}
}
} else if (null != active) {
if (value != active.getAlpha()) { // because there's a callback from setActive that would then affect all other selected Displayable without having dragged the slider, i.e. just by being selected.
canvas.invalidateVolatile();
selection.setAlpha(value);
}
}
}
public void setTransparencySlider(final float transp) {
if (transp >= 0.0f && transp <= 1.0f) {
// fire event
transp_slider.setValue((int)(transp * 100));
}
}
/** Mark the canvas for updating the offscreen images if the given Displayable is NOT the active. */ // Used by the Displayable.setVisible for example.
static public void setUpdateGraphics(final Layer layer, final Displayable displ) {
for (final Display d : al_displays) {
if (layer == d.layer && null != d.active && d.active != displ) {
d.canvas.setUpdateGraphics(true);
}
}
}
/** Flag the DisplayCanvas of Displays showing the given Layer to update their offscreen images.*/
static public void setUpdateGraphics(final Layer layer, final boolean update) {
for (final Display d : al_displays) {
if (layer == d.layer) {
d.canvas.setUpdateGraphics(update);
}
}
}
/** Whether to update the offscreen images or not. */
public void setUpdateGraphics(boolean b) {
canvas.setUpdateGraphics(b);
}
/** Update the entire GUI:
* 1 - The layer scroller
* 2 - The visible tab panels
* 3 - The toolbar
* 4 - The navigator
* 5 - The canvas
*/
static public void update() {
for (final Display d : al_displays) {
d.updateLayerScroller(d.layer);
d.updateVisibleTab(true);
d.toolbar_panel.repaint();
d.navigator.repaint(true);
d.canvas.repaint(true);
}
}
/** Find all Display instances that contain the layer and repaint them, in the Swing GUI thread. */
static public void update(final Layer layer) {
if (null == layer) return;
SwingUtilities.invokeLater(new Runnable() { public void run() {
for (final Display d : al_displays) {
if (d.isShowing(layer)) {
d.repaintAll();
}
}
}});
}
static public void update(final LayerSet set) {
update(set, true);
}
/** Find all Display instances showing a Layer of this LayerSet, and update the dimensions of the navigator and canvas and snapshots, and repaint, in the Swing GUI thread. */
static public void update(final LayerSet set, final boolean update_canvas_dimensions) {
if (null == set) return;
SwingUtilities.invokeLater(new Runnable() { public void run() {
for (final Display d : al_displays) {
if (set.contains(d.layer)) {
d.updateSnapshots();
if (update_canvas_dimensions) d.canvas.setDimensions(set.getLayerWidth(), set.getLayerHeight());
d.repaintAll();
}
}
}});
}
/** Release all resources held by this Display and close the frame. */
protected void destroy() {
dispatcher.quit();
canvas.setReceivesInput(false);
slt.quit();
// update the coloring in the ProjectTree and LayerTree
if (!project.isBeingDestroyed()) {
try {
project.getProjectTree().updateUILater();
project.getLayerTree().updateUILater();
} catch (Exception e) {
Utils.log2("updateUI failed at Display.destroy()");
}
}
frame.removeComponentListener(component_listener);
frame.removeWindowListener(window_listener);
frame.removeWindowFocusListener(window_listener);
frame.removeWindowStateListener(window_listener);
frame.removeKeyListener(canvas);
frame.removeMouseListener(frame_mouse_listener);
canvas_panel.removeKeyListener(canvas);
canvas.removeKeyListener(canvas);
tabs.removeChangeListener(tabs_listener);
tabs.removeKeyListener(canvas);
IJ.removeEventListener(this);
bytypelistener = null;
canvas.destroy();
navigator.destroy();
scroller.removeAdjustmentListener(scroller_listener);
frame.setVisible(false);
//no need, and throws exception//frame.dispose();
active = null;
if (null != selection) selection.clear();
//Utils.log2("destroying selection");
// below, need for SetLayerThread threads to quit
slt.quit();
// set a new front if any
if (null == front && al_displays.size() > 0) {
front = (Display)al_displays.get(al_displays.size() -1);
}
// repaint layer tree (to update the label color)
try {
project.getLayerTree().updateUILater(); // works only after setting the front above
} catch (Exception e) {} // ignore swing sync bullshit when closing everything too fast
// remove the drag and drop listener
dnd.destroy();
}
/** Find all Display instances that contain a Layer of the given project and close them without removing the Display entries from the database. */
static synchronized public void close(final Project project) {
/* // concurrent modifications if more than 1 Display are being removed asynchronously
for (final Display d : al_displays) {
if (d.getLayer().getProject().equals(project)) {
it.remove();
d.destroy();
}
}
*/
Display[] d = new Display[al_displays.size()];
al_displays.toArray(d);
for (int i=0; i<d.length; i++) {
if (d[i].getProject() == project) {
al_displays.remove(d[i]);
d[i].destroy();
}
}
}
/** Find all Display instances that contain the layer and close them and remove the Display from the database. */
static public void close(final Layer layer) {
for (Iterator it = al_displays.iterator(); it.hasNext(); ) {
Display d = (Display)it.next();
if (d.isShowing(layer)) {
d.remove(false);
it.remove();
}
}
}
/** Find all Display instances that are showing the layer and either move to the next or previous layer, or close it if none. */
static public void remove(final Layer layer) {
for (Iterator<Display> it = al_displays.iterator(); it.hasNext(); ) {
final Display d = it.next();
if (d.isShowing(layer)) {
Layer la = layer.getParent().next(layer);
if (layer == la || null == la) la = layer.getParent().previous(layer);
if (null == la || layer == la) {
d.remove(false);
it.remove();
} else {
d.slt.set(la);
}
}
}
}
public boolean remove(boolean check) {
if (check) {
if (!Utils.check("Delete the Display ?")) return false;
}
// flush the offscreen images and close the frame
destroy();
removeFromDatabase();
return true;
}
public Layer getLayer() {
return layer;
}
public LayerSet getLayerSet() {
return layer.getParent();
}
public boolean isShowing(final Layer layer) {
return this.layer == layer;
}
public DisplayNavigator getNavigator() {
return navigator;
}
/** Repaint both the canvas and the navigator, updating the graphics, and the title and tabs. */
public void repaintAll() {
if (repaint_disabled) return;
navigator.repaint(true);
canvas.repaint(true);
Utils.updateComponent(tabs);
updateFrameTitle();
}
/** Repaint the canvas updating graphics, the navigator without updating graphics, and the title. */
public void repaintAll2() {
if (repaint_disabled) return;
navigator.repaint(false);
canvas.repaint(true);
updateFrameTitle();
}
static public void repaintSnapshots(final LayerSet set) {
if (repaint_disabled) return;
for (final Display d : al_displays) {
if (d.getLayer().getParent() == set) {
d.navigator.repaint(true);
Utils.updateComponent(d.tabs);
}
}
}
static public void repaintSnapshots(final Layer layer) {
if (repaint_disabled) return;
for (final Display d : al_displays) {
if (d.getLayer() == layer) {
d.navigator.repaint(true);
Utils.updateComponent(d.tabs);
}
}
}
public void pack() {
dispatcher.exec(new Runnable() { public void run() {
try {
Thread.currentThread().sleep(100);
SwingUtilities.invokeAndWait(new Runnable() { public void run() {
frame.pack();
navigator.repaint(false); // upate srcRect red frame position/size
}});
} catch (Exception e) { IJError.print(e); }
}});
}
static public void pack(final LayerSet ls) {
for (final Display d : al_displays) {
if (d.layer.getParent() == ls) d.pack();
}
}
private void adjustCanvas() {
SwingUtilities.invokeLater(new Runnable() { public void run() {
Rectangle r = split.getRightComponent().getBounds();
canvas.setDrawingSize(r.width, r.height, true);
// fix not-on-top-left problem
canvas.setLocation(0, 0);
//frame.pack(); // don't! Would go into an infinite loop
canvas.repaint(true);
updateInDatabase("srcRect");
}});
}
/** Grab the last selected display (or create an new one if none) and show in it the layer,centered on the Displayable object. */
static public void setFront(final Layer layer, final Displayable displ) {
if (null == front) {
Display display = new Display(layer.getProject(), layer); // gets set to front
display.showCentered(displ);
} else if (layer == front.layer) {
front.showCentered(displ);
} else {
// find one:
for (final Display d : al_displays) {
if (d.layer == layer) {
d.frame.toFront();
d.showCentered(displ);
return;
}
}
// else, open new one
new Display(layer.getProject(), layer).showCentered(displ);
}
}
/** Find the displays that show the given Layer, and add the given Displayable to the GUI and sets it active only in the front Display and only if 'activate' is true. */
static public void add(final Layer layer, final Displayable displ, final boolean activate) {
for (final Display d : al_displays) {
if (d.layer == layer) {
if (front == d) {
d.add(displ, activate, true);
//front.frame.toFront();
} else {
d.add(displ, false, true);
}
}
}
}
static public void add(final Layer layer, final Displayable displ) {
add(layer, displ, true);
}
/** Add the ZDisplayable to all Displays that show a Layer belonging to the given LayerSet. */
static public void add(final LayerSet set, final ZDisplayable zdispl) {
for (final Display d : al_displays) {
if (set.contains(d.layer)) {
if (front == d) {
zdispl.setLayer(d.layer); // the active one
d.add(zdispl, true, true); // calling add(Displayable, boolean, boolean)
//front.frame.toFront();
} else {
d.add(zdispl, false, true);
}
}
}
}
static public void addAll(final Layer layer, final Collection<? extends Displayable> coll) {
for (final Display d : al_displays) {
if (d.layer == layer) {
d.addAll(coll);
}
}
}
static public void addAll(final LayerSet set, final Collection<? extends ZDisplayable> coll) {
for (final Display d : al_displays) {
if (set.contains(d.layer)) {
for (final ZDisplayable zd : coll) {
if (front == d) zd.setLayer(d.layer);
}
d.addAll(coll);
}
}
}
private final void addAll(final Collection<? extends Displayable> coll) {
// if any of the elements in the collection matches the type of the current tab, update that tab
// ... it's easier to just update the front tab
updateVisibleTab(true);
selection.clear();
navigator.repaint(true);
}
/** Add it to the proper panel, at the top, and set it active. */
private final void add(final Displayable d, final boolean activate, final boolean repaint_snapshot) {
if (activate) {
DisplayablePanel dp = ht_panels.get(d);
if (null != dp) dp.setActive(true);
else updateVisibleTab(d instanceof ZDisplayable);
selection.clear();
selection.add(d);
Display.repaint(d.getLayerSet()); // update the al_top list to contain the active one, or background image for a new Patch.
Utils.log2("Added " + d);
}
if (repaint_snapshot) navigator.repaint(true);
}
private void addToPanel(JPanel panel, int index, DisplayablePanel dp, boolean repaint) {
// remove the label
if (1 == panel.getComponentCount() && panel.getComponent(0) instanceof JLabel) {
panel.removeAll();
}
panel.add(dp, index);
if (repaint) {
Utils.updateComponent(tabs);
}
}
/** Find the displays that show the given Layer, and remove the given Displayable from the GUI. */
static public void remove(final Layer layer, final Displayable displ) {
for (final Display d : al_displays) {
if (layer == d.layer) d.remove(displ);
}
}
private void remove(final Displayable displ) {
DisplayablePanel ob = ht_panels.remove(displ);
if (null != ob) {
final JScrollPane jsp = ht_tabs.get(displ.getClass());
if (null != jsp) {
JPanel p = (JPanel)jsp.getViewport().getView();
p.remove((Component)ob);
Utils.revalidateComponent(p);
}
}
if (null == active || !selection.contains(displ)) {
canvas.setUpdateGraphics(true);
}
canvas.invalidateVolatile(); // removing active, no need to update offscreen but yes the volatile
repaint(displ, null, 5, true, false);
// from Selection.deleteAll this method is called ... but it's ok: same thread, no locking problems.
selection.remove(displ);
}
static public void remove(final ZDisplayable zdispl) {
for (final Display d : al_displays) {
if (zdispl.getLayerSet() == d.layer.getParent()) {
d.remove((Displayable)zdispl);
}
}
}
static public void repaint(final Layer layer, final Displayable displ, final int extra) {
repaint(layer, displ, displ.getBoundingBox(), extra);
}
static public void repaint(final Layer layer, final Displayable displ, final Rectangle r, final int extra) {
repaint(layer, displ, r, extra, true);
}
/** Find the displays that show the given Layer, and repaint the given Displayable. */
static public void repaint(final Layer layer, final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator) {
if (repaint_disabled) return;
for (final Display d : al_displays) {
if (layer == d.layer) {
d.repaint(displ, r, extra, repaint_navigator, false);
}
}
}
static public void repaint(final Displayable d) {
if (d instanceof ZDisplayable) repaint(d.getLayerSet(), d, d.getBoundingBox(null), 5, true);
repaint(d.getLayer(), d, d.getBoundingBox(null), 5, true);
}
/** Repaint as much as the bounding box around the given Displayable, or the r if not null. */
private void repaint(final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator, final boolean update_graphics) {
if (repaint_disabled || null == displ) return;
canvas.invalidateVolatile();
if (update_graphics || displ.getClass() == Patch.class || displ != active) {
canvas.setUpdateGraphics(true);
}
if (null != r) canvas.repaint(r, extra);
else canvas.repaint(displ, extra);
if (repaint_navigator) {
DisplayablePanel dp = ht_panels.get(displ);
if (null != dp) dp.repaint(); // is null when creating it, or after deleting it
navigator.repaint(true); // everything
}
}
/** Repaint the snapshot for the given Displayable both at the DisplayNavigator and on its panel,and only if it has not been painted before. This method is intended for the loader to know when to paint a snap, to avoid overhead. */
static public void repaintSnapshot(final Displayable displ) {
for (final Display d : al_displays) {
if (d.layer.contains(displ)) {
if (!d.navigator.isPainted(displ)) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) dp.repaint(); // is null when creating it, or after deleting it
d.navigator.repaint(displ);
}
}
}
}
/** Repaint the given Rectangle in all Displays showing the layer, updating the offscreen image if any. */
static public void repaint(final Layer layer, final Rectangle r, final int extra) {
repaint(layer, extra, r, true, true);
}
static public void repaint(final Layer layer, final int extra, final Rectangle r, final boolean update_navigator) {
repaint(layer, extra, r, update_navigator, true);
}
static public void repaint(final Layer layer, final int extra, final Rectangle r, final boolean update_navigator, final boolean update_graphics) {
if (repaint_disabled) return;
for (final Display d : al_displays) {
if (layer == d.layer) {
d.canvas.setUpdateGraphics(update_graphics);
d.canvas.repaint(r, extra);
if (update_navigator) {
d.navigator.repaint(true);
Utils.updateComponent(d.tabs.getSelectedComponent());
}
}
}
}
/** Repaint the given Rectangle in all Displays showing the layer, optionally updating the offscreen image (if any). */
static public void repaint(final Layer layer, final Rectangle r, final int extra, final boolean update_graphics) {
if (repaint_disabled) return;
for (final Display d : al_displays) {
if (layer == d.layer) {
d.canvas.setUpdateGraphics(update_graphics);
d.canvas.repaint(r, extra);
d.navigator.repaint(update_graphics);
if (update_graphics) Utils.updateComponent(d.tabs.getSelectedComponent());
}
}
}
/** Repaint the DisplayablePanel (and DisplayNavigator) only for the given Displayable, in all Displays showing the given Layer. */
static public void repaint(final Layer layer, final Displayable displ) {
if (repaint_disabled) return;
for (final Display d : al_displays) {
if (layer == d.layer) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) dp.repaint();
d.navigator.repaint(true);
}
}
}
static public void repaint(LayerSet set, Displayable displ, int extra) {
repaint(set, displ, null, extra);
}
static public void repaint(LayerSet set, Displayable displ, Rectangle r, int extra) {
repaint(set, displ, r, extra, true);
}
/** Repaint the Displayable in every Display that shows a Layer belonging to the given LayerSet. */
static public void repaint(final LayerSet set, final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator) {
if (repaint_disabled) return;
if (null == set) return;
for (final Display d : al_displays) {
if (set.contains(d.layer)) {
if (repaint_navigator) {
if (null != displ) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) dp.repaint();
}
d.navigator.repaint(true);
}
if (null == displ || displ != d.active) d.setUpdateGraphics(true); // safeguard
// paint the given box or the actual Displayable's box
if (null != r) d.canvas.repaint(r, extra);
else d.canvas.repaint(displ, extra);
}
}
}
/** Repaint the entire LayerSet, in all Displays showing a Layer of it.*/
static public void repaint(final LayerSet set) {
if (repaint_disabled) return;
for (final Display d : al_displays) {
if (set.contains(d.layer)) {
d.navigator.repaint(true);
d.canvas.repaint(true);
}
}
}
/** Repaint the given box in the LayerSet, in all Displays showing a Layer of it.*/
static public void repaint(final LayerSet set, final Rectangle box) {
if (repaint_disabled) return;
for (final Display d : al_displays) {
if (set.contains(d.layer)) {
d.navigator.repaint(box);
d.canvas.repaint(box, 0, true);
}
}
}
/** Repaint the entire Layer, in all Displays showing it, including the tabs.*/
static public void repaint(final Layer layer) { // TODO this method overlaps with update(layer)
if (repaint_disabled) return;
for (final Display d : al_displays) {
if (layer == d.layer) {
d.navigator.repaint(true);
d.canvas.repaint(true);
}
}
}
/** Call repaint on all open Displays. */
static public void repaint() {
if (repaint_disabled) {
Utils.logAll("Can't repaint -- repainting is disabled!");
return;
}
for (final Display d : al_displays) {
d.navigator.repaint(true);
d.canvas.repaint(true);
}
}
static private boolean repaint_disabled = false;
/** Set a flag to enable/disable repainting of all Display instances. */
static protected void setRepaint(boolean b) {
repaint_disabled = !b;
}
public Rectangle getBounds() {
return frame.getBounds();
}
public Point getLocation() {
return frame.getLocation();
}
public JFrame getFrame() {
return frame;
}
/** Feel free to add more tabs. Don't remove any of the existing tabs or the sky will fall on your head. */
public JTabbedPane getTabbedPane() {
return tabs;
}
/** Returns the tab index in this Display's JTabbedPane. */
public int addTab(final String title, final Component comp) {
this.tabs.add(title, comp);
return this.tabs.getTabCount() -1;
}
public void setLocation(Point p) {
this.frame.setLocation(p);
}
public Displayable getActive() {
return active; //TODO this should return selection.active !!
}
public void select(Displayable d) {
select(d, false);
}
/** Select/deselect accordingly to the current state and the shift key. */
public void select(final Displayable d, final boolean shift_down) {
if (null != active && active != d && active.getClass() != Patch.class) {
// active is being deselected, so link underlying patches
final String prop = active.getClass() == DLabel.class ? project.getProperty("label_nolinks")
: project.getProperty("segmentations_nolinks");
HashSet<Displayable> glinked = null;
if (null != prop && prop.equals("true")) {
// do nothing: linking disabled for active's type
} else if (active.linkPatches()) {
// Locking state changed:
glinked = active.getLinkedGroup(null);
updateCheckboxes(glinked, DisplayablePanel.LOCK_STATE, true);
}
// Update link icons:
Display.updateCheckboxes(null == glinked ? active.getLinkedGroup(null) : glinked, DisplayablePanel.LINK_STATE);
}
if (null == d) {
//Utils.log2("Display.select: clearing selection");
canvas.setUpdateGraphics(true);
selection.clear();
return;
}
if (!shift_down) {
//Utils.log2("Display.select: single selection");
if (d != active) {
selection.clear();
selection.add(d);
}
} else if (selection.contains(d)) {
if (active == d) {
selection.remove(d);
//Utils.log2("Display.select: removing from a selection");
} else {
//Utils.log2("Display.select: activing within a selection");
selection.setActive(d);
}
} else {
//Utils.log2("Display.select: adding to an existing selection");
selection.add(d);
}
// update the image shown to ImageJ
// NO longer necessary, always he same FakeImagePlus // setTempCurrentImage();
}
protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p, final Class c) {
choose(screen_x_p, screen_y_p, x_p, y_p, false, c);
}
protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p) {
choose(screen_x_p, screen_y_p, x_p, y_p, false, null);
}
/** Find a Displayable to add to the selection under the given point (which is in offscreen coords); will use a popup menu to give the user a range of Displayable objects to select from. */
protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p, boolean shift_down, Class c) {
//Utils.log("Display.choose: x,y " + x_p + "," + y_p);
final ArrayList<Displayable> al = new ArrayList<Displayable>(layer.find(x_p, y_p, true));
al.addAll(layer.getParent().findZDisplayables(layer, x_p, y_p, true)); // only visible ones
if (al.isEmpty()) {
Displayable act = this.active;
selection.clear();
canvas.setUpdateGraphics(true);
//Utils.log("choose: set active to null");
// fixing lack of repainting for unknown reasons, of the active one TODO this is a temporary solution
if (null != act) Display.repaint(layer, act, 5);
} else if (1 == al.size()) {
Displayable d = (Displayable)al.get(0);
if (null != c && d.getClass() != c) {
selection.clear();
return;
}
select(d, shift_down);
//Utils.log("choose 1: set active to " + active);
} else {
if (al.contains(active) && !shift_down) {
// do nothing
} else {
if (null != c) {
// check if at least one of them is of class c
// if only one is of class c, set as selected
// else show menu
for (Iterator it = al.iterator(); it.hasNext(); ) {
Object ob = it.next();
if (ob.getClass() != c) it.remove();
}
if (0 == al.size()) {
// deselect
selection.clear();
return;
}
if (1 == al.size()) {
select((Displayable)al.get(0), shift_down);
return;
}
// else, choose among the many
}
choose(screen_x_p, screen_y_p, al, shift_down, x_p, y_p);
}
//Utils.log("choose many: set active to " + active);
}
}
private void choose(final int screen_x_p, final int screen_y_p, final Collection al, final boolean shift_down, final int x_p, final int y_p) {
// show a popup on the canvas to choose
new Thread() {
public void run() {
final Object lock = new Object();
final DisplayableChooser d_chooser = new DisplayableChooser(al, lock);
final JPopupMenu pop = new JPopupMenu("Select:");
final Iterator itu = al.iterator();
while (itu.hasNext()) {
Displayable d = (Displayable)itu.next();
JMenuItem menu_item = new JMenuItem(d.toString());
menu_item.addActionListener(d_chooser);
pop.add(menu_item);
}
new Thread() {
public void run() {
pop.show(canvas, screen_x_p, screen_y_p);
}
}.start();
//now wait until selecting something
synchronized(lock) {
do {
try {
lock.wait();
} catch (InterruptedException ie) {}
} while (d_chooser.isWaiting() && pop.isShowing());
}
//grab the chosen Displayable object
Displayable d = d_chooser.getChosen();
//Utils.log("Chosen: " + d.toString());
if (null == d) { Utils.log2("Display.choose: returning a null!"); }
select(d, shift_down);
pop.setVisible(false);
// fix selection bug: never receives mouseReleased event when the popup shows
getMode().mouseReleased(null, x_p, y_p, x_p, y_p, x_p, y_p);
}
}.start();
}
/** Used by the Selection exclusively. This method will change a lot in the near future, and may disappear in favor of getSelection().getActive(). All this method does is update GUI components related to the currently active and the newly active Displayable; called through SwingUtilities.invokeLater. */
protected void setActive(final Displayable displ) {
final Displayable prev_active = this.active;
this.active = displ;
SwingUtilities.invokeLater(new Runnable() { public void run() {
if (null != displ && displ == prev_active && tabs.getSelectedComponent() != annot_panel) {
// make sure the proper tab is selected.
selectTab(displ);
return; // the same
}
// deactivate previously active
if (null != prev_active) {
final DisplayablePanel ob = ht_panels.get(prev_active);
if (null != ob) ob.setActive(false);
// erase "decorations" of the previously active
canvas.repaint(selection.getBox(), 4);
// Adjust annotation doc
synchronized (annot_docs) {
boolean remove_doc = true;
for (final Display d : al_displays) {
if (prev_active == d.active) {
remove_doc = false;
break;
}
}
if (remove_doc) annot_docs.remove(prev_active);
}
}
// activate the new active
if (null != displ) {
final DisplayablePanel ob = ht_panels.get(displ);
if (null != ob) ob.setActive(true);
updateInDatabase("active_displayable_id");
if (displ.getClass() != Patch.class) project.select(displ); // select the node in the corresponding tree, if any.
// select the proper tab, and scroll to visible
if (tabs.getSelectedComponent() != annot_panel) { // don't swap tab if its the annotation one
selectTab(displ);
}
boolean update_graphics = null == prev_active || paintsBelow(prev_active, displ); // or if it's an image, but that's by default in the repaint method
repaint(displ, null, 5, false, update_graphics); // to show the border, and to repaint out of the background image
transp_slider.setValue((int)(displ.getAlpha() * 100));
// Adjust annotation tab:
synchronized (annot_docs) {
annot_label.setText(displ.toString());
Document doc = annot_docs.get(displ); // could be open in another Display
if (null == doc) {
doc = annot_editor.getEditorKit().createDefaultDocument();
doc.addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {}
public void insertUpdate(DocumentEvent e) { push(); }
public void removeUpdate(DocumentEvent e) { push(); }
private void push() {
displ.setAnnotation(annot_editor.getText());
}
});
annot_docs.put(displ, doc);
}
annot_editor.setDocument(doc);
if (null != displ.getAnnotation()) annot_editor.setText(displ.getAnnotation());
}
annot_editor.setEnabled(true);
} else {
//ensure decorations are removed from the panels, for Displayables in a selection besides the active one
Utils.updateComponent(tabs.getSelectedComponent());
annot_label.setText("(No selected object)");
annot_editor.setDocument(annot_editor.getEditorKit().createDefaultDocument()); // a clear, empty one
annot_editor.setEnabled(false);
}
}});
}
/** If the other paints under the base. */
public boolean paintsBelow(Displayable base, Displayable other) {
boolean zd_base = base instanceof ZDisplayable;
boolean zd_other = other instanceof ZDisplayable;
if (zd_other) {
if (base instanceof DLabel) return true; // zd paints under label
if (!zd_base) return false; // any zd paints over a mere displ if not a label
else {
// both zd, compare indices
ArrayList<ZDisplayable> al = other.getLayerSet().getZDisplayables();
return al.indexOf(base) > al.indexOf(other);
}
} else {
if (!zd_base) {
// both displ, compare indices
ArrayList<Displayable> al = other.getLayer().getDisplayables();
return al.indexOf(base) > al.indexOf(other);
} else {
// base is zd, other is d
if (other instanceof DLabel) return false;
return true;
}
}
}
/** Select the proper tab, and also scroll it to show the given Displayable -unless it's a LayerSet, and unless the proper tab is already showing. */
private void selectTab(final Displayable displ) {
Method method = null;
try {
if (!(displ instanceof LayerSet)) {
method = Display.class.getDeclaredMethod("selectTab", new Class[]{displ.getClass()});
}
} catch (Exception e) {
IJError.print(e);
}
if (null != method) {
final Method me = method;
dispatcher.exec(new Runnable() { public void run() {
try {
me.setAccessible(true);
me.invoke(Display.this, new Object[]{displ});
} catch (Exception e) { IJError.print(e); }
}});
}
}
private void selectTab(Patch patch) {
tabs.setSelectedComponent(scroll_patches);
scrollToShow(scroll_patches, ht_panels.get(patch));
}
private void selectTab(Profile profile) {
tabs.setSelectedComponent(scroll_profiles);
scrollToShow(scroll_profiles, ht_panels.get(profile));
}
private void selectTab(DLabel label) {
tabs.setSelectedComponent(scroll_labels);
scrollToShow(scroll_labels, ht_panels.get(label));
}
private void selectTab(ZDisplayable zd) {
tabs.setSelectedComponent(scroll_zdispl);
scrollToShow(scroll_zdispl, ht_panels.get(zd));
}
private void selectTab(Pipe d) { selectTab((ZDisplayable)d); }
private void selectTab(Polyline d) { selectTab((ZDisplayable)d); }
private void selectTab(Treeline d) { selectTab((ZDisplayable)d); }
private void selectTab(AreaTree d) { selectTab((ZDisplayable)d); }
private void selectTab(Connector d) { selectTab((ZDisplayable)d); }
private void selectTab(AreaList d) { selectTab((ZDisplayable)d); }
private void selectTab(Ball d) { selectTab((ZDisplayable)d); }
private void selectTab(Dissector d) { selectTab((ZDisplayable)d); }
private void selectTab(Stack d) { selectTab((ZDisplayable)d); }
/** A method to update the given tab, creating a new DisplayablePanel for each Displayable present in the given ArrayList, and storing it in the ht_panels (which is cleared first). */
private void updateTab(final JPanel tab, final ArrayList al) {
if (null == al) return;
dispatcher.exec(new Runnable() { public void run() {
try {
if (0 == al.size()) {
tab.removeAll();
} else {
Component[] comp = tab.getComponents();
int next = 0;
if (1 == comp.length && comp[0].getClass() == JLabel.class) {
next = 1;
tab.remove(0);
}
// In reverse order:
for (ListIterator it = al.listIterator(al.size()); it.hasPrevious(); ) {
Displayable d = (Displayable)it.previous();
DisplayablePanel dp = null;
if (next < comp.length) {
dp = (DisplayablePanel)comp[next++]; // recycling panels
dp.set(d);
} else {
dp = new DisplayablePanel(Display.this, d);
tab.add(dp);
}
ht_panels.put(d, dp);
}
if (next < comp.length) {
// remove from the end, to avoid potential repaints of other panels
for (int i=comp.length-1; i>=next; i--) {
tab.remove(i);
}
}
}
if (null != Display.this.active) scrollToShow(Display.this.active);
} catch (Throwable e) { IJError.print(e); }
// invokeLater:
Utils.updateComponent(tabs);
}});
}
static public void setActive(final Object event, final Displayable displ) {
if (!(event instanceof InputEvent)) return;
// find which Display
for (final Display d : al_displays) {
if (d.isOrigin((InputEvent)event)) {
d.setActive(displ);
break;
}
}
}
/** Find out whether this Display is Transforming its active Displayable. */
public boolean isTransforming() {
return canvas.isTransforming();
}
/** Find whether any Display is transforming the given Displayable. */
static public boolean isTransforming(final Displayable displ) {
for (final Display d : al_displays) {
if (null != d.active && d.active == displ && d.canvas.isTransforming()) return true;
}
return false;
}
/** Check whether the source of the event is located in this instance.*/
private boolean isOrigin(InputEvent event) {
Object source = event.getSource();
// find it ... check the canvas for now TODO
if (canvas == source) {
return true;
}
return false;
}
/** Get the layer of the front Display, or null if none.*/
static public Layer getFrontLayer() {
if (null == front) return null;
return front.layer;
}
/** Get the layer of an open Display of the given Project, or null if none.*/
static public Layer getFrontLayer(final Project project) {
if (null == front) return null;
if (front.project == project) return front.layer;
// else, find an open Display for the given Project, if any
for (final Display d : al_displays) {
if (d.project == project) {
d.frame.toFront();
return d.layer;
}
}
return null; // none found
}
/** Get a pointer to a Display for @param project, or null if none. */
static public Display getFront(final Project project) {
if (null == front) return null;
if (front.project == project) return front;
for (final Display d : al_displays) {
if (d.project == project) {
d.frame.toFront();
return d;
}
}
return null;
}
/** Return the list of selected Displayable objects of the front Display, or an emtpy list if no Display or none selected. */
static public List<Displayable> getSelected() {
if (null == front) return new ArrayList<Displayable>();
return front.selection.getSelected();
}
/** Return the list of selected Displayable objects of class @param c of the front Display, or an emtpy list if no Display or none selected. */
static public List<Displayable> getSelected(final Class c) {
if (null == front) return new ArrayList<Displayable>();
return front.selection.getSelected(c);
}
public boolean isReadOnly() {
// TEMPORARY: in the future one will be able show displays as read-only to other people, remotely
return false;
}
static public void showPopup(Component c, int x, int y) {
if (null != front) front.getPopupMenu().show(c, x, y);
}
/** Return a context-sensitive popup menu. */
public JPopupMenu getPopupMenu() { // called from canvas
// get the job canceling dialog
if (!canvas.isInputEnabled()) {
return project.getLoader().getJobsPopup(this);
}
// create new
this.popup = new JPopupMenu();
JMenuItem item = null;
JMenu menu = null;
if (canvas.isTransforming()) {
item = new JMenuItem("Apply transform"); item.addActionListener(this); popup.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true)); // dummy, for I don't add a MenuKeyListener, but "works" through the normal key listener. It's here to provide a visual cue
item = new JMenuItem("Apply transform propagating to last layer"); item.addActionListener(this); popup.add(item);
if (layer.getParent().indexOf(layer) == layer.getParent().size() -1) item.setEnabled(false);
if (!(getMode().getClass() == AffineTransformMode.class || getMode().getClass() == NonLinearTransformMode.class)) item.setEnabled(false);
item = new JMenuItem("Apply transform propagating to first layer"); item.addActionListener(this); popup.add(item);
if (0 == layer.getParent().indexOf(layer)) item.setEnabled(false);
if (!(getMode().getClass() == AffineTransformMode.class || getMode().getClass() == NonLinearTransformMode.class)) item.setEnabled(false);
item = new JMenuItem("Cancel transform"); item.addActionListener(this); popup.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true));
item = new JMenuItem("Specify transform..."); item.addActionListener(this); popup.add(item);
if (getMode().getClass() != AffineTransformMode.class) item.setEnabled(false);
return popup;
}
final Class aclass = null == active ? null : active.getClass();
if (null != active) {
if (Profile.class == aclass) {
item = new JMenuItem("Duplicate, link and send to next layer"); item.addActionListener(this); popup.add(item);
Layer nl = layer.getParent().next(layer);
if (nl == layer) item.setEnabled(false);
item = new JMenuItem("Duplicate, link and send to previous layer"); item.addActionListener(this); popup.add(item);
nl = layer.getParent().previous(layer);
if (nl == layer) item.setEnabled(false);
menu = new JMenu("Duplicate, link and send to");
ArrayList al = layer.getParent().getLayers();
final Iterator it = al.iterator();
int i = 1;
while (it.hasNext()) {
Layer la = (Layer)it.next();
item = new JMenuItem(i + ": z = " + la.getZ()); item.addActionListener(this); menu.add(item); // TODO should label which layers contain Profile instances linked to the one being duplicated
if (la == this.layer) item.setEnabled(false);
i++;
}
popup.add(menu);
item = new JMenuItem("Duplicate, link and send to..."); item.addActionListener(this); popup.add(item);
popup.addSeparator();
item = new JMenuItem("Unlink from images"); item.addActionListener(this); popup.add(item);
if (!active.isLinked()) item.setEnabled(false); // isLinked() checks if it's linked to a Patch in its own layer
item = new JMenuItem("Show in 3D"); item.addActionListener(this); popup.add(item);
popup.addSeparator();
} else if (Patch.class == aclass) {
item = new JMenuItem("Unlink from images"); item.addActionListener(this); popup.add(item);
if (!active.isLinked(Patch.class)) item.setEnabled(false);
if (((Patch)active).isStack()) {
item = new JMenuItem("Unlink slices"); item.addActionListener(this); popup.add(item);
}
int n_sel_patches = selection.getSelected(Patch.class).size();
if (1 == n_sel_patches) {
item = new JMenuItem("Snap"); item.addActionListener(this); popup.add(item);
} else if (n_sel_patches > 1) {
item = new JMenuItem("Montage"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Lens correction"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Blend"); item.addActionListener(this); popup.add(item);
}
item = new JMenuItem("Remove alpha mask"); item.addActionListener(this); popup.add(item);
if ( ! ((Patch)active).hasAlphaMask()) item.setEnabled(false);
item = new JMenuItem("View volume"); item.addActionListener(this); popup.add(item);
HashSet hs = active.getLinked(Patch.class);
if (null == hs || 0 == hs.size()) item.setEnabled(false);
item = new JMenuItem("View orthoslices"); item.addActionListener(this); popup.add(item);
if (null == hs || 0 == hs.size()) item.setEnabled(false); // if no Patch instances among the directly linked, then it's not a stack
popup.addSeparator();
} else {
item = new JMenuItem("Unlink"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Show in 3D"); item.addActionListener(this); popup.add(item);
popup.addSeparator();
}
if (AreaList.class == aclass) {
item = new JMenuItem("Merge"); item.addActionListener(this); popup.add(item);
ArrayList al = selection.getSelected();
int n = 0;
for (Iterator it = al.iterator(); it.hasNext(); ) {
if (it.next().getClass() == AreaList.class) n++;
}
if (n < 2) item.setEnabled(false);
popup.addSeparator();
} else if (Pipe.class == aclass) {
item = new JMenuItem("Reverse point order"); item.addActionListener(this); popup.add(item);
popup.addSeparator();
} else if (Treeline.class == aclass || AreaTree.class == aclass) {
item = new JMenuItem("Reroot"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Part subtree"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Mark"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Clear marks (selected Trees)"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Join"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Show tabular view"); item.addActionListener(this); popup.add(item);
item.setSelected(selection.getSelected(Tree.class).size() > 1);
JMenu go = new JMenu("Go");
item = new JMenuItem("Previous branch point or start"); item.addActionListener(this); go.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, 0, true));
item = new JMenuItem("Next branch point or end"); item.addActionListener(this); go.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, 0, true));
item = new JMenuItem("Root"); item.addActionListener(this); go.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0, true));
go.addSeparator();
item = new JMenuItem("Last added point"); item.addActionListener(this); go.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, 0, true));
item = new JMenuItem("Last edited point"); item.addActionListener(this); go.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, 0, true));
popup.add(go);
popup.addSeparator();
} else if (Connector.class == aclass) {
item = new JMenuItem("Merge"); item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (null == getActive() || getActive().getClass() != Connector.class) {
Utils.log("Active object must be a Connector!");
return;
}
final List<Connector> col = (List<Connector>) (List) selection.getSelected(Connector.class);
if (col.size() < 2) {
Utils.log("Select more than one Connector!");
return;
}
if (col.get(0) != getActive()) {
if (col.remove(getActive())) {
col.add(0, (Connector)getActive());
} else {
Utils.log("ERROR: cannot find active object in selection list!");
return;
}
}
Bureaucrat.createAndStart(new Worker.Task("Merging connectors") {
public void exec() {
getLayerSet().addChangeTreesStep();
Connector base = null;
try {
base = Connector.merge(col);
} catch (Exception e) {
IJError.print(e);
}
if (null == base) {
Utils.log("ERROR: could not merge connectors!");
getLayerSet().undoOneStep();
} else {
getLayerSet().addChangeTreesStep();
}
Display.repaint();
}
}, getProject());
}
});
popup.add(item);
item.setEnabled(selection.getSelected(Connector.class).size() > 1);
}
item = new JMenuItem("Duplicate"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Color..."); item.addActionListener(this); popup.add(item);
if (active instanceof LayerSet) item.setEnabled(false);
if (active.isLocked()) {
item = new JMenuItem("Unlock"); item.addActionListener(this); popup.add(item);
} else {
item = new JMenuItem("Lock"); item.addActionListener(this); popup.add(item);
}
menu = new JMenu("Move");
popup.addSeparator();
LayerSet ls = layer.getParent();
item = new JMenuItem("Move to top"); item.addActionListener(this); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0, true)); // this is just to draw the key name by the menu; it does not incur on any event being generated (that I know if), and certainly not any event being listened to by TrakEM2.
if (ls.isTop(active)) item.setEnabled(false);
item = new JMenuItem("Move up"); item.addActionListener(this); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0, true));
if (ls.isTop(active)) item.setEnabled(false);
item = new JMenuItem("Move down"); item.addActionListener(this); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0, true));
if (ls.isBottom(active)) item.setEnabled(false);
item = new JMenuItem("Move to bottom"); item.addActionListener(this); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0, true));
if (ls.isBottom(active)) item.setEnabled(false);
popup.add(menu);
popup.addSeparator();
item = new JMenuItem("Delete..."); item.addActionListener(this); popup.add(item);
try {
if (Patch.class == aclass) {
if (!active.isOnlyLinkedTo(Patch.class)) {
item.setEnabled(false);
}
} else if (!(DLabel.class == aclass || Stack.class == aclass)) { // can't delete elements from the trees (Profile, Pipe, LayerSet, Ball, Dissector, AreaList, Polyline)
item.setEnabled(false);
}
} catch (Exception e) { IJError.print(e); item.setEnabled(false); }
if (Patch.class == aclass) {
item = new JMenuItem("Revert"); item.addActionListener(this); popup.add(item);
if ( null == ((Patch)active).getOriginalPath()) item.setEnabled(false);
popup.addSeparator();
}
item = new JMenuItem("Properties..."); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Show centered"); item.addActionListener(this); popup.add(item);
popup.addSeparator();
if (! (active instanceof ZDisplayable)) {
ArrayList al_layers = layer.getParent().getLayers();
int i_layer = al_layers.indexOf(layer);
int n_layers = al_layers.size();
item = new JMenuItem("Send to previous layer"); item.addActionListener(this); popup.add(item);
if (1 == n_layers || 0 == i_layer || active.isLinked()) item.setEnabled(false);
// check if the active is a profile and contains a link to another profile in the layer it is going to be sent to, or it is linked
else if (active instanceof Profile && !active.canSendTo(layer.getParent().previous(layer))) item.setEnabled(false);
item = new JMenuItem("Send to next layer"); item.addActionListener(this); popup.add(item);
if (1 == n_layers || n_layers -1 == i_layer || active.isLinked()) item.setEnabled(false);
else if (active instanceof Profile && !active.canSendTo(layer.getParent().next(layer))) item.setEnabled(false);
menu = new JMenu("Send linked group to...");
if (active.hasLinkedGroupWithinLayer(this.layer)) {
int i = 1;
for (final Layer la : ls.getLayers()) {
String layer_title = i + ": " + la.getTitle();
if (-1 == layer_title.indexOf(' ')) layer_title += " ";
item = new JMenuItem(layer_title); item.addActionListener(this); menu.add(item);
if (la == this.layer) item.setEnabled(false);
i++;
}
popup.add(menu);
} else {
menu.setEnabled(false);
//Utils.log("Active's linked group not within layer.");
}
popup.add(menu);
popup.addSeparator();
}
}
item = new JMenuItem("Undo");item.addActionListener(this); popup.add(item);
if (!layer.getParent().canUndo() || canvas.isTransforming()) item.setEnabled(false);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Utils.getControlModifier(), true));
item = new JMenuItem("Redo");item.addActionListener(this); popup.add(item);
if (!layer.getParent().canRedo() || canvas.isTransforming()) item.setEnabled(false);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.SHIFT_MASK | Event.CTRL_MASK, true));
popup.addSeparator();
// Would get so much simpler with a clojure macro ...
try {
menu = new JMenu("Hide/Unhide");
item = new JMenuItem("Hide deselected"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.SHIFT_MASK, true));
boolean none = 0 == selection.getNSelected();
if (none) item.setEnabled(false);
item = new JMenuItem("Hide deselected except images"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.SHIFT_MASK | Event.ALT_MASK, true));
if (none) item.setEnabled(false);
item = new JMenuItem("Hide selected"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, 0, true));
if (none) item.setEnabled(false);
none = ! layer.getParent().containsDisplayable(DLabel.class);
item = new JMenuItem("Hide all labels"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all labels"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().contains(AreaList.class);
item = new JMenuItem("Hide all arealists"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all arealists"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.contains(Profile.class);
item = new JMenuItem("Hide all profiles"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all profiles"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().contains(Pipe.class);
item = new JMenuItem("Hide all pipes"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all pipes"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().contains(Polyline.class);
item = new JMenuItem("Hide all polylines"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all polylines"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().contains(Treeline.class);
item = new JMenuItem("Hide all treelines"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all treelines"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().contains(AreaTree.class);
item = new JMenuItem("Hide all areatrees"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all areatrees"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().contains(Ball.class);
item = new JMenuItem("Hide all balls"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all balls"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().contains(Connector.class);
item = new JMenuItem("Hide all connectors"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all connectors"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().containsDisplayable(Patch.class);
item = new JMenuItem("Hide all images"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all images"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Hide all but images"); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Unhide all"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.ALT_MASK, true));
popup.add(menu);
} catch (Exception e) { IJError.print(e); }
// plugins, if any
Utils.addPlugIns(popup, "Display", project, new Callable<Displayable>() { public Displayable call() { return Display.this.getActive(); }});
JMenu align_menu = new JMenu("Align");
item = new JMenuItem("Align stack slices"); item.addActionListener(this); align_menu.add(item);
if (selection.isEmpty() || ! (getActive().getClass() == Patch.class && ((Patch)getActive()).isStack())) item.setEnabled(false);
item = new JMenuItem("Align layers"); item.addActionListener(this); align_menu.add(item);
if (1 == layer.getParent().size()) item.setEnabled(false);
item = new JMenuItem("Align layers with manual landmarks"); item.addActionListener(this); align_menu.add(item);
if (1 == layer.getParent().size()) item.setEnabled(false);
item = new JMenuItem("Align multi-layer mosaic"); item.addActionListener(this); align_menu.add(item);
if (1 == layer.getParent().size()) item.setEnabled(false);
item = new JMenuItem("Montage all images in this layer"); item.addActionListener(this); align_menu.add(item);
if (layer.getDisplayables(Patch.class).size() < 2) item.setEnabled(false);
item = new JMenuItem("Montage selected images (SIFT)"); item.addActionListener(this); align_menu.add(item);
if (selection.getSelected(Patch.class).size() < 2) item.setEnabled(false);
item = new JMenuItem("Montage selected images (phase correlation)"); item.addActionListener(this); align_menu.add(item);
if (selection.getSelected(Patch.class).size() < 2) item.setEnabled(false);
item = new JMenuItem("Montage multiple layers (phase correlation)"); item.addActionListener(this); align_menu.add(item);
popup.add(align_menu);
item = new JMenuItem("Montage multiple layers (SIFT)"); item.addActionListener(this); align_menu.add(item);
popup.add(align_menu);
JMenuItem st = new JMenu("Transform");
StartTransformMenuListener tml = new StartTransformMenuListener();
item = new JMenuItem("Transform (affine)"); item.addActionListener(tml); st.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, 0, true));
if (null == active) item.setEnabled(false);
item = new JMenuItem("Transform (non-linear)"); item.addActionListener(tml); st.add(item);
if (null == active) item.setEnabled(false);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, Event.SHIFT_MASK, true));
item = new JMenuItem("Cancel transform"); st.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true));
item.setEnabled(false); // just added as a self-documenting cue; no listener
item = new JMenuItem("Remove rotation, scaling and shear (selected images)"); item.addActionListener(tml); st.add(item);
if (null == active) item.setEnabled(false);
item = new JMenuItem("Remove rotation, scaling and shear layer-wise"); item.addActionListener(tml); st.add(item);
item = new JMenuItem("Remove coordinate transforms (selected images)"); item.addActionListener(tml); st.add(item);
if (null == active) item.setEnabled(false);
item = new JMenuItem("Remove coordinate transforms layer-wise"); item.addActionListener(tml); st.add(item);
popup.add(st);
JMenu link_menu = new JMenu("Link");
item = new JMenuItem("Link images..."); item.addActionListener(this); link_menu.add(item);
item = new JMenuItem("Unlink all selected images"); item.addActionListener(this); link_menu.add(item);
item.setEnabled(selection.getSelected(Patch.class).size() > 0);
item = new JMenuItem("Unlink all"); item.addActionListener(this); link_menu.add(item);
popup.add(link_menu);
JMenu adjust_menu = new JMenu("Adjust images");
item = new JMenuItem("Enhance contrast layer-wise..."); item.addActionListener(this); adjust_menu.add(item);
item = new JMenuItem("Enhance contrast (selected images)..."); item.addActionListener(this); adjust_menu.add(item);
if (selection.isEmpty()) item.setEnabled(false);
item = new JMenuItem("Set Min and Max layer-wise..."); item.addActionListener(this); adjust_menu.add(item);
item = new JMenuItem("Set Min and Max (selected images)..."); item.addActionListener(this); adjust_menu.add(item);
if (selection.isEmpty()) item.setEnabled(false);
item = new JMenuItem("Adjust min and max (selected images)..."); item.addActionListener(this); adjust_menu.add(item);
if (selection.isEmpty()) item.setEnabled(false);
item = new JMenuItem("Mask image borders (layer-wise)..."); item.addActionListener(this); adjust_menu.add(item);
item = new JMenuItem("Mask image borders (selected images)..."); item.addActionListener(this); adjust_menu.add(item);
if (selection.isEmpty()) item.setEnabled(false);
popup.add(adjust_menu);
JMenu script = new JMenu("Script");
MenuScriptListener msl = new MenuScriptListener();
item = new JMenuItem("Set preprocessor script layer-wise..."); item.addActionListener(msl); script.add(item);
item = new JMenuItem("Set preprocessor script (selected images)..."); item.addActionListener(msl); script.add(item);
if (selection.isEmpty()) item.setEnabled(false);
item = new JMenuItem("Remove preprocessor script layer-wise..."); item.addActionListener(msl); script.add(item);
item = new JMenuItem("Remove preprocessor script (selected images)..."); item.addActionListener(msl); script.add(item);
if (selection.isEmpty()) item.setEnabled(false);
popup.add(script);
menu = new JMenu("Import");
item = new JMenuItem("Import image"); item.addActionListener(this); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK & Event.SHIFT_MASK, true));
item = new JMenuItem("Import stack..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Import stack with landmarks..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Import grid..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Import sequence as grid..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Import from text file..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Import labels as arealists..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Tags ..."); item.addActionListener(this); menu.add(item);
popup.add(menu);
menu = new JMenu("Export");
item = new JMenuItem("Make flat image..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Arealists as labels (tif)"); item.addActionListener(this); menu.add(item);
if (0 == layer.getParent().getZDisplayables(AreaList.class).size()) item.setEnabled(false);
item = new JMenuItem("Arealists as labels (amira)"); item.addActionListener(this); menu.add(item);
if (0 == layer.getParent().getZDisplayables(AreaList.class).size()) item.setEnabled(false);
item = new JMenuItem("Image stack under selected Arealist"); item.addActionListener(this); menu.add(item);
item.setEnabled(null != active && AreaList.class == active.getClass());
item = new JMenuItem("Fly through selected Treeline/AreaTree"); item.addActionListener(this); menu.add(item);
item.setEnabled(null != active && Tree.class.isInstance(active));
item = new JMenuItem("Tags..."); item.addActionListener(this); menu.add(item);
popup.add(menu);
menu = new JMenu("Display");
item = new JMenuItem("Resize canvas/LayerSet..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Autoresize canvas/LayerSet"); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Properties ..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Calibration..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Grid overlay..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Adjust snapping parameters..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Adjust fast-marching parameters..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Adjust arealist paint parameters..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Show current 2D position in 3D"); item.addActionListener(this); menu.add(item);
popup.add(menu);
menu = new JMenu("Project");
this.project.getLoader().setupMenuItems(menu, this.getProject());
item = new JMenuItem("Project properties..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Create subproject"); item.addActionListener(this); menu.add(item);
if (null == canvas.getFakeImagePlus().getRoi()) item.setEnabled(false);
item = new JMenuItem("Release memory..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Flush image cache"); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Regenerate all mipmaps"); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Regenerate mipmaps (selected images)"); item.addActionListener(this); menu.add(item);
popup.add(menu);
menu = new JMenu("Selection");
item = new JMenuItem("Select all"); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Select all visible"); item.addActionListener(this); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Utils.getControlModifier(), true));
if (0 == layer.getDisplayables().size() && 0 == layer.getParent().getZDisplayables().size()) item.setEnabled(false);
item = new JMenuItem("Select none"); item.addActionListener(this); menu.add(item);
if (0 == selection.getNSelected()) item.setEnabled(false);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true));
JMenu bytype = new JMenu("Select all by type");
item = new JMenuItem("AreaList"); item.addActionListener(bytypelistener); bytype.add(item);
item = new JMenuItem("AreaTree"); item.addActionListener(bytypelistener); bytype.add(item);
item = new JMenuItem("Ball"); item.addActionListener(bytypelistener); bytype.add(item);
item = new JMenuItem("Connector"); item.addActionListener(bytypelistener); bytype.add(item);
item = new JMenuItem("Dissector"); item.addActionListener(bytypelistener); bytype.add(item);
item = new JMenuItem("Image"); item.addActionListener(bytypelistener); bytype.add(item);
item = new JMenuItem("Pipe"); item.addActionListener(bytypelistener); bytype.add(item);
item = new JMenuItem("Polyline"); item.addActionListener(bytypelistener); bytype.add(item);
item = new JMenuItem("Profile"); item.addActionListener(bytypelistener); bytype.add(item);
item = new JMenuItem("Text"); item.addActionListener(bytypelistener); bytype.add(item);
item = new JMenuItem("Treeline"); item.addActionListener(bytypelistener); bytype.add(item);
menu.add(bytype);
item = new JMenuItem("Restore selection"); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Select under ROI"); item.addActionListener(this); menu.add(item);
if (canvas.getFakeImagePlus().getRoi() == null) item.setEnabled(false);
JMenu graph = new JMenu("Graph");
GraphMenuListener gl = new GraphMenuListener();
item = new JMenuItem("Select outgoing Connectors"); item.addActionListener(gl); graph.add(item);
item = new JMenuItem("Select incomming Connectors"); item.addActionListener(gl); graph.add(item);
item = new JMenuItem("Select downstream targets"); item.addActionListener(gl); graph.add(item);
item = new JMenuItem("Select upstream targets"); item.addActionListener(gl); graph.add(item);
graph.setEnabled(!selection.isEmpty());
menu.add(graph);
popup.add(menu);
menu = new JMenu("Tool");
item = new JMenuItem("Rectangular ROI"); item.addActionListener(new SetToolListener(Toolbar.RECTANGLE)); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0, true));
item = new JMenuItem("Polygon ROI"); item.addActionListener(new SetToolListener(Toolbar.POLYGON)); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0, true));
item = new JMenuItem("Freehand ROI"); item.addActionListener(new SetToolListener(Toolbar.FREEROI)); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0, true));
item = new JMenuItem("Text"); item.addActionListener(new SetToolListener(Toolbar.TEXT)); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0, true));
item = new JMenuItem("Magnifier glass"); item.addActionListener(new SetToolListener(Toolbar.MAGNIFIER)); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0, true));
item = new JMenuItem("Hand"); item.addActionListener(new SetToolListener(Toolbar.HAND)); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0, true));
item = new JMenuItem("Select"); item.addActionListener(new SetToolListener(ProjectToolbar.SELECT)); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0, true));
item = new JMenuItem("Pencil"); item.addActionListener(new SetToolListener(ProjectToolbar.PENCIL)); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0, true));
item = new JMenuItem("Pen"); item.addActionListener(new SetToolListener(ProjectToolbar.PEN)); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0, true));
popup.add(menu);
item = new JMenuItem("Search..."); item.addActionListener(this); popup.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, Utils.getControlModifier(), true));
//canvas.add(popup);
return popup;
}
private final class GraphMenuListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
final String command = ae.getActionCommand();
final Collection<Displayable> sel = selection.getSelected();
if (null == sel || sel.isEmpty()) return;
final Collection<Connector> connectors = (Collection<Connector>) (Collection) getLayerSet().getZDisplayables(Connector.class);
final HashSet<Displayable> to_select = new HashSet<Displayable>();
if (command.equals("Select outgoing Connectors")) {
for (final Connector con : connectors) {
Set<Displayable> origins = con.getOrigins();
origins.retainAll(sel);
if (origins.isEmpty()) continue;
to_select.add(con);
}
} else if (command.equals("Select incomming Connectors")) {
for (final Connector con : connectors) {
for (final Set<Displayable> targets : con.getTargets()) {
targets.retainAll(sel);
if (targets.isEmpty()) continue;
to_select.add(con);
}
}
} else if (command.equals("Select downstream targets")) {
for (final Connector con : connectors) {
Set<Displayable> origins = con.getOrigins();
origins.retainAll(sel);
if (origins.isEmpty()) continue;
// else, add all targets
for (final Set<Displayable> targets : con.getTargets()) {
to_select.addAll(targets);
}
}
} else if (command.equals("Select upstream targets")) {
for (final Connector con : connectors) {
for (final Set<Displayable> targets : con.getTargets()) {
targets.retainAll(sel);
if (targets.isEmpty()) continue;
to_select.addAll(con.getOrigins());
break; // origins will be the same for all targets of 'con'
}
}
}
selection.selectAll(new ArrayList<Displayable>(to_select));
}
}
protected class GridOverlay {
ArrayList<Line2D> lines = new ArrayList<Line2D>();
int ox=0, oy=0,
width=(int)layer.getLayerWidth(),
height=(int)layer.getLayerHeight(),
xoffset=0, yoffset=0,
tilewidth=100, tileheight=100,
linewidth=1;
boolean visible = true;
Color color = new Color(255,255,0,255); // yellow with full alpha
/** Expects values in pixels. */
void init() {
lines.clear();
// Vertical lines:
if (0 != xoffset) {
lines.add(new Line2D.Float(ox, oy, ox, oy+height));
}
lines.add(new Line2D.Float(ox+width, oy, ox+width, oy+height));
for (int x = ox + xoffset; x <= ox + width; x += tilewidth) {
lines.add(new Line2D.Float(x, oy, x, oy + height));
}
// Horizontal lines:
if (0 != yoffset) {
lines.add(new Line2D.Float(ox, oy, ox+width, oy));
}
lines.add(new Line2D.Float(ox, oy+height, ox+width, oy+height));
for (int y = oy + yoffset; y <= oy + height; y += tileheight) {
lines.add(new Line2D.Float(ox, y, ox + width, y));
}
}
protected void paint(final Graphics2D g) {
if (!visible) return;
g.setStroke(new BasicStroke((float)(linewidth/canvas.getMagnification())));
g.setColor(color);
for (final Line2D line : lines) {
g.draw(line);
}
}
void setup(Roi roi) {
GenericDialog gd = new GenericDialog("Grid overlay");
Calibration cal = getLayerSet().getCalibration();
gd.addNumericField("Top-left corner X:", ox*cal.pixelWidth, 1, 10, cal.getUnits());
gd.addNumericField("Top-left corner Y:", oy*cal.pixelHeight, 1, 10, cal.getUnits());
gd.addNumericField("Grid total width:", width*cal.pixelWidth, 1, 10, cal.getUnits());
gd.addNumericField("Grid total height:", height*cal.pixelHeight, 1, 10, cal.getUnits());
gd.addCheckbox("Read bounds from ROI", null != roi);
((Component)gd.getCheckboxes().get(0)).setEnabled(null != roi);
gd.addMessage("");
gd.addNumericField("Tile width:", tilewidth*cal.pixelWidth, 1, 10, cal.getUnits());
gd.addNumericField("Tile height:", tileheight*cal.pixelHeight, 1, 10, cal.getUnits());
gd.addNumericField("Tile offset X:", xoffset*cal.pixelWidth, 1, 10, cal.getUnits());
gd.addNumericField("Tile offset Y:", yoffset*cal.pixelHeight, 1, 10, cal.getUnits());
gd.addMessage("");
gd.addNumericField("Line width:", linewidth, 1, 10, "pixels");
gd.addSlider("Red: ", 0, 255, color.getRed());
gd.addSlider("Green: ", 0, 255, color.getGreen());
gd.addSlider("Blue: ", 0, 255, color.getBlue());
gd.addSlider("Alpha: ", 0, 255, color.getAlpha());
gd.addMessage("");
gd.addCheckbox("Visible", visible);
gd.showDialog();
if (gd.wasCanceled()) return;
this.ox = (int)(gd.getNextNumber() / cal.pixelWidth);
this.oy = (int)(gd.getNextNumber() / cal.pixelHeight);
this.width = (int)(gd.getNextNumber() / cal.pixelWidth);
this.height = (int)(gd.getNextNumber() / cal.pixelHeight);
if (gd.getNextBoolean() && null != roi) {
Rectangle r = roi.getBounds();
this.ox = r.x;
this.oy = r.y;
this.width = r.width;
this.height = r.height;
}
this.tilewidth = (int)(gd.getNextNumber() / cal.pixelWidth);
this.tileheight = (int)(gd.getNextNumber() / cal.pixelHeight);
this.xoffset = (int)(gd.getNextNumber() / cal.pixelWidth) % tilewidth;
this.yoffset = (int)(gd.getNextNumber() / cal.pixelHeight) % tileheight;
this.linewidth = (int)gd.getNextNumber();
this.color = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber());
this.visible = gd.getNextBoolean();
init();
}
}
protected GridOverlay gridoverlay = null;
private class StartTransformMenuListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if (null == active) return;
String command = ae.getActionCommand();
if (command.equals("Transform (affine)")) {
getLayerSet().addTransformStepWithData(selection.getAffected());
setMode(new AffineTransformMode(Display.this));
} else if (command.equals("Transform (non-linear)")) {
getLayerSet().addTransformStepWithData(selection.getAffected());
List<Displayable> col = selection.getSelected(Patch.class);
for (final Displayable d : col) {
if (d.isLinked()) {
Utils.showMessage("Can't enter manual non-linear transformation mode:\nat least one image is linked.");
return;
}
}
setMode(new NonLinearTransformMode(Display.this, col));
} else if (command.equals("Remove coordinate transforms (selected images)")) {
final List<Displayable> col = selection.getSelected(Patch.class);
if (col.isEmpty()) return;
removeCoordinateTransforms( (List<Patch>) (List) col);
} else if (command.equals("Remove coordinate transforms layer-wise")) {
GenericDialog gd = new GenericDialog("Remove Coordinate Transforms");
gd.addMessage("Remove coordinate transforms");
gd.addMessage("for all images in:");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final ArrayList<Displayable> patches = new ArrayList<Displayable>();
for (final Layer layer : getLayerSet().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()+1)) {
patches.addAll(layer.getDisplayables(Patch.class));
}
removeCoordinateTransforms( (List<Patch>) (List) patches);
} else if (command.equals("Remove rotation, scaling and shear (selected images)")) {
final List<Displayable> col = selection.getSelected(Patch.class);
if (col.isEmpty()) return;
removeScalingRotationShear( (List<Patch>) (List) col);
} else if (command.equals("Remove rotation, scaling and shear layer-wise")) {
// Because we love copy-paste
GenericDialog gd = new GenericDialog("Remove Scaling/Rotation/Shear");
gd.addMessage("Remove scaling, translation");
gd.addMessage("and shear for all images in:");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final ArrayList<Displayable> patches = new ArrayList<Displayable>();
for (final Layer layer : getLayerSet().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()+1)) {
patches.addAll(layer.getDisplayables(Patch.class));
}
removeScalingRotationShear( (List<Patch>) (List) patches);
}
}
}
public Bureaucrat removeScalingRotationShear(final List<Patch> patches) {
return Bureaucrat.createAndStart(new Worker.Task("Removing coordinate transforms") { public void exec() {
getLayerSet().addTransformStep(patches);
for (final Patch p : patches) {
Rectangle box = p.getBoundingBox();
final AffineTransform aff = new AffineTransform();
// translate so that the center remains where it is
aff.setToTranslation(box.x + (box.width - p.getWidth())/2, box.y + (box.height - p.getHeight())/2);
p.setAffineTransform(aff);
}
getLayerSet().addTransformStep(patches);
Display.repaint();
}}, this.project);
}
public Bureaucrat removeCoordinateTransforms(final List<Patch> patches) {
return Bureaucrat.createAndStart(new Worker.Task("Removing coordinate transforms") { public void exec() {
// Check if any are linked: cannot remove, would break image-to-segmentation relationship
for (final Patch p : patches) {
if (p.isLinked()) {
Utils.logAll("Cannot remove coordinate transform: some images are linked to segmentations!");
return;
}
}
// Collect Patch instances to modify:
final HashSet<Patch> ds = new HashSet<Patch>(patches);
for (final Patch p : patches) {
if (null != p.getCoordinateTransform()) {
ds.add(p);
}
}
// Add undo step:
getLayerSet().addDataEditStep(ds);
// Remove coordinate transforms:
final ArrayList<Future> fus = new ArrayList<Future>();
for (final Patch p : ds) {
p.setCoordinateTransform(null);
fus.add(p.getProject().getLoader().regenerateMipMaps(p)); // queue
}
// wait until all done
for (Future fu : fus) try { fu.get(); } catch (Exception e) { IJError.print(e); }
// Set current state
getLayerSet().addDataEditStep(ds);
}}, project);
}
private class MenuScriptListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
final String command = ae.getActionCommand();
Bureaucrat.createAndStart(new Worker.Task("Setting preprocessor script") { public void exec() {
if (command.equals("Set preprocessor script layer-wise...")) {
Collection<Layer> ls = getLayerList("Set preprocessor script");
if (null == ls) return;
String path = getScriptPath();
if (null == path) return;
setScriptPathToLayers(ls, path);
} else if (command.equals("Set preprocessor script (selected images)...")) {
if (selection.isEmpty()) return;
String path = getScriptPath();
if (null == path) return;
setScriptPath(selection.getSelected(Patch.class), path);
} else if (command.equals("Remove preprocessor script layer-wise...")) {
Collection<Layer> ls = getLayerList("Remove preprocessor script");
if (null == ls) return;
setScriptPathToLayers(ls, null);
} else if (command.equals("Remove preprocessor script (selected images)...")) {
if (selection.isEmpty()) return;
setScriptPath(selection.getSelected(Patch.class), null);
}
}}, Display.this.project);
}
private void setScriptPathToLayers(final Collection<Layer> ls, final String script) {
for (final Layer la : ls) {
if (Thread.currentThread().isInterrupted()) return;
setScriptPath(la.getDisplayables(Patch.class), script);
}
}
/** Accepts null script, to remove it if there. */
private void setScriptPath(final Collection<Displayable> list, final String script) {
for (final Displayable d : list) {
if (Thread.currentThread().isInterrupted()) return;
Patch p = (Patch) d;
p.setPreprocessorScriptPath(script);
}
}
private Collection<Layer> getLayerList(String title) {
final GenericDialog gd = new GenericDialog(title);
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return null;
return layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end
}
private String getScriptPath() {
OpenDialog od = new OpenDialog("Select script", OpenDialog.getLastDirectory(), null);
String dir = od.getDirectory();
if (null == dir) return null;
if (IJ.isWindows()) dir = dir.replace('\\','/');
if (!dir.endsWith("/")) dir += "/";
return dir + od.getFileName();
}
}
private class SetToolListener implements ActionListener {
final int tool;
SetToolListener(int tool) {
this.tool = tool;
}
public void actionPerformed(ActionEvent ae) {
ProjectToolbar.setTool(tool);
toolbar_panel.repaint();
}
}
private ByTypeListener bytypelistener = new ByTypeListener(this);
static private class ByTypeListener implements ActionListener {
final Display d;
ByTypeListener(final Display d) {
this.d = d;
}
public void actionPerformed(final ActionEvent ae) {
final String command = ae.getActionCommand();
final Area aroi = M.getArea(d.canvas.getFakeImagePlus().getRoi());
d.dispatcher.exec(new Runnable() { public void run() {
try {
String type = command;
if (type.equals("Image")) type = "Patch";
else if (type.equals("Text")) type = "DLabel";
Class c = Class.forName("ini.trakem2.display." + type);
java.util.List<Displayable> a = new ArrayList<Displayable>();
if (null != aroi) {
a.addAll(d.layer.getDisplayables(c, aroi, true));
a.addAll(d.layer.getParent().getZDisplayables(c, d.layer, aroi, true));
} else {
a.addAll(d.layer.getDisplayables(c));
a.addAll(d.layer.getParent().getZDisplayables(c));
// Remove non-visible ones
for (final Iterator<Displayable> it = a.iterator(); it.hasNext(); ) {
if (!it.next().isVisible()) it.remove();
}
}
if (0 == a.size()) return;
boolean selected = false;
if (0 == ae.getModifiers()) {
Utils.log2("first");
d.selection.clear();
d.selection.selectAll(a);
selected = true;
} else if (0 == (ae.getModifiers() ^ Event.SHIFT_MASK)) {
Utils.log2("with shift");
d.selection.selectAll(a); // just add them to the current selection
selected = true;
}
if (selected) {
// Activate last:
d.selection.setActive(a.get(a.size() -1));
}
} catch (ClassNotFoundException e) {
Utils.log2(e.toString());
}
}});
}
}
/** Check if a panel for the given Displayable is completely visible in the JScrollPane */
public boolean isWithinViewport(final Displayable d) {
Component comp = tabs.getSelectedComponent();
if (!(comp instanceof JScrollPane)) return false;
final JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent();
if (ht_tabs.get(d.getClass()) == scroll) return isWithinViewport(scroll, ht_panels.get(d));
return false;
}
private boolean isWithinViewport(JScrollPane scroll, DisplayablePanel dp) {
if(null == dp) return false;
JViewport view = scroll.getViewport();
java.awt.Dimension dimensions = view.getExtentSize();
java.awt.Point p = view.getViewPosition();
int y = dp.getY();
if ((y + DisplayablePanel.HEIGHT - p.y) <= dimensions.height && y >= p.y) {
return true;
}
return false;
}
/** Check if a panel for the given Displayable is partially visible in the JScrollPane */
public boolean isPartiallyWithinViewport(final Displayable d) {
final JScrollPane scroll = ht_tabs.get(d.getClass());
if (tabs.getSelectedComponent() == scroll) return isPartiallyWithinViewport(scroll, ht_panels.get(d));
return false;
}
/** Check if a panel for the given Displayable is at least partially visible in the JScrollPane */
private boolean isPartiallyWithinViewport(final JScrollPane scroll, final DisplayablePanel dp) {
if(null == dp) {
//Utils.log2("Display.isPartiallyWithinViewport: null DisplayablePanel ??");
return false; // to fast for you baby
}
JViewport view = scroll.getViewport();
java.awt.Dimension dimensions = view.getExtentSize();
java.awt.Point p = view.getViewPosition();
int y = dp.getY();
if ( ((y + DisplayablePanel.HEIGHT - p.y) <= dimensions.height && y >= p.y) // completely visible
|| ((y + DisplayablePanel.HEIGHT - p.y) > dimensions.height && y < p.y + dimensions.height) // partially hovering at the bottom
|| ((y + DisplayablePanel.HEIGHT) > p.y && y < p.y) // partially hovering at the top
) {
return true;
}
return false;
}
/** A function to make a Displayable panel be visible in the screen, by scrolling the viewport of the JScrollPane. */
private void scrollToShow(final Displayable d) {
if (!(tabs.getSelectedComponent() instanceof JScrollPane)) return;
dispatcher.execSwing(new Runnable() { public void run() {
final JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent();
if (d instanceof ZDisplayable && scroll == scroll_zdispl) {
scrollToShow(scroll_zdispl, ht_panels.get(d));
return;
}
final Class c = d.getClass();
if (Patch.class == c && scroll == scroll_patches) {
scrollToShow(scroll_patches, ht_panels.get(d));
} else if (DLabel.class == c && scroll == scroll_labels) {
scrollToShow(scroll_labels, ht_panels.get(d));
} else if (Profile.class == c && scroll == scroll_profiles) {
scrollToShow(scroll_profiles, ht_panels.get(d));
}
}});
}
private void scrollToShow(final JScrollPane scroll, final JPanel dp) {
if (null == dp) return;
JViewport view = scroll.getViewport();
Point current = view.getViewPosition();
Dimension extent = view.getExtentSize();
int panel_y = dp.getY();
if ((panel_y + DisplayablePanel.HEIGHT - current.y) <= extent.height && panel_y >= current.y) {
// it's completely visible already
return;
} else {
// scroll just enough
// if it's above, show at the top
if (panel_y - current.y < 0) {
view.setViewPosition(new Point(0, panel_y));
}
// if it's below (even if partially), show at the bottom
else if (panel_y + 50 > current.y + extent.height) {
view.setViewPosition(new Point(0, panel_y - extent.height + 50));
//Utils.log("Display.scrollToShow: panel_y: " + panel_y + " current.y: " + current.y + " extent.height: " + extent.height);
}
}
}
/** Update the title of the given Displayable in its DisplayablePanel, if any. */
static public void updateTitle(final Layer layer, final Displayable displ) {
for (final Display d : al_displays) {
if (layer == d.layer) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) dp.updateTitle();
}
}
}
/** Update the Display's title in all Displays showing the given Layer. */
static public void updateTitle(final Layer layer) {
for (final Display d : al_displays) {
if (d.layer == layer) d.updateFrameTitle();
}
}
static public void updateTitle(final Project project) {
for (final Display d : al_displays) {
if (d.project == project) d.updateFrameTitle();
}
}
/** Update the Display's title in all Displays showing a Layer of the given LayerSet. */
static public void updateTitle(final LayerSet ls) {
for (final Display d : al_displays) {
if (d.layer.getParent() == ls) d.updateFrameTitle(d.layer);
}
}
/** Set a new title in the JFrame, showing info on the layer 'z' and the magnification. */
public void updateFrameTitle() {
updateFrameTitle(layer);
}
private void updateFrameTitle(Layer layer) {
// From ij.ImagePlus class, the solution:
String scale = "";
final double magnification = canvas.getMagnification();
if (magnification!=1.0) {
final double percent = magnification*100.0;
scale = new StringBuilder(" (").append(Utils.d2s(percent, percent==(int)percent ? 0 : 1)).append("%)").toString();
}
final Calibration cal = layer.getParent().getCalibration();
String title = new StringBuilder().append(layer.getParent().indexOf(layer) + 1).append('/').append(layer.getParent().size()).append(' ').append((null == layer.getTitle() ? "" : layer.getTitle())).append(scale).append(" -- ").append(getProject().toString()).append(' ').append(' ').append(Utils.cutNumber(layer.getParent().getLayerWidth() * cal.pixelWidth, 2, true)).append('x').append(Utils.cutNumber(layer.getParent().getLayerHeight() * cal.pixelHeight, 2, true)).append(' ').append(cal.getUnit()).toString();
frame.setTitle(title);
// fix the title for the FakeImageWindow and thus the WindowManager listing in the menus
canvas.getFakeImagePlus().setTitle(title);
}
/** If shift is down, scroll to the next non-empty layer; otherwise, if scroll_step is larger than 1, then scroll 'scroll_step' layers ahead; else just the next Layer. */
public void nextLayer(final int modifiers) {
final Layer l;
if (0 == (modifiers ^ Event.SHIFT_MASK)) {
l = layer.getParent().nextNonEmpty(layer);
} else if (scroll_step > 1) {
int i = layer.getParent().indexOf(this.layer);
Layer la = layer.getParent().getLayer(i + scroll_step);
if (null != la) l = la;
else l = null;
} else {
l = layer.getParent().next(layer);
}
if (l != layer) {
slt.set(l);
updateInDatabase("layer_id");
}
}
private final void translateLayerColors(final Layer current, final Layer other) {
if (current == other) return;
if (layer_channels.size() > 0) {
final LayerSet ls = getLayerSet();
// translate colors by distance from current layer to new Layer l
final int dist = ls.indexOf(other) - ls.indexOf(current);
translateLayerColor(Color.red, dist);
translateLayerColor(Color.blue, dist);
}
}
private final void translateLayerColor(final Color color, final int dist) {
final LayerSet ls = getLayerSet();
final Layer l = layer_channels.get(color);
if (null == l) return;
updateColor(Color.white, layer_panels.get(l));
final Layer l2 = ls.getLayer(ls.indexOf(l) + dist);
if (null != l2) updateColor(color, layer_panels.get(l2));
}
private final void updateColor(final Color color, final LayerPanel lp) {
lp.setColor(color);
setColorChannel(lp.layer, color);
}
/** Calls setLayer(la) on the SetLayerThread. */
public void toLayer(final Layer la) {
if (la.getParent() != layer.getParent()) return; // not of the same LayerSet
if (la == layer) return; // nothing to do
slt.set(la);
updateInDatabase("layer_id");
}
/** If shift is down, scroll to the previous non-empty layer; otherwise, if scroll_step is larger than 1, then scroll 'scroll_step' layers backward; else just the previous Layer. */
public void previousLayer(final int modifiers) {
final Layer l;
if (0 == (modifiers ^ Event.SHIFT_MASK)) {
l = layer.getParent().previousNonEmpty(layer);
} else if (scroll_step > 1) {
int i = layer.getParent().indexOf(this.layer);
Layer la = layer.getParent().getLayer(i - scroll_step);
if (null != la) l = la;
else l = null;
} else {
l = layer.getParent().previous(layer);
}
if (l != layer) {
slt.set(l);
updateInDatabase("layer_id");
}
}
static public void updateLayerScroller(LayerSet set) {
for (final Display d : al_displays) {
if (d.layer.getParent() == set) {
d.updateLayerScroller(d.layer);
}
}
}
private void updateLayerScroller(Layer layer) {
int size = layer.getParent().size();
if (size <= 1) {
scroller.setValues(0, 1, 0, 0);
scroller.setEnabled(false);
} else {
scroller.setEnabled(true);
scroller.setValues(layer.getParent().getLayerIndex(layer.getId()), 1, 0, size);
}
recreateLayerPanels(layer);
}
// Can't use this.layer, may still be null. User argument instead.
private synchronized void recreateLayerPanels(final Layer layer) {
synchronized (layer_channels) {
panel_layers.removeAll();
if (0 == layer_panels.size()) {
for (final Layer la : layer.getParent().getLayers()) {
final LayerPanel lp = new LayerPanel(this, la);
layer_panels.put(la, lp);
this.panel_layers.add(lp);
}
} else {
// Set theory at work: keep old to reuse
layer_panels.keySet().retainAll(layer.getParent().getLayers());
for (final Layer la : layer.getParent().getLayers()) {
LayerPanel lp = layer_panels.get(la);
if (null == lp) {
lp = new LayerPanel(this, la);
layer_panels.put(la, lp);
}
this.panel_layers.add(lp);
}
for (final Iterator<Map.Entry<Integer,LayerPanel>> it = layer_alpha.entrySet().iterator(); it.hasNext(); ) {
final Map.Entry<Integer,LayerPanel> e = it.next();
if (-1 == getLayerSet().indexOf(e.getValue().layer)) it.remove();
}
for (final Iterator<Map.Entry<Color,Layer>> it = layer_channels.entrySet().iterator(); it.hasNext(); ) {
final Map.Entry<Color,Layer> e = it.next();
if (-1 == getLayerSet().indexOf(e.getValue())) it.remove();
}
scroll_layers.repaint();
}
}
}
private void updateSnapshots() {
Enumeration<DisplayablePanel> e = ht_panels.elements();
while (e.hasMoreElements()) {
e.nextElement().repaint();
}
Utils.updateComponent(tabs.getSelectedComponent());
}
static public void updatePanel(Layer layer, final Displayable displ) {
if (null == layer && null != front) layer = front.layer; // the front layer
for (final Display d : al_displays) {
if (d.layer == layer) {
d.updatePanel(displ);
}
}
}
private void updatePanel(Displayable d) {
JPanel c = null;
if (d instanceof Profile) {
c = panel_profiles;
} else if (d instanceof Patch) {
c = panel_patches;
} else if (d instanceof DLabel) {
c = panel_labels;
} else if (d instanceof Pipe) {
c = panel_zdispl;
}
if (null == c) return;
DisplayablePanel dp = ht_panels.get(d);
if (null != dp) {
dp.repaint();
Utils.updateComponent(c);
}
}
static public void updatePanelIndex(final Layer layer, final Displayable displ) {
for (final Display d : al_displays) {
if (d.layer == layer || displ instanceof ZDisplayable) {
d.updatePanelIndex(displ);
}
}
}
private void updatePanelIndex(final Displayable d) {
updateTab( (JPanel) ht_tabs.get(d.getClass()).getViewport().getView(),
ZDisplayable.class.isAssignableFrom(d.getClass()) ?
layer.getParent().getZDisplayables()
: layer.getDisplayables(d.getClass()));
}
/** Repair possibly missing panels and other components by simply resetting the same Layer */
public void repairGUI() {
Layer layer = this.layer;
this.layer = null;
setLayer(layer);
}
public void actionPerformed(final ActionEvent ae) {
dispatcher.exec(new Runnable() { public void run() {
String command = ae.getActionCommand();
if (command.startsWith("Job")) {
if (Utils.checkYN("Really cancel job?")) {
project.getLoader().quitJob(command);
repairGUI();
}
return;
} else if (command.equals("Move to top")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.TOP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move up")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.UP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move down")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.DOWN, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move to bottom")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.BOTTOM, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Duplicate, link and send to next layer")) {
duplicateLinkAndSendTo(active, 1, layer.getParent().next(layer));
} else if (command.equals("Duplicate, link and send to previous layer")) {
duplicateLinkAndSendTo(active, 0, layer.getParent().previous(layer));
} else if (command.equals("Duplicate, link and send to...")) {
// fix non-scrolling popup menu
GenericDialog gd = new GenericDialog("Send to");
gd.addMessage("Duplicate, link and send to...");
String[] sl = new String[layer.getParent().size()];
int next = 0;
for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) {
sl[next++] = project.findLayerThing(it.next()).toString();
}
gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex());
if (layer == la) {
Utils.showMessage("Can't duplicate, link and send to the same layer.");
return;
}
duplicateLinkAndSendTo(active, 0, la);
} else if (-1 != command.indexOf("z = ")) {
// this is an item from the "Duplicate, link and send to" menu of layer z's
Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1)));
Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__");
if (null == target_layer) return;
duplicateLinkAndSendTo(active, 0, target_layer);
} else if (-1 != command.indexOf("z=")) {
// WARNING the indexOf is very similar to the previous one
// Send the linked group to the selected layer
int iz = command.indexOf("z=")+2;
Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2));
int end = command.indexOf(' ', iz);
if (-1 == end) end = command.length();
double lz = Double.parseDouble(command.substring(iz, end));
Layer target = layer.getParent().getLayer(lz);
layer.getParent().move(selection.getAffected(), active.getLayer(), target); // TODO what happens when ZDisplayable are selected?
} else if (command.equals("Unlink")) {
if (null == active || active instanceof Patch) return;
active.unlink();
updateSelection();//selection.update();
} else if (command.equals("Unlink from images")) {
if (null == active) return;
try {
for (Displayable displ: selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
} else if (command.equals("Unlink slices")) {
YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo.");
if (!yn.yesPressed()) return;
final ArrayList<Patch> pa = ((Patch)active).getStackPatches();
for (int i=pa.size()-1; i>0; i--) {
pa.get(i).unlink(pa.get(i-1));
}
} else if (command.equals("Send to next layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
for (final Displayable displ : selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveDown(layer, active); // will repaint whatever appropriate layers
selection.moveDown();
repaint(layer.getParent(), box);
} else if (command.equals("Send to previous layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
for (final Displayable displ : selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveUp(layer, active); // will repaint whatever appropriate layers
selection.moveUp();
repaint(layer.getParent(), box);
} else if (command.equals("Show centered")) {
if (active == null) return;
showCentered(active);
} else if (command.equals("Delete...")) {
/*
if (null != active) {
Displayable d = active;
selection.remove(d);
d.remove(true); // will repaint
}
*/
// remove all selected objects
selection.deleteAll();
} else if (command.equals("Color...")) {
IJ.doCommand("Color Picker...");
} else if (command.equals("Revert")) {
if (null == active || active.getClass() != Patch.class) return;
Patch p = (Patch)active;
if (!p.revert()) {
if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId());
else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId());
}
} else if (command.equals("Remove alpha mask")) {
final ArrayList<Displayable> patches = selection.getSelected(Patch.class);
if (patches.size() > 0) {
Bureaucrat.createAndStart(new Worker.Task("Removing alpha mask" + (patches.size() > 1 ? "s" : "")) { public void exec() {
final ArrayList<Future> jobs = new ArrayList<Future>();
for (final Displayable d : patches) {
final Patch p = (Patch) d;
p.setAlphaMask(null);
Future job = p.getProject().getLoader().regenerateMipMaps(p); // submit to queue
if (null != job) jobs.add(job);
}
// join all
for (final Future job : jobs) try {
job.get();
} catch (Exception ie) {}
}}, patches.get(0).getProject());
}
} else if (command.equals("Undo")) {
Bureaucrat.createAndStart(new Worker.Task("Undo") { public void exec() {
layer.getParent().undoOneStep();
Display.repaint(layer.getParent());
}}, project);
} else if (command.equals("Redo")) {
Bureaucrat.createAndStart(new Worker.Task("Redo") { public void exec() {
layer.getParent().redoOneStep();
Display.repaint(layer.getParent());
}}, project);
} else if (command.equals("Apply transform")) {
canvas.applyTransform();
} else if (command.equals("Apply transform propagating to last layer")) {
if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) {
final java.util.List<Layer> layers = layer.getParent().getLayers();
final HashSet<Layer> subset = new HashSet<Layer>(layers.subList(layers.indexOf(Display.this.layer)+1, layers.size())); // +1 to exclude current layer
if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset);
else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset);
setMode(new DefaultMode(Display.this));
}
} else if (command.equals("Apply transform propagating to first layer")) {
if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) {
final java.util.List<Layer> layers = layer.getParent().getLayers();
final HashSet<Layer> subset = new HashSet<Layer>(layers.subList(0, layers.indexOf(Display.this.layer)));
if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset);
else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset);
setMode(new DefaultMode(Display.this));
}
} else if (command.equals("Cancel transform")) {
canvas.cancelTransform(); // calls getMode().cancel()
} else if (command.equals("Specify transform...")) {
if (null == active) return;
selection.specify();
} else if (command.equals("Hide all but images")) {
ArrayList<Class> type = new ArrayList<Class>();
type.add(Patch.class);
type.add(Stack.class);
Collection<Displayable> col = layer.getParent().hideExcept(type, false);
selection.removeAll(col);
Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE);
Display.update(layer.getParent(), false);
} else if (command.equals("Unhide all")) {
Display.updateCheckboxes(layer.getParent().setAllVisible(false), DisplayablePanel.VISIBILITY_STATE);
Display.update(layer.getParent(), false);
} else if (command.startsWith("Hide all ")) {
String type = command.substring(9, command.length() -1); // skip the ending plural 's'
Collection<Displayable> col = layer.getParent().setVisible(type, false, true);
selection.removeAll(col);
Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE);
} else if (command.startsWith("Unhide all ")) {
String type = command.substring(11, command.length() -1); // skip the ending plural 's'
type = type.substring(0, 1).toUpperCase() + type.substring(1);
updateCheckboxes(layer.getParent().setVisible(type, true, true), DisplayablePanel.VISIBILITY_STATE);
} else if (command.equals("Hide deselected")) {
hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers()));
} else if (command.equals("Hide deselected except images")) {
hideDeselected(true);
} else if (command.equals("Hide selected")) {
selection.setVisible(false); // TODO should deselect them too? I don't think so.
Display.updateCheckboxes(selection.getSelected(), DisplayablePanel.VISIBILITY_STATE);
} else if (command.equals("Resize canvas/LayerSet...")) {
resizeCanvas();
} else if (command.equals("Autoresize canvas/LayerSet")) {
layer.getParent().setMinimumDimensions();
} else if (command.equals("Import image")) {
importImage();
} else if (command.equals("Import next image")) {
importNextImage();
} else if (command.equals("Import stack...")) {
Display.this.getLayerSet().addChangeTreesStep();
Rectangle sr = getCanvas().getSrcRect();
Bureaucrat burro = project.getLoader().importStack(layer, sr.x + sr.width/2, sr.y + sr.height/2, null, true, null, false);
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Import stack with landmarks...")) {
// 1 - Find out if there's any other project open
List<Project> pr = Project.getProjects();
if (1 == pr.size()) {
Utils.logAll("Need another project open!");
return;
}
// 2 - Ask for a "landmarks" type
GenericDialog gd = new GenericDialog("Landmarks");
gd.addStringField("landmarks type:", "landmarks");
final String[] none = {"-- None --"};
final Hashtable<String,Project> mpr = new Hashtable<String,Project>();
for (Project p : pr) {
if (p == project) continue;
mpr.put(p.toString(), p);
}
final String[] project_titles = mpr.keySet().toArray(new String[0]);
final Hashtable<String,ProjectThing> map_target = findLandmarkNodes(project, "landmarks");
String[] target_landmark_titles = map_target.isEmpty() ? none : map_target.keySet().toArray(new String[0]);
gd.addChoice("Landmarks node in this project:", target_landmark_titles, target_landmark_titles[0]);
gd.addMessage("");
gd.addChoice("Source project:", project_titles, project_titles[0]);
final Hashtable<String,ProjectThing> map_source = findLandmarkNodes(mpr.get(project_titles[0]), "landmarks");
String[] source_landmark_titles = map_source.isEmpty() ? none : map_source.keySet().toArray(new String[0]);
gd.addChoice("Landmarks node in source project:", source_landmark_titles, source_landmark_titles[0]);
final List<Patch> stacks = Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet());
String[] stack_titles;
if (stacks.isEmpty()) {
if (1 == mpr.size()) {
IJ.showMessage("Project " + project_titles[0] + " does not contain any Stack.");
return;
}
stack_titles = none;
} else {
stack_titles = new String[stacks.size()];
int next = 0;
for (Patch pa : stacks) stack_titles[next++] = pa.toString();
}
gd.addChoice("Stacks:", stack_titles, stack_titles[0]);
Vector vc = gd.getChoices();
final Choice choice_target_landmarks = (Choice) vc.get(0);
final Choice choice_source_projects = (Choice) vc.get(1);
final Choice choice_source_landmarks = (Choice) vc.get(2);
final Choice choice_stacks = (Choice) vc.get(3);
final TextField input = (TextField) gd.getStringFields().get(0);
input.addTextListener(new TextListener() {
public void textValueChanged(TextEvent te) {
final String text = input.getText();
update(choice_target_landmarks, Display.this.project, text, map_target);
update(choice_source_landmarks, mpr.get(choice_source_projects.getSelectedItem()), text, map_source);
}
private void update(Choice c, Project p, String type, Hashtable<String,ProjectThing> table) {
table.clear();
table.putAll(findLandmarkNodes(p, type));
c.removeAll();
if (table.isEmpty()) c.add(none[0]);
else for (String t : table.keySet()) c.add(t);
}
});
choice_source_projects.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String item = (String) e.getItem();
Project p = mpr.get(choice_source_projects.getSelectedItem());
// 1 - Update choice of landmark items
map_source.clear();
map_source.putAll(findLandmarkNodes(p, input.getText()));
choice_target_landmarks.removeAll();
if (map_source.isEmpty()) choice_target_landmarks.add(none[0]);
else for (String t : map_source.keySet()) choice_target_landmarks.add(t);
// 2 - Update choice of Stack items
stacks.clear();
choice_stacks.removeAll();
stacks.addAll(Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet()));
if (stacks.isEmpty()) choice_stacks.add(none[0]);
else for (Patch pa : stacks) choice_stacks.add(pa.toString());
}
});
gd.showDialog();
if (gd.wasCanceled()) return;
String type = gd.getNextString();
if (null == type || 0 == type.trim().length()) {
Utils.log("Invalid landmarks node type!");
return;
}
ProjectThing target_landmarks_node = map_target.get(gd.getNextChoice());
Project source = mpr.get(gd.getNextChoice());
ProjectThing source_landmarks_node = map_source.get(gd.getNextChoice());
Patch stack_patch = stacks.get(gd.getNextChoiceIndex());
// Store current state
Display.this.getLayerSet().addLayerContentStep(layer);
// Insert stack
insertStack(target_landmarks_node, source, source_landmarks_node, stack_patch);
// Store new state
Display.this.getLayerSet().addChangeTreesStep();
} else if (command.equals("Import grid...")) {
Display.this.getLayerSet().addLayerContentStep(layer);
Bureaucrat burro = project.getLoader().importGrid(layer);
if (null != burro)
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addLayerContentStep(layer);
}});
} else if (command.equals("Import sequence as grid...")) {
Display.this.getLayerSet().addChangeTreesStep();
Bureaucrat burro = project.getLoader().importSequenceAsGrid(layer);
if (null != burro)
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Import from text file...")) {
Display.this.getLayerSet().addChangeTreesStep();
Bureaucrat burro = project.getLoader().importImages(layer);
if (null != burro)
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Import labels as arealists...")) {
Display.this.getLayerSet().addChangeTreesStep();
Bureaucrat burro = project.getLoader().importLabelsAsAreaLists(layer, null, Double.MAX_VALUE, 0, 0.4f, false);
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Make flat image...")) {
// if there's a ROI, just use that as cropping rectangle
Rectangle srcRect = null;
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null != roi) {
srcRect = roi.getBounds();
} else {
// otherwise, whatever is visible
//srcRect = canvas.getSrcRect();
// The above is confusing. That is what ROIs are for. So paint all:
srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight()));
}
double scale = 1.0;
final String[] types = new String[]{"8-bit grayscale", "RGB Color"};
int the_type = ImagePlus.GRAY8;
final GenericDialog gd = new GenericDialog("Choose", frame);
gd.addSlider("Scale: ", 1, 100, 100);
gd.addNumericField("Width: ", srcRect.width, 0);
gd.addNumericField("height: ", srcRect.height, 0);
// connect the above 3 fields:
Vector numfields = gd.getNumericFields();
UpdateDimensionField udf = new UpdateDimensionField(srcRect.width, srcRect.height, (TextField) numfields.get(1), (TextField) numfields.get(2), (TextField) numfields.get(0), (Scrollbar) gd.getSliders().get(0));
for (Object ob : numfields) ((TextField)ob).addTextListener(udf);
gd.addChoice("Type: ", types, types[0]);
if (layer.getParent().size() > 1) {
Utils.addLayerRangeChoices(Display.this.layer, gd); /// $#%! where are my lisp macros
gd.addCheckbox("Include non-empty layers only", true);
}
gd.addMessage("Background color:");
Utils.addRGBColorSliders(gd, Color.black);
gd.addCheckbox("Best quality", false);
gd.addMessage("");
gd.addCheckbox("Save to file", false);
gd.addCheckbox("Save for web", false);
gd.showDialog();
if (gd.wasCanceled()) return;
scale = gd.getNextNumber() / 100;
the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB);
if (Double.isNaN(scale) || scale <= 0.0) {
Utils.showMessage("Invalid scale.");
return;
}
// consuming and ignoring width and height:
gd.getNextNumber();
gd.getNextNumber();
Layer[] layer_array = null;
boolean non_empty_only = false;
if (layer.getParent().size() > 1) {
non_empty_only = gd.getNextBoolean();
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
ArrayList al = new ArrayList();
ArrayList al_zd = layer.getParent().getZDisplayables();
ZDisplayable[] zd = new ZDisplayable[al_zd.size()];
al_zd.toArray(zd);
for (int i=i_start, j=0; i <= i_end; i++, j++) {
Layer la = layer.getParent().getLayer(i);
if (!la.isEmpty() || !non_empty_only) al.add(la); // checks both the Layer and the ZDisplayable objects in the parent LayerSet
}
if (0 == al.size()) {
Utils.showMessage("All layers are empty!");
return;
}
layer_array = new Layer[al.size()];
al.toArray(layer_array);
} else {
layer_array = new Layer[]{Display.this.layer};
}
final Color background = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber());
final boolean quality = gd.getNextBoolean();
final boolean save_to_file = gd.getNextBoolean();
final boolean save_for_web = gd.getNextBoolean();
// in its own thread
if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type);
else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality, background);
} else if (command.equals("Lock")) {
selection.setLocked(true);
Utils.revalidateComponent(tabs.getSelectedComponent());
} else if (command.equals("Unlock")) {
selection.setLocked(false);
Utils.revalidateComponent(tabs.getSelectedComponent());
} else if (command.equals("Properties...")) {
active.adjustProperties();
updateSelection();
} else if (command.equals("Show current 2D position in 3D")) {
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
Display3D.addFatPoint("Current 2D Position", getLayerSet(), p.x, p.y, layer.getZ(), 10, Color.magenta);
} else if (command.equals("Align stack slices")) {
if (getActive() instanceof Patch) {
final Patch slice = (Patch)getActive();
if (slice.isStack()) {
// check linked group
final HashSet hs = slice.getLinkedGroup(new HashSet());
for (Iterator it = hs.iterator(); it.hasNext(); ) {
if (it.next().getClass() != Patch.class) {
Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); // labels should be fine, need to check that
return;
}
}
final LayerSet ls = slice.getLayerSet();
final HashSet<Displayable> linked = slice.getLinkedGroup(null);
ls.addTransformStepWithData(linked);
Bureaucrat burro = AlignTask.registerStackSlices((Patch)getActive()); // will repaint
burro.addPostTask(new Runnable() { public void run() {
ls.enlargeToFit(linked);
// The current state when done
ls.addTransformStepWithData(linked);
}});
} else {
Utils.log("Align stack slices: selected image is not part of a stack.");
}
}
} else if (command.equals("Align layers with manual landmarks")) {
setMode(new ManualAlignMode(Display.this));
} else if (command.equals("Align layers")) {
final Layer la = layer; // caching, since scroll wheel may change it
la.getParent().addTransformStep(la.getParent().getLayers());
Bureaucrat burro = AlignLayersTask.alignLayersTask( la );
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class));
la.getParent().addTransformStep(la.getParent().getLayers());
}});
} else if (command.equals("Align multi-layer mosaic")) {
final Layer la = layer; // caching, since scroll wheel may change it
la.getParent().addTransformStep();
Bureaucrat burro = AlignTask.alignMultiLayerMosaicTask( la );
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class));
la.getParent().addTransformStep();
}});
} else if (command.equals("Montage all images in this layer")) {
final Layer la = layer;
final List<Patch> patches = new ArrayList<Patch>( (List<Patch>) (List) la.getDisplayables(Patch.class));
if (patches.size() < 2) {
Utils.showMessage("Montage needs 2 or more images selected");
return;
}
final Collection<Displayable> col = la.getParent().addTransformStepWithData(Arrays.asList(new Layer[]{la}));
Bureaucrat burro = AlignTask.alignPatchesTask(patches, Arrays.asList(new Patch[]{patches.get(0)}));
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().enlargeToFit(patches);
la.getParent().addTransformStepWithData(col);
}});
} else if (command.equals("Montage selected images (SIFT)")) {
montage(0);
} else if (command.equals("Montage selected images (phase correlation)")) {
montage(1);
} else if (command.equals("Montage multiple layers (phase correlation)")) {
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex());
final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers);
Bureaucrat burro = StitchingTEM.montageWithPhaseCorrelation(layers);
if (null == burro) return;
burro.addPostTask(new Runnable() { public void run() {
Collection<Displayable> ds = new ArrayList<Displayable>();
for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class));
getLayerSet().enlargeToFit(ds);
getLayerSet().addTransformStepWithData(col);
}});
} else if (command.equals("Montage multiple layers (SIFT)")) {
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex());
final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers);
Bureaucrat burro = AlignTask.montageLayersTask(layers);
burro.addPostTask(new Runnable() { public void run() {
Collection<Displayable> ds = new ArrayList<Displayable>();
for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class));
getLayerSet().enlargeToFit(ds);
getLayerSet().addTransformStepWithData(col);
}});
} else if (command.equals("Properties ...")) { // NOTE the space before the dots, to distinguish from the "Properties..." command that works on Displayable objects.
GenericDialog gd = new GenericDialog("Properties", Display.this.frame);
//gd.addNumericField("layer_scroll_step: ", this.scroll_step, 0);
gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step);
gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]);
gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality());
Loader lo = getProject().getLoader();
boolean using_mipmaps = lo.isMipMapsEnabled();
gd.addCheckbox("enable_mipmaps", using_mipmaps);
gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled());
double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight();
gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsMaxDimension());
gd.addCheckbox("Show arrow heads in Treeline/AreaTree", layer.getParent().paint_arrows);
gd.addCheckbox("Show edge confidence boxes in Treeline/AreaTree", layer.getParent().paint_edge_confidence_boxes);
gd.addCheckbox("Show color cues", layer.getParent().color_cues);
gd.addSlider("+/- layers to color cue", 0, 10, layer.getParent().n_layers_color_cue);
// --------
gd.showDialog();
if (gd.wasCanceled()) return;
// --------
int sc = (int) gd.getNextNumber();
if (sc < 1) sc = 1;
Display.this.scroll_step = sc;
updateInDatabase("scroll_step");
//
layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex());
layer.getParent().setSnapshotsQuality(gd.getNextBoolean());
//
boolean generate_mipmaps = gd.getNextBoolean();
if (using_mipmaps && generate_mipmaps) {
// nothing changed
} else {
if (using_mipmaps) { // and !generate_mipmaps
lo.flushMipMaps(true);
} else {
// not using mipmaps before, and true == generate_mipmaps
lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class));
}
}
//
layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean());
layer.getParent().setPixelsMaxDimension((int)gd.getNextNumber());
layer.getParent().paint_arrows = gd.getNextBoolean();
layer.getParent().paint_edge_confidence_boxes = gd.getNextBoolean();
layer.getParent().color_cues = gd.getNextBoolean();
layer.getParent().n_layers_color_cue = (int)gd.getNextNumber();
Display.repaint(layer.getParent());
} else if (command.equals("Adjust snapping parameters...")) {
AlignTask.p_snap.setup("Snap");
} else if (command.equals("Adjust fast-marching parameters...")) {
Segmentation.fmp.setup();
} else if (command.equals("Adjust arealist paint parameters...")) {
AreaWrapper.PP.setup();
} else if (command.equals("Search...")) {
new Search();
} else if (command.equals("Select all")) {
selection.selectAll();
repaint(Display.this.layer, selection.getBox(), 0);
} else if (command.equals("Select all visible")) {
selection.selectAllVisible();
repaint(Display.this.layer, selection.getBox(), 0);
} else if (command.equals("Select none")) {
Rectangle box = selection.getBox();
selection.clear();
repaint(Display.this.layer, box, 0);
} else if (command.equals("Restore selection")) {
selection.restore();
} else if (command.equals("Select under ROI")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return;
selection.selectAll(roi, true);
} else if (command.equals("Merge")) {
Bureaucrat burro = Bureaucrat.create(new Worker.Task("Merging AreaLists") {
public void exec() {
ArrayList al_sel = selection.getSelected(AreaList.class);
// put active at the beginning, to work as the base on which other's will get merged
al_sel.remove(Display.this.active);
al_sel.add(0, Display.this.active);
Set<DoStep> dataedits = new HashSet<DoStep>();
dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"}));
getLayerSet().addChangeTreesStep(dataedits);
AreaList ali = AreaList.merge(al_sel);
if (null != ali) {
// remove all but the first from the selection
for (int i=1; i<al_sel.size(); i++) {
Object ob = al_sel.get(i);
if (ob.getClass() == AreaList.class) {
selection.remove((Displayable)ob);
}
}
selection.updateTransform(ali);
repaint(ali.getLayerSet(), ali, 0);
}
}
}, Display.this.project);
burro.addPostTask(new Runnable() { public void run() {
Set<DoStep> dataedits = new HashSet<DoStep>();
dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"}));
getLayerSet().addChangeTreesStep(dataedits);
}});
burro.goHaveBreakfast();
} else if (command.equals("Reroot")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
getLayerSet().addDataEditStep(active);
((Tree)active).reRoot(p.x, p.y, layer, canvas.getMagnification());
getLayerSet().addDataEditStep(active);
Display.repaint(getLayerSet());
} else if (command.equals("Part subtree")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
- getLayerSet().addChangeTreesStep();
List<Tree> ts = ((Tree)active).splitNear(p.x, p.y, layer, canvas.getMagnification());
if (null == ts) return;
Displayable elder = Display.this.active;
for (Tree t : ts) {
if (t == elder) continue;
getLayerSet().add(t); // will change Display.this.active !
project.getProjectTree().addSibling(elder, t);
}
selection.clear();
selection.selectAll(ts);
selection.add(elder);
getLayerSet().addChangeTreesStep();
Display.repaint(getLayerSet());
} else if (command.equals("Show tabular view")) {
if (!(active instanceof Tree)) return;
((Tree)active).createMultiTableView();
} else if (command.equals("Mark")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
if (((Tree)active).markNear(p.x, p.y, layer, canvas.getMagnification())) {
Display.repaint(getLayerSet());
}
} else if (command.equals("Clear marks (selected Trees)")) {
for (Displayable d : selection.getSelected(Tree.class)) {
((Tree)d).unmark();
}
Display.repaint(getLayerSet());
} else if (command.equals("Join")) {
if (!(active instanceof Tree)) return;
final List<Tree> tlines = (List<Tree>) (List) selection.getSelected(Treeline.class);
if (((Tree)active).canJoin(tlines)) {
- getLayerSet().addChangeTreesStep();
+ // Record current state
+ class State {{
+ Set<DoStep> dataedits = new HashSet<DoStep>();
+ for (final Tree tl : tlines) {
+ dataedits.add(new Displayable.DoEdit(tl).init(tl, new String[]{"data"}));
+ }
+ getLayerSet().addChangeTreesStep(dataedits);
+ }};
+ new State();
+ //
((Tree)active).join(tlines);
for (final Tree tl : tlines) {
if (tl == active) continue;
tl.remove2(false);
}
Display.repaint(getLayerSet());
- getLayerSet().addChangeTreesStep();
+ // Again, to record current state
+ new State();
}
} else if (command.equals("Previous branch point or start")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
center(((Treeline)active).findPreviousBranchOrRootPoint(p.x, p.y, layer, canvas.getMagnification()));
} else if (command.equals("Next branch point or end")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
center(((Tree)active).findNextBranchOrEndPoint(p.x, p.y, layer, canvas.getMagnification()));
} else if (command.equals("Root")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
center(((Tree)active).createCoordinate(((Tree)active).getRoot()));
} else if (command.equals("Last added point")) {
if (!(active instanceof Tree)) return;
center(((Treeline)active).getLastAdded());
} else if (command.equals("Last edited point")) {
if (!(active instanceof Tree)) return;
center(((Treeline)active).getLastEdited());
} else if (command.equals("Reverse point order")) {
if (!(active instanceof Pipe)) return;
getLayerSet().addDataEditStep(active);
((Pipe)active).reverse();
Display.repaint(Display.this.layer);
getLayerSet().addDataEditStep(active);
} else if (command.equals("View orthoslices")) {
if (!(active instanceof Patch)) return;
Display3D.showOrthoslices(((Patch)active));
} else if (command.equals("View volume")) {
if (!(active instanceof Patch)) return;
Display3D.showVolume(((Patch)active));
} else if (command.equals("Show in 3D")) {
for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) {
ZDisplayable zd = (ZDisplayable)it.next();
Display3D.show(zd.getProject().findProjectThing(zd));
}
// handle profile lists ...
HashSet hs = new HashSet();
for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) {
Displayable d = (Displayable)it.next();
ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent();
if (!hs.contains(profile_list)) {
Display3D.show(profile_list);
hs.add(profile_list);
}
}
} else if (command.equals("Snap")) {
// Take the active if it's a Patch
if (!(active instanceof Patch)) return;
Display.snap((Patch)active);
} else if (command.equals("Blend")) {
HashSet<Patch> patches = new HashSet<Patch>();
for (final Displayable d : selection.getSelected()) {
if (d.getClass() == Patch.class) patches.add((Patch)d);
}
if (patches.size() > 1) {
GenericDialog gd = new GenericDialog("Blending");
gd.addCheckbox("Respect current alpha mask", true);
gd.showDialog();
if (gd.wasCanceled()) return;
Blending.blend(patches, gd.getNextBoolean());
} else {
IJ.log("Please select more than one overlapping image.");
}
} else if (command.equals("Montage")) {
final Set<Displayable> affected = new HashSet<Displayable>(selection.getAffected());
// make an undo step!
final LayerSet ls = layer.getParent();
ls.addTransformStepWithData(affected);
Bureaucrat burro = AlignTask.alignSelectionTask( selection );
burro.addPostTask(new Runnable() { public void run() {
ls.enlargeToFit(affected);
ls.addTransformStepWithData(affected);
}});
} else if (command.equals("Lens correction")) {
final Layer la = layer;
la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables()));
Bureaucrat burro = DistortionCorrectionTask.correctDistortionFromSelection( selection );
burro.addPostTask(new Runnable() { public void run() {
// no means to know which where modified and from which layers!
la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables()));
}});
} else if (command.equals("Link images...")) {
GenericDialog gd = new GenericDialog("Options");
gd.addMessage("Linking images to images (within their own layer only):");
String[] options = {"all images to all images", "each image with any other overlapping image"};
gd.addChoice("Link: ", options, options[1]);
String[] options2 = {"selected images only", "all images in this layer", "all images in all layers, within the layer only", "all images in all layers, within and across consecutive layers"};
gd.addChoice("Apply to: ", options2, options2[0]);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer lay = layer;
final HashSet<Displayable> ds = new HashSet<Displayable>(lay.getParent().getDisplayables());
lay.getParent().addDataEditStep(ds, new String[]{"data"});
boolean overlapping_only = 1 == gd.getNextChoiceIndex();
Collection<Displayable> coll = null;
switch (gd.getNextChoiceIndex()) {
case 0:
coll = selection.getSelected(Patch.class);
Patch.crosslink(coll, overlapping_only);
break;
case 1:
coll = lay.getDisplayables(Patch.class);
Patch.crosslink(coll, overlapping_only);
break;
case 2:
coll = new ArrayList<Displayable>();
for (final Layer la : lay.getParent().getLayers()) {
Collection<Displayable> acoll = la.getDisplayables(Patch.class);
Patch.crosslink(acoll, overlapping_only);
coll.addAll(acoll);
}
break;
case 3:
ArrayList<Layer> layers = lay.getParent().getLayers();
Collection<Displayable> lc1 = layers.get(0).getDisplayables(Patch.class);
if (lay == layers.get(0)) coll = lc1;
for (int i=1; i<layers.size(); i++) {
Collection<Displayable> lc2 = layers.get(i).getDisplayables(Patch.class);
if (null == coll && Display.this.layer == layers.get(i)) coll = lc2;
Collection<Displayable> both = new ArrayList<Displayable>();
both.addAll(lc1);
both.addAll(lc2);
Patch.crosslink(both, overlapping_only);
lc1 = lc2;
}
break;
}
if (null != coll) Display.updateCheckboxes(coll, DisplayablePanel.LINK_STATE, true);
lay.getParent().addDataEditStep(ds);
} else if (command.equals("Unlink all selected images")) {
if (Utils.check("Really unlink selected images?")) {
for (final Displayable d : selection.getSelected(Patch.class)) {
d.unlink();
}
}
} else if (command.equals("Unlink all")) {
if (Utils.check("Really unlink all objects from all layers?")) {
for (final Displayable d : layer.getParent().getDisplayables()) {
d.unlink();
}
}
} else if (command.equals("Calibration...")) {
try {
IJ.run(canvas.getFakeImagePlus(), "Properties...", "");
Display.updateTitle(getLayerSet());
} catch (RuntimeException re) {
Utils.log2("Calibration dialog canceled.");
}
} else if (command.equals("Grid overlay...")) {
if (null == gridoverlay) gridoverlay = new GridOverlay();
gridoverlay.setup(canvas.getFakeImagePlus().getRoi());
canvas.invalidateVolatile();
canvas.repaint(false);
} else if (command.equals("Enhance contrast (selected images)...")) {
final Layer la = layer;
ArrayList<Displayable> selected = selection.getSelected(Patch.class);
final HashSet<Displayable> ds = new HashSet<Displayable>(selected);
la.getParent().addDataEditStep(ds);
Displayable active = Display.this.getActive();
Patch ref = active.getClass() == Patch.class ? (Patch)active : null;
Bureaucrat burro = getProject().getLoader().enhanceContrast(selected, ref);
burro.addPostTask(new Runnable() { public void run() {
la.getParent().addDataEditStep(ds);
}});
} else if (command.equals("Enhance contrast layer-wise...")) {
// ask for range of layers
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
java.util.List<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end
final HashSet<Displayable> ds = new HashSet<Displayable>();
for (final Layer l : layers) ds.addAll(l.getDisplayables(Patch.class));
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().enhanceContrast(layers);
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Set Min and Max layer-wise...")) {
Displayable active = getActive();
double min = 0;
double max = 0;
if (null != active && active.getClass() == Patch.class) {
min = ((Patch)active).getMin();
max = ((Patch)active).getMax();
}
final GenericDialog gd = new GenericDialog("Min and Max");
gd.addMessage("Set min and max to all images in the layer range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.addNumericField("min: ", min, 2);
gd.addNumericField("max: ", max, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
//
min = gd.getNextNumber();
max = gd.getNextNumber();
ArrayList<Displayable> al = new ArrayList<Displayable>();
for (final Layer la : layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1)) { // exclusive end
al.addAll(la.getDisplayables(Patch.class));
}
final HashSet<Displayable> ds = new HashSet<Displayable>(al);
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().setMinAndMax(al, min, max);
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Set Min and Max (selected images)...")) {
Displayable active = getActive();
double min = 0;
double max = 0;
if (null != active && active.getClass() == Patch.class) {
min = ((Patch)active).getMin();
max = ((Patch)active).getMax();
}
final GenericDialog gd = new GenericDialog("Min and Max");
gd.addMessage("Set min and max to all selected images");
gd.addNumericField("min: ", min, 2);
gd.addNumericField("max: ", max, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
//
min = gd.getNextNumber();
max = gd.getNextNumber();
final HashSet<Displayable> ds = new HashSet<Displayable>(selection.getSelected(Patch.class));
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().setMinAndMax(selection.getSelected(Patch.class), min, max);
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Adjust min and max (selected images)...")) {
final List<Displayable> list = selection.getSelected(Patch.class);
if (list.isEmpty()) {
Utils.log("No images selected!");
return;
}
Bureaucrat.createAndStart(new Worker.Task("Init contrast adjustment") {
public void exec() {
try {
setMode(new ContrastAdjustmentMode(Display.this, list));
} catch (Exception e) {
Utils.log("All images must be of the same type!");
}
}
}, list.get(0).getProject());
} else if (command.equals("Mask image borders (layer-wise)...")) {
final GenericDialog gd = new GenericDialog("Mask borders");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.addMessage("Borders:");
gd.addNumericField("left: ", 6, 2);
gd.addNumericField("top: ", 6, 2);
gd.addNumericField("right: ", 6, 2);
gd.addNumericField("bottom: ", 6, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
Collection<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1);
final HashSet<Displayable> ds = new HashSet<Displayable>();
for (Layer l : layers) ds.addAll(l.getDisplayables(Patch.class));
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().maskBordersLayerWise(layers, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber());
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Mask image borders (selected images)...")) {
final GenericDialog gd = new GenericDialog("Mask borders");
gd.addMessage("Borders:");
gd.addNumericField("left: ", 6, 2);
gd.addNumericField("top: ", 6, 2);
gd.addNumericField("right: ", 6, 2);
gd.addNumericField("bottom: ", 6, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
Collection<Displayable> patches = selection.getSelected(Patch.class);
final HashSet<Displayable> ds = new HashSet<Displayable>(patches);
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().maskBorders(patches, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber());
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Duplicate")) {
// only Patch and DLabel, i.e. Layer-only resident objects that don't exist in the Project Tree
final HashSet<Class> accepted = new HashSet<Class>();
accepted.add(Patch.class);
accepted.add(DLabel.class);
accepted.add(Stack.class);
final ArrayList<Displayable> originals = new ArrayList<Displayable>();
final ArrayList<Displayable> selected = selection.getSelected();
for (final Displayable d : selected) {
if (accepted.contains(d.getClass())) {
originals.add(d);
}
}
if (originals.size() > 0) {
getLayerSet().addChangeTreesStep();
for (final Displayable d : originals) {
if (d instanceof ZDisplayable) {
d.getLayerSet().add((ZDisplayable)d.clone());
} else {
d.getLayer().add(d.clone());
}
}
getLayerSet().addChangeTreesStep();
} else if (selected.size() > 0) {
Utils.log("Can only duplicate images and text labels.\nDuplicate *other* objects in the Project Tree.\n");
}
} else if (command.equals("Create subproject")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return; // the menu item is not active unless there is a ROI
Layer first, last;
if (1 == layer.getParent().size()) {
first = last = layer;
} else {
GenericDialog gd = new GenericDialog("Choose layer range");
Utils.addLayerRangeChoices(layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
first = layer.getParent().getLayer(gd.getNextChoiceIndex());
last = layer.getParent().getLayer(gd.getNextChoiceIndex());
Utils.log2("first, last: " + first + ", " + last);
}
Project sub = getProject().createSubproject(roi.getBounds(), first, last);
final LayerSet subls = sub.getRootLayerSet();
Display.createDisplay(sub, subls.getLayer(0));
} else if (command.startsWith("Image stack under selected Arealist")) {
if (null == active || active.getClass() != AreaList.class) return;
GenericDialog gd = new GenericDialog("Stack options");
String[] types = {"8-bit", "16-bit", "32-bit", "RGB"};
gd.addChoice("type:", types, types[0]);
gd.addSlider("Scale: ", 1, 100, 100);
gd.showDialog();
if (gd.wasCanceled()) return;
final int type;
switch (gd.getNextChoiceIndex()) {
case 0: type = ImagePlus.GRAY8; break;
case 1: type = ImagePlus.GRAY16; break;
case 2: type = ImagePlus.GRAY32; break;
case 3: type = ImagePlus.COLOR_RGB; break;
default: type = ImagePlus.GRAY8; break;
}
ImagePlus imp = ((AreaList)active).getStack(type, gd.getNextNumber()/100);
if (null != imp) imp.show();
} else if (command.equals("Fly through selected Treeline/AreaTree")) {
if (null == active || !(active instanceof Tree)) return;
Bureaucrat.createAndStart(new Worker.Task("Creating fly through", true) {
public void exec() {
GenericDialog gd = new GenericDialog("Fly through");
gd.addNumericField("Width", 512, 0);
gd.addNumericField("Height", 512, 0);
String[] types = new String[]{"8-bit gray", "Color RGB"};
gd.addChoice("Image type", types, types[0]);
gd.addSlider("scale", 0, 100, 100);
gd.addCheckbox("save to file", false);
gd.showDialog();
if (gd.wasCanceled()) return;
int w = (int)gd.getNextNumber();
int h = (int)gd.getNextNumber();
int type = 0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB;
double scale = gd.getNextNumber();
if (w <=0 || h <=0) {
Utils.log("Invalid width or height: " + w + ", " + h);
return;
}
if (0 == scale || Double.isNaN(scale)) {
Utils.log("Invalid scale: " + scale);
return;
}
String dir = null;
if (gd.getNextBoolean()) {
DirectoryChooser dc = new DirectoryChooser("Target directory");
dir = dc.getDirectory();
if (null == dir) return; // canceled
dir = Utils.fixDir(dir);
}
ImagePlus imp = ((Tree)active).flyThroughMarked(w, h, scale/100, type, dir);
if (null == imp) {
Utils.log("Mark a node first!");
return;
}
imp.show();
}
}, project);
} else if (command.startsWith("Arealists as labels")) {
GenericDialog gd = new GenericDialog("Export labels");
gd.addSlider("Scale: ", 1, 100, 100);
final String[] options = {"All area list", "Selected area lists"};
gd.addChoice("Export: ", options, options[0]);
Utils.addLayerRangeChoices(layer, gd);
gd.addCheckbox("Visible only", true);
gd.showDialog();
if (gd.wasCanceled()) return;
final float scale = (float)(gd.getNextNumber() / 100);
java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class);
if (null == al) {
Utils.log("No area lists found to export.");
return;
}
// Generics are ... a pain? I don't understand them? They fail when they shouldn't? And so easy to workaround that they are a shame?
al = (java.util.List<Displayable>) al;
int first = gd.getNextChoiceIndex();
int last = gd.getNextChoiceIndex();
boolean visible_only = gd.getNextBoolean();
if (-1 != command.indexOf("(amira)")) {
AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, true, true);
} else if (-1 != command.indexOf("(tif)")) {
AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, false, false);
}
} else if (command.equals("Project properties...")) {
project.adjustProperties();
} else if (command.equals("Release memory...")) {
Bureaucrat.createAndStart(new Worker("Releasing memory") {
public void run() {
startedWorking();
try {
GenericDialog gd = new GenericDialog("Release Memory");
int max = (int)(IJ.maxMemory() / 1000000);
gd.addSlider("Megabytes: ", 0, max, max/2);
gd.showDialog();
if (!gd.wasCanceled()) {
int n_mb = (int)gd.getNextNumber();
project.getLoader().releaseToFit((long)n_mb*1000000);
}
} catch (Throwable e) {
IJError.print(e);
} finally {
finishedWorking();
}
}
}, project);
} else if (command.equals("Flush image cache")) {
Loader.releaseAllCaches();
} else if (command.equals("Regenerate all mipmaps")) {
project.getLoader().regenerateMipMaps(getLayerSet().getDisplayables(Patch.class));
} else if (command.equals("Regenerate mipmaps (selected images)")) {
project.getLoader().regenerateMipMaps(selection.getSelected(Patch.class));
} else if (command.equals("Tags...")) {
// get a file first
File f = Utils.chooseFile(null, "tags", ".xml");
if (null == f) return;
if (!Utils.saveToFile(f, getLayerSet().exportTags())) {
Utils.logAll("ERROR when saving tags to file " + f.getAbsolutePath());
}
} else if (command.equals("Tags ...")) {
String[] ff = Utils.selectFile("Import tags");
if (null == ff) return;
GenericDialog gd = new GenericDialog("Import tags");
String[] modes = new String[]{"Append to current tags", "Replace current tags"};
gd.addChoice("Import tags mode:", modes, modes[0]);
gd.addMessage("Replacing current tags\nwill remove all tags\n from all nodes first!");
gd.showDialog();
if (gd.wasCanceled()) return;
getLayerSet().importTags(new StringBuilder(ff[0]).append('/').append(ff[1]).toString(), 1 == gd.getNextChoiceIndex());
} else {
Utils.log2("Display: don't know what to do with command " + command);
}
}});
}
private static class UpdateDimensionField implements TextListener {
final TextField width, height, scale;
final Scrollbar bar;
final int initial_width, initial_height;
UpdateDimensionField(int initial_width, int initial_height, TextField width, TextField height, TextField scale, Scrollbar bar) {
this.initial_width = initial_width;
this.initial_height = initial_height;
this.width = width;
this.height = height;
this.scale = scale;
this.bar = bar;
}
public void textValueChanged(TextEvent e) {
try {
final TextField source = (TextField) e.getSource();
if (scale == source && (scale.isFocusOwner() || bar.isFocusOwner())) {
final double sc = Double.parseDouble(scale.getText()) / 100;
// update both
width.setText(Integer.toString((int) (sc * initial_width + 0.5)));
height.setText(Integer.toString((int) (sc * initial_height + 0.5)));
} else if (width == source && width.isFocusOwner()) {
/*
final int width = Integer.toString((int) (width.getText() + 0.5));
final double sc = width / (double)initial_width;
scale.setText(Integer.toString((int)(sc * 100 + 0.5)));
height.setText(Integer.toString((int)(sc * initial_height + 0.5)));
*/
set(width, height, initial_width, initial_height);
} else if (height == source && height.isFocusOwner()) {
set(height, width, initial_height, initial_width);
}
} catch (NumberFormatException nfe) {
Utils.logAll("Unparsable number: " + nfe.getMessage());
} catch (Exception ee) {
IJError.print(ee);
}
}
private void set(TextField source, TextField target, int initial_source, int initial_target) {
final int dim = (int) ((Double.parseDouble(source.getText()) + 0.5));
final double sc = dim / (double)initial_source;
scale.setText(Utils.cutNumber(sc * 100, 3));
target.setText(Integer.toString((int)(sc * initial_target + 0.5)));
}
}
/** Update in all displays the Transform for the given Displayable if it's selected. */
static public void updateTransform(final Displayable displ) {
for (final Display d : al_displays) {
if (d.selection.contains(displ)) d.selection.updateTransform(displ);
}
}
/** Order the profiles of the parent profile_list by Z order, and fix the ProjectTree.*/
/*
private void fixZOrdering(Profile profile) {
ProjectThing thing = project.findProjectThing(profile);
if (null == thing) {
Utils.log2("Display.fixZOrdering: null thing?");
return;
}
((ProjectThing)thing.getParent()).fixZOrdering();
project.getProjectTree().updateList(thing.getParent());
}
*/
/** The number of layers to scroll through with the wheel; 1 by default.*/
public int getScrollStep() { return this.scroll_step; }
public void setScrollStep(int scroll_step) {
if (scroll_step < 1) scroll_step = 1;
this.scroll_step = scroll_step;
updateInDatabase("scroll_step");
}
protected Bureaucrat importImage() {
Worker worker = new Worker("Import image") { /// all this verbosity is what happens when functions are not first class citizens. I could abstract it away by passing a string name "importImage" and invoking it with reflection, but that is an even bigger PAIN
public void run() {
startedWorking();
try {
///
Rectangle srcRect = canvas.getSrcRect();
int x = srcRect.x + srcRect.width / 2;
int y = srcRect.y + srcRect.height/ 2;
Patch p = project.getLoader().importImage(project, x, y);
if (null == p) {
finishedWorking();
Utils.showMessage("Could not open the image.");
return;
}
Display.this.getLayerSet().addLayerContentStep(layer);
layer.add(p); // will add it to the proper Displays
Display.this.getLayerSet().addLayerContentStep(layer);
///
} catch (Exception e) {
IJError.print(e);
}
finishedWorking();
}
};
return Bureaucrat.createAndStart(worker, getProject());
}
protected Bureaucrat importNextImage() {
Worker worker = new Worker("Import image") { /// all this verbosity is what happens when functions are not first class citizens. I could abstract it away by passing a string name "importImage" and invoking it with reflection, but that is an even bigger PAIN
public void run() {
startedWorking();
try {
Rectangle srcRect = canvas.getSrcRect();
int x = srcRect.x + srcRect.width / 2;// - imp.getWidth() / 2;
int y = srcRect.y + srcRect.height/ 2;// - imp.getHeight()/ 2;
Patch p = project.getLoader().importNextImage(project, x, y);
if (null == p) {
Utils.showMessage("Could not open next image.");
finishedWorking();
return;
}
Display.this.getLayerSet().addLayerContentStep(layer);
layer.add(p); // will add it to the proper Displays
Display.this.getLayerSet().addLayerContentStep(layer);
} catch (Exception e) {
IJError.print(e);
}
finishedWorking();
}
};
return Bureaucrat.createAndStart(worker, getProject());
}
/** Make the given channel have the given alpha (transparency). */
public void setChannel(int c, float alpha) {
int a = (int)(255 * alpha);
int l = (c_alphas&0xff000000)>>24;
int r = (c_alphas&0xff0000)>>16;
int g = (c_alphas&0xff00)>>8;
int b = c_alphas&0xff;
switch (c) {
case Channel.MONO:
// all to the given alpha
c_alphas = (l<<24) + (r<<16) + (g<<8) + b; // parenthesis are NECESSARY
break;
case Channel.RED:
// modify only the red
c_alphas = (l<<24) + (a<<16) + (g<<8) + b;
break;
case Channel.GREEN:
c_alphas = (l<<24) + (r<<16) + (a<<8) + b;
break;
case Channel.BLUE:
c_alphas = (l<<24) + (r<<16) + (g<<8) + a;
break;
}
//Utils.log2("c_alphas: " + c_alphas);
//canvas.setUpdateGraphics(true);
canvas.repaint(true);
updateInDatabase("c_alphas");
}
/** Set the channel as active and the others as inactive. */
public void setActiveChannel(Channel channel) {
for (int i=0; i<4; i++) {
if (channel != channels[i]) channels[i].setActive(false);
else channel.setActive(true);
}
Utils.updateComponent(panel_channels);
transp_slider.setValue((int)(channel.getAlpha() * 100));
}
public int getDisplayChannelAlphas() { return c_alphas; }
// rename this method and the getDisplayChannelAlphas ! They sound the same!
public int getChannelAlphas() {
return ((int)(channels[0].getAlpha() * 255)<<24) + ((int)(channels[1].getAlpha() * 255)<<16) + ((int)(channels[2].getAlpha() * 255)<<8) + (int)(channels[3].getAlpha() * 255);
}
public int getChannelAlphasState() {
return ((channels[0].isSelected() ? 255 : 0)<<24)
+ ((channels[1].isSelected() ? 255 : 0)<<16)
+ ((channels[2].isSelected() ? 255 : 0)<<8)
+ (channels[3].isSelected() ? 255 : 0);
}
/** Show the layer in the front Display, or in a new Display if the front Display is showing a layer from a different LayerSet. */
static public void showFront(final Layer layer) {
Display display = front;
if (null == display || display.layer.getParent() != layer.getParent()) {
display = new Display(layer.getProject(), layer, null); // gets set to front
} else {
display.setLayer(layer);
}
}
/** Show the given Displayable centered and selected. If select is false, the selection is cleared. */
static public void showCentered(Layer layer, Displayable displ, boolean select, boolean shift_down) {
// see if the given layer belongs to the layer set being displayed
Display display = front; // to ensure thread consistency to some extent
if (null == display || display.layer.getParent() != layer.getParent()) {
display = new Display(layer.getProject(), layer, displ); // gets set to front
} else if (display.layer != layer) {
display.setLayer(layer);
}
if (select) {
if (!shift_down) display.selection.clear();
display.selection.add(displ);
} else {
display.selection.clear();
}
display.showCentered(displ);
}
/** Center the view, if possible, on x,y. It's not possible when zoomed out, in which case it will try to do its best. */
public final void center(final double x, final double y) {
SwingUtilities.invokeLater(new Runnable() { public void run() {
Rectangle r = (Rectangle)canvas.getSrcRect().clone();
r.x = (int)x - r.width/2;
r.y = (int)y - r.height/2;
canvas.center(r, canvas.getMagnification());
}});
}
public final void center(final Coordinate c) {
if (null == c) return;
slt.set(c.layer);
center(c.x, c.y);
}
public final void centerIfNotWithinSrcRect(final Coordinate c) {
if (null == c) return;
slt.set(c.layer);
Rectangle srcRect = canvas.getSrcRect();
if (srcRect.contains((int)(c.x+0.5), (int)(c.y+0.5))) return;
center(c.x, c.y);
}
public final void animateBrowsingTo(final Coordinate c) {
if (null == c) return;
final double padding = 50/canvas.getMagnification(); // 50 screen pixels
canvas.animateBrowsing(new Rectangle((int)(c.x - padding), (int)(c.y - padding), (int)(2*padding), (int)(2*padding)), c.layer);
}
static public final void centerAt(final Coordinate c) {
centerAt(c, false, false);
}
static public final void centerAt(final Coordinate<Displayable> c, final boolean select, final boolean shift_down) {
if (null == c) return;
SwingUtilities.invokeLater(new Runnable() { public void run() {
Display display = front;
if (null == display || c.layer.getParent() != display.getLayerSet()) {
display = new Display(c.layer.getProject(), c.layer); // gets set to front
}
display.center(c);
if (select) {
if (!shift_down) display.selection.clear();
display.selection.add(c.object);
}
}});
}
private final void showCentered(final Displayable displ) {
if (null == displ) return;
SwingUtilities.invokeLater(new Runnable() { public void run() {
displ.setVisible(true);
Rectangle box = displ.getBoundingBox();
if (0 == box.width && 0 == box.height) {
box.width = 100; // old: (int)layer.getLayerWidth();
box.height = 100; // old: (int)layer.getLayerHeight();
} else if (0 == box.width) {
box.width = box.height;
} else if (0 == box.height) {
box.height = box.width;
}
canvas.showCentered(box);
scrollToShow(displ);
if (displ instanceof ZDisplayable) {
// scroll to first layer that has a point
ZDisplayable zd = (ZDisplayable)displ;
setLayer(zd.getFirstLayer());
}
}});
}
public void eventOccurred(final int eventID) {
if (IJEventListener.FOREGROUND_COLOR_CHANGED == eventID) {
if (this != front || null == active || !project.isInputEnabled()) return;
selection.setColor(Toolbar.getForegroundColor());
Display.repaint(front.layer, selection.getBox(), 0);
} else if (IJEventListener.TOOL_CHANGED == eventID) {
Display.repaintToolbar();
}
}
public void imageClosed(ImagePlus imp) {}
public void imageOpened(ImagePlus imp) {}
/** Release memory captured by the offscreen images */
static public void flushAll() {
for (final Display d : al_displays) {
d.canvas.flush();
}
//System.gc();
Thread.yield();
}
/** Can be null. */
static public Display getFront() {
return front;
}
static public void setCursorToAll(final Cursor c) {
for (final Display d : al_displays) {
d.frame.setCursor(c);
}
}
protected void setCursor(Cursor c) {
frame.setCursor(c);
}
/** Used by the Displayable to update the visibility and locking state checkboxes in other Displays. */
static public void updateCheckboxes(final Displayable displ, final int cb, final boolean state) {
for (final Display d : al_displays) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) {
dp.updateCheckbox(cb, state);
}
}
}
/** Set the checkbox @param cb state to @param state value, for each Displayable. Assumes all Displayable objects belong to one specific project. */
static public void updateCheckboxes(final Collection<Displayable> displs, final int cb, final boolean state) {
if (null == displs || 0 == displs.size()) return;
final Project p = displs.iterator().next().getProject();
for (final Display d : al_displays) {
if (d.getProject() != p) continue;
for (final Displayable displ : displs) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) {
dp.updateCheckbox(cb, state);
}
}
}
}
/** Update the checkbox @param cb state to an appropriate value for each Displayable. Assumes all Displayable objects belong to one specific project. */
static public void updateCheckboxes(final Collection<Displayable> displs, final int cb) {
if (null == displs || 0 == displs.size()) return;
final Project p = displs.iterator().next().getProject();
for (final Display d : al_displays) {
if (d.getProject() != p) continue;
for (final Displayable displ : displs) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) {
dp.updateCheckbox(cb);
}
}
}
}
protected boolean isActiveWindow() {
return frame.isActive();
}
/** Toggle user input; pan and zoom are always enabled though.*/
static public void setReceivesInput(final Project project, final boolean b) {
for (final Display d : al_displays) {
if (d.project == project) d.canvas.setReceivesInput(b);
}
}
/** Export the DTD that defines this object. */
static public void exportDTD(StringBuffer sb_header, HashSet hs, String indent) {
if (hs.contains("t2_display")) return; // TODO to avoid collisions the type shoud be in a namespace such as tm2:display
hs.add("t2_display");
sb_header.append(indent).append("<!ELEMENT t2_display EMPTY>\n")
.append(indent).append("<!ATTLIST t2_display id NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display layer_id NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display x NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display y NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display magnification NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display srcrect_x NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display srcrect_y NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display srcrect_width NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display srcrect_height NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display scroll_step NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display c_alphas NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display c_alphas_state NMTOKEN #REQUIRED>\n")
;
}
/** Export all displays of the given project as XML entries. */
static public void exportXML(final Project project, final Writer writer, final String indent, final Object any) throws Exception {
final StringBuffer sb_body = new StringBuffer();
final String in = indent + "\t";
for (final Display d : al_displays) {
if (d.project != project) continue;
final Rectangle r = d.frame.getBounds();
final Rectangle srcRect = d.canvas.getSrcRect();
final double magnification = d.canvas.getMagnification();
sb_body.append(indent).append("<t2_display id=\"").append(d.id).append("\"\n")
.append(in).append("layer_id=\"").append(d.layer.getId()).append("\"\n")
.append(in).append("c_alphas=\"").append(d.c_alphas).append("\"\n")
.append(in).append("c_alphas_state=\"").append(d.getChannelAlphasState()).append("\"\n")
.append(in).append("x=\"").append(r.x).append("\"\n")
.append(in).append("y=\"").append(r.y).append("\"\n")
.append(in).append("magnification=\"").append(magnification).append("\"\n")
.append(in).append("srcrect_x=\"").append(srcRect.x).append("\"\n")
.append(in).append("srcrect_y=\"").append(srcRect.y).append("\"\n")
.append(in).append("srcrect_width=\"").append(srcRect.width).append("\"\n")
.append(in).append("srcrect_height=\"").append(srcRect.height).append("\"\n")
.append(in).append("scroll_step=\"").append(d.scroll_step).append("\"\n")
;
sb_body.append(indent).append("/>\n");
}
writer.write(sb_body.toString());
}
private void updateToolTab() {
OptionPanel op = null;
switch (ProjectToolbar.getToolId()) {
case ProjectToolbar.PENCIL:
op = Segmentation.fmp.asOptionPanel();
break;
case ProjectToolbar.BRUSH:
op = AreaWrapper.PP.asOptionPanel();
break;
default:
break;
}
scroll_options.getViewport().removeAll();
if (null != op) {
op.bottomPadding();
scroll_options.setViewportView(op);
}
scroll_options.invalidate();
scroll_options.validate();
scroll_options.repaint();
}
// Never called; ProjectToolbar.toolChanged is also never called, which should forward here.
static public void toolChanged(final String tool_name) {
Utils.log2("tool name: " + tool_name);
for (final Display d : al_displays) {
d.updateToolTab();
Utils.updateComponent(d.toolbar_panel);
Utils.log2("updating toolbar_panel");
}
}
static public void toolChanged(final int tool) {
//Utils.log2("int tool is " + tool);
if (ProjectToolbar.PEN == tool) {
// erase bounding boxes
for (final Display d : al_displays) {
if (null != d.active) d.repaint(d.layer, d.selection.getBox(), 2);
}
}
for (final Display d: al_displays) {
d.updateToolTab();
}
if (null != front) {
try {
WindowManager.setTempCurrentImage(front.canvas.getFakeImagePlus());
} catch (Exception e) {} // may fail when changing tools while opening a Display
}
}
public Selection getSelection() {
return selection;
}
public boolean isSelected(Displayable d) {
return selection.contains(d);
}
static public void updateSelection() {
Display.updateSelection(null);
}
static public void updateSelection(final Display calling) {
final HashSet hs = new HashSet();
for (final Display d : al_displays) {
if (hs.contains(d.layer)) continue;
hs.add(d.layer);
if (null == d || null == d.selection) {
Utils.log2("d is : "+ d + " d.selection is " + d.selection);
} else {
d.selection.update(); // recomputes box
}
if (d != calling) { // TODO this is so dirty!
if (d.selection.getNLinked() > 1) d.canvas.setUpdateGraphics(true); // this is overkill anyway
d.canvas.repaint(d.selection.getLinkedBox(), Selection.PADDING);
d.navigator.repaint(true); // everything
}
}
}
static public void clearSelection(final Layer layer) {
for (final Display d : al_displays) {
if (d.layer == layer) d.selection.clear();
}
}
static public void clearSelection() {
for (final Display d : al_displays) {
d.selection.clear();
}
}
static public void clearSelection(final Project p) {
for (final Display d : al_displays) {
if (d.project == p) d.selection.clear();
}
}
private void setTempCurrentImage() {
WindowManager.setCurrentWindow(canvas.getFakeImagePlus().getWindow(), true);
WindowManager.setTempCurrentImage(canvas.getFakeImagePlus());
}
/** Check if any display will paint the given Displayable at the given magnification. */
static public boolean willPaint(final Displayable displ, final double magnification) {
Rectangle box = null; ;
for (final Display d : al_displays) {
/* // Can no longer do this check, because 'magnification' is now affected by the Displayable AffineTransform! And thus it would not paint after the prePaint.
if (Math.abs(d.canvas.getMagnification() - magnification) > 0.00000001) {
continue;
}
*/
if (null == box) box = displ.getBoundingBox(null);
if (d.getLayer() == d.layer && d.canvas.getSrcRect().intersects(box)) {
return true;
}
}
return false;
}
public void hideDeselected(final boolean not_images) {
// hide deselected
final ArrayList all = layer.getParent().getZDisplayables(); // a copy
all.addAll(layer.getDisplayables());
all.removeAll(selection.getSelected());
if (not_images) all.removeAll(layer.getDisplayables(Patch.class));
for (final Displayable d : (ArrayList<Displayable>)all) {
if (d.isVisible()) {
d.setVisible(false);
Display.updateCheckboxes(d, DisplayablePanel.VISIBILITY_STATE, false);
}
}
Display.update(layer);
}
/** Cleanup internal lists that may contain the given Displayable. */
static public void flush(final Displayable displ) {
for (final Display d : al_displays) {
d.selection.removeFromPrev(displ);
}
}
public void resizeCanvas() {
GenericDialog gd = new GenericDialog("Resize LayerSet");
gd.addNumericField("new width: ", layer.getLayerWidth(), 1, 8, "pixels");
gd.addNumericField("new height: ", layer.getLayerHeight(), 1, 8, "pixels");
gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[7]);
gd.showDialog();
if (gd.wasCanceled()) return;
double new_width = gd.getNextNumber();
double new_height =gd.getNextNumber();
layer.getParent().setDimensions(new_width, new_height, gd.getNextChoiceIndex()); // will complain and prevent cropping existing Displayable objects
}
/*
// To record layer changes -- but it's annoying, this is visualization not data.
static class DoSetLayer implements DoStep {
final Display display;
final Layer layer;
DoSetLayer(final Display display) {
this.display = display;
this.layer = display.layer;
}
public Displayable getD() { return null; }
public boolean isEmpty() { return false; }
public boolean apply(final int action) {
display.setLayer(layer);
}
public boolean isIdenticalTo(final Object ob) {
if (!ob instanceof DoSetLayer) return false;
final DoSetLayer dsl = (DoSetLayer) ob;
return dsl.display == this.display && dsl.layer == this.layer;
}
}
*/
protected void duplicateLinkAndSendTo(final Displayable active, final int position, final Layer other_layer) {
if (null == active || !(active instanceof Profile)) return;
if (active.getLayer() == other_layer) return; // can't do that!
// set current state
Set<DoStep> dataedits = new HashSet<DoStep>();
dataedits.add(new Displayable.DoEdit(active).init(active, new String[]{"data"})); // the links!
getLayerSet().addChangeTreesStep(dataedits);
Profile profile = project.getProjectTree().duplicateChild((Profile)active, position, other_layer);
if (null == profile) {
getLayerSet().removeLastUndoStep();
return;
}
active.link(profile);
other_layer.add(profile);
slt.setAndWait(other_layer);
selection.add(profile);
// set new state
dataedits = new HashSet<DoStep>();
dataedits.add(new Displayable.DoEdit(active).init(active, new String[]{"data"})); // the links!
dataedits.add(new Displayable.DoEdit(profile).init(profile, new String[]{"data"})); // the links!
getLayerSet().addChangeTreesStep(dataedits);
}
private final HashMap<Color,Layer> layer_channels = new HashMap<Color,Layer>();
private final TreeMap<Integer,LayerPanel> layer_alpha = new TreeMap<Integer,LayerPanel>();
private final HashMap<Layer,Byte> layer_composites = new HashMap<Layer,Byte>();
boolean invert_colors = false;
protected byte getLayerCompositeMode(final Layer layer) {
synchronized (layer_composites) {
Byte b = layer_composites.get(layer);
return null == b ? Displayable.COMPOSITE_NORMAL : b;
}
}
protected void setLayerCompositeMode(final Layer layer, final byte compositeMode) {
synchronized (layer_composites) {
if (-1 == compositeMode || Displayable.COMPOSITE_NORMAL == compositeMode) {
layer_composites.remove(layer);
} else {
layer_composites.put(layer, compositeMode);
}
}
}
protected void resetLayerComposites() {
synchronized (layer_composites) {
layer_composites.clear();
}
canvas.repaint(true);
}
/** Remove all red/blue coloring of layers, and repaint canvas. */
protected void resetLayerColors() {
synchronized (layer_channels) {
for (final Layer l : new ArrayList<Layer>(layer_channels.values())) { // avoid concurrent modification exception
final LayerPanel lp = layer_panels.get(l);
lp.setColor(Color.white);
setColorChannel(lp.layer, Color.white);
lp.slider.setEnabled(true);
}
layer_channels.clear();
}
canvas.repaint(true);
}
/** Set all layer alphas to zero, and repaint canvas. */
protected void resetLayerAlphas() {
synchronized (layer_channels) {
for (final LayerPanel lp : new ArrayList<LayerPanel>(layer_alpha.values())) {
lp.setAlpha(0);
}
layer_alpha.clear(); // should have already been cleared
}
canvas.repaint(true);
}
/** Add to layer_alpha table, or remove if alpha is zero. */
protected void storeLayerAlpha(final LayerPanel lp, final float a) {
synchronized (layer_channels) {
if (M.equals(0, a)) {
layer_alpha.remove(lp.layer.getParent().indexOf(lp.layer));
} else {
layer_alpha.put(lp.layer.getParent().indexOf(lp.layer), lp);
}
}
}
static protected final int REPAINT_SINGLE_LAYER = 0;
static protected final int REPAINT_MULTI_LAYER = 1;
static protected final int REPAINT_RGB_LAYER = 2;
/** Sets the values atomically, returns the painting mode. */
protected int getPaintMode(final HashMap<Color,Layer> hm, final ArrayList<LayerPanel> list) {
synchronized (layer_channels) {
if (layer_channels.size() > 0) {
hm.putAll(layer_channels);
hm.put(Color.green, this.layer);
return REPAINT_RGB_LAYER;
}
list.addAll(layer_alpha.values());
final int len = list.size();
if (len > 1) return REPAINT_MULTI_LAYER;
if (1 == len) {
if (list.get(0).layer == this.layer) return REPAINT_SINGLE_LAYER; // normal mode
return REPAINT_MULTI_LAYER;
}
return REPAINT_SINGLE_LAYER;
}
}
/** Set a layer to be painted as a specific color channel in the canvas.
* Only Color.red and Color.blue are accepted.
* Color.green is reserved for the current layer. */
protected void setColorChannel(final Layer layer, final Color color) {
synchronized (layer_channels) {
if (Color.white == color) {
// Remove
for (final Iterator<Layer> it = layer_channels.values().iterator(); it.hasNext(); ) {
if (it.next() == layer) {
it.remove();
break;
}
}
canvas.repaint();
} else if (Color.red == color || Color.blue == color) {
// Reset current of that color, if any, to white
final Layer l = layer_channels.remove(color);
if (null != l) layer_panels.get(l).setColor(Color.white);
// Replace or set new
layer_channels.put(color, layer);
tabs.repaint();
canvas.repaint();
} else {
Utils.log2("Trying to set unacceptable color for layer " + layer + " : " + color);
}
// enable/disable sliders
final boolean b = 0 == layer_channels.size();
for (final LayerPanel lp : layer_panels.values()) lp.slider.setEnabled(b);
}
this.canvas.repaint(true);
}
static public final void updateComponentTreeUI() {
try {
for (final Display d : al_displays) SwingUtilities.updateComponentTreeUI(d.frame);
} catch (Exception e) {
IJError.print(e);
}
}
/** Snap a Patch to the most overlapping Patch, if any.
* This method is a shallow wrap around AlignTask.snap, setting proper undo steps. */
static public final Bureaucrat snap(final Patch patch) {
final Set<Displayable> linked = patch.getLinkedGroup(null);
patch.getLayerSet().addTransformStep(linked);
Bureaucrat burro = AlignTask.snap(patch, null, false);
burro.addPostTask(new Runnable() { public void run() {
patch.getLayerSet().addTransformStep(linked);
}});
return burro;
}
private Mode mode = new DefaultMode(this);
public void setMode(final Mode mode) {
ProjectToolbar.setTool(ProjectToolbar.SELECT);
this.mode = mode;
canvas.repaint(true);
scroller.setEnabled(mode.canChangeLayer());
}
public Mode getMode() {
return mode;
}
static private final Hashtable<String,ProjectThing> findLandmarkNodes(Project p, String landmarks_type) {
Set<ProjectThing> landmark_nodes = p.getRootProjectThing().findChildrenOfTypeR(landmarks_type);
Hashtable<String,ProjectThing> map = new Hashtable<String,ProjectThing>();
for (ProjectThing pt : landmark_nodes) {
map.put(pt.toString() + "# " + pt.getId(), pt);
}
return map;
}
/** @param stack_patch is just a Patch of a series of Patch that make a stack of Patches. */
private boolean insertStack(ProjectThing target_landmarks, Project source, ProjectThing source_landmarks, Patch stack_patch) {
List<Ball> l1 = new ArrayList<Ball>();
List<Ball> l2 = new ArrayList<Ball>();
Collection<ProjectThing> b1s = source_landmarks.findChildrenOfType("ball"); // source is the one that has the stack_patch
Collection<ProjectThing> b2s = target_landmarks.findChildrenOfType("ball"); // target is this
HashSet<String> seen = new HashSet<String>();
for (ProjectThing b1 : b1s) {
Ball ball1 = (Ball) b1.getObject();
if (null == ball1) {
Utils.log("ERROR: there's an empty 'ball' node in target project" + project.toString());
return false;
}
String title1 = ball1.getTitle();
for (ProjectThing b2 : b2s) {
Ball ball2 = (Ball) b2.getObject();
if (null == ball2) {
Utils.log("ERROR: there's an empty 'ball' node in source project" + source.toString());
return false;
}
if (title1.equals(ball2.getTitle())) {
if (seen.contains(title1)) continue;
seen.add(title1);
l1.add(ball1);
l2.add(ball2);
}
}
}
if (l1.size() < 4) {
Utils.log("ERROR: found only " + l1.size() + " common landmarks: needs at least 4!");
return false;
}
// Extract coordinates of source project landmarks, in patch stack coordinate space
List<float[]> c1 = new ArrayList<float[]>();
for (Ball ball1 : l1) {
Map<Layer,double[]> m = ball1.getRawBalls();
if (1 != m.size()) {
Utils.log("ERROR: ball object " + ball1 + " from target project " + project + " has " + m.size() + " balls instead of just 1.");
return false;
}
Map.Entry<Layer,double[]> e = m.entrySet().iterator().next();
Layer layer = e.getKey();
double[] xyr = e.getValue();
float[] fin = new float[]{(float)xyr[0], (float)xyr[1]};
AffineTransform affine = ball1.getAffineTransformCopy();
try {
affine.preConcatenate(stack_patch.getAffineTransform().createInverse());
} catch (Exception nite) {
IJError.print(nite);
return false;
}
float[] fout = new float[2];
affine.transform(fin, 0, fout, 0, 1);
c1.add(new float[]{fout[0], fout[1], layer.getParent().indexOf(layer)});
}
// Extract coordinates of target (this) project landmarks, in calibrated world space
List<float[]> c2 = new ArrayList<float[]>();
for (Ball ball2 : l2) {
double[][] b = ball2.getBalls();
if (1 != b.length) {
Utils.log("ERROR: ball object " + ball2 + " from source project " + source + " has " + b.length + " balls instead of just 1.");
return false;
}
float[] fin = new float[]{(float)b[0][0], (float)b[0][1]};
AffineTransform affine = ball2.getAffineTransformCopy();
float[] fout = new float[2];
affine.transform(fin, 0, fout, 0, 1);
c2.add(new float[]{fout[0], fout[1], (float)b[0][2]});
}
// Print landmarks:
Utils.log("Landmarks:");
for (Iterator<float[]> it1 = c1.iterator(), it2 = c2.iterator(); it1.hasNext(); ) {
Utils.log(Utils.toString(it1.next()) + " <--> " + Utils.toString(it2.next()));
}
// Create point matches
List<PointMatch> pm = new ArrayList<PointMatch>();
for (Iterator<float[]> it1 = c1.iterator(), it2 = c2.iterator(); it1.hasNext(); ) {
pm.add(new mpicbg.models.PointMatch(new mpicbg.models.Point(it1.next()), new mpicbg.models.Point(it2.next())));
}
// Estimate AffineModel3D
AffineModel3D aff3d = new AffineModel3D();
try {
aff3d.fit(pm);
} catch (Exception e) {
IJError.print(e);
return false;
}
// Create and add the Stack
String path = stack_patch.getImageFilePath();
Stack st = new Stack(project, new File(path).getName(), 0, 0, getLayerSet().getLayers().get(0), path);
st.setInvertibleCoordinateTransform(aff3d);
getLayerSet().add(st);
return true;
}
static private List<Patch> getPatchStacks(final LayerSet ls) {
HashSet<Patch> stacks = new HashSet<Patch>();
for (Patch pa : (Collection<Patch>) (Collection) ls.getDisplayables(Patch.class)) {
PatchStack ps = pa.makePatchStack();
if (1 == ps.getNSlices()) continue;
stacks.add(ps.getPatch(0));
}
return new ArrayList<Patch>(stacks);
}
private void montage(int type) {
final Layer la = layer;
if (selection.getSelected(Patch.class).size() < 2) {
Utils.showMessage("Montage needs 2 or more images selected");
return;
}
final Collection<Displayable> col = la.getParent().addTransformStepWithData(Arrays.asList(new Layer[]{la}));
Bureaucrat burro;
switch (type) {
case 0:
burro = AlignTask.alignSelectionTask(selection);
break;
case 1:
burro = StitchingTEM.montageWithPhaseCorrelation( (Collection<Patch>) (Collection) selection.getSelected(Patch.class));
break;
default:
Utils.log("Unknown montage type " + type);
return;
}
if (null == burro) return;
burro.addPostTask(new Runnable() { public void run() {
la.getParent().enlargeToFit(selection.getAffected());
la.getParent().addTransformStepWithData(col);
}});
}
}
| false | true | public void actionPerformed(final ActionEvent ae) {
dispatcher.exec(new Runnable() { public void run() {
String command = ae.getActionCommand();
if (command.startsWith("Job")) {
if (Utils.checkYN("Really cancel job?")) {
project.getLoader().quitJob(command);
repairGUI();
}
return;
} else if (command.equals("Move to top")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.TOP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move up")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.UP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move down")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.DOWN, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move to bottom")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.BOTTOM, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Duplicate, link and send to next layer")) {
duplicateLinkAndSendTo(active, 1, layer.getParent().next(layer));
} else if (command.equals("Duplicate, link and send to previous layer")) {
duplicateLinkAndSendTo(active, 0, layer.getParent().previous(layer));
} else if (command.equals("Duplicate, link and send to...")) {
// fix non-scrolling popup menu
GenericDialog gd = new GenericDialog("Send to");
gd.addMessage("Duplicate, link and send to...");
String[] sl = new String[layer.getParent().size()];
int next = 0;
for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) {
sl[next++] = project.findLayerThing(it.next()).toString();
}
gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex());
if (layer == la) {
Utils.showMessage("Can't duplicate, link and send to the same layer.");
return;
}
duplicateLinkAndSendTo(active, 0, la);
} else if (-1 != command.indexOf("z = ")) {
// this is an item from the "Duplicate, link and send to" menu of layer z's
Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1)));
Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__");
if (null == target_layer) return;
duplicateLinkAndSendTo(active, 0, target_layer);
} else if (-1 != command.indexOf("z=")) {
// WARNING the indexOf is very similar to the previous one
// Send the linked group to the selected layer
int iz = command.indexOf("z=")+2;
Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2));
int end = command.indexOf(' ', iz);
if (-1 == end) end = command.length();
double lz = Double.parseDouble(command.substring(iz, end));
Layer target = layer.getParent().getLayer(lz);
layer.getParent().move(selection.getAffected(), active.getLayer(), target); // TODO what happens when ZDisplayable are selected?
} else if (command.equals("Unlink")) {
if (null == active || active instanceof Patch) return;
active.unlink();
updateSelection();//selection.update();
} else if (command.equals("Unlink from images")) {
if (null == active) return;
try {
for (Displayable displ: selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
} else if (command.equals("Unlink slices")) {
YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo.");
if (!yn.yesPressed()) return;
final ArrayList<Patch> pa = ((Patch)active).getStackPatches();
for (int i=pa.size()-1; i>0; i--) {
pa.get(i).unlink(pa.get(i-1));
}
} else if (command.equals("Send to next layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
for (final Displayable displ : selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveDown(layer, active); // will repaint whatever appropriate layers
selection.moveDown();
repaint(layer.getParent(), box);
} else if (command.equals("Send to previous layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
for (final Displayable displ : selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveUp(layer, active); // will repaint whatever appropriate layers
selection.moveUp();
repaint(layer.getParent(), box);
} else if (command.equals("Show centered")) {
if (active == null) return;
showCentered(active);
} else if (command.equals("Delete...")) {
/*
if (null != active) {
Displayable d = active;
selection.remove(d);
d.remove(true); // will repaint
}
*/
// remove all selected objects
selection.deleteAll();
} else if (command.equals("Color...")) {
IJ.doCommand("Color Picker...");
} else if (command.equals("Revert")) {
if (null == active || active.getClass() != Patch.class) return;
Patch p = (Patch)active;
if (!p.revert()) {
if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId());
else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId());
}
} else if (command.equals("Remove alpha mask")) {
final ArrayList<Displayable> patches = selection.getSelected(Patch.class);
if (patches.size() > 0) {
Bureaucrat.createAndStart(new Worker.Task("Removing alpha mask" + (patches.size() > 1 ? "s" : "")) { public void exec() {
final ArrayList<Future> jobs = new ArrayList<Future>();
for (final Displayable d : patches) {
final Patch p = (Patch) d;
p.setAlphaMask(null);
Future job = p.getProject().getLoader().regenerateMipMaps(p); // submit to queue
if (null != job) jobs.add(job);
}
// join all
for (final Future job : jobs) try {
job.get();
} catch (Exception ie) {}
}}, patches.get(0).getProject());
}
} else if (command.equals("Undo")) {
Bureaucrat.createAndStart(new Worker.Task("Undo") { public void exec() {
layer.getParent().undoOneStep();
Display.repaint(layer.getParent());
}}, project);
} else if (command.equals("Redo")) {
Bureaucrat.createAndStart(new Worker.Task("Redo") { public void exec() {
layer.getParent().redoOneStep();
Display.repaint(layer.getParent());
}}, project);
} else if (command.equals("Apply transform")) {
canvas.applyTransform();
} else if (command.equals("Apply transform propagating to last layer")) {
if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) {
final java.util.List<Layer> layers = layer.getParent().getLayers();
final HashSet<Layer> subset = new HashSet<Layer>(layers.subList(layers.indexOf(Display.this.layer)+1, layers.size())); // +1 to exclude current layer
if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset);
else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset);
setMode(new DefaultMode(Display.this));
}
} else if (command.equals("Apply transform propagating to first layer")) {
if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) {
final java.util.List<Layer> layers = layer.getParent().getLayers();
final HashSet<Layer> subset = new HashSet<Layer>(layers.subList(0, layers.indexOf(Display.this.layer)));
if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset);
else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset);
setMode(new DefaultMode(Display.this));
}
} else if (command.equals("Cancel transform")) {
canvas.cancelTransform(); // calls getMode().cancel()
} else if (command.equals("Specify transform...")) {
if (null == active) return;
selection.specify();
} else if (command.equals("Hide all but images")) {
ArrayList<Class> type = new ArrayList<Class>();
type.add(Patch.class);
type.add(Stack.class);
Collection<Displayable> col = layer.getParent().hideExcept(type, false);
selection.removeAll(col);
Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE);
Display.update(layer.getParent(), false);
} else if (command.equals("Unhide all")) {
Display.updateCheckboxes(layer.getParent().setAllVisible(false), DisplayablePanel.VISIBILITY_STATE);
Display.update(layer.getParent(), false);
} else if (command.startsWith("Hide all ")) {
String type = command.substring(9, command.length() -1); // skip the ending plural 's'
Collection<Displayable> col = layer.getParent().setVisible(type, false, true);
selection.removeAll(col);
Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE);
} else if (command.startsWith("Unhide all ")) {
String type = command.substring(11, command.length() -1); // skip the ending plural 's'
type = type.substring(0, 1).toUpperCase() + type.substring(1);
updateCheckboxes(layer.getParent().setVisible(type, true, true), DisplayablePanel.VISIBILITY_STATE);
} else if (command.equals("Hide deselected")) {
hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers()));
} else if (command.equals("Hide deselected except images")) {
hideDeselected(true);
} else if (command.equals("Hide selected")) {
selection.setVisible(false); // TODO should deselect them too? I don't think so.
Display.updateCheckboxes(selection.getSelected(), DisplayablePanel.VISIBILITY_STATE);
} else if (command.equals("Resize canvas/LayerSet...")) {
resizeCanvas();
} else if (command.equals("Autoresize canvas/LayerSet")) {
layer.getParent().setMinimumDimensions();
} else if (command.equals("Import image")) {
importImage();
} else if (command.equals("Import next image")) {
importNextImage();
} else if (command.equals("Import stack...")) {
Display.this.getLayerSet().addChangeTreesStep();
Rectangle sr = getCanvas().getSrcRect();
Bureaucrat burro = project.getLoader().importStack(layer, sr.x + sr.width/2, sr.y + sr.height/2, null, true, null, false);
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Import stack with landmarks...")) {
// 1 - Find out if there's any other project open
List<Project> pr = Project.getProjects();
if (1 == pr.size()) {
Utils.logAll("Need another project open!");
return;
}
// 2 - Ask for a "landmarks" type
GenericDialog gd = new GenericDialog("Landmarks");
gd.addStringField("landmarks type:", "landmarks");
final String[] none = {"-- None --"};
final Hashtable<String,Project> mpr = new Hashtable<String,Project>();
for (Project p : pr) {
if (p == project) continue;
mpr.put(p.toString(), p);
}
final String[] project_titles = mpr.keySet().toArray(new String[0]);
final Hashtable<String,ProjectThing> map_target = findLandmarkNodes(project, "landmarks");
String[] target_landmark_titles = map_target.isEmpty() ? none : map_target.keySet().toArray(new String[0]);
gd.addChoice("Landmarks node in this project:", target_landmark_titles, target_landmark_titles[0]);
gd.addMessage("");
gd.addChoice("Source project:", project_titles, project_titles[0]);
final Hashtable<String,ProjectThing> map_source = findLandmarkNodes(mpr.get(project_titles[0]), "landmarks");
String[] source_landmark_titles = map_source.isEmpty() ? none : map_source.keySet().toArray(new String[0]);
gd.addChoice("Landmarks node in source project:", source_landmark_titles, source_landmark_titles[0]);
final List<Patch> stacks = Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet());
String[] stack_titles;
if (stacks.isEmpty()) {
if (1 == mpr.size()) {
IJ.showMessage("Project " + project_titles[0] + " does not contain any Stack.");
return;
}
stack_titles = none;
} else {
stack_titles = new String[stacks.size()];
int next = 0;
for (Patch pa : stacks) stack_titles[next++] = pa.toString();
}
gd.addChoice("Stacks:", stack_titles, stack_titles[0]);
Vector vc = gd.getChoices();
final Choice choice_target_landmarks = (Choice) vc.get(0);
final Choice choice_source_projects = (Choice) vc.get(1);
final Choice choice_source_landmarks = (Choice) vc.get(2);
final Choice choice_stacks = (Choice) vc.get(3);
final TextField input = (TextField) gd.getStringFields().get(0);
input.addTextListener(new TextListener() {
public void textValueChanged(TextEvent te) {
final String text = input.getText();
update(choice_target_landmarks, Display.this.project, text, map_target);
update(choice_source_landmarks, mpr.get(choice_source_projects.getSelectedItem()), text, map_source);
}
private void update(Choice c, Project p, String type, Hashtable<String,ProjectThing> table) {
table.clear();
table.putAll(findLandmarkNodes(p, type));
c.removeAll();
if (table.isEmpty()) c.add(none[0]);
else for (String t : table.keySet()) c.add(t);
}
});
choice_source_projects.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String item = (String) e.getItem();
Project p = mpr.get(choice_source_projects.getSelectedItem());
// 1 - Update choice of landmark items
map_source.clear();
map_source.putAll(findLandmarkNodes(p, input.getText()));
choice_target_landmarks.removeAll();
if (map_source.isEmpty()) choice_target_landmarks.add(none[0]);
else for (String t : map_source.keySet()) choice_target_landmarks.add(t);
// 2 - Update choice of Stack items
stacks.clear();
choice_stacks.removeAll();
stacks.addAll(Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet()));
if (stacks.isEmpty()) choice_stacks.add(none[0]);
else for (Patch pa : stacks) choice_stacks.add(pa.toString());
}
});
gd.showDialog();
if (gd.wasCanceled()) return;
String type = gd.getNextString();
if (null == type || 0 == type.trim().length()) {
Utils.log("Invalid landmarks node type!");
return;
}
ProjectThing target_landmarks_node = map_target.get(gd.getNextChoice());
Project source = mpr.get(gd.getNextChoice());
ProjectThing source_landmarks_node = map_source.get(gd.getNextChoice());
Patch stack_patch = stacks.get(gd.getNextChoiceIndex());
// Store current state
Display.this.getLayerSet().addLayerContentStep(layer);
// Insert stack
insertStack(target_landmarks_node, source, source_landmarks_node, stack_patch);
// Store new state
Display.this.getLayerSet().addChangeTreesStep();
} else if (command.equals("Import grid...")) {
Display.this.getLayerSet().addLayerContentStep(layer);
Bureaucrat burro = project.getLoader().importGrid(layer);
if (null != burro)
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addLayerContentStep(layer);
}});
} else if (command.equals("Import sequence as grid...")) {
Display.this.getLayerSet().addChangeTreesStep();
Bureaucrat burro = project.getLoader().importSequenceAsGrid(layer);
if (null != burro)
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Import from text file...")) {
Display.this.getLayerSet().addChangeTreesStep();
Bureaucrat burro = project.getLoader().importImages(layer);
if (null != burro)
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Import labels as arealists...")) {
Display.this.getLayerSet().addChangeTreesStep();
Bureaucrat burro = project.getLoader().importLabelsAsAreaLists(layer, null, Double.MAX_VALUE, 0, 0.4f, false);
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Make flat image...")) {
// if there's a ROI, just use that as cropping rectangle
Rectangle srcRect = null;
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null != roi) {
srcRect = roi.getBounds();
} else {
// otherwise, whatever is visible
//srcRect = canvas.getSrcRect();
// The above is confusing. That is what ROIs are for. So paint all:
srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight()));
}
double scale = 1.0;
final String[] types = new String[]{"8-bit grayscale", "RGB Color"};
int the_type = ImagePlus.GRAY8;
final GenericDialog gd = new GenericDialog("Choose", frame);
gd.addSlider("Scale: ", 1, 100, 100);
gd.addNumericField("Width: ", srcRect.width, 0);
gd.addNumericField("height: ", srcRect.height, 0);
// connect the above 3 fields:
Vector numfields = gd.getNumericFields();
UpdateDimensionField udf = new UpdateDimensionField(srcRect.width, srcRect.height, (TextField) numfields.get(1), (TextField) numfields.get(2), (TextField) numfields.get(0), (Scrollbar) gd.getSliders().get(0));
for (Object ob : numfields) ((TextField)ob).addTextListener(udf);
gd.addChoice("Type: ", types, types[0]);
if (layer.getParent().size() > 1) {
Utils.addLayerRangeChoices(Display.this.layer, gd); /// $#%! where are my lisp macros
gd.addCheckbox("Include non-empty layers only", true);
}
gd.addMessage("Background color:");
Utils.addRGBColorSliders(gd, Color.black);
gd.addCheckbox("Best quality", false);
gd.addMessage("");
gd.addCheckbox("Save to file", false);
gd.addCheckbox("Save for web", false);
gd.showDialog();
if (gd.wasCanceled()) return;
scale = gd.getNextNumber() / 100;
the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB);
if (Double.isNaN(scale) || scale <= 0.0) {
Utils.showMessage("Invalid scale.");
return;
}
// consuming and ignoring width and height:
gd.getNextNumber();
gd.getNextNumber();
Layer[] layer_array = null;
boolean non_empty_only = false;
if (layer.getParent().size() > 1) {
non_empty_only = gd.getNextBoolean();
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
ArrayList al = new ArrayList();
ArrayList al_zd = layer.getParent().getZDisplayables();
ZDisplayable[] zd = new ZDisplayable[al_zd.size()];
al_zd.toArray(zd);
for (int i=i_start, j=0; i <= i_end; i++, j++) {
Layer la = layer.getParent().getLayer(i);
if (!la.isEmpty() || !non_empty_only) al.add(la); // checks both the Layer and the ZDisplayable objects in the parent LayerSet
}
if (0 == al.size()) {
Utils.showMessage("All layers are empty!");
return;
}
layer_array = new Layer[al.size()];
al.toArray(layer_array);
} else {
layer_array = new Layer[]{Display.this.layer};
}
final Color background = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber());
final boolean quality = gd.getNextBoolean();
final boolean save_to_file = gd.getNextBoolean();
final boolean save_for_web = gd.getNextBoolean();
// in its own thread
if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type);
else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality, background);
} else if (command.equals("Lock")) {
selection.setLocked(true);
Utils.revalidateComponent(tabs.getSelectedComponent());
} else if (command.equals("Unlock")) {
selection.setLocked(false);
Utils.revalidateComponent(tabs.getSelectedComponent());
} else if (command.equals("Properties...")) {
active.adjustProperties();
updateSelection();
} else if (command.equals("Show current 2D position in 3D")) {
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
Display3D.addFatPoint("Current 2D Position", getLayerSet(), p.x, p.y, layer.getZ(), 10, Color.magenta);
} else if (command.equals("Align stack slices")) {
if (getActive() instanceof Patch) {
final Patch slice = (Patch)getActive();
if (slice.isStack()) {
// check linked group
final HashSet hs = slice.getLinkedGroup(new HashSet());
for (Iterator it = hs.iterator(); it.hasNext(); ) {
if (it.next().getClass() != Patch.class) {
Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); // labels should be fine, need to check that
return;
}
}
final LayerSet ls = slice.getLayerSet();
final HashSet<Displayable> linked = slice.getLinkedGroup(null);
ls.addTransformStepWithData(linked);
Bureaucrat burro = AlignTask.registerStackSlices((Patch)getActive()); // will repaint
burro.addPostTask(new Runnable() { public void run() {
ls.enlargeToFit(linked);
// The current state when done
ls.addTransformStepWithData(linked);
}});
} else {
Utils.log("Align stack slices: selected image is not part of a stack.");
}
}
} else if (command.equals("Align layers with manual landmarks")) {
setMode(new ManualAlignMode(Display.this));
} else if (command.equals("Align layers")) {
final Layer la = layer; // caching, since scroll wheel may change it
la.getParent().addTransformStep(la.getParent().getLayers());
Bureaucrat burro = AlignLayersTask.alignLayersTask( la );
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class));
la.getParent().addTransformStep(la.getParent().getLayers());
}});
} else if (command.equals("Align multi-layer mosaic")) {
final Layer la = layer; // caching, since scroll wheel may change it
la.getParent().addTransformStep();
Bureaucrat burro = AlignTask.alignMultiLayerMosaicTask( la );
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class));
la.getParent().addTransformStep();
}});
} else if (command.equals("Montage all images in this layer")) {
final Layer la = layer;
final List<Patch> patches = new ArrayList<Patch>( (List<Patch>) (List) la.getDisplayables(Patch.class));
if (patches.size() < 2) {
Utils.showMessage("Montage needs 2 or more images selected");
return;
}
final Collection<Displayable> col = la.getParent().addTransformStepWithData(Arrays.asList(new Layer[]{la}));
Bureaucrat burro = AlignTask.alignPatchesTask(patches, Arrays.asList(new Patch[]{patches.get(0)}));
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().enlargeToFit(patches);
la.getParent().addTransformStepWithData(col);
}});
} else if (command.equals("Montage selected images (SIFT)")) {
montage(0);
} else if (command.equals("Montage selected images (phase correlation)")) {
montage(1);
} else if (command.equals("Montage multiple layers (phase correlation)")) {
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex());
final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers);
Bureaucrat burro = StitchingTEM.montageWithPhaseCorrelation(layers);
if (null == burro) return;
burro.addPostTask(new Runnable() { public void run() {
Collection<Displayable> ds = new ArrayList<Displayable>();
for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class));
getLayerSet().enlargeToFit(ds);
getLayerSet().addTransformStepWithData(col);
}});
} else if (command.equals("Montage multiple layers (SIFT)")) {
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex());
final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers);
Bureaucrat burro = AlignTask.montageLayersTask(layers);
burro.addPostTask(new Runnable() { public void run() {
Collection<Displayable> ds = new ArrayList<Displayable>();
for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class));
getLayerSet().enlargeToFit(ds);
getLayerSet().addTransformStepWithData(col);
}});
} else if (command.equals("Properties ...")) { // NOTE the space before the dots, to distinguish from the "Properties..." command that works on Displayable objects.
GenericDialog gd = new GenericDialog("Properties", Display.this.frame);
//gd.addNumericField("layer_scroll_step: ", this.scroll_step, 0);
gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step);
gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]);
gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality());
Loader lo = getProject().getLoader();
boolean using_mipmaps = lo.isMipMapsEnabled();
gd.addCheckbox("enable_mipmaps", using_mipmaps);
gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled());
double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight();
gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsMaxDimension());
gd.addCheckbox("Show arrow heads in Treeline/AreaTree", layer.getParent().paint_arrows);
gd.addCheckbox("Show edge confidence boxes in Treeline/AreaTree", layer.getParent().paint_edge_confidence_boxes);
gd.addCheckbox("Show color cues", layer.getParent().color_cues);
gd.addSlider("+/- layers to color cue", 0, 10, layer.getParent().n_layers_color_cue);
// --------
gd.showDialog();
if (gd.wasCanceled()) return;
// --------
int sc = (int) gd.getNextNumber();
if (sc < 1) sc = 1;
Display.this.scroll_step = sc;
updateInDatabase("scroll_step");
//
layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex());
layer.getParent().setSnapshotsQuality(gd.getNextBoolean());
//
boolean generate_mipmaps = gd.getNextBoolean();
if (using_mipmaps && generate_mipmaps) {
// nothing changed
} else {
if (using_mipmaps) { // and !generate_mipmaps
lo.flushMipMaps(true);
} else {
// not using mipmaps before, and true == generate_mipmaps
lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class));
}
}
//
layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean());
layer.getParent().setPixelsMaxDimension((int)gd.getNextNumber());
layer.getParent().paint_arrows = gd.getNextBoolean();
layer.getParent().paint_edge_confidence_boxes = gd.getNextBoolean();
layer.getParent().color_cues = gd.getNextBoolean();
layer.getParent().n_layers_color_cue = (int)gd.getNextNumber();
Display.repaint(layer.getParent());
} else if (command.equals("Adjust snapping parameters...")) {
AlignTask.p_snap.setup("Snap");
} else if (command.equals("Adjust fast-marching parameters...")) {
Segmentation.fmp.setup();
} else if (command.equals("Adjust arealist paint parameters...")) {
AreaWrapper.PP.setup();
} else if (command.equals("Search...")) {
new Search();
} else if (command.equals("Select all")) {
selection.selectAll();
repaint(Display.this.layer, selection.getBox(), 0);
} else if (command.equals("Select all visible")) {
selection.selectAllVisible();
repaint(Display.this.layer, selection.getBox(), 0);
} else if (command.equals("Select none")) {
Rectangle box = selection.getBox();
selection.clear();
repaint(Display.this.layer, box, 0);
} else if (command.equals("Restore selection")) {
selection.restore();
} else if (command.equals("Select under ROI")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return;
selection.selectAll(roi, true);
} else if (command.equals("Merge")) {
Bureaucrat burro = Bureaucrat.create(new Worker.Task("Merging AreaLists") {
public void exec() {
ArrayList al_sel = selection.getSelected(AreaList.class);
// put active at the beginning, to work as the base on which other's will get merged
al_sel.remove(Display.this.active);
al_sel.add(0, Display.this.active);
Set<DoStep> dataedits = new HashSet<DoStep>();
dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"}));
getLayerSet().addChangeTreesStep(dataedits);
AreaList ali = AreaList.merge(al_sel);
if (null != ali) {
// remove all but the first from the selection
for (int i=1; i<al_sel.size(); i++) {
Object ob = al_sel.get(i);
if (ob.getClass() == AreaList.class) {
selection.remove((Displayable)ob);
}
}
selection.updateTransform(ali);
repaint(ali.getLayerSet(), ali, 0);
}
}
}, Display.this.project);
burro.addPostTask(new Runnable() { public void run() {
Set<DoStep> dataedits = new HashSet<DoStep>();
dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"}));
getLayerSet().addChangeTreesStep(dataedits);
}});
burro.goHaveBreakfast();
} else if (command.equals("Reroot")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
getLayerSet().addDataEditStep(active);
((Tree)active).reRoot(p.x, p.y, layer, canvas.getMagnification());
getLayerSet().addDataEditStep(active);
Display.repaint(getLayerSet());
} else if (command.equals("Part subtree")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
getLayerSet().addChangeTreesStep();
List<Tree> ts = ((Tree)active).splitNear(p.x, p.y, layer, canvas.getMagnification());
if (null == ts) return;
Displayable elder = Display.this.active;
for (Tree t : ts) {
if (t == elder) continue;
getLayerSet().add(t); // will change Display.this.active !
project.getProjectTree().addSibling(elder, t);
}
selection.clear();
selection.selectAll(ts);
selection.add(elder);
getLayerSet().addChangeTreesStep();
Display.repaint(getLayerSet());
} else if (command.equals("Show tabular view")) {
if (!(active instanceof Tree)) return;
((Tree)active).createMultiTableView();
} else if (command.equals("Mark")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
if (((Tree)active).markNear(p.x, p.y, layer, canvas.getMagnification())) {
Display.repaint(getLayerSet());
}
} else if (command.equals("Clear marks (selected Trees)")) {
for (Displayable d : selection.getSelected(Tree.class)) {
((Tree)d).unmark();
}
Display.repaint(getLayerSet());
} else if (command.equals("Join")) {
if (!(active instanceof Tree)) return;
final List<Tree> tlines = (List<Tree>) (List) selection.getSelected(Treeline.class);
if (((Tree)active).canJoin(tlines)) {
getLayerSet().addChangeTreesStep();
((Tree)active).join(tlines);
for (final Tree tl : tlines) {
if (tl == active) continue;
tl.remove2(false);
}
Display.repaint(getLayerSet());
getLayerSet().addChangeTreesStep();
}
} else if (command.equals("Previous branch point or start")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
center(((Treeline)active).findPreviousBranchOrRootPoint(p.x, p.y, layer, canvas.getMagnification()));
} else if (command.equals("Next branch point or end")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
center(((Tree)active).findNextBranchOrEndPoint(p.x, p.y, layer, canvas.getMagnification()));
} else if (command.equals("Root")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
center(((Tree)active).createCoordinate(((Tree)active).getRoot()));
} else if (command.equals("Last added point")) {
if (!(active instanceof Tree)) return;
center(((Treeline)active).getLastAdded());
} else if (command.equals("Last edited point")) {
if (!(active instanceof Tree)) return;
center(((Treeline)active).getLastEdited());
} else if (command.equals("Reverse point order")) {
if (!(active instanceof Pipe)) return;
getLayerSet().addDataEditStep(active);
((Pipe)active).reverse();
Display.repaint(Display.this.layer);
getLayerSet().addDataEditStep(active);
} else if (command.equals("View orthoslices")) {
if (!(active instanceof Patch)) return;
Display3D.showOrthoslices(((Patch)active));
} else if (command.equals("View volume")) {
if (!(active instanceof Patch)) return;
Display3D.showVolume(((Patch)active));
} else if (command.equals("Show in 3D")) {
for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) {
ZDisplayable zd = (ZDisplayable)it.next();
Display3D.show(zd.getProject().findProjectThing(zd));
}
// handle profile lists ...
HashSet hs = new HashSet();
for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) {
Displayable d = (Displayable)it.next();
ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent();
if (!hs.contains(profile_list)) {
Display3D.show(profile_list);
hs.add(profile_list);
}
}
} else if (command.equals("Snap")) {
// Take the active if it's a Patch
if (!(active instanceof Patch)) return;
Display.snap((Patch)active);
} else if (command.equals("Blend")) {
HashSet<Patch> patches = new HashSet<Patch>();
for (final Displayable d : selection.getSelected()) {
if (d.getClass() == Patch.class) patches.add((Patch)d);
}
if (patches.size() > 1) {
GenericDialog gd = new GenericDialog("Blending");
gd.addCheckbox("Respect current alpha mask", true);
gd.showDialog();
if (gd.wasCanceled()) return;
Blending.blend(patches, gd.getNextBoolean());
} else {
IJ.log("Please select more than one overlapping image.");
}
} else if (command.equals("Montage")) {
final Set<Displayable> affected = new HashSet<Displayable>(selection.getAffected());
// make an undo step!
final LayerSet ls = layer.getParent();
ls.addTransformStepWithData(affected);
Bureaucrat burro = AlignTask.alignSelectionTask( selection );
burro.addPostTask(new Runnable() { public void run() {
ls.enlargeToFit(affected);
ls.addTransformStepWithData(affected);
}});
} else if (command.equals("Lens correction")) {
final Layer la = layer;
la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables()));
Bureaucrat burro = DistortionCorrectionTask.correctDistortionFromSelection( selection );
burro.addPostTask(new Runnable() { public void run() {
// no means to know which where modified and from which layers!
la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables()));
}});
} else if (command.equals("Link images...")) {
GenericDialog gd = new GenericDialog("Options");
gd.addMessage("Linking images to images (within their own layer only):");
String[] options = {"all images to all images", "each image with any other overlapping image"};
gd.addChoice("Link: ", options, options[1]);
String[] options2 = {"selected images only", "all images in this layer", "all images in all layers, within the layer only", "all images in all layers, within and across consecutive layers"};
gd.addChoice("Apply to: ", options2, options2[0]);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer lay = layer;
final HashSet<Displayable> ds = new HashSet<Displayable>(lay.getParent().getDisplayables());
lay.getParent().addDataEditStep(ds, new String[]{"data"});
boolean overlapping_only = 1 == gd.getNextChoiceIndex();
Collection<Displayable> coll = null;
switch (gd.getNextChoiceIndex()) {
case 0:
coll = selection.getSelected(Patch.class);
Patch.crosslink(coll, overlapping_only);
break;
case 1:
coll = lay.getDisplayables(Patch.class);
Patch.crosslink(coll, overlapping_only);
break;
case 2:
coll = new ArrayList<Displayable>();
for (final Layer la : lay.getParent().getLayers()) {
Collection<Displayable> acoll = la.getDisplayables(Patch.class);
Patch.crosslink(acoll, overlapping_only);
coll.addAll(acoll);
}
break;
case 3:
ArrayList<Layer> layers = lay.getParent().getLayers();
Collection<Displayable> lc1 = layers.get(0).getDisplayables(Patch.class);
if (lay == layers.get(0)) coll = lc1;
for (int i=1; i<layers.size(); i++) {
Collection<Displayable> lc2 = layers.get(i).getDisplayables(Patch.class);
if (null == coll && Display.this.layer == layers.get(i)) coll = lc2;
Collection<Displayable> both = new ArrayList<Displayable>();
both.addAll(lc1);
both.addAll(lc2);
Patch.crosslink(both, overlapping_only);
lc1 = lc2;
}
break;
}
if (null != coll) Display.updateCheckboxes(coll, DisplayablePanel.LINK_STATE, true);
lay.getParent().addDataEditStep(ds);
} else if (command.equals("Unlink all selected images")) {
if (Utils.check("Really unlink selected images?")) {
for (final Displayable d : selection.getSelected(Patch.class)) {
d.unlink();
}
}
} else if (command.equals("Unlink all")) {
if (Utils.check("Really unlink all objects from all layers?")) {
for (final Displayable d : layer.getParent().getDisplayables()) {
d.unlink();
}
}
} else if (command.equals("Calibration...")) {
try {
IJ.run(canvas.getFakeImagePlus(), "Properties...", "");
Display.updateTitle(getLayerSet());
} catch (RuntimeException re) {
Utils.log2("Calibration dialog canceled.");
}
} else if (command.equals("Grid overlay...")) {
if (null == gridoverlay) gridoverlay = new GridOverlay();
gridoverlay.setup(canvas.getFakeImagePlus().getRoi());
canvas.invalidateVolatile();
canvas.repaint(false);
} else if (command.equals("Enhance contrast (selected images)...")) {
final Layer la = layer;
ArrayList<Displayable> selected = selection.getSelected(Patch.class);
final HashSet<Displayable> ds = new HashSet<Displayable>(selected);
la.getParent().addDataEditStep(ds);
Displayable active = Display.this.getActive();
Patch ref = active.getClass() == Patch.class ? (Patch)active : null;
Bureaucrat burro = getProject().getLoader().enhanceContrast(selected, ref);
burro.addPostTask(new Runnable() { public void run() {
la.getParent().addDataEditStep(ds);
}});
} else if (command.equals("Enhance contrast layer-wise...")) {
// ask for range of layers
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
java.util.List<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end
final HashSet<Displayable> ds = new HashSet<Displayable>();
for (final Layer l : layers) ds.addAll(l.getDisplayables(Patch.class));
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().enhanceContrast(layers);
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Set Min and Max layer-wise...")) {
Displayable active = getActive();
double min = 0;
double max = 0;
if (null != active && active.getClass() == Patch.class) {
min = ((Patch)active).getMin();
max = ((Patch)active).getMax();
}
final GenericDialog gd = new GenericDialog("Min and Max");
gd.addMessage("Set min and max to all images in the layer range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.addNumericField("min: ", min, 2);
gd.addNumericField("max: ", max, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
//
min = gd.getNextNumber();
max = gd.getNextNumber();
ArrayList<Displayable> al = new ArrayList<Displayable>();
for (final Layer la : layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1)) { // exclusive end
al.addAll(la.getDisplayables(Patch.class));
}
final HashSet<Displayable> ds = new HashSet<Displayable>(al);
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().setMinAndMax(al, min, max);
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Set Min and Max (selected images)...")) {
Displayable active = getActive();
double min = 0;
double max = 0;
if (null != active && active.getClass() == Patch.class) {
min = ((Patch)active).getMin();
max = ((Patch)active).getMax();
}
final GenericDialog gd = new GenericDialog("Min and Max");
gd.addMessage("Set min and max to all selected images");
gd.addNumericField("min: ", min, 2);
gd.addNumericField("max: ", max, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
//
min = gd.getNextNumber();
max = gd.getNextNumber();
final HashSet<Displayable> ds = new HashSet<Displayable>(selection.getSelected(Patch.class));
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().setMinAndMax(selection.getSelected(Patch.class), min, max);
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Adjust min and max (selected images)...")) {
final List<Displayable> list = selection.getSelected(Patch.class);
if (list.isEmpty()) {
Utils.log("No images selected!");
return;
}
Bureaucrat.createAndStart(new Worker.Task("Init contrast adjustment") {
public void exec() {
try {
setMode(new ContrastAdjustmentMode(Display.this, list));
} catch (Exception e) {
Utils.log("All images must be of the same type!");
}
}
}, list.get(0).getProject());
} else if (command.equals("Mask image borders (layer-wise)...")) {
final GenericDialog gd = new GenericDialog("Mask borders");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.addMessage("Borders:");
gd.addNumericField("left: ", 6, 2);
gd.addNumericField("top: ", 6, 2);
gd.addNumericField("right: ", 6, 2);
gd.addNumericField("bottom: ", 6, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
Collection<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1);
final HashSet<Displayable> ds = new HashSet<Displayable>();
for (Layer l : layers) ds.addAll(l.getDisplayables(Patch.class));
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().maskBordersLayerWise(layers, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber());
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Mask image borders (selected images)...")) {
final GenericDialog gd = new GenericDialog("Mask borders");
gd.addMessage("Borders:");
gd.addNumericField("left: ", 6, 2);
gd.addNumericField("top: ", 6, 2);
gd.addNumericField("right: ", 6, 2);
gd.addNumericField("bottom: ", 6, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
Collection<Displayable> patches = selection.getSelected(Patch.class);
final HashSet<Displayable> ds = new HashSet<Displayable>(patches);
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().maskBorders(patches, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber());
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Duplicate")) {
// only Patch and DLabel, i.e. Layer-only resident objects that don't exist in the Project Tree
final HashSet<Class> accepted = new HashSet<Class>();
accepted.add(Patch.class);
accepted.add(DLabel.class);
accepted.add(Stack.class);
final ArrayList<Displayable> originals = new ArrayList<Displayable>();
final ArrayList<Displayable> selected = selection.getSelected();
for (final Displayable d : selected) {
if (accepted.contains(d.getClass())) {
originals.add(d);
}
}
if (originals.size() > 0) {
getLayerSet().addChangeTreesStep();
for (final Displayable d : originals) {
if (d instanceof ZDisplayable) {
d.getLayerSet().add((ZDisplayable)d.clone());
} else {
d.getLayer().add(d.clone());
}
}
getLayerSet().addChangeTreesStep();
} else if (selected.size() > 0) {
Utils.log("Can only duplicate images and text labels.\nDuplicate *other* objects in the Project Tree.\n");
}
} else if (command.equals("Create subproject")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return; // the menu item is not active unless there is a ROI
Layer first, last;
if (1 == layer.getParent().size()) {
first = last = layer;
} else {
GenericDialog gd = new GenericDialog("Choose layer range");
Utils.addLayerRangeChoices(layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
first = layer.getParent().getLayer(gd.getNextChoiceIndex());
last = layer.getParent().getLayer(gd.getNextChoiceIndex());
Utils.log2("first, last: " + first + ", " + last);
}
Project sub = getProject().createSubproject(roi.getBounds(), first, last);
final LayerSet subls = sub.getRootLayerSet();
Display.createDisplay(sub, subls.getLayer(0));
} else if (command.startsWith("Image stack under selected Arealist")) {
if (null == active || active.getClass() != AreaList.class) return;
GenericDialog gd = new GenericDialog("Stack options");
String[] types = {"8-bit", "16-bit", "32-bit", "RGB"};
gd.addChoice("type:", types, types[0]);
gd.addSlider("Scale: ", 1, 100, 100);
gd.showDialog();
if (gd.wasCanceled()) return;
final int type;
switch (gd.getNextChoiceIndex()) {
case 0: type = ImagePlus.GRAY8; break;
case 1: type = ImagePlus.GRAY16; break;
case 2: type = ImagePlus.GRAY32; break;
case 3: type = ImagePlus.COLOR_RGB; break;
default: type = ImagePlus.GRAY8; break;
}
ImagePlus imp = ((AreaList)active).getStack(type, gd.getNextNumber()/100);
if (null != imp) imp.show();
} else if (command.equals("Fly through selected Treeline/AreaTree")) {
if (null == active || !(active instanceof Tree)) return;
Bureaucrat.createAndStart(new Worker.Task("Creating fly through", true) {
public void exec() {
GenericDialog gd = new GenericDialog("Fly through");
gd.addNumericField("Width", 512, 0);
gd.addNumericField("Height", 512, 0);
String[] types = new String[]{"8-bit gray", "Color RGB"};
gd.addChoice("Image type", types, types[0]);
gd.addSlider("scale", 0, 100, 100);
gd.addCheckbox("save to file", false);
gd.showDialog();
if (gd.wasCanceled()) return;
int w = (int)gd.getNextNumber();
int h = (int)gd.getNextNumber();
int type = 0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB;
double scale = gd.getNextNumber();
if (w <=0 || h <=0) {
Utils.log("Invalid width or height: " + w + ", " + h);
return;
}
if (0 == scale || Double.isNaN(scale)) {
Utils.log("Invalid scale: " + scale);
return;
}
String dir = null;
if (gd.getNextBoolean()) {
DirectoryChooser dc = new DirectoryChooser("Target directory");
dir = dc.getDirectory();
if (null == dir) return; // canceled
dir = Utils.fixDir(dir);
}
ImagePlus imp = ((Tree)active).flyThroughMarked(w, h, scale/100, type, dir);
if (null == imp) {
Utils.log("Mark a node first!");
return;
}
imp.show();
}
}, project);
} else if (command.startsWith("Arealists as labels")) {
GenericDialog gd = new GenericDialog("Export labels");
gd.addSlider("Scale: ", 1, 100, 100);
final String[] options = {"All area list", "Selected area lists"};
gd.addChoice("Export: ", options, options[0]);
Utils.addLayerRangeChoices(layer, gd);
gd.addCheckbox("Visible only", true);
gd.showDialog();
if (gd.wasCanceled()) return;
final float scale = (float)(gd.getNextNumber() / 100);
java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class);
if (null == al) {
Utils.log("No area lists found to export.");
return;
}
// Generics are ... a pain? I don't understand them? They fail when they shouldn't? And so easy to workaround that they are a shame?
al = (java.util.List<Displayable>) al;
int first = gd.getNextChoiceIndex();
int last = gd.getNextChoiceIndex();
boolean visible_only = gd.getNextBoolean();
if (-1 != command.indexOf("(amira)")) {
AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, true, true);
} else if (-1 != command.indexOf("(tif)")) {
AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, false, false);
}
} else if (command.equals("Project properties...")) {
project.adjustProperties();
} else if (command.equals("Release memory...")) {
Bureaucrat.createAndStart(new Worker("Releasing memory") {
public void run() {
startedWorking();
try {
GenericDialog gd = new GenericDialog("Release Memory");
int max = (int)(IJ.maxMemory() / 1000000);
gd.addSlider("Megabytes: ", 0, max, max/2);
gd.showDialog();
if (!gd.wasCanceled()) {
int n_mb = (int)gd.getNextNumber();
project.getLoader().releaseToFit((long)n_mb*1000000);
}
} catch (Throwable e) {
IJError.print(e);
} finally {
finishedWorking();
}
}
}, project);
} else if (command.equals("Flush image cache")) {
Loader.releaseAllCaches();
} else if (command.equals("Regenerate all mipmaps")) {
project.getLoader().regenerateMipMaps(getLayerSet().getDisplayables(Patch.class));
} else if (command.equals("Regenerate mipmaps (selected images)")) {
project.getLoader().regenerateMipMaps(selection.getSelected(Patch.class));
} else if (command.equals("Tags...")) {
// get a file first
File f = Utils.chooseFile(null, "tags", ".xml");
if (null == f) return;
if (!Utils.saveToFile(f, getLayerSet().exportTags())) {
Utils.logAll("ERROR when saving tags to file " + f.getAbsolutePath());
}
} else if (command.equals("Tags ...")) {
String[] ff = Utils.selectFile("Import tags");
if (null == ff) return;
GenericDialog gd = new GenericDialog("Import tags");
String[] modes = new String[]{"Append to current tags", "Replace current tags"};
gd.addChoice("Import tags mode:", modes, modes[0]);
gd.addMessage("Replacing current tags\nwill remove all tags\n from all nodes first!");
gd.showDialog();
if (gd.wasCanceled()) return;
getLayerSet().importTags(new StringBuilder(ff[0]).append('/').append(ff[1]).toString(), 1 == gd.getNextChoiceIndex());
} else {
Utils.log2("Display: don't know what to do with command " + command);
}
}});
| public void actionPerformed(final ActionEvent ae) {
dispatcher.exec(new Runnable() { public void run() {
String command = ae.getActionCommand();
if (command.startsWith("Job")) {
if (Utils.checkYN("Really cancel job?")) {
project.getLoader().quitJob(command);
repairGUI();
}
return;
} else if (command.equals("Move to top")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.TOP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move up")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.UP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move down")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.DOWN, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move to bottom")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.BOTTOM, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Duplicate, link and send to next layer")) {
duplicateLinkAndSendTo(active, 1, layer.getParent().next(layer));
} else if (command.equals("Duplicate, link and send to previous layer")) {
duplicateLinkAndSendTo(active, 0, layer.getParent().previous(layer));
} else if (command.equals("Duplicate, link and send to...")) {
// fix non-scrolling popup menu
GenericDialog gd = new GenericDialog("Send to");
gd.addMessage("Duplicate, link and send to...");
String[] sl = new String[layer.getParent().size()];
int next = 0;
for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) {
sl[next++] = project.findLayerThing(it.next()).toString();
}
gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex());
if (layer == la) {
Utils.showMessage("Can't duplicate, link and send to the same layer.");
return;
}
duplicateLinkAndSendTo(active, 0, la);
} else if (-1 != command.indexOf("z = ")) {
// this is an item from the "Duplicate, link and send to" menu of layer z's
Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1)));
Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__");
if (null == target_layer) return;
duplicateLinkAndSendTo(active, 0, target_layer);
} else if (-1 != command.indexOf("z=")) {
// WARNING the indexOf is very similar to the previous one
// Send the linked group to the selected layer
int iz = command.indexOf("z=")+2;
Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2));
int end = command.indexOf(' ', iz);
if (-1 == end) end = command.length();
double lz = Double.parseDouble(command.substring(iz, end));
Layer target = layer.getParent().getLayer(lz);
layer.getParent().move(selection.getAffected(), active.getLayer(), target); // TODO what happens when ZDisplayable are selected?
} else if (command.equals("Unlink")) {
if (null == active || active instanceof Patch) return;
active.unlink();
updateSelection();//selection.update();
} else if (command.equals("Unlink from images")) {
if (null == active) return;
try {
for (Displayable displ: selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
} else if (command.equals("Unlink slices")) {
YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo.");
if (!yn.yesPressed()) return;
final ArrayList<Patch> pa = ((Patch)active).getStackPatches();
for (int i=pa.size()-1; i>0; i--) {
pa.get(i).unlink(pa.get(i-1));
}
} else if (command.equals("Send to next layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
for (final Displayable displ : selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveDown(layer, active); // will repaint whatever appropriate layers
selection.moveDown();
repaint(layer.getParent(), box);
} else if (command.equals("Send to previous layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
for (final Displayable displ : selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveUp(layer, active); // will repaint whatever appropriate layers
selection.moveUp();
repaint(layer.getParent(), box);
} else if (command.equals("Show centered")) {
if (active == null) return;
showCentered(active);
} else if (command.equals("Delete...")) {
/*
if (null != active) {
Displayable d = active;
selection.remove(d);
d.remove(true); // will repaint
}
*/
// remove all selected objects
selection.deleteAll();
} else if (command.equals("Color...")) {
IJ.doCommand("Color Picker...");
} else if (command.equals("Revert")) {
if (null == active || active.getClass() != Patch.class) return;
Patch p = (Patch)active;
if (!p.revert()) {
if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId());
else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId());
}
} else if (command.equals("Remove alpha mask")) {
final ArrayList<Displayable> patches = selection.getSelected(Patch.class);
if (patches.size() > 0) {
Bureaucrat.createAndStart(new Worker.Task("Removing alpha mask" + (patches.size() > 1 ? "s" : "")) { public void exec() {
final ArrayList<Future> jobs = new ArrayList<Future>();
for (final Displayable d : patches) {
final Patch p = (Patch) d;
p.setAlphaMask(null);
Future job = p.getProject().getLoader().regenerateMipMaps(p); // submit to queue
if (null != job) jobs.add(job);
}
// join all
for (final Future job : jobs) try {
job.get();
} catch (Exception ie) {}
}}, patches.get(0).getProject());
}
} else if (command.equals("Undo")) {
Bureaucrat.createAndStart(new Worker.Task("Undo") { public void exec() {
layer.getParent().undoOneStep();
Display.repaint(layer.getParent());
}}, project);
} else if (command.equals("Redo")) {
Bureaucrat.createAndStart(new Worker.Task("Redo") { public void exec() {
layer.getParent().redoOneStep();
Display.repaint(layer.getParent());
}}, project);
} else if (command.equals("Apply transform")) {
canvas.applyTransform();
} else if (command.equals("Apply transform propagating to last layer")) {
if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) {
final java.util.List<Layer> layers = layer.getParent().getLayers();
final HashSet<Layer> subset = new HashSet<Layer>(layers.subList(layers.indexOf(Display.this.layer)+1, layers.size())); // +1 to exclude current layer
if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset);
else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset);
setMode(new DefaultMode(Display.this));
}
} else if (command.equals("Apply transform propagating to first layer")) {
if (mode.getClass() == AffineTransformMode.class || mode.getClass() == NonLinearTransformMode.class) {
final java.util.List<Layer> layers = layer.getParent().getLayers();
final HashSet<Layer> subset = new HashSet<Layer>(layers.subList(0, layers.indexOf(Display.this.layer)));
if (mode.getClass() == AffineTransformMode.class) ((AffineTransformMode)mode).applyAndPropagate(subset);
else if (mode.getClass() == NonLinearTransformMode.class) ((NonLinearTransformMode)mode).apply(subset);
setMode(new DefaultMode(Display.this));
}
} else if (command.equals("Cancel transform")) {
canvas.cancelTransform(); // calls getMode().cancel()
} else if (command.equals("Specify transform...")) {
if (null == active) return;
selection.specify();
} else if (command.equals("Hide all but images")) {
ArrayList<Class> type = new ArrayList<Class>();
type.add(Patch.class);
type.add(Stack.class);
Collection<Displayable> col = layer.getParent().hideExcept(type, false);
selection.removeAll(col);
Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE);
Display.update(layer.getParent(), false);
} else if (command.equals("Unhide all")) {
Display.updateCheckboxes(layer.getParent().setAllVisible(false), DisplayablePanel.VISIBILITY_STATE);
Display.update(layer.getParent(), false);
} else if (command.startsWith("Hide all ")) {
String type = command.substring(9, command.length() -1); // skip the ending plural 's'
Collection<Displayable> col = layer.getParent().setVisible(type, false, true);
selection.removeAll(col);
Display.updateCheckboxes(col, DisplayablePanel.VISIBILITY_STATE);
} else if (command.startsWith("Unhide all ")) {
String type = command.substring(11, command.length() -1); // skip the ending plural 's'
type = type.substring(0, 1).toUpperCase() + type.substring(1);
updateCheckboxes(layer.getParent().setVisible(type, true, true), DisplayablePanel.VISIBILITY_STATE);
} else if (command.equals("Hide deselected")) {
hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers()));
} else if (command.equals("Hide deselected except images")) {
hideDeselected(true);
} else if (command.equals("Hide selected")) {
selection.setVisible(false); // TODO should deselect them too? I don't think so.
Display.updateCheckboxes(selection.getSelected(), DisplayablePanel.VISIBILITY_STATE);
} else if (command.equals("Resize canvas/LayerSet...")) {
resizeCanvas();
} else if (command.equals("Autoresize canvas/LayerSet")) {
layer.getParent().setMinimumDimensions();
} else if (command.equals("Import image")) {
importImage();
} else if (command.equals("Import next image")) {
importNextImage();
} else if (command.equals("Import stack...")) {
Display.this.getLayerSet().addChangeTreesStep();
Rectangle sr = getCanvas().getSrcRect();
Bureaucrat burro = project.getLoader().importStack(layer, sr.x + sr.width/2, sr.y + sr.height/2, null, true, null, false);
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Import stack with landmarks...")) {
// 1 - Find out if there's any other project open
List<Project> pr = Project.getProjects();
if (1 == pr.size()) {
Utils.logAll("Need another project open!");
return;
}
// 2 - Ask for a "landmarks" type
GenericDialog gd = new GenericDialog("Landmarks");
gd.addStringField("landmarks type:", "landmarks");
final String[] none = {"-- None --"};
final Hashtable<String,Project> mpr = new Hashtable<String,Project>();
for (Project p : pr) {
if (p == project) continue;
mpr.put(p.toString(), p);
}
final String[] project_titles = mpr.keySet().toArray(new String[0]);
final Hashtable<String,ProjectThing> map_target = findLandmarkNodes(project, "landmarks");
String[] target_landmark_titles = map_target.isEmpty() ? none : map_target.keySet().toArray(new String[0]);
gd.addChoice("Landmarks node in this project:", target_landmark_titles, target_landmark_titles[0]);
gd.addMessage("");
gd.addChoice("Source project:", project_titles, project_titles[0]);
final Hashtable<String,ProjectThing> map_source = findLandmarkNodes(mpr.get(project_titles[0]), "landmarks");
String[] source_landmark_titles = map_source.isEmpty() ? none : map_source.keySet().toArray(new String[0]);
gd.addChoice("Landmarks node in source project:", source_landmark_titles, source_landmark_titles[0]);
final List<Patch> stacks = Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet());
String[] stack_titles;
if (stacks.isEmpty()) {
if (1 == mpr.size()) {
IJ.showMessage("Project " + project_titles[0] + " does not contain any Stack.");
return;
}
stack_titles = none;
} else {
stack_titles = new String[stacks.size()];
int next = 0;
for (Patch pa : stacks) stack_titles[next++] = pa.toString();
}
gd.addChoice("Stacks:", stack_titles, stack_titles[0]);
Vector vc = gd.getChoices();
final Choice choice_target_landmarks = (Choice) vc.get(0);
final Choice choice_source_projects = (Choice) vc.get(1);
final Choice choice_source_landmarks = (Choice) vc.get(2);
final Choice choice_stacks = (Choice) vc.get(3);
final TextField input = (TextField) gd.getStringFields().get(0);
input.addTextListener(new TextListener() {
public void textValueChanged(TextEvent te) {
final String text = input.getText();
update(choice_target_landmarks, Display.this.project, text, map_target);
update(choice_source_landmarks, mpr.get(choice_source_projects.getSelectedItem()), text, map_source);
}
private void update(Choice c, Project p, String type, Hashtable<String,ProjectThing> table) {
table.clear();
table.putAll(findLandmarkNodes(p, type));
c.removeAll();
if (table.isEmpty()) c.add(none[0]);
else for (String t : table.keySet()) c.add(t);
}
});
choice_source_projects.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String item = (String) e.getItem();
Project p = mpr.get(choice_source_projects.getSelectedItem());
// 1 - Update choice of landmark items
map_source.clear();
map_source.putAll(findLandmarkNodes(p, input.getText()));
choice_target_landmarks.removeAll();
if (map_source.isEmpty()) choice_target_landmarks.add(none[0]);
else for (String t : map_source.keySet()) choice_target_landmarks.add(t);
// 2 - Update choice of Stack items
stacks.clear();
choice_stacks.removeAll();
stacks.addAll(Display.getPatchStacks(mpr.get(project_titles[0]).getRootLayerSet()));
if (stacks.isEmpty()) choice_stacks.add(none[0]);
else for (Patch pa : stacks) choice_stacks.add(pa.toString());
}
});
gd.showDialog();
if (gd.wasCanceled()) return;
String type = gd.getNextString();
if (null == type || 0 == type.trim().length()) {
Utils.log("Invalid landmarks node type!");
return;
}
ProjectThing target_landmarks_node = map_target.get(gd.getNextChoice());
Project source = mpr.get(gd.getNextChoice());
ProjectThing source_landmarks_node = map_source.get(gd.getNextChoice());
Patch stack_patch = stacks.get(gd.getNextChoiceIndex());
// Store current state
Display.this.getLayerSet().addLayerContentStep(layer);
// Insert stack
insertStack(target_landmarks_node, source, source_landmarks_node, stack_patch);
// Store new state
Display.this.getLayerSet().addChangeTreesStep();
} else if (command.equals("Import grid...")) {
Display.this.getLayerSet().addLayerContentStep(layer);
Bureaucrat burro = project.getLoader().importGrid(layer);
if (null != burro)
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addLayerContentStep(layer);
}});
} else if (command.equals("Import sequence as grid...")) {
Display.this.getLayerSet().addChangeTreesStep();
Bureaucrat burro = project.getLoader().importSequenceAsGrid(layer);
if (null != burro)
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Import from text file...")) {
Display.this.getLayerSet().addChangeTreesStep();
Bureaucrat burro = project.getLoader().importImages(layer);
if (null != burro)
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Import labels as arealists...")) {
Display.this.getLayerSet().addChangeTreesStep();
Bureaucrat burro = project.getLoader().importLabelsAsAreaLists(layer, null, Double.MAX_VALUE, 0, 0.4f, false);
burro.addPostTask(new Runnable() { public void run() {
Display.this.getLayerSet().addChangeTreesStep();
}});
} else if (command.equals("Make flat image...")) {
// if there's a ROI, just use that as cropping rectangle
Rectangle srcRect = null;
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null != roi) {
srcRect = roi.getBounds();
} else {
// otherwise, whatever is visible
//srcRect = canvas.getSrcRect();
// The above is confusing. That is what ROIs are for. So paint all:
srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight()));
}
double scale = 1.0;
final String[] types = new String[]{"8-bit grayscale", "RGB Color"};
int the_type = ImagePlus.GRAY8;
final GenericDialog gd = new GenericDialog("Choose", frame);
gd.addSlider("Scale: ", 1, 100, 100);
gd.addNumericField("Width: ", srcRect.width, 0);
gd.addNumericField("height: ", srcRect.height, 0);
// connect the above 3 fields:
Vector numfields = gd.getNumericFields();
UpdateDimensionField udf = new UpdateDimensionField(srcRect.width, srcRect.height, (TextField) numfields.get(1), (TextField) numfields.get(2), (TextField) numfields.get(0), (Scrollbar) gd.getSliders().get(0));
for (Object ob : numfields) ((TextField)ob).addTextListener(udf);
gd.addChoice("Type: ", types, types[0]);
if (layer.getParent().size() > 1) {
Utils.addLayerRangeChoices(Display.this.layer, gd); /// $#%! where are my lisp macros
gd.addCheckbox("Include non-empty layers only", true);
}
gd.addMessage("Background color:");
Utils.addRGBColorSliders(gd, Color.black);
gd.addCheckbox("Best quality", false);
gd.addMessage("");
gd.addCheckbox("Save to file", false);
gd.addCheckbox("Save for web", false);
gd.showDialog();
if (gd.wasCanceled()) return;
scale = gd.getNextNumber() / 100;
the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB);
if (Double.isNaN(scale) || scale <= 0.0) {
Utils.showMessage("Invalid scale.");
return;
}
// consuming and ignoring width and height:
gd.getNextNumber();
gd.getNextNumber();
Layer[] layer_array = null;
boolean non_empty_only = false;
if (layer.getParent().size() > 1) {
non_empty_only = gd.getNextBoolean();
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
ArrayList al = new ArrayList();
ArrayList al_zd = layer.getParent().getZDisplayables();
ZDisplayable[] zd = new ZDisplayable[al_zd.size()];
al_zd.toArray(zd);
for (int i=i_start, j=0; i <= i_end; i++, j++) {
Layer la = layer.getParent().getLayer(i);
if (!la.isEmpty() || !non_empty_only) al.add(la); // checks both the Layer and the ZDisplayable objects in the parent LayerSet
}
if (0 == al.size()) {
Utils.showMessage("All layers are empty!");
return;
}
layer_array = new Layer[al.size()];
al.toArray(layer_array);
} else {
layer_array = new Layer[]{Display.this.layer};
}
final Color background = new Color((int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber());
final boolean quality = gd.getNextBoolean();
final boolean save_to_file = gd.getNextBoolean();
final boolean save_for_web = gd.getNextBoolean();
// in its own thread
if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type);
else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality, background);
} else if (command.equals("Lock")) {
selection.setLocked(true);
Utils.revalidateComponent(tabs.getSelectedComponent());
} else if (command.equals("Unlock")) {
selection.setLocked(false);
Utils.revalidateComponent(tabs.getSelectedComponent());
} else if (command.equals("Properties...")) {
active.adjustProperties();
updateSelection();
} else if (command.equals("Show current 2D position in 3D")) {
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
Display3D.addFatPoint("Current 2D Position", getLayerSet(), p.x, p.y, layer.getZ(), 10, Color.magenta);
} else if (command.equals("Align stack slices")) {
if (getActive() instanceof Patch) {
final Patch slice = (Patch)getActive();
if (slice.isStack()) {
// check linked group
final HashSet hs = slice.getLinkedGroup(new HashSet());
for (Iterator it = hs.iterator(); it.hasNext(); ) {
if (it.next().getClass() != Patch.class) {
Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); // labels should be fine, need to check that
return;
}
}
final LayerSet ls = slice.getLayerSet();
final HashSet<Displayable> linked = slice.getLinkedGroup(null);
ls.addTransformStepWithData(linked);
Bureaucrat burro = AlignTask.registerStackSlices((Patch)getActive()); // will repaint
burro.addPostTask(new Runnable() { public void run() {
ls.enlargeToFit(linked);
// The current state when done
ls.addTransformStepWithData(linked);
}});
} else {
Utils.log("Align stack slices: selected image is not part of a stack.");
}
}
} else if (command.equals("Align layers with manual landmarks")) {
setMode(new ManualAlignMode(Display.this));
} else if (command.equals("Align layers")) {
final Layer la = layer; // caching, since scroll wheel may change it
la.getParent().addTransformStep(la.getParent().getLayers());
Bureaucrat burro = AlignLayersTask.alignLayersTask( la );
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class));
la.getParent().addTransformStep(la.getParent().getLayers());
}});
} else if (command.equals("Align multi-layer mosaic")) {
final Layer la = layer; // caching, since scroll wheel may change it
la.getParent().addTransformStep();
Bureaucrat burro = AlignTask.alignMultiLayerMosaicTask( la );
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().enlargeToFit(getLayerSet().getDisplayables(Patch.class));
la.getParent().addTransformStep();
}});
} else if (command.equals("Montage all images in this layer")) {
final Layer la = layer;
final List<Patch> patches = new ArrayList<Patch>( (List<Patch>) (List) la.getDisplayables(Patch.class));
if (patches.size() < 2) {
Utils.showMessage("Montage needs 2 or more images selected");
return;
}
final Collection<Displayable> col = la.getParent().addTransformStepWithData(Arrays.asList(new Layer[]{la}));
Bureaucrat burro = AlignTask.alignPatchesTask(patches, Arrays.asList(new Patch[]{patches.get(0)}));
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().enlargeToFit(patches);
la.getParent().addTransformStepWithData(col);
}});
} else if (command.equals("Montage selected images (SIFT)")) {
montage(0);
} else if (command.equals("Montage selected images (phase correlation)")) {
montage(1);
} else if (command.equals("Montage multiple layers (phase correlation)")) {
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex());
final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers);
Bureaucrat burro = StitchingTEM.montageWithPhaseCorrelation(layers);
if (null == burro) return;
burro.addPostTask(new Runnable() { public void run() {
Collection<Displayable> ds = new ArrayList<Displayable>();
for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class));
getLayerSet().enlargeToFit(ds);
getLayerSet().addTransformStepWithData(col);
}});
} else if (command.equals("Montage multiple layers (SIFT)")) {
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final List<Layer> layers = getLayerSet().getLayers(gd.getNextChoiceIndex(), gd.getNextChoiceIndex());
final Collection<Displayable> col = getLayerSet().addTransformStepWithData(layers);
Bureaucrat burro = AlignTask.montageLayersTask(layers);
burro.addPostTask(new Runnable() { public void run() {
Collection<Displayable> ds = new ArrayList<Displayable>();
for (Layer la : layers) ds.addAll(la.getDisplayables(Patch.class));
getLayerSet().enlargeToFit(ds);
getLayerSet().addTransformStepWithData(col);
}});
} else if (command.equals("Properties ...")) { // NOTE the space before the dots, to distinguish from the "Properties..." command that works on Displayable objects.
GenericDialog gd = new GenericDialog("Properties", Display.this.frame);
//gd.addNumericField("layer_scroll_step: ", this.scroll_step, 0);
gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step);
gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]);
gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality());
Loader lo = getProject().getLoader();
boolean using_mipmaps = lo.isMipMapsEnabled();
gd.addCheckbox("enable_mipmaps", using_mipmaps);
gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled());
double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight();
gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsMaxDimension());
gd.addCheckbox("Show arrow heads in Treeline/AreaTree", layer.getParent().paint_arrows);
gd.addCheckbox("Show edge confidence boxes in Treeline/AreaTree", layer.getParent().paint_edge_confidence_boxes);
gd.addCheckbox("Show color cues", layer.getParent().color_cues);
gd.addSlider("+/- layers to color cue", 0, 10, layer.getParent().n_layers_color_cue);
// --------
gd.showDialog();
if (gd.wasCanceled()) return;
// --------
int sc = (int) gd.getNextNumber();
if (sc < 1) sc = 1;
Display.this.scroll_step = sc;
updateInDatabase("scroll_step");
//
layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex());
layer.getParent().setSnapshotsQuality(gd.getNextBoolean());
//
boolean generate_mipmaps = gd.getNextBoolean();
if (using_mipmaps && generate_mipmaps) {
// nothing changed
} else {
if (using_mipmaps) { // and !generate_mipmaps
lo.flushMipMaps(true);
} else {
// not using mipmaps before, and true == generate_mipmaps
lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class));
}
}
//
layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean());
layer.getParent().setPixelsMaxDimension((int)gd.getNextNumber());
layer.getParent().paint_arrows = gd.getNextBoolean();
layer.getParent().paint_edge_confidence_boxes = gd.getNextBoolean();
layer.getParent().color_cues = gd.getNextBoolean();
layer.getParent().n_layers_color_cue = (int)gd.getNextNumber();
Display.repaint(layer.getParent());
} else if (command.equals("Adjust snapping parameters...")) {
AlignTask.p_snap.setup("Snap");
} else if (command.equals("Adjust fast-marching parameters...")) {
Segmentation.fmp.setup();
} else if (command.equals("Adjust arealist paint parameters...")) {
AreaWrapper.PP.setup();
} else if (command.equals("Search...")) {
new Search();
} else if (command.equals("Select all")) {
selection.selectAll();
repaint(Display.this.layer, selection.getBox(), 0);
} else if (command.equals("Select all visible")) {
selection.selectAllVisible();
repaint(Display.this.layer, selection.getBox(), 0);
} else if (command.equals("Select none")) {
Rectangle box = selection.getBox();
selection.clear();
repaint(Display.this.layer, box, 0);
} else if (command.equals("Restore selection")) {
selection.restore();
} else if (command.equals("Select under ROI")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return;
selection.selectAll(roi, true);
} else if (command.equals("Merge")) {
Bureaucrat burro = Bureaucrat.create(new Worker.Task("Merging AreaLists") {
public void exec() {
ArrayList al_sel = selection.getSelected(AreaList.class);
// put active at the beginning, to work as the base on which other's will get merged
al_sel.remove(Display.this.active);
al_sel.add(0, Display.this.active);
Set<DoStep> dataedits = new HashSet<DoStep>();
dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"}));
getLayerSet().addChangeTreesStep(dataedits);
AreaList ali = AreaList.merge(al_sel);
if (null != ali) {
// remove all but the first from the selection
for (int i=1; i<al_sel.size(); i++) {
Object ob = al_sel.get(i);
if (ob.getClass() == AreaList.class) {
selection.remove((Displayable)ob);
}
}
selection.updateTransform(ali);
repaint(ali.getLayerSet(), ali, 0);
}
}
}, Display.this.project);
burro.addPostTask(new Runnable() { public void run() {
Set<DoStep> dataedits = new HashSet<DoStep>();
dataedits.add(new Displayable.DoEdit(Display.this.active).init(Display.this.active, new String[]{"data"}));
getLayerSet().addChangeTreesStep(dataedits);
}});
burro.goHaveBreakfast();
} else if (command.equals("Reroot")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
getLayerSet().addDataEditStep(active);
((Tree)active).reRoot(p.x, p.y, layer, canvas.getMagnification());
getLayerSet().addDataEditStep(active);
Display.repaint(getLayerSet());
} else if (command.equals("Part subtree")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
List<Tree> ts = ((Tree)active).splitNear(p.x, p.y, layer, canvas.getMagnification());
if (null == ts) return;
Displayable elder = Display.this.active;
for (Tree t : ts) {
if (t == elder) continue;
getLayerSet().add(t); // will change Display.this.active !
project.getProjectTree().addSibling(elder, t);
}
selection.clear();
selection.selectAll(ts);
selection.add(elder);
getLayerSet().addChangeTreesStep();
Display.repaint(getLayerSet());
} else if (command.equals("Show tabular view")) {
if (!(active instanceof Tree)) return;
((Tree)active).createMultiTableView();
} else if (command.equals("Mark")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
if (((Tree)active).markNear(p.x, p.y, layer, canvas.getMagnification())) {
Display.repaint(getLayerSet());
}
} else if (command.equals("Clear marks (selected Trees)")) {
for (Displayable d : selection.getSelected(Tree.class)) {
((Tree)d).unmark();
}
Display.repaint(getLayerSet());
} else if (command.equals("Join")) {
if (!(active instanceof Tree)) return;
final List<Tree> tlines = (List<Tree>) (List) selection.getSelected(Treeline.class);
if (((Tree)active).canJoin(tlines)) {
// Record current state
class State {{
Set<DoStep> dataedits = new HashSet<DoStep>();
for (final Tree tl : tlines) {
dataedits.add(new Displayable.DoEdit(tl).init(tl, new String[]{"data"}));
}
getLayerSet().addChangeTreesStep(dataedits);
}};
new State();
//
((Tree)active).join(tlines);
for (final Tree tl : tlines) {
if (tl == active) continue;
tl.remove2(false);
}
Display.repaint(getLayerSet());
// Again, to record current state
new State();
}
} else if (command.equals("Previous branch point or start")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
center(((Treeline)active).findPreviousBranchOrRootPoint(p.x, p.y, layer, canvas.getMagnification()));
} else if (command.equals("Next branch point or end")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
center(((Tree)active).findNextBranchOrEndPoint(p.x, p.y, layer, canvas.getMagnification()));
} else if (command.equals("Root")) {
if (!(active instanceof Tree)) return;
Point p = canvas.consumeLastPopupPoint();
if (null == p) return;
center(((Tree)active).createCoordinate(((Tree)active).getRoot()));
} else if (command.equals("Last added point")) {
if (!(active instanceof Tree)) return;
center(((Treeline)active).getLastAdded());
} else if (command.equals("Last edited point")) {
if (!(active instanceof Tree)) return;
center(((Treeline)active).getLastEdited());
} else if (command.equals("Reverse point order")) {
if (!(active instanceof Pipe)) return;
getLayerSet().addDataEditStep(active);
((Pipe)active).reverse();
Display.repaint(Display.this.layer);
getLayerSet().addDataEditStep(active);
} else if (command.equals("View orthoslices")) {
if (!(active instanceof Patch)) return;
Display3D.showOrthoslices(((Patch)active));
} else if (command.equals("View volume")) {
if (!(active instanceof Patch)) return;
Display3D.showVolume(((Patch)active));
} else if (command.equals("Show in 3D")) {
for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) {
ZDisplayable zd = (ZDisplayable)it.next();
Display3D.show(zd.getProject().findProjectThing(zd));
}
// handle profile lists ...
HashSet hs = new HashSet();
for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) {
Displayable d = (Displayable)it.next();
ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent();
if (!hs.contains(profile_list)) {
Display3D.show(profile_list);
hs.add(profile_list);
}
}
} else if (command.equals("Snap")) {
// Take the active if it's a Patch
if (!(active instanceof Patch)) return;
Display.snap((Patch)active);
} else if (command.equals("Blend")) {
HashSet<Patch> patches = new HashSet<Patch>();
for (final Displayable d : selection.getSelected()) {
if (d.getClass() == Patch.class) patches.add((Patch)d);
}
if (patches.size() > 1) {
GenericDialog gd = new GenericDialog("Blending");
gd.addCheckbox("Respect current alpha mask", true);
gd.showDialog();
if (gd.wasCanceled()) return;
Blending.blend(patches, gd.getNextBoolean());
} else {
IJ.log("Please select more than one overlapping image.");
}
} else if (command.equals("Montage")) {
final Set<Displayable> affected = new HashSet<Displayable>(selection.getAffected());
// make an undo step!
final LayerSet ls = layer.getParent();
ls.addTransformStepWithData(affected);
Bureaucrat burro = AlignTask.alignSelectionTask( selection );
burro.addPostTask(new Runnable() { public void run() {
ls.enlargeToFit(affected);
ls.addTransformStepWithData(affected);
}});
} else if (command.equals("Lens correction")) {
final Layer la = layer;
la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables()));
Bureaucrat burro = DistortionCorrectionTask.correctDistortionFromSelection( selection );
burro.addPostTask(new Runnable() { public void run() {
// no means to know which where modified and from which layers!
la.getParent().addDataEditStep(new HashSet<Displayable>(la.getParent().getDisplayables()));
}});
} else if (command.equals("Link images...")) {
GenericDialog gd = new GenericDialog("Options");
gd.addMessage("Linking images to images (within their own layer only):");
String[] options = {"all images to all images", "each image with any other overlapping image"};
gd.addChoice("Link: ", options, options[1]);
String[] options2 = {"selected images only", "all images in this layer", "all images in all layers, within the layer only", "all images in all layers, within and across consecutive layers"};
gd.addChoice("Apply to: ", options2, options2[0]);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer lay = layer;
final HashSet<Displayable> ds = new HashSet<Displayable>(lay.getParent().getDisplayables());
lay.getParent().addDataEditStep(ds, new String[]{"data"});
boolean overlapping_only = 1 == gd.getNextChoiceIndex();
Collection<Displayable> coll = null;
switch (gd.getNextChoiceIndex()) {
case 0:
coll = selection.getSelected(Patch.class);
Patch.crosslink(coll, overlapping_only);
break;
case 1:
coll = lay.getDisplayables(Patch.class);
Patch.crosslink(coll, overlapping_only);
break;
case 2:
coll = new ArrayList<Displayable>();
for (final Layer la : lay.getParent().getLayers()) {
Collection<Displayable> acoll = la.getDisplayables(Patch.class);
Patch.crosslink(acoll, overlapping_only);
coll.addAll(acoll);
}
break;
case 3:
ArrayList<Layer> layers = lay.getParent().getLayers();
Collection<Displayable> lc1 = layers.get(0).getDisplayables(Patch.class);
if (lay == layers.get(0)) coll = lc1;
for (int i=1; i<layers.size(); i++) {
Collection<Displayable> lc2 = layers.get(i).getDisplayables(Patch.class);
if (null == coll && Display.this.layer == layers.get(i)) coll = lc2;
Collection<Displayable> both = new ArrayList<Displayable>();
both.addAll(lc1);
both.addAll(lc2);
Patch.crosslink(both, overlapping_only);
lc1 = lc2;
}
break;
}
if (null != coll) Display.updateCheckboxes(coll, DisplayablePanel.LINK_STATE, true);
lay.getParent().addDataEditStep(ds);
} else if (command.equals("Unlink all selected images")) {
if (Utils.check("Really unlink selected images?")) {
for (final Displayable d : selection.getSelected(Patch.class)) {
d.unlink();
}
}
} else if (command.equals("Unlink all")) {
if (Utils.check("Really unlink all objects from all layers?")) {
for (final Displayable d : layer.getParent().getDisplayables()) {
d.unlink();
}
}
} else if (command.equals("Calibration...")) {
try {
IJ.run(canvas.getFakeImagePlus(), "Properties...", "");
Display.updateTitle(getLayerSet());
} catch (RuntimeException re) {
Utils.log2("Calibration dialog canceled.");
}
} else if (command.equals("Grid overlay...")) {
if (null == gridoverlay) gridoverlay = new GridOverlay();
gridoverlay.setup(canvas.getFakeImagePlus().getRoi());
canvas.invalidateVolatile();
canvas.repaint(false);
} else if (command.equals("Enhance contrast (selected images)...")) {
final Layer la = layer;
ArrayList<Displayable> selected = selection.getSelected(Patch.class);
final HashSet<Displayable> ds = new HashSet<Displayable>(selected);
la.getParent().addDataEditStep(ds);
Displayable active = Display.this.getActive();
Patch ref = active.getClass() == Patch.class ? (Patch)active : null;
Bureaucrat burro = getProject().getLoader().enhanceContrast(selected, ref);
burro.addPostTask(new Runnable() { public void run() {
la.getParent().addDataEditStep(ds);
}});
} else if (command.equals("Enhance contrast layer-wise...")) {
// ask for range of layers
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
java.util.List<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end
final HashSet<Displayable> ds = new HashSet<Displayable>();
for (final Layer l : layers) ds.addAll(l.getDisplayables(Patch.class));
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().enhanceContrast(layers);
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Set Min and Max layer-wise...")) {
Displayable active = getActive();
double min = 0;
double max = 0;
if (null != active && active.getClass() == Patch.class) {
min = ((Patch)active).getMin();
max = ((Patch)active).getMax();
}
final GenericDialog gd = new GenericDialog("Min and Max");
gd.addMessage("Set min and max to all images in the layer range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.addNumericField("min: ", min, 2);
gd.addNumericField("max: ", max, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
//
min = gd.getNextNumber();
max = gd.getNextNumber();
ArrayList<Displayable> al = new ArrayList<Displayable>();
for (final Layer la : layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1)) { // exclusive end
al.addAll(la.getDisplayables(Patch.class));
}
final HashSet<Displayable> ds = new HashSet<Displayable>(al);
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().setMinAndMax(al, min, max);
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Set Min and Max (selected images)...")) {
Displayable active = getActive();
double min = 0;
double max = 0;
if (null != active && active.getClass() == Patch.class) {
min = ((Patch)active).getMin();
max = ((Patch)active).getMax();
}
final GenericDialog gd = new GenericDialog("Min and Max");
gd.addMessage("Set min and max to all selected images");
gd.addNumericField("min: ", min, 2);
gd.addNumericField("max: ", max, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
//
min = gd.getNextNumber();
max = gd.getNextNumber();
final HashSet<Displayable> ds = new HashSet<Displayable>(selection.getSelected(Patch.class));
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().setMinAndMax(selection.getSelected(Patch.class), min, max);
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Adjust min and max (selected images)...")) {
final List<Displayable> list = selection.getSelected(Patch.class);
if (list.isEmpty()) {
Utils.log("No images selected!");
return;
}
Bureaucrat.createAndStart(new Worker.Task("Init contrast adjustment") {
public void exec() {
try {
setMode(new ContrastAdjustmentMode(Display.this, list));
} catch (Exception e) {
Utils.log("All images must be of the same type!");
}
}
}, list.get(0).getProject());
} else if (command.equals("Mask image borders (layer-wise)...")) {
final GenericDialog gd = new GenericDialog("Mask borders");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.addMessage("Borders:");
gd.addNumericField("left: ", 6, 2);
gd.addNumericField("top: ", 6, 2);
gd.addNumericField("right: ", 6, 2);
gd.addNumericField("bottom: ", 6, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
Collection<Layer> layers = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1);
final HashSet<Displayable> ds = new HashSet<Displayable>();
for (Layer l : layers) ds.addAll(l.getDisplayables(Patch.class));
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().maskBordersLayerWise(layers, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber());
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Mask image borders (selected images)...")) {
final GenericDialog gd = new GenericDialog("Mask borders");
gd.addMessage("Borders:");
gd.addNumericField("left: ", 6, 2);
gd.addNumericField("top: ", 6, 2);
gd.addNumericField("right: ", 6, 2);
gd.addNumericField("bottom: ", 6, 2);
gd.showDialog();
if (gd.wasCanceled()) return;
Collection<Displayable> patches = selection.getSelected(Patch.class);
final HashSet<Displayable> ds = new HashSet<Displayable>(patches);
getLayerSet().addDataEditStep(ds);
Bureaucrat burro = project.getLoader().maskBorders(patches, (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber(), (int)gd.getNextNumber());
burro.addPostTask(new Runnable() { public void run() {
getLayerSet().addDataEditStep(ds);
}});
} else if (command.equals("Duplicate")) {
// only Patch and DLabel, i.e. Layer-only resident objects that don't exist in the Project Tree
final HashSet<Class> accepted = new HashSet<Class>();
accepted.add(Patch.class);
accepted.add(DLabel.class);
accepted.add(Stack.class);
final ArrayList<Displayable> originals = new ArrayList<Displayable>();
final ArrayList<Displayable> selected = selection.getSelected();
for (final Displayable d : selected) {
if (accepted.contains(d.getClass())) {
originals.add(d);
}
}
if (originals.size() > 0) {
getLayerSet().addChangeTreesStep();
for (final Displayable d : originals) {
if (d instanceof ZDisplayable) {
d.getLayerSet().add((ZDisplayable)d.clone());
} else {
d.getLayer().add(d.clone());
}
}
getLayerSet().addChangeTreesStep();
} else if (selected.size() > 0) {
Utils.log("Can only duplicate images and text labels.\nDuplicate *other* objects in the Project Tree.\n");
}
} else if (command.equals("Create subproject")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return; // the menu item is not active unless there is a ROI
Layer first, last;
if (1 == layer.getParent().size()) {
first = last = layer;
} else {
GenericDialog gd = new GenericDialog("Choose layer range");
Utils.addLayerRangeChoices(layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
first = layer.getParent().getLayer(gd.getNextChoiceIndex());
last = layer.getParent().getLayer(gd.getNextChoiceIndex());
Utils.log2("first, last: " + first + ", " + last);
}
Project sub = getProject().createSubproject(roi.getBounds(), first, last);
final LayerSet subls = sub.getRootLayerSet();
Display.createDisplay(sub, subls.getLayer(0));
} else if (command.startsWith("Image stack under selected Arealist")) {
if (null == active || active.getClass() != AreaList.class) return;
GenericDialog gd = new GenericDialog("Stack options");
String[] types = {"8-bit", "16-bit", "32-bit", "RGB"};
gd.addChoice("type:", types, types[0]);
gd.addSlider("Scale: ", 1, 100, 100);
gd.showDialog();
if (gd.wasCanceled()) return;
final int type;
switch (gd.getNextChoiceIndex()) {
case 0: type = ImagePlus.GRAY8; break;
case 1: type = ImagePlus.GRAY16; break;
case 2: type = ImagePlus.GRAY32; break;
case 3: type = ImagePlus.COLOR_RGB; break;
default: type = ImagePlus.GRAY8; break;
}
ImagePlus imp = ((AreaList)active).getStack(type, gd.getNextNumber()/100);
if (null != imp) imp.show();
} else if (command.equals("Fly through selected Treeline/AreaTree")) {
if (null == active || !(active instanceof Tree)) return;
Bureaucrat.createAndStart(new Worker.Task("Creating fly through", true) {
public void exec() {
GenericDialog gd = new GenericDialog("Fly through");
gd.addNumericField("Width", 512, 0);
gd.addNumericField("Height", 512, 0);
String[] types = new String[]{"8-bit gray", "Color RGB"};
gd.addChoice("Image type", types, types[0]);
gd.addSlider("scale", 0, 100, 100);
gd.addCheckbox("save to file", false);
gd.showDialog();
if (gd.wasCanceled()) return;
int w = (int)gd.getNextNumber();
int h = (int)gd.getNextNumber();
int type = 0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB;
double scale = gd.getNextNumber();
if (w <=0 || h <=0) {
Utils.log("Invalid width or height: " + w + ", " + h);
return;
}
if (0 == scale || Double.isNaN(scale)) {
Utils.log("Invalid scale: " + scale);
return;
}
String dir = null;
if (gd.getNextBoolean()) {
DirectoryChooser dc = new DirectoryChooser("Target directory");
dir = dc.getDirectory();
if (null == dir) return; // canceled
dir = Utils.fixDir(dir);
}
ImagePlus imp = ((Tree)active).flyThroughMarked(w, h, scale/100, type, dir);
if (null == imp) {
Utils.log("Mark a node first!");
return;
}
imp.show();
}
}, project);
} else if (command.startsWith("Arealists as labels")) {
GenericDialog gd = new GenericDialog("Export labels");
gd.addSlider("Scale: ", 1, 100, 100);
final String[] options = {"All area list", "Selected area lists"};
gd.addChoice("Export: ", options, options[0]);
Utils.addLayerRangeChoices(layer, gd);
gd.addCheckbox("Visible only", true);
gd.showDialog();
if (gd.wasCanceled()) return;
final float scale = (float)(gd.getNextNumber() / 100);
java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class);
if (null == al) {
Utils.log("No area lists found to export.");
return;
}
// Generics are ... a pain? I don't understand them? They fail when they shouldn't? And so easy to workaround that they are a shame?
al = (java.util.List<Displayable>) al;
int first = gd.getNextChoiceIndex();
int last = gd.getNextChoiceIndex();
boolean visible_only = gd.getNextBoolean();
if (-1 != command.indexOf("(amira)")) {
AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, true, true);
} else if (-1 != command.indexOf("(tif)")) {
AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last, visible_only, false, false);
}
} else if (command.equals("Project properties...")) {
project.adjustProperties();
} else if (command.equals("Release memory...")) {
Bureaucrat.createAndStart(new Worker("Releasing memory") {
public void run() {
startedWorking();
try {
GenericDialog gd = new GenericDialog("Release Memory");
int max = (int)(IJ.maxMemory() / 1000000);
gd.addSlider("Megabytes: ", 0, max, max/2);
gd.showDialog();
if (!gd.wasCanceled()) {
int n_mb = (int)gd.getNextNumber();
project.getLoader().releaseToFit((long)n_mb*1000000);
}
} catch (Throwable e) {
IJError.print(e);
} finally {
finishedWorking();
}
}
}, project);
} else if (command.equals("Flush image cache")) {
Loader.releaseAllCaches();
} else if (command.equals("Regenerate all mipmaps")) {
project.getLoader().regenerateMipMaps(getLayerSet().getDisplayables(Patch.class));
} else if (command.equals("Regenerate mipmaps (selected images)")) {
project.getLoader().regenerateMipMaps(selection.getSelected(Patch.class));
} else if (command.equals("Tags...")) {
// get a file first
File f = Utils.chooseFile(null, "tags", ".xml");
if (null == f) return;
if (!Utils.saveToFile(f, getLayerSet().exportTags())) {
Utils.logAll("ERROR when saving tags to file " + f.getAbsolutePath());
}
} else if (command.equals("Tags ...")) {
String[] ff = Utils.selectFile("Import tags");
if (null == ff) return;
GenericDialog gd = new GenericDialog("Import tags");
String[] modes = new String[]{"Append to current tags", "Replace current tags"};
gd.addChoice("Import tags mode:", modes, modes[0]);
gd.addMessage("Replacing current tags\nwill remove all tags\n from all nodes first!");
gd.showDialog();
if (gd.wasCanceled()) return;
getLayerSet().importTags(new StringBuilder(ff[0]).append('/').append(ff[1]).toString(), 1 == gd.getNextChoiceIndex());
} else {
Utils.log2("Display: don't know what to do with command " + command);
}
}});
|
diff --git a/main/src/main/java/com/chinarewards/qqgbvpn/main/protocol/socket/mina/codec/MessageEncoder.java b/main/src/main/java/com/chinarewards/qqgbvpn/main/protocol/socket/mina/codec/MessageEncoder.java
index 41297128..18d42b86 100644
--- a/main/src/main/java/com/chinarewards/qqgbvpn/main/protocol/socket/mina/codec/MessageEncoder.java
+++ b/main/src/main/java/com/chinarewards/qqgbvpn/main/protocol/socket/mina/codec/MessageEncoder.java
@@ -1,156 +1,156 @@
package com.chinarewards.qqgbvpn.main.protocol.socket.mina.codec;
import java.nio.charset.Charset;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.chinarewards.qqgbvpn.common.Tools;
import com.chinarewards.qqgbvpn.main.protocol.CmdCodecFactory;
import com.chinarewards.qqgbvpn.main.protocol.cmd.ErrorBodyMessage;
import com.chinarewards.qqgbvpn.main.protocol.cmd.HeadMessage;
import com.chinarewards.qqgbvpn.main.protocol.cmd.ICommand;
import com.chinarewards.qqgbvpn.main.protocol.cmd.Message;
import com.chinarewards.qqgbvpn.main.protocol.socket.ProtocolLengths;
import com.chinarewards.qqgbvpn.main.session.SessionKeyCodec;
public class MessageEncoder implements ProtocolEncoder {
private Logger log = LoggerFactory.getLogger(getClass());
private Charset charset;
private PackageHeadCodec packageHeadCodec;
protected CmdCodecFactory cmdCodecFactory;
SessionKeyCodec skCodec = new SessionKeyCodec();
/**
* XXX can 'injector' be skipped?
*
* @param charset
* @param injector
* @param cmdCodecFactory
*/
public MessageEncoder(Charset charset, CmdCodecFactory cmdCodecFactory) {
this.charset = charset;
this.cmdCodecFactory = cmdCodecFactory;
this.packageHeadCodec = new PackageHeadCodec();
}
/*
* (non-Javadoc)
*
* @see
* org.apache.mina.filter.codec.ProtocolEncoder#dispose(org.apache.mina.
* core.session.IoSession)
*/
@Override
public void dispose(IoSession session) throws Exception {
}
/*
* (non-Javadoc)
*
* @see
* org.apache.mina.filter.codec.ProtocolEncoder#encode(org.apache.mina.core
* .session.IoSession, java.lang.Object,
* org.apache.mina.filter.codec.ProtocolEncoderOutput)
*/
@Override
public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
log.debug("encode message start");
if (session != null && session.isConnected()) {
log.trace("Mina session ID: {}", session.getId());
}
Message msg = (Message) message;
HeadMessage headMessage = msg.getHeadMessage();
ICommand bodyMessage = msg.getBodyMessage();
long cmdId = bodyMessage.getCmdId();
byte[] bodyByte = null;
log.debug("cmdId to send: ({})", cmdId);
int totalMsgLength = 0;
if (bodyMessage instanceof ErrorBodyMessage) {
bodyByte = new byte[ProtocolLengths.COMMAND + 4];
ErrorBodyMessage errorBodyMessage = (ErrorBodyMessage) bodyMessage;
Tools.putUnsignedInt(bodyByte, errorBodyMessage.getCmdId(), 0);
Tools.putUnsignedInt(bodyByte, errorBodyMessage.getErrorCode(),
ProtocolLengths.COMMAND);
} else {
// throw new RuntimeException("cmd id is not exits,cmdId is :"+cmdId);
// }
//Dispatcher
//IBodyMessageCoder bodyMessageCoder = injector.getInstance(Key.get(IBodyMessageCoder.class, Names.named(cmdName)));
// XXX handles the case no codec is found for the command ID.
ICommandCodec bodyMessageCoder = cmdCodecFactory.getCodec(cmdId);
log.trace("bodyMessageCoder = {}", bodyMessageCoder);
bodyByte = bodyMessageCoder.encode(bodyMessage, charset);
}
totalMsgLength = ProtocolLengths.HEAD + bodyByte.length;
byte[] serializedSessionKey = null;
if ((headMessage.getFlags() & HeadMessage.FLAG_SESSION_ID) != 0) {
log.debug("message header indicates session ID presence, will encode");
// session key is present
// FIXME should respect the version ID in the session key.
serializedSessionKey = skCodec.encode(headMessage.getSessionKey());
- totalMsgLength = serializedSessionKey.length;
+ totalMsgLength += serializedSessionKey.length;
}
byte[] result = new byte[totalMsgLength];
// head process
headMessage.setMessageSize(totalMsgLength);
byte[] headByte = packageHeadCodec.encode(headMessage);
/* build the complete encoded buffer in vaiable 'result' */
int idx = 0;
Tools.putBytes(result, headByte, 0);
idx += ProtocolLengths.HEAD;
if (serializedSessionKey != null) {
Tools.putBytes(result, serializedSessionKey, idx);
idx += serializedSessionKey.length;
}
Tools.putBytes(result, bodyByte, idx);
idx += bodyByte.length;
/* calculate the checksum using the 'result' buffer */
int checkSumVal = Tools.checkSum(result, result.length);
Tools.putUnsignedShort(result, checkSumVal, 10);
log.debug("Encoded message checkum: 0x{}", Integer.toHexString(checkSumVal));
// write to Mina session
// prepare buffer
IoBuffer buf = IoBuffer.allocate(totalMsgLength);
// write header (16 byte)
buf.put(result);
// debug print
log.debug("Encoded byte content");
// TODO make the '96' be configurable.
CodecUtil.hexDumpForLogging(log, buf.array(), 96);
buf.flip();
out.write(buf);
log.debug("encode message end");
}
}
| true | true | public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
log.debug("encode message start");
if (session != null && session.isConnected()) {
log.trace("Mina session ID: {}", session.getId());
}
Message msg = (Message) message;
HeadMessage headMessage = msg.getHeadMessage();
ICommand bodyMessage = msg.getBodyMessage();
long cmdId = bodyMessage.getCmdId();
byte[] bodyByte = null;
log.debug("cmdId to send: ({})", cmdId);
int totalMsgLength = 0;
if (bodyMessage instanceof ErrorBodyMessage) {
bodyByte = new byte[ProtocolLengths.COMMAND + 4];
ErrorBodyMessage errorBodyMessage = (ErrorBodyMessage) bodyMessage;
Tools.putUnsignedInt(bodyByte, errorBodyMessage.getCmdId(), 0);
Tools.putUnsignedInt(bodyByte, errorBodyMessage.getErrorCode(),
ProtocolLengths.COMMAND);
} else {
// throw new RuntimeException("cmd id is not exits,cmdId is :"+cmdId);
// }
//Dispatcher
//IBodyMessageCoder bodyMessageCoder = injector.getInstance(Key.get(IBodyMessageCoder.class, Names.named(cmdName)));
// XXX handles the case no codec is found for the command ID.
ICommandCodec bodyMessageCoder = cmdCodecFactory.getCodec(cmdId);
log.trace("bodyMessageCoder = {}", bodyMessageCoder);
bodyByte = bodyMessageCoder.encode(bodyMessage, charset);
}
totalMsgLength = ProtocolLengths.HEAD + bodyByte.length;
byte[] serializedSessionKey = null;
if ((headMessage.getFlags() & HeadMessage.FLAG_SESSION_ID) != 0) {
log.debug("message header indicates session ID presence, will encode");
// session key is present
// FIXME should respect the version ID in the session key.
serializedSessionKey = skCodec.encode(headMessage.getSessionKey());
totalMsgLength = serializedSessionKey.length;
}
byte[] result = new byte[totalMsgLength];
// head process
headMessage.setMessageSize(totalMsgLength);
byte[] headByte = packageHeadCodec.encode(headMessage);
/* build the complete encoded buffer in vaiable 'result' */
int idx = 0;
Tools.putBytes(result, headByte, 0);
idx += ProtocolLengths.HEAD;
if (serializedSessionKey != null) {
Tools.putBytes(result, serializedSessionKey, idx);
idx += serializedSessionKey.length;
}
Tools.putBytes(result, bodyByte, idx);
idx += bodyByte.length;
/* calculate the checksum using the 'result' buffer */
int checkSumVal = Tools.checkSum(result, result.length);
Tools.putUnsignedShort(result, checkSumVal, 10);
log.debug("Encoded message checkum: 0x{}", Integer.toHexString(checkSumVal));
// write to Mina session
// prepare buffer
IoBuffer buf = IoBuffer.allocate(totalMsgLength);
// write header (16 byte)
buf.put(result);
// debug print
log.debug("Encoded byte content");
// TODO make the '96' be configurable.
CodecUtil.hexDumpForLogging(log, buf.array(), 96);
buf.flip();
out.write(buf);
log.debug("encode message end");
}
| public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
log.debug("encode message start");
if (session != null && session.isConnected()) {
log.trace("Mina session ID: {}", session.getId());
}
Message msg = (Message) message;
HeadMessage headMessage = msg.getHeadMessage();
ICommand bodyMessage = msg.getBodyMessage();
long cmdId = bodyMessage.getCmdId();
byte[] bodyByte = null;
log.debug("cmdId to send: ({})", cmdId);
int totalMsgLength = 0;
if (bodyMessage instanceof ErrorBodyMessage) {
bodyByte = new byte[ProtocolLengths.COMMAND + 4];
ErrorBodyMessage errorBodyMessage = (ErrorBodyMessage) bodyMessage;
Tools.putUnsignedInt(bodyByte, errorBodyMessage.getCmdId(), 0);
Tools.putUnsignedInt(bodyByte, errorBodyMessage.getErrorCode(),
ProtocolLengths.COMMAND);
} else {
// throw new RuntimeException("cmd id is not exits,cmdId is :"+cmdId);
// }
//Dispatcher
//IBodyMessageCoder bodyMessageCoder = injector.getInstance(Key.get(IBodyMessageCoder.class, Names.named(cmdName)));
// XXX handles the case no codec is found for the command ID.
ICommandCodec bodyMessageCoder = cmdCodecFactory.getCodec(cmdId);
log.trace("bodyMessageCoder = {}", bodyMessageCoder);
bodyByte = bodyMessageCoder.encode(bodyMessage, charset);
}
totalMsgLength = ProtocolLengths.HEAD + bodyByte.length;
byte[] serializedSessionKey = null;
if ((headMessage.getFlags() & HeadMessage.FLAG_SESSION_ID) != 0) {
log.debug("message header indicates session ID presence, will encode");
// session key is present
// FIXME should respect the version ID in the session key.
serializedSessionKey = skCodec.encode(headMessage.getSessionKey());
totalMsgLength += serializedSessionKey.length;
}
byte[] result = new byte[totalMsgLength];
// head process
headMessage.setMessageSize(totalMsgLength);
byte[] headByte = packageHeadCodec.encode(headMessage);
/* build the complete encoded buffer in vaiable 'result' */
int idx = 0;
Tools.putBytes(result, headByte, 0);
idx += ProtocolLengths.HEAD;
if (serializedSessionKey != null) {
Tools.putBytes(result, serializedSessionKey, idx);
idx += serializedSessionKey.length;
}
Tools.putBytes(result, bodyByte, idx);
idx += bodyByte.length;
/* calculate the checksum using the 'result' buffer */
int checkSumVal = Tools.checkSum(result, result.length);
Tools.putUnsignedShort(result, checkSumVal, 10);
log.debug("Encoded message checkum: 0x{}", Integer.toHexString(checkSumVal));
// write to Mina session
// prepare buffer
IoBuffer buf = IoBuffer.allocate(totalMsgLength);
// write header (16 byte)
buf.put(result);
// debug print
log.debug("Encoded byte content");
// TODO make the '96' be configurable.
CodecUtil.hexDumpForLogging(log, buf.array(), 96);
buf.flip();
out.write(buf);
log.debug("encode message end");
}
|
diff --git a/src/ClientHandler.java b/src/ClientHandler.java
index b0ccd28..5a467a3 100644
--- a/src/ClientHandler.java
+++ b/src/ClientHandler.java
@@ -1,154 +1,157 @@
import java.net.*;
import java.io.*;
public class ClientHandler implements Runnable
{
private Socket client;
ClientHandler(Socket client)
{
this.client = client;
}
public void run()
{
BufferedReader inputReader;
PrintStream outputStream;
URL url;
HttpRequest request;
HttpResponse response;
Socket upstreamSocket;
try
{
inputReader = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
outputStream = new PrintStream(this.client.getOutputStream());
}
catch(IOException e)
{
System.out.println("Failed to initialize input/output streams!");
return;
}
while(true)
{
if(this.client.isClosed()) break;
request = null;
response = null;
upstreamSocket = null;
url = null;
try
{
request = new HttpRequest(inputReader);
}
catch(HttpParseException e)
{
System.out.println("Error parsing HTTP message: " + e.getMessage() + " (" +
this.client.getInetAddress() + ":" + this.client.getPort() + ")");
response = new HttpResponse(400, "Bad Request");
}
if(request != null && request.method.equals("CONNECT"))
{
response = new HttpResponse(501, "Not Implemented");
}
if(response == null)
{
try
{
url = new URL(request.uri);
}
catch(MalformedURLException e)
{
response = new HttpResponse(400, "Bad Request");
}
if(url != null)
{
// Rewrite the request with the upstream URL and host
request.uri = url.getPath();
if(url.getQuery() != null) request.uri += "?" + url.getQuery();
request.removeHeader("Host");
request.addHeader("Host", url.getHost());
try
{
upstreamSocket = new Socket(DnsCache.get(url.getHost()), url.getPort() < 0 ? 80 : url.getPort());
}
catch(UnknownHostException e)
{
response = new HttpResponse(404, "Not Found");
}
catch(IOException e)
{
response = new HttpResponse(504, "Gateway Timeout");
}
if(response == null && upstreamSocket != null)
{
try
{
OutputStream output = upstreamSocket.getOutputStream();
output.write(request.serialize().getBytes());
}
catch(IOException e)
{
response = new HttpResponse(500, "Internal Server Error");
}
}
if(response == null)
{
try
{
response = new HttpResponse(upstreamSocket.getInputStream());
}
catch(IOException e)
{
response = new HttpResponse(502, "Bad Gateway");
}
catch(HttpParseException e)
{
response = new HttpResponse(502, "Bad Gateway");
}
}
try
{
upstreamSocket.close();
}
catch(IOException e)
{
// If we got this far, might as well finish handling the request
}
}
+ }
+ if(response != null)
+ {
try
{
outputStream.write(response.serialize().toByteArray());
if(url != null)
System.out.println(request.method + " " + url.getHost() + request.uri + " " + response.statusCode);
else
System.out.println(request.method + " " + " " + response.statusCode);
}
catch(IOException e)
{
System.out.println("Failed to send response to client " +
this.client.getInetAddress() + ":" + this.client.getPort());
}
if(response.statusCode == 400)
{
// Chrome in particular doesn't give up when sending its
// cute not-really HTTP requests
try
{
this.client.close();
}
catch(IOException e) { }
}
}
}
}
}
| false | true | public void run()
{
BufferedReader inputReader;
PrintStream outputStream;
URL url;
HttpRequest request;
HttpResponse response;
Socket upstreamSocket;
try
{
inputReader = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
outputStream = new PrintStream(this.client.getOutputStream());
}
catch(IOException e)
{
System.out.println("Failed to initialize input/output streams!");
return;
}
while(true)
{
if(this.client.isClosed()) break;
request = null;
response = null;
upstreamSocket = null;
url = null;
try
{
request = new HttpRequest(inputReader);
}
catch(HttpParseException e)
{
System.out.println("Error parsing HTTP message: " + e.getMessage() + " (" +
this.client.getInetAddress() + ":" + this.client.getPort() + ")");
response = new HttpResponse(400, "Bad Request");
}
if(request != null && request.method.equals("CONNECT"))
{
response = new HttpResponse(501, "Not Implemented");
}
if(response == null)
{
try
{
url = new URL(request.uri);
}
catch(MalformedURLException e)
{
response = new HttpResponse(400, "Bad Request");
}
if(url != null)
{
// Rewrite the request with the upstream URL and host
request.uri = url.getPath();
if(url.getQuery() != null) request.uri += "?" + url.getQuery();
request.removeHeader("Host");
request.addHeader("Host", url.getHost());
try
{
upstreamSocket = new Socket(DnsCache.get(url.getHost()), url.getPort() < 0 ? 80 : url.getPort());
}
catch(UnknownHostException e)
{
response = new HttpResponse(404, "Not Found");
}
catch(IOException e)
{
response = new HttpResponse(504, "Gateway Timeout");
}
if(response == null && upstreamSocket != null)
{
try
{
OutputStream output = upstreamSocket.getOutputStream();
output.write(request.serialize().getBytes());
}
catch(IOException e)
{
response = new HttpResponse(500, "Internal Server Error");
}
}
if(response == null)
{
try
{
response = new HttpResponse(upstreamSocket.getInputStream());
}
catch(IOException e)
{
response = new HttpResponse(502, "Bad Gateway");
}
catch(HttpParseException e)
{
response = new HttpResponse(502, "Bad Gateway");
}
}
try
{
upstreamSocket.close();
}
catch(IOException e)
{
// If we got this far, might as well finish handling the request
}
}
try
{
outputStream.write(response.serialize().toByteArray());
if(url != null)
System.out.println(request.method + " " + url.getHost() + request.uri + " " + response.statusCode);
else
System.out.println(request.method + " " + " " + response.statusCode);
}
catch(IOException e)
{
System.out.println("Failed to send response to client " +
this.client.getInetAddress() + ":" + this.client.getPort());
}
if(response.statusCode == 400)
{
// Chrome in particular doesn't give up when sending its
// cute not-really HTTP requests
try
{
this.client.close();
}
catch(IOException e) { }
}
}
}
}
| public void run()
{
BufferedReader inputReader;
PrintStream outputStream;
URL url;
HttpRequest request;
HttpResponse response;
Socket upstreamSocket;
try
{
inputReader = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
outputStream = new PrintStream(this.client.getOutputStream());
}
catch(IOException e)
{
System.out.println("Failed to initialize input/output streams!");
return;
}
while(true)
{
if(this.client.isClosed()) break;
request = null;
response = null;
upstreamSocket = null;
url = null;
try
{
request = new HttpRequest(inputReader);
}
catch(HttpParseException e)
{
System.out.println("Error parsing HTTP message: " + e.getMessage() + " (" +
this.client.getInetAddress() + ":" + this.client.getPort() + ")");
response = new HttpResponse(400, "Bad Request");
}
if(request != null && request.method.equals("CONNECT"))
{
response = new HttpResponse(501, "Not Implemented");
}
if(response == null)
{
try
{
url = new URL(request.uri);
}
catch(MalformedURLException e)
{
response = new HttpResponse(400, "Bad Request");
}
if(url != null)
{
// Rewrite the request with the upstream URL and host
request.uri = url.getPath();
if(url.getQuery() != null) request.uri += "?" + url.getQuery();
request.removeHeader("Host");
request.addHeader("Host", url.getHost());
try
{
upstreamSocket = new Socket(DnsCache.get(url.getHost()), url.getPort() < 0 ? 80 : url.getPort());
}
catch(UnknownHostException e)
{
response = new HttpResponse(404, "Not Found");
}
catch(IOException e)
{
response = new HttpResponse(504, "Gateway Timeout");
}
if(response == null && upstreamSocket != null)
{
try
{
OutputStream output = upstreamSocket.getOutputStream();
output.write(request.serialize().getBytes());
}
catch(IOException e)
{
response = new HttpResponse(500, "Internal Server Error");
}
}
if(response == null)
{
try
{
response = new HttpResponse(upstreamSocket.getInputStream());
}
catch(IOException e)
{
response = new HttpResponse(502, "Bad Gateway");
}
catch(HttpParseException e)
{
response = new HttpResponse(502, "Bad Gateway");
}
}
try
{
upstreamSocket.close();
}
catch(IOException e)
{
// If we got this far, might as well finish handling the request
}
}
}
if(response != null)
{
try
{
outputStream.write(response.serialize().toByteArray());
if(url != null)
System.out.println(request.method + " " + url.getHost() + request.uri + " " + response.statusCode);
else
System.out.println(request.method + " " + " " + response.statusCode);
}
catch(IOException e)
{
System.out.println("Failed to send response to client " +
this.client.getInetAddress() + ":" + this.client.getPort());
}
if(response.statusCode == 400)
{
// Chrome in particular doesn't give up when sending its
// cute not-really HTTP requests
try
{
this.client.close();
}
catch(IOException e) { }
}
}
}
}
|
diff --git a/src/hunternif/mc/dota2items/network/EntityStatsSyncPacket.java b/src/hunternif/mc/dota2items/network/EntityStatsSyncPacket.java
index 4365afd..767d264 100644
--- a/src/hunternif/mc/dota2items/network/EntityStatsSyncPacket.java
+++ b/src/hunternif/mc/dota2items/network/EntityStatsSyncPacket.java
@@ -1,86 +1,87 @@
package hunternif.mc.dota2items.network;
import hunternif.mc.dota2items.Dota2Items;
import hunternif.mc.dota2items.Sound;
import hunternif.mc.dota2items.core.EntityStats;
import hunternif.mc.dota2items.core.Mechanics;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import cpw.mods.fml.relauncher.Side;
public class EntityStatsSyncPacket extends CustomPacket {
private int entityID;
public float baseStrength;
public float baseAgility;
public float baseIntelligence;
private float partialHalfHeart;
private float mana;
private float reliableGold;
private float unreliableGold;
public EntityStatsSyncPacket() {}
public EntityStatsSyncPacket(EntityStats stats) {
entityID = stats.entityId;
partialHalfHeart = stats.partialHalfHeart;
mana = stats.getFloatMana();
reliableGold = stats.getReliableGold();
unreliableGold = stats.getUnreliableGold();
baseStrength = stats.getFloatBaseStrength();
baseAgility = stats.getFloatBaseAgility();
baseIntelligence = stats.getFloatBaseIntelligence();
}
@Override
public void write(ByteArrayDataOutput out) {
out.writeInt(entityID);
out.writeFloat(partialHalfHeart);
out.writeFloat(mana);
out.writeFloat(reliableGold);
out.writeFloat(unreliableGold);
out.writeFloat(baseStrength);
out.writeFloat(baseAgility);
out.writeFloat(baseIntelligence);
}
@Override
public void read(ByteArrayDataInput in) throws ProtocolException {
entityID = in.readInt();
partialHalfHeart = in.readFloat();
mana = in.readFloat();
reliableGold = in.readFloat();
unreliableGold = in.readFloat();
baseStrength = in.readFloat();
baseAgility = in.readFloat();
baseIntelligence =in.readFloat();
}
@Override
public void execute(EntityPlayer player, Side side) throws ProtocolException {
if (side.isClient()) {
Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(entityID);
if (entity != null && entity instanceof EntityLivingBase) {
EntityStats stats = Dota2Items.mechanics.getOrCreateEntityStats((EntityLivingBase)entity);
stats.partialHalfHeart = partialHalfHeart;
int oldGold = stats.getGold();
stats.setGold(reliableGold, unreliableGold);
- if (stats.getGold() - oldGold > Mechanics.GOLD_PER_SECOND * Mechanics.SYNC_STATS_INTERVAL) {
+ if (stats.getGold() - oldGold > Mechanics.GOLD_PER_SECOND * Mechanics.SYNC_STATS_INTERVAL
+ && stats.lastSyncTime > 0 /* Not the first sync */) {
Minecraft.getMinecraft().sndManager.playSoundFX(Sound.COINS.getName(), 1, 1);
}
stats.setMana(mana);
stats.setBaseStrength(baseStrength);
stats.setBaseAgility(baseAgility);
stats.setBaseIntelligence(baseIntelligence);
stats.lastSyncTime = entity.ticksExisted;
}
} else {
throw new ProtocolException("Cannot send this packet to the server!");
}
}
}
| true | true | public void execute(EntityPlayer player, Side side) throws ProtocolException {
if (side.isClient()) {
Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(entityID);
if (entity != null && entity instanceof EntityLivingBase) {
EntityStats stats = Dota2Items.mechanics.getOrCreateEntityStats((EntityLivingBase)entity);
stats.partialHalfHeart = partialHalfHeart;
int oldGold = stats.getGold();
stats.setGold(reliableGold, unreliableGold);
if (stats.getGold() - oldGold > Mechanics.GOLD_PER_SECOND * Mechanics.SYNC_STATS_INTERVAL) {
Minecraft.getMinecraft().sndManager.playSoundFX(Sound.COINS.getName(), 1, 1);
}
stats.setMana(mana);
stats.setBaseStrength(baseStrength);
stats.setBaseAgility(baseAgility);
stats.setBaseIntelligence(baseIntelligence);
stats.lastSyncTime = entity.ticksExisted;
}
} else {
throw new ProtocolException("Cannot send this packet to the server!");
}
}
| public void execute(EntityPlayer player, Side side) throws ProtocolException {
if (side.isClient()) {
Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(entityID);
if (entity != null && entity instanceof EntityLivingBase) {
EntityStats stats = Dota2Items.mechanics.getOrCreateEntityStats((EntityLivingBase)entity);
stats.partialHalfHeart = partialHalfHeart;
int oldGold = stats.getGold();
stats.setGold(reliableGold, unreliableGold);
if (stats.getGold() - oldGold > Mechanics.GOLD_PER_SECOND * Mechanics.SYNC_STATS_INTERVAL
&& stats.lastSyncTime > 0 /* Not the first sync */) {
Minecraft.getMinecraft().sndManager.playSoundFX(Sound.COINS.getName(), 1, 1);
}
stats.setMana(mana);
stats.setBaseStrength(baseStrength);
stats.setBaseAgility(baseAgility);
stats.setBaseIntelligence(baseIntelligence);
stats.lastSyncTime = entity.ticksExisted;
}
} else {
throw new ProtocolException("Cannot send this packet to the server!");
}
}
|
diff --git a/src/org/geworkbench/builtin/projects/util/CaARRAYPanel.java b/src/org/geworkbench/builtin/projects/util/CaARRAYPanel.java
index 82402024..5111573f 100755
--- a/src/org/geworkbench/builtin/projects/util/CaARRAYPanel.java
+++ b/src/org/geworkbench/builtin/projects/util/CaARRAYPanel.java
@@ -1,857 +1,855 @@
package org.geworkbench.builtin.projects.util;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Observer;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.border.Border;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.builtin.projects.LoadData;
import org.geworkbench.builtin.projects.remoteresources.carraydata.CaArray2Experiment;
import org.geworkbench.engine.config.VisualPlugin;
import org.geworkbench.engine.management.Publish;
import org.geworkbench.engine.management.Subscribe;
import org.geworkbench.events.CaArrayEvent;
import org.geworkbench.events.CaArrayRequestEvent;
import org.geworkbench.events.CaArrayRequestHybridizationListEvent;
import org.geworkbench.events.CaArrayReturnHybridizationListEvent;
import org.geworkbench.events.CaArraySuccessEvent;
import org.geworkbench.util.ProgressBar;
/**
* @author xiaoqing
* @version $Id: CaARRAYPanel.java,v 1.48 2009-10-12 18:13:29 jiz Exp $
*/
@SuppressWarnings("unchecked")
public class CaARRAYPanel extends JPanel implements Observer, VisualPlugin {
private static final String LOADING_SELECTED_BIOASSAYS_ELAPSED_TIME = "Loading selected bioassays - elapsed time: ";
private static final long serialVersionUID = -4876378958265466224L;
private static final String CAARRAY_TITLE = "caARRAY";
private static Log log = LogFactory.getLog(CaARRAYPanel.class);
/**
* Used to avoid querying the server for all experiments all the time.
*/
protected boolean experimentsLoaded = false;
private String currentResourceName = null;
private String previousResourceName = null;
private JLabel displayLabel = new JLabel();
private JPanel jPanel6 = new JPanel();
private GridLayout grid4 = new GridLayout();
private JPanel caArrayDetailPanel = new JPanel();
private JPanel caArrayTreePanel = new JPanel();
private BorderLayout borderLayout4 = new BorderLayout();
private BorderLayout borderLayout7 = new BorderLayout();
private Border border1 = null;
private Border border2 = null;
private JScrollPane jScrollPane1 = new JScrollPane();
private JPanel jPanel10 = new JPanel();
private JLabel jLabel4 = new JLabel();
private JScrollPane jScrollPane2 = new JScrollPane();
private JPanel jPanel14 = new JPanel();
private JPanel jPanel16 = new JPanel();
private JLabel derivedLabel = new JLabel("Number of Assays");
private JTextField measuredField = new JTextField();
private JTextField derivedField = new JTextField();
private JTextArea experimentInfoArea = new JTextArea();
private JPanel jPanel13 = new JPanel();
private JButton extendButton = new JButton();
private JButton openButton = new JButton();
private JButton cancelButton = new JButton();
private LoadData parent = null;
private DefaultMutableTreeNode root = new DefaultMutableTreeNode(
"caARRAY experiments");
private DefaultTreeModel remoteTreeModel = new DefaultTreeModel(root);
private JTree remoteFileTree = new JTree(remoteTreeModel);
private JPopupMenu jRemoteDataPopup = new JPopupMenu();
private JMenuItem jGetRemoteDataMenu = new JMenuItem();
private boolean connectionSuccess = true;
private String user;
private String passwd;
private String url;
private int portnumber;
private ProgressBar progressBar = ProgressBar
.create(ProgressBar.INDETERMINATE_TYPE);
private LoadData parentPanel;
private boolean merge;
private boolean stillWaitForConnecting = true;
private TreeMap<String, CaArray2Experiment> treeMap;
private String currentSelectedExperimentName;
private Map<String, String> currentSelectedBioAssay;
private CaArray2Experiment[] currentLoadedExps;
private String currentQuantitationType;
private static final int INTERNALTIMEOUTLIMIT = 600;
private static final int INCREASE_EACHTIME = 300;
private int internalTimeoutLimit = INTERNALTIMEOUTLIMIT;
public CaARRAYPanel() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setParent(LoadData p) {
parent = p;
}
public boolean isStillWaitForConnecting() {
return stillWaitForConnecting;
}
public void setStillWaitForConnecting(boolean stillWaitForConnecting) {
this.stillWaitForConnecting = stillWaitForConnecting;
}
@Subscribe
public void receive(CaArrayEvent ce, Object source) {
if (!stillWaitForConnecting) {
return;
}
stillWaitForConnecting = false;
progressBar.stop();
if (!ce.isPopulated()) {
String errorMessage = ce.getErrorMessage();
if (errorMessage == null) {
errorMessage = "Cannot connect with the server.";
}
if (!ce.isSucceed()) {
JOptionPane.showMessageDialog(null, "The error: "
+ errorMessage);
} else {
JOptionPane.showMessageDialog(null, errorMessage);
}
}
if (ce.getInfoType().equalsIgnoreCase(CaArrayEvent.EXPERIMENT)) {
currentLoadedExps = ce.getExperiments();
treeMap = new TreeMap<String, CaArray2Experiment>();
root = new DefaultMutableTreeNode("caARRAY experiments");
remoteTreeModel.setRoot(root);
if (currentLoadedExps == null) {
return;
}
for (int i = 0; i < currentLoadedExps.length; ++i) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(
currentLoadedExps[i].getName());
treeMap.put(currentLoadedExps[i].getName(),
currentLoadedExps[i]);
remoteTreeModel
.insertNodeInto(node, root, root.getChildCount());
}
remoteFileTree.expandRow(0);
experimentsLoaded = true;
previousResourceName = currentResourceName;
connectionSuccess = true;
if (currentLoadedExps != null) {
displayLabel.setText("Total Experiments: "
+ currentLoadedExps.length);
caArrayTreePanel.add(displayLabel, BorderLayout.SOUTH);
}
revalidate();
} else {
dispose();// make itself disappear.
}
}
@Publish
public CaArrayRequestEvent publishCaArrayRequestEvent(
CaArrayRequestEvent event) {
return event;
}
public void publishProjectNodeAddedEvent(
org.geworkbench.events.ProjectNodeAddedEvent event) {
parent.publishProjectNodeAddedEvent(event);
}
private void jbInit() throws Exception {
border1 = BorderFactory.createLineBorder(SystemColor.controlText, 1);
border2 = BorderFactory.createLineBorder(SystemColor.controlText, 1);
grid4.setColumns(2);
grid4.setHgap(10);
grid4.setRows(1);
grid4.setVgap(10);
jLabel4.setMaximumSize(new Dimension(200, 15));
jLabel4.setMinimumSize(new Dimension(200, 15));
jLabel4.setPreferredSize(new Dimension(200, 15));
jLabel4.setText("Experiment Information:");
jPanel13.setLayout(new BoxLayout(jPanel13, BoxLayout.X_AXIS));
jPanel13.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
derivedField.setMinimumSize(new Dimension(8, 20));
derivedField.setPreferredSize(new Dimension(8, 20));
caArrayTreePanel.setPreferredSize(new Dimension(197, 280));// change
// from 137
// to 167.
caArrayDetailPanel.setPreferredSize(new Dimension(380, 300));
jPanel10.setPreferredSize(new Dimension(370, 280));
this.setMinimumSize(new Dimension(510, 200));
this.setPreferredSize(new Dimension(510, 200));
jPanel13.add(extendButton);
// jPanel13.add(Box.createHorizontalGlue());
jPanel13.add(openButton);
// jPanel13.add(Box.createRigidArea(new Dimension(10, 0)));
jPanel13.add(cancelButton);
measuredField.setEditable(false);
extendButton.setPreferredSize(new Dimension(100, 25));
extendButton.setText("Show arrays");
extendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
extendBioassays_action(e);
}
});
extendButton.setToolTipText("Display Bioassys");
openButton.setPreferredSize(new Dimension(60, 25));
openButton.setText("Open");
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openRemoteFile_action(e);
}
});
openButton.setToolTipText("Load remote MicroarrayDataSet");
cancelButton.setMinimumSize(new Dimension(68, 25));
cancelButton.setPreferredSize(new Dimension(68, 25));
cancelButton.setText("Cancel");
cancelButton.setToolTipText("Close the Window");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jPanel16.setLayout(new BoxLayout(jPanel16, BoxLayout.Y_AXIS));
jPanel16.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
jPanel16.add(Box.createVerticalGlue());
jPanel16.add(Box.createRigidArea(new Dimension(10, 0)));
jPanel16.add(derivedLabel);
jPanel16.add(derivedField);
jPanel16.add(Box.createRigidArea(new Dimension(10, 0)));
derivedField.setEditable(false);
jScrollPane2.getViewport().add(experimentInfoArea, null);
jScrollPane2.setPreferredSize(new Dimension(300, 500));
jPanel14.setLayout(new BoxLayout(jPanel14, BoxLayout.X_AXIS));
jPanel14.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
jPanel14.add(Box.createHorizontalGlue());
jPanel14.add(Box.createRigidArea(new Dimension(10, 0)));
jPanel14.add(Box.createRigidArea(new Dimension(10, 0)));
experimentInfoArea.setPreferredSize(new Dimension(300, 600));
experimentInfoArea.setText("");
experimentInfoArea.setEditable(false);
experimentInfoArea.setLineWrap(true);
experimentInfoArea.setWrapStyleWord(true);
jPanel6.setLayout(grid4);
caArrayTreePanel.setLayout(borderLayout4);
caArrayDetailPanel.setLayout(borderLayout7);
jPanel10.setLayout(new BoxLayout(jPanel10, BoxLayout.Y_AXIS));
jPanel10.add(jLabel4, null);
jPanel10.add(Box.createRigidArea(new Dimension(0, 10)));
jPanel10.add(jScrollPane2, null);
jPanel10.add(Box.createRigidArea(new Dimension(0, 10)));
jPanel10.add(jPanel14, null);
jPanel14.add(jPanel16);
jPanel10.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
caArrayDetailPanel.setBorder(border1);
caArrayTreePanel.setBorder(border2);
jScrollPane1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
caArrayDetailPanel.add(jPanel10, BorderLayout.CENTER);
caArrayDetailPanel.add(jPanel13, BorderLayout.SOUTH);
- jPanel6.setMaximumSize(new Dimension(700, 449));
- jPanel6.setMinimumSize(new Dimension(675, 339));
- jPanel6.setPreferredSize(new Dimension(700, 449));
jPanel6.add(caArrayTreePanel);
caArrayTreePanel.add(jScrollPane1, BorderLayout.CENTER);
jScrollPane1.getViewport().add(remoteFileTree, null);
jPanel6.add(caArrayDetailPanel);
remoteFileTree.setToolTipText("");
remoteFileTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
remoteFileTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse) {
remoteFileSelection_action(tse);
}
});
remoteFileTree.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(MouseEvent e) {
jRemoteFileTree_mouseReleased(e);
}
});
jGetRemoteDataMenu.setText("Get bioassays");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
extendBioassays_action(e);
}
};
jGetRemoteDataMenu.addActionListener(listener);
jRemoteDataPopup.add(jGetRemoteDataMenu);
jPanel6.setMaximumSize(new Dimension(500, 300));
jPanel6.setMinimumSize(new Dimension(500, 285));
jPanel6.setPreferredSize(new Dimension(500, 285));
+ this.setLayout(new BorderLayout());
this.add(jPanel6, BorderLayout.CENTER);
}
/**
* Update the progressBar to reflect the current time.
*
* @param text
*/
public void updateProgressBar(final String text) {
Runnable r = new Runnable() {
public void run() {
try {
if (text.startsWith("Loading")) {
int i = 0;
internalTimeoutLimit = INTERNALTIMEOUTLIMIT;
do {
Thread.sleep(250);
i++;
String currentState = "";
if (numTotalArrays>1)
currentState = "Downloaded " + numCurrentArray + " of "+numTotalArrays + " arrays.";
if (i > 4) {
String htmltext = "<html>" + text + i / 4 + " seconds." + "<br>" + currentState +"</html>";
progressBar.setMessage(htmltext);
}
//FIXME: Bug #1797, temporarily disabled for code freeze.
// if (i > internalTimeoutLimit * 4) {
// stillWaitForConnecting = false;
// JOptionPane.showMessageDialog(null,
// "Cannot connect with the server in "
// + internalTimeoutLimit
// + " seconds.", "Timeout",
// JOptionPane.ERROR_MESSAGE);
// update(null, null);
// }
} while (stillWaitForConnecting);
}
} catch (InterruptedException e) {
log.info("caArray Data Download Thread Interrupted: ",e);
}
}
};
new Thread(r).start();
// SwingUtilities.invokeLater(r);
}
/**
*
* @param seconds
*/
public void increaseInternalTimeoutLimitBy(int seconds){
log.debug("Due time has been increased from "+internalTimeoutLimit+" seconds to " +(internalTimeoutLimit+seconds)+" seconds.");
internalTimeoutLimit += seconds;
}
/**
*
* @param ce
* @param source
*/
@Subscribe
public void receive(CaArraySuccessEvent ce, Object source) {
this.numCurrentArray = numCurrentArray+1;
this.numTotalArrays = ce.getTotalArrays();
increaseInternalTimeoutLimitBy(INCREASE_EACHTIME);
}
private int numTotalArrays = 0;
private int numCurrentArray = 0;
/**
* Action listener invoked when the user presses the "Open" button after
* having selected a remote microarray. The listener will attempt to get the
* microarray data from the remote server and load them in the application.
*
* @param e
*/
private void openRemoteFile_action(ActionEvent e) {
// If there are multiple parents in the paths, it means user tries
// to select arrays from different experiments, it's not allowed.
TreePath[] paths = remoteFileTree.getSelectionPaths();
HashSet set = new HashSet();
for (TreePath treePath : paths) {
set.add(treePath.getParentPath());
}
if (set.size() > 1) {
JOptionPane
.showMessageDialog(
null,
"Only datasets from the same experiment can be merged.",
"Can't merge datasets",
JOptionPane.INFORMATION_MESSAGE);
return;
}
// If there is only one parent, we continue.
String qType = checkQuantationTypeSelection();
if (qType != null) {
numCurrentArray = 0;
numTotalArrays = 0;
stillWaitForConnecting = true;
progressBar
.setMessage(LOADING_SELECTED_BIOASSAYS_ELAPSED_TIME);
updateProgressBar(LOADING_SELECTED_BIOASSAYS_ELAPSED_TIME);
progressBar.addObserver(this);
progressBar.setTitle(CAARRAY_TITLE);
progressBar.start();
Runnable dataLoader = new Runnable() {
public void run() {
getBioAssay();
}
};
Thread t = new Thread(dataLoader);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
}
public void startProgressBar() {
stillWaitForConnecting = true;
updateProgressBar("Loading the filtered experiments - elapsed time: ");
progressBar.setTitle(CAARRAY_TITLE);
progressBar.start();
}
/**
* Action listener invoked when the user presses the "Show Bioassays" button
* after having selected a remote microarray. If no node is selected, all
* experiments will be extended with their associated bioassays. Otherwise,
* only current selection will be extended.
*
* @param e
*/
private void extendBioassays_action(ActionEvent e) {
if (treeMap == null || treeMap.size() == 0) {
JOptionPane.showMessageDialog(null, "No Experiment to display");
return;
}
DefaultMutableTreeNode node = (DefaultMutableTreeNode) remoteFileTree
.getLastSelectedPathComponent();
if (node != null && node != root) {
if (treeMap.containsKey(node.getUserObject())) { // this is always true. why check?
if (node.getChildCount() == 0) {
CaArray2Experiment caArray2Experiment = treeMap.get(node
.getUserObject());
if (caArray2Experiment.getHybridizations() == null)
publishCaArrayRequestHybridizationListEvent(new CaArrayRequestHybridizationListEvent(
null, url, portnumber, user, passwd,
caArray2Experiment));
}
}
}
}
@Publish
public CaArrayRequestHybridizationListEvent publishCaArrayRequestHybridizationListEvent(CaArrayRequestHybridizationListEvent event) {
return event;
}
@Subscribe
public void receive(CaArrayReturnHybridizationListEvent event, Object source) {
CaArray2Experiment caArray2Experiment = event.getCaArray2Experiment();
treeMap.put(caArray2Experiment.getName(), caArray2Experiment);
Object root = remoteTreeModel.getRoot();
DefaultMutableTreeNode experimentNode = null;
for(int i=0; i<remoteTreeModel.getChildCount(root); i++) {
experimentNode = (DefaultMutableTreeNode)remoteTreeModel.getChild(root, i);
if( ((String)experimentNode.getUserObject()).equals(caArray2Experiment.getName())) {
break; // found the right experiment node. done
}
}
// at this point, caArray2Experiment.getHybridizations() should never be null. It could be zero size though.
for (String hybName: caArray2Experiment.getHybridizations().keySet()) {
DefaultMutableTreeNode assayNode = new DefaultMutableTreeNode(hybName);
remoteTreeModel.insertNodeInto(assayNode, experimentNode, experimentNode
.getChildCount());
}
remoteFileTree.expandPath(new TreePath(experimentNode.getPath()));
updateTextArea();
}
private String checkQuantationTypeSelection() {
merge = parent.isMerge();
TreePath[] paths = remoteFileTree.getSelectionPaths();
CaArray2Experiment exp = null;
if (paths.length > 0) {
currentSelectedExperimentName = (String) ((DefaultMutableTreeNode) paths[0]
.getPath()[1]).getUserObject();
exp = treeMap.get(currentSelectedExperimentName);
Map<String, String> hyb = exp.getHybridizations();
if(hyb==null || paths[0].getPath().length<=2 ) { // hyb==null means 'before experiment expansion'; length<=2 means not 'a hybridization'
return null;
}
currentSelectedBioAssay = new HashMap<String, String>();
for (int i = 0; i < paths.length; i++) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[i]
.getLastPathComponent();
String hybName = (String) node.getUserObject();
currentSelectedBioAssay.put(hybName, hyb.get(hybName));
}
String[] qTypes = exp.getQuantitationTypes();
if (qTypes != null && qTypes.length > 0) {
boolean findMatchedQType = false;
if (currentQuantitationType != null) {
for (String candidateQType : qTypes) {
if (currentQuantitationType
.equalsIgnoreCase(candidateQType)) {
findMatchedQType = true;
break;
}
}
}
String s = null;
if (findMatchedQType) {
s = (String) JOptionPane.showInputDialog(null,
"Please select the quantitation type to query:\n",
"Selection Dialog", JOptionPane.PLAIN_MESSAGE,
null, qTypes, currentQuantitationType);
} else {
s = (String) JOptionPane.showInputDialog(null,
"Please select the quantitation type to query:\n",
"Selection Dialog", JOptionPane.PLAIN_MESSAGE,
null, qTypes, qTypes[0]);
}
// If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
currentQuantitationType = s;
return currentQuantitationType;
}
} else {
JOptionPane.showMessageDialog(null,
"There is no data associated with that experiment.");
}
} else {
JOptionPane.showMessageDialog(null,
"Please select at least one Bioassay to retrieve.");
}
return null;
}
/**
* This method is called if the cancel button is pressed.
*
* @param e -
* Event information.
*/
private void jButton1_actionPerformed(ActionEvent e) {
dispose();
}
public void getExperiments(ActionEvent e) {
displayLabel.setText("");
if (!experimentsLoaded
|| !currentResourceName.equals(previousResourceName)) {
getExperiments();
this.validate();
this.repaint();
} else if (currentResourceName.equals(previousResourceName)
&& experimentsLoaded) {
if (parentPanel != null) {
parentPanel.addRemotePanel();
}
}
}
/**
* Menu action listener that brings up the popup menu that allows populating
* the tree node for a remote file.
*
* @param e
*/
private void jRemoteFileTree_mouseReleased(MouseEvent e) {
TreePath path = remoteFileTree.getPathForLocation(e.getX(), e.getY());
if (path != null) {
DefaultMutableTreeNode selectedNode = ((DefaultMutableTreeNode) path
.getLastPathComponent());
Object nodeObj = selectedNode.getUserObject();
if (e.isMetaDown() && (treeMap.containsKey(nodeObj))) {
jRemoteDataPopup.show(remoteFileTree, e.getX(), e.getY());
if (selectedNode.getChildCount() > 0) {
jGetRemoteDataMenu.setEnabled(false);
} else {
jGetRemoteDataMenu.setEnabled(true);
}
}
}
}
/**
* Action listener invoked when a remote file is selected in the remote file
* tree. Updates the experiment information text area.
*
* @param
*/
private void remoteFileSelection_action(TreeSelectionEvent tse) {
if (tse == null) {
return;
}
updateTextArea(); // Update the contents of the text area.
}
/**
* Properly update the experiment text area, based on the currently selected
* node.
*/
private void updateTextArea() {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) remoteFileTree
.getLastSelectedPathComponent();
if (node == null || node == root || treeMap == null
|| treeMap.size() == 0) {
experimentInfoArea.setText("");
measuredField.setText("");
derivedField.setText("");
} else {
// get the parent experiment.
String exp = (String) ((DefaultMutableTreeNode) node.getPath()[1])
.getUserObject();
experimentInfoArea.setText(treeMap.get(exp).getDescription());
Map<String, String> hybridization = treeMap.get(exp).getHybridizations();
if (hybridization != null) {
measuredField.setText(String.valueOf(hybridization.size()));
derivedField.setText(String.valueOf(hybridization.size()));
} else {
measuredField.setText("");
derivedField.setText("");
}
}
experimentInfoArea.setCaretPosition(0); // For long text.
}
private void getBioAssay() {
CaArrayRequestEvent event = new CaArrayRequestEvent(url, portnumber);
if (user == null || user.trim().length() == 0) {
event.setUsername(null);
} else {
event.setUsername(user);
event.setPassword(passwd);
}
event.setRequestItem(CaArrayRequestEvent.BIOASSAY);
event.setMerge(merge);
Map<String, String> filterCrit = new HashMap<String, String>();
filterCrit.put(CaArrayRequestEvent.EXPERIMENT, currentSelectedExperimentName );
SortedMap<String, String> assayNameFilter = new TreeMap<String, String>(currentSelectedBioAssay);
event.setFilterCrit(filterCrit);
event.setAssayNameFilter(assayNameFilter);
event.setQType(currentQuantitationType);
log.info("publish CaArrayEvent at CaArrayPanel");
publishCaArrayRequestEvent(event);
}
/**
* Gets a list of all experiments available on the remote server.
*/
private void getExperiments() {
stillWaitForConnecting = true;
progressBar
.setMessage("Loading experiments from the remote resource...");
updateProgressBar("Loading experiments from the remote resource for ");
progressBar.addObserver(this);
progressBar.setTitle(CAARRAY_TITLE);
progressBar.start();
try {
if (url == null) {
user = System.getProperty("caarray.mage.user");
passwd = System.getProperty("caarray.mage.password");
url = System.getProperty("SecureSessionManagerURL");
}
System.setProperty("SecureSessionManagerURL", url);
// update the progress message.
stillWaitForConnecting = true;
progressBar
.setMessage("Connecting with the server... The initial step may take a few minutes.");
CaArrayRequestEvent event = new CaArrayRequestEvent(url, portnumber);
if (user == null || user.trim().length() == 0) {
event.setUsername(null);
} else {
event.setUsername(user);
event.setPassword(passwd);
}
event.setRequestItem(CaArrayRequestEvent.EXPERIMENT);
Thread thread = new PubilshThread(event);
thread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private class PubilshThread extends Thread {
CaArrayRequestEvent event;
PubilshThread(CaArrayRequestEvent event) {
this.event = event;
}
public void run() {
publishCaArrayRequestEvent(event);
}
}
private void dispose() {
parent.dispose();
}
public void update(java.util.Observable ob, Object o) {
stillWaitForConnecting = false;
log.error("Get Cancelled");
progressBar.dispose();
CaArrayRequestEvent event = new CaArrayRequestEvent(url, portnumber);
if (user == null || user.trim().length() == 0) {
event.setUsername(null);
} else {
event.setUsername(user);
event.setPassword(passwd);
}
event.setRequestItem(CaArrayRequestEvent.CANCEL);
publishCaArrayRequestEvent(event);
}
public boolean isConnectionSuccess() {
return connectionSuccess;
}
public int getPortnumber() {
return portnumber;
}
public void setPortnumber(int portnumber) {
this.portnumber = portnumber;
}
public String getUrl() {
return url;
}
public String getUser() {
return user;
}
public String getPasswd() {
return passwd;
}
public String getCurrentResourceName() {
return currentResourceName;
}
public LoadData getParentPanel() {
return parentPanel;
}
public boolean isExperimentsLoaded() {
return experimentsLoaded;
}
public boolean isMerge() {
return merge;
}
public void setConnectionSuccess(boolean isConnectionSuccess) {
this.connectionSuccess = isConnectionSuccess;
}
public void setUrl(String url) {
this.url = url;
}
public void setUser(String user) {
this.user = user;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public void setCurrentResourceName(String currentResourceName) {
this.currentResourceName = currentResourceName;
}
public void initializeExperimentTree() {
root = new DefaultMutableTreeNode("caARRAY experiments");
remoteTreeModel.setRoot(root);
repaint();
}
public void setParentPanel(LoadData parentPanel) {
this.parentPanel = parentPanel;
}
public void setExperimentsLoaded(boolean experimentsLoaded) {
this.experimentsLoaded = experimentsLoaded;
}
public void setMerge(boolean merge) {
this.merge = merge;
}
public Component getComponent() {
return this;
}
}
| false | true | private void jbInit() throws Exception {
border1 = BorderFactory.createLineBorder(SystemColor.controlText, 1);
border2 = BorderFactory.createLineBorder(SystemColor.controlText, 1);
grid4.setColumns(2);
grid4.setHgap(10);
grid4.setRows(1);
grid4.setVgap(10);
jLabel4.setMaximumSize(new Dimension(200, 15));
jLabel4.setMinimumSize(new Dimension(200, 15));
jLabel4.setPreferredSize(new Dimension(200, 15));
jLabel4.setText("Experiment Information:");
jPanel13.setLayout(new BoxLayout(jPanel13, BoxLayout.X_AXIS));
jPanel13.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
derivedField.setMinimumSize(new Dimension(8, 20));
derivedField.setPreferredSize(new Dimension(8, 20));
caArrayTreePanel.setPreferredSize(new Dimension(197, 280));// change
// from 137
// to 167.
caArrayDetailPanel.setPreferredSize(new Dimension(380, 300));
jPanel10.setPreferredSize(new Dimension(370, 280));
this.setMinimumSize(new Dimension(510, 200));
this.setPreferredSize(new Dimension(510, 200));
jPanel13.add(extendButton);
// jPanel13.add(Box.createHorizontalGlue());
jPanel13.add(openButton);
// jPanel13.add(Box.createRigidArea(new Dimension(10, 0)));
jPanel13.add(cancelButton);
measuredField.setEditable(false);
extendButton.setPreferredSize(new Dimension(100, 25));
extendButton.setText("Show arrays");
extendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
extendBioassays_action(e);
}
});
extendButton.setToolTipText("Display Bioassys");
openButton.setPreferredSize(new Dimension(60, 25));
openButton.setText("Open");
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openRemoteFile_action(e);
}
});
openButton.setToolTipText("Load remote MicroarrayDataSet");
cancelButton.setMinimumSize(new Dimension(68, 25));
cancelButton.setPreferredSize(new Dimension(68, 25));
cancelButton.setText("Cancel");
cancelButton.setToolTipText("Close the Window");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jPanel16.setLayout(new BoxLayout(jPanel16, BoxLayout.Y_AXIS));
jPanel16.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
jPanel16.add(Box.createVerticalGlue());
jPanel16.add(Box.createRigidArea(new Dimension(10, 0)));
jPanel16.add(derivedLabel);
jPanel16.add(derivedField);
jPanel16.add(Box.createRigidArea(new Dimension(10, 0)));
derivedField.setEditable(false);
jScrollPane2.getViewport().add(experimentInfoArea, null);
jScrollPane2.setPreferredSize(new Dimension(300, 500));
jPanel14.setLayout(new BoxLayout(jPanel14, BoxLayout.X_AXIS));
jPanel14.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
jPanel14.add(Box.createHorizontalGlue());
jPanel14.add(Box.createRigidArea(new Dimension(10, 0)));
jPanel14.add(Box.createRigidArea(new Dimension(10, 0)));
experimentInfoArea.setPreferredSize(new Dimension(300, 600));
experimentInfoArea.setText("");
experimentInfoArea.setEditable(false);
experimentInfoArea.setLineWrap(true);
experimentInfoArea.setWrapStyleWord(true);
jPanel6.setLayout(grid4);
caArrayTreePanel.setLayout(borderLayout4);
caArrayDetailPanel.setLayout(borderLayout7);
jPanel10.setLayout(new BoxLayout(jPanel10, BoxLayout.Y_AXIS));
jPanel10.add(jLabel4, null);
jPanel10.add(Box.createRigidArea(new Dimension(0, 10)));
jPanel10.add(jScrollPane2, null);
jPanel10.add(Box.createRigidArea(new Dimension(0, 10)));
jPanel10.add(jPanel14, null);
jPanel14.add(jPanel16);
jPanel10.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
caArrayDetailPanel.setBorder(border1);
caArrayTreePanel.setBorder(border2);
jScrollPane1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
caArrayDetailPanel.add(jPanel10, BorderLayout.CENTER);
caArrayDetailPanel.add(jPanel13, BorderLayout.SOUTH);
jPanel6.setMaximumSize(new Dimension(700, 449));
jPanel6.setMinimumSize(new Dimension(675, 339));
jPanel6.setPreferredSize(new Dimension(700, 449));
jPanel6.add(caArrayTreePanel);
caArrayTreePanel.add(jScrollPane1, BorderLayout.CENTER);
jScrollPane1.getViewport().add(remoteFileTree, null);
jPanel6.add(caArrayDetailPanel);
remoteFileTree.setToolTipText("");
remoteFileTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
remoteFileTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse) {
remoteFileSelection_action(tse);
}
});
remoteFileTree.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(MouseEvent e) {
jRemoteFileTree_mouseReleased(e);
}
});
jGetRemoteDataMenu.setText("Get bioassays");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
extendBioassays_action(e);
}
};
jGetRemoteDataMenu.addActionListener(listener);
jRemoteDataPopup.add(jGetRemoteDataMenu);
jPanel6.setMaximumSize(new Dimension(500, 300));
jPanel6.setMinimumSize(new Dimension(500, 285));
jPanel6.setPreferredSize(new Dimension(500, 285));
this.add(jPanel6, BorderLayout.CENTER);
}
| private void jbInit() throws Exception {
border1 = BorderFactory.createLineBorder(SystemColor.controlText, 1);
border2 = BorderFactory.createLineBorder(SystemColor.controlText, 1);
grid4.setColumns(2);
grid4.setHgap(10);
grid4.setRows(1);
grid4.setVgap(10);
jLabel4.setMaximumSize(new Dimension(200, 15));
jLabel4.setMinimumSize(new Dimension(200, 15));
jLabel4.setPreferredSize(new Dimension(200, 15));
jLabel4.setText("Experiment Information:");
jPanel13.setLayout(new BoxLayout(jPanel13, BoxLayout.X_AXIS));
jPanel13.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
derivedField.setMinimumSize(new Dimension(8, 20));
derivedField.setPreferredSize(new Dimension(8, 20));
caArrayTreePanel.setPreferredSize(new Dimension(197, 280));// change
// from 137
// to 167.
caArrayDetailPanel.setPreferredSize(new Dimension(380, 300));
jPanel10.setPreferredSize(new Dimension(370, 280));
this.setMinimumSize(new Dimension(510, 200));
this.setPreferredSize(new Dimension(510, 200));
jPanel13.add(extendButton);
// jPanel13.add(Box.createHorizontalGlue());
jPanel13.add(openButton);
// jPanel13.add(Box.createRigidArea(new Dimension(10, 0)));
jPanel13.add(cancelButton);
measuredField.setEditable(false);
extendButton.setPreferredSize(new Dimension(100, 25));
extendButton.setText("Show arrays");
extendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
extendBioassays_action(e);
}
});
extendButton.setToolTipText("Display Bioassys");
openButton.setPreferredSize(new Dimension(60, 25));
openButton.setText("Open");
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openRemoteFile_action(e);
}
});
openButton.setToolTipText("Load remote MicroarrayDataSet");
cancelButton.setMinimumSize(new Dimension(68, 25));
cancelButton.setPreferredSize(new Dimension(68, 25));
cancelButton.setText("Cancel");
cancelButton.setToolTipText("Close the Window");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jPanel16.setLayout(new BoxLayout(jPanel16, BoxLayout.Y_AXIS));
jPanel16.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
jPanel16.add(Box.createVerticalGlue());
jPanel16.add(Box.createRigidArea(new Dimension(10, 0)));
jPanel16.add(derivedLabel);
jPanel16.add(derivedField);
jPanel16.add(Box.createRigidArea(new Dimension(10, 0)));
derivedField.setEditable(false);
jScrollPane2.getViewport().add(experimentInfoArea, null);
jScrollPane2.setPreferredSize(new Dimension(300, 500));
jPanel14.setLayout(new BoxLayout(jPanel14, BoxLayout.X_AXIS));
jPanel14.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
jPanel14.add(Box.createHorizontalGlue());
jPanel14.add(Box.createRigidArea(new Dimension(10, 0)));
jPanel14.add(Box.createRigidArea(new Dimension(10, 0)));
experimentInfoArea.setPreferredSize(new Dimension(300, 600));
experimentInfoArea.setText("");
experimentInfoArea.setEditable(false);
experimentInfoArea.setLineWrap(true);
experimentInfoArea.setWrapStyleWord(true);
jPanel6.setLayout(grid4);
caArrayTreePanel.setLayout(borderLayout4);
caArrayDetailPanel.setLayout(borderLayout7);
jPanel10.setLayout(new BoxLayout(jPanel10, BoxLayout.Y_AXIS));
jPanel10.add(jLabel4, null);
jPanel10.add(Box.createRigidArea(new Dimension(0, 10)));
jPanel10.add(jScrollPane2, null);
jPanel10.add(Box.createRigidArea(new Dimension(0, 10)));
jPanel10.add(jPanel14, null);
jPanel14.add(jPanel16);
jPanel10.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
caArrayDetailPanel.setBorder(border1);
caArrayTreePanel.setBorder(border2);
jScrollPane1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
caArrayDetailPanel.add(jPanel10, BorderLayout.CENTER);
caArrayDetailPanel.add(jPanel13, BorderLayout.SOUTH);
jPanel6.add(caArrayTreePanel);
caArrayTreePanel.add(jScrollPane1, BorderLayout.CENTER);
jScrollPane1.getViewport().add(remoteFileTree, null);
jPanel6.add(caArrayDetailPanel);
remoteFileTree.setToolTipText("");
remoteFileTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
remoteFileTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse) {
remoteFileSelection_action(tse);
}
});
remoteFileTree.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(MouseEvent e) {
jRemoteFileTree_mouseReleased(e);
}
});
jGetRemoteDataMenu.setText("Get bioassays");
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
extendBioassays_action(e);
}
};
jGetRemoteDataMenu.addActionListener(listener);
jRemoteDataPopup.add(jGetRemoteDataMenu);
jPanel6.setMaximumSize(new Dimension(500, 300));
jPanel6.setMinimumSize(new Dimension(500, 285));
jPanel6.setPreferredSize(new Dimension(500, 285));
this.setLayout(new BorderLayout());
this.add(jPanel6, BorderLayout.CENTER);
}
|
diff --git a/src/ui-test/java/com/gmail/at/zhuikov/aleksandr/it/AbstractWebDriverTest.java b/src/ui-test/java/com/gmail/at/zhuikov/aleksandr/it/AbstractWebDriverTest.java
index 0c826a5..776454f 100644
--- a/src/ui-test/java/com/gmail/at/zhuikov/aleksandr/it/AbstractWebDriverTest.java
+++ b/src/ui-test/java/com/gmail/at/zhuikov/aleksandr/it/AbstractWebDriverTest.java
@@ -1,62 +1,62 @@
package com.gmail.at.zhuikov.aleksandr.it;
import static org.springframework.util.StringUtils.hasText;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.saucelabs.selenium.client.factory.SeleniumFactory;
public abstract class AbstractWebDriverTest {
private static final Logger LOG = LoggerFactory.getLogger(AbstractWebDriverTest.class);
protected WebDriver driver;
@Rule public TestName name = new TestName();
protected WebDriver createDriver() {
LOG.info("Creating WebDriver");
String seleniumDriverUri = System.getenv("SELENIUM_DRIVER");
if (hasText(seleniumDriverUri)) {
- seleniumDriverUri = seleniumDriverUri.replace("windows 2008", "win7");
+ seleniumDriverUri = seleniumDriverUri.replace("Windows 2008", "win7");
seleniumDriverUri += "&job-name=" + getClass().getName() + "." + name.getMethodName();
seleniumDriverUri += "&username=" + System.getenv("SAUCE_ONDEMAND_USERNAME");
seleniumDriverUri += "&access-key=" + System.getenv("SAUCE_ONDEMAND_ACCESS_KEY");
System.setProperty("SELENIUM_DRIVER", seleniumDriverUri);
}
LOG.info("env SELENIUM_DRIVER=" + System.getenv("SELENIUM_DRIVER"));
LOG.info("sys SELENIUM_DRIVER=" + System.getProperty("SELENIUM_DRIVER"));
return SeleniumFactory.createWebDriver();
}
@Before
public void openPage() {
driver = createDriver();
}
@After
public void closePage() {
driver.quit();
}
protected String getUniqueCharString() {
String millis = String.valueOf(System.currentTimeMillis());
char[] random = new char[millis.length()];
for (int i = 0; i < millis.length(); i++) {
random[i] = (char) (millis.charAt(i) - '0' + 'a');
}
return new String(random);
}
}
| true | true | protected WebDriver createDriver() {
LOG.info("Creating WebDriver");
String seleniumDriverUri = System.getenv("SELENIUM_DRIVER");
if (hasText(seleniumDriverUri)) {
seleniumDriverUri = seleniumDriverUri.replace("windows 2008", "win7");
seleniumDriverUri += "&job-name=" + getClass().getName() + "." + name.getMethodName();
seleniumDriverUri += "&username=" + System.getenv("SAUCE_ONDEMAND_USERNAME");
seleniumDriverUri += "&access-key=" + System.getenv("SAUCE_ONDEMAND_ACCESS_KEY");
System.setProperty("SELENIUM_DRIVER", seleniumDriverUri);
}
LOG.info("env SELENIUM_DRIVER=" + System.getenv("SELENIUM_DRIVER"));
LOG.info("sys SELENIUM_DRIVER=" + System.getProperty("SELENIUM_DRIVER"));
return SeleniumFactory.createWebDriver();
}
| protected WebDriver createDriver() {
LOG.info("Creating WebDriver");
String seleniumDriverUri = System.getenv("SELENIUM_DRIVER");
if (hasText(seleniumDriverUri)) {
seleniumDriverUri = seleniumDriverUri.replace("Windows 2008", "win7");
seleniumDriverUri += "&job-name=" + getClass().getName() + "." + name.getMethodName();
seleniumDriverUri += "&username=" + System.getenv("SAUCE_ONDEMAND_USERNAME");
seleniumDriverUri += "&access-key=" + System.getenv("SAUCE_ONDEMAND_ACCESS_KEY");
System.setProperty("SELENIUM_DRIVER", seleniumDriverUri);
}
LOG.info("env SELENIUM_DRIVER=" + System.getenv("SELENIUM_DRIVER"));
LOG.info("sys SELENIUM_DRIVER=" + System.getProperty("SELENIUM_DRIVER"));
return SeleniumFactory.createWebDriver();
}
|
diff --git a/src/org/telekommunisten/ListPdn.java b/src/org/telekommunisten/ListPdn.java
index f12c613..4b40e75 100644
--- a/src/org/telekommunisten/ListPdn.java
+++ b/src/org/telekommunisten/ListPdn.java
@@ -1,138 +1,138 @@
package org.telekommunisten;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ListPdn extends ListActivity {
private Cursor cursor;
private String force = "";
private String tag = "ListPdn";
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onListItemClick(ListView l, View v, int pos, long id) {
String pdntext = (String) l.getItemAtPosition(pos);
Log.d("dialstation", pdntext);
// startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:+491792900944")));
// startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:+" + pdntext )));
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:+" + pdntext )));
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
Log.d(tag,"onstart");
super.onStart();
if (PreferenceManager.getDefaultSharedPreferences(this).getString("dialstation_user_path", null) == null)
{
startActivity(new Intent(this,SettingsActivity.class));
Toast.makeText(this, "enter credentials"+force, Toast.LENGTH_LONG).show();
force += "!!!";
if (force.contains("!!!!!!!!!!!!")) force = " AND DESTROY YOUR PHONE!";
}
else {
Log.d(tag,"really provider called");
cursor = getContentResolver().query(Uri.parse("content://com.dialstation"), null, null, null, null);
//Log.d(tag,"cols.....: "+cursor.getColumnCount());
Log.d(tag,"nooooclomun");
setListAdapter(new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(android.R.layout.simple_list_item_2, null);
}
cursor.moveToPosition(position);
- ((TextView) convertView.findViewById(android.R.id.text1)).setText(cursor.getString(6));
- ((TextView) convertView.findViewById(android.R.id.text2)).setText(cursor.getString(1));
+ ((TextView) convertView.findViewById(android.R.id.text1)).setText(cursor.getString(cursor.getColumnIndex("pstn_number")));
+ ((TextView) convertView.findViewById(android.R.id.text2)).setText(cursor.getString(cursor.getColumnIndex("description")));
((TextView) convertView.findViewById(android.R.id.text1)).setTextColor(Color.GREEN);
((TextView) convertView.findViewById(android.R.id.text2)).setTextColor(Color.RED);
// ((TextView) convertView).setTextSize(42);
// ((TextView) convertView).setTextColor(Color.GREEN);
return convertView;
}
@Override
public long getItemId(int position) {
cursor.moveToPosition(position);
return Long.valueOf(cursor.getString(cursor.getColumnIndex("id")));
// TODO Auto-generated method stub
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
cursor.moveToPosition(position);
return cursor.getString(1);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
Log.d("ListPdn",cursor.getCount()+"<- cursor.length");
return cursor.getCount();
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
break;
case R.id.settings:
startActivity(new Intent(this, SettingsActivity.class));
break;
case R.id.feedback:
LogCollector.feedback(this, "[email protected]", "blah blah blah");
break;
}
return super.onOptionsItemSelected(item);
}
}
| true | true | protected void onStart() {
// TODO Auto-generated method stub
Log.d(tag,"onstart");
super.onStart();
if (PreferenceManager.getDefaultSharedPreferences(this).getString("dialstation_user_path", null) == null)
{
startActivity(new Intent(this,SettingsActivity.class));
Toast.makeText(this, "enter credentials"+force, Toast.LENGTH_LONG).show();
force += "!!!";
if (force.contains("!!!!!!!!!!!!")) force = " AND DESTROY YOUR PHONE!";
}
else {
Log.d(tag,"really provider called");
cursor = getContentResolver().query(Uri.parse("content://com.dialstation"), null, null, null, null);
//Log.d(tag,"cols.....: "+cursor.getColumnCount());
Log.d(tag,"nooooclomun");
setListAdapter(new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(android.R.layout.simple_list_item_2, null);
}
cursor.moveToPosition(position);
((TextView) convertView.findViewById(android.R.id.text1)).setText(cursor.getString(6));
((TextView) convertView.findViewById(android.R.id.text2)).setText(cursor.getString(1));
((TextView) convertView.findViewById(android.R.id.text1)).setTextColor(Color.GREEN);
((TextView) convertView.findViewById(android.R.id.text2)).setTextColor(Color.RED);
// ((TextView) convertView).setTextSize(42);
// ((TextView) convertView).setTextColor(Color.GREEN);
return convertView;
}
@Override
public long getItemId(int position) {
cursor.moveToPosition(position);
return Long.valueOf(cursor.getString(cursor.getColumnIndex("id")));
// TODO Auto-generated method stub
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
cursor.moveToPosition(position);
return cursor.getString(1);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
Log.d("ListPdn",cursor.getCount()+"<- cursor.length");
return cursor.getCount();
}
});
}
}
| protected void onStart() {
// TODO Auto-generated method stub
Log.d(tag,"onstart");
super.onStart();
if (PreferenceManager.getDefaultSharedPreferences(this).getString("dialstation_user_path", null) == null)
{
startActivity(new Intent(this,SettingsActivity.class));
Toast.makeText(this, "enter credentials"+force, Toast.LENGTH_LONG).show();
force += "!!!";
if (force.contains("!!!!!!!!!!!!")) force = " AND DESTROY YOUR PHONE!";
}
else {
Log.d(tag,"really provider called");
cursor = getContentResolver().query(Uri.parse("content://com.dialstation"), null, null, null, null);
//Log.d(tag,"cols.....: "+cursor.getColumnCount());
Log.d(tag,"nooooclomun");
setListAdapter(new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(android.R.layout.simple_list_item_2, null);
}
cursor.moveToPosition(position);
((TextView) convertView.findViewById(android.R.id.text1)).setText(cursor.getString(cursor.getColumnIndex("pstn_number")));
((TextView) convertView.findViewById(android.R.id.text2)).setText(cursor.getString(cursor.getColumnIndex("description")));
((TextView) convertView.findViewById(android.R.id.text1)).setTextColor(Color.GREEN);
((TextView) convertView.findViewById(android.R.id.text2)).setTextColor(Color.RED);
// ((TextView) convertView).setTextSize(42);
// ((TextView) convertView).setTextColor(Color.GREEN);
return convertView;
}
@Override
public long getItemId(int position) {
cursor.moveToPosition(position);
return Long.valueOf(cursor.getString(cursor.getColumnIndex("id")));
// TODO Auto-generated method stub
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
cursor.moveToPosition(position);
return cursor.getString(1);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
Log.d("ListPdn",cursor.getCount()+"<- cursor.length");
return cursor.getCount();
}
});
}
}
|
diff --git a/src/main/java/nl/mineleni/cbsviewer/servlet/wms/FeatureInfoResponseConverter.java b/src/main/java/nl/mineleni/cbsviewer/servlet/wms/FeatureInfoResponseConverter.java
index 2f73d40bb..f2e247fe1 100644
--- a/src/main/java/nl/mineleni/cbsviewer/servlet/wms/FeatureInfoResponseConverter.java
+++ b/src/main/java/nl/mineleni/cbsviewer/servlet/wms/FeatureInfoResponseConverter.java
@@ -1,182 +1,182 @@
/*
* Copyright (c) 2012, Dienst Landelijk Gebied - Ministerie van Economische Zaken
*
* Gepubliceerd onder de BSD 2-clause licentie,
* zie https://github.com/MinELenI/CBSviewer/blob/master/LICENSE.md voor de volledige licentie.
*/
package nl.mineleni.cbsviewer.servlet.wms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.parsers.ParserConfigurationException;
import nl.mineleni.cbsviewer.util.LabelsBundle;
import org.geotools.GML;
import org.geotools.GML.Version;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.opengis.feature.simple.SimpleFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
/**
* Utility klasse FeatureInfoResponseConverter kan gebruikt worden om
* FeatureInfo responses te parsen en te converteren naar een andere vorm.
*
* @author mprins
* @since 1.7
*/
public final class FeatureInfoResponseConverter {
/** logger. */
private static final Logger LOGGER = LoggerFactory
.getLogger(FeatureInfoResponseConverter.class);
/** resource bundle. */
private static final LabelsBundle RESOURCES = new LabelsBundle();
/**
* Cleanup html.
*
* @param htmlStream
* the html stream
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
* @todo implementatie
*/
private static String cleanupHTML(final InputStream htmlStream)
throws IOException {
LOGGER.warn("unsported feature");
// misschien met net.sourceforge.htmlcleaner:htmlcleaner
// http://search.maven.org/#artifactdetails%7Cnet.sourceforge.htmlcleaner%7Chtmlcleaner%7C2.2%7Cjar
// of jsoup
return convertStreamToString(htmlStream);
}
/**
* Converteer gml imputstream naar html tabel.
*
* @param gmlStream
* the gml stream
* @param attributes
* the attributes
* @return een html tabel
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private static String convertGML(final InputStream gmlStream,
final String[] attributes) throws IOException {
final StringBuilder sb = new StringBuilder();
try {
final GML gml = new GML(Version.WFS1_0);
final SimpleFeatureIterator iter = gml
.decodeFeatureIterator(gmlStream);
if (iter.hasNext()) {
// tabel maken
sb.append("<table id=\"attribuutTabel\" class=\"attribuutTabel\">");
- sb.append("<caption>");
+ //sb.append("<caption>");
// removed because also in header accordion
//sb.append("Informatie over de zoeklocatie.");
- sb.append("</caption>");
+ //sb.append("</caption>");
sb.append("<thead><tr>");
for (final String n : attributes) {
sb.append("<th scope=\"col\">" + n + "</th>");
}
sb.append("</tr></thead>");
sb.append("<tbody>");
int i = 0;
while (iter.hasNext()) {
sb.append("<tr class=\"" + (((i++ % 2) == 0) ? "" : "even")
+ "\">");
final SimpleFeature f = iter.next();
for (final String n : attributes) {
sb.append("<td>" + f.getAttribute(n) + "</td>");
}
sb.append("</tr>");
}
sb.append("</tbody>");
sb.append("</table>");
iter.close();
LOGGER.debug("Gemaakte HTML tabel:\n" + sb);
} else {
LOGGER.debug("Geen attribuut info voor deze locatie/zoomnivo");
return RESOURCES.getString("KEY_INFO_GEEN_FEATURES");
}
} catch (ParserConfigurationException | SAXException e) {
LOGGER.error("Fout tijdens parsen van GML. ", e);
} finally {
gmlStream.close();
}
return sb.toString();
}
/**
* Converteert een stream naar een string.
*
* @param is
* de InputStream met data
* @return de data als string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private static String convertStreamToString(final InputStream is)
throws IOException {
if (is != null) {
final Writer writer = new StringWriter();
final char[] buffer = new char[1024];
try {
final Reader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
/**
* Converteer de input naar een html tabel.
*
* @param input
* inputstream met de featureinfo response.
* @param type
* het type conversie, ondersteund is {@code "GMLTYPE"}
* @param attributes
* namen van de feature attributen
* @return een html tabel
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static String convertToHTMLTable(final InputStream input,
final String type, final String[] attributes) throws IOException {
switch (type.toUpperCase()) {
case "GMLTYPE":
return convertGML(input, attributes);
case "HTMLTYPE":
return cleanupHTML(input);
default:
return convertStreamToString(input);
}
}
/**
* private constructor.
*/
private FeatureInfoResponseConverter() {
// private constructor voor utility klasse
}
}
| false | true | private static String convertGML(final InputStream gmlStream,
final String[] attributes) throws IOException {
final StringBuilder sb = new StringBuilder();
try {
final GML gml = new GML(Version.WFS1_0);
final SimpleFeatureIterator iter = gml
.decodeFeatureIterator(gmlStream);
if (iter.hasNext()) {
// tabel maken
sb.append("<table id=\"attribuutTabel\" class=\"attribuutTabel\">");
sb.append("<caption>");
// removed because also in header accordion
//sb.append("Informatie over de zoeklocatie.");
sb.append("</caption>");
sb.append("<thead><tr>");
for (final String n : attributes) {
sb.append("<th scope=\"col\">" + n + "</th>");
}
sb.append("</tr></thead>");
sb.append("<tbody>");
int i = 0;
while (iter.hasNext()) {
sb.append("<tr class=\"" + (((i++ % 2) == 0) ? "" : "even")
+ "\">");
final SimpleFeature f = iter.next();
for (final String n : attributes) {
sb.append("<td>" + f.getAttribute(n) + "</td>");
}
sb.append("</tr>");
}
sb.append("</tbody>");
sb.append("</table>");
iter.close();
LOGGER.debug("Gemaakte HTML tabel:\n" + sb);
} else {
LOGGER.debug("Geen attribuut info voor deze locatie/zoomnivo");
return RESOURCES.getString("KEY_INFO_GEEN_FEATURES");
}
} catch (ParserConfigurationException | SAXException e) {
LOGGER.error("Fout tijdens parsen van GML. ", e);
} finally {
gmlStream.close();
}
return sb.toString();
}
| private static String convertGML(final InputStream gmlStream,
final String[] attributes) throws IOException {
final StringBuilder sb = new StringBuilder();
try {
final GML gml = new GML(Version.WFS1_0);
final SimpleFeatureIterator iter = gml
.decodeFeatureIterator(gmlStream);
if (iter.hasNext()) {
// tabel maken
sb.append("<table id=\"attribuutTabel\" class=\"attribuutTabel\">");
//sb.append("<caption>");
// removed because also in header accordion
//sb.append("Informatie over de zoeklocatie.");
//sb.append("</caption>");
sb.append("<thead><tr>");
for (final String n : attributes) {
sb.append("<th scope=\"col\">" + n + "</th>");
}
sb.append("</tr></thead>");
sb.append("<tbody>");
int i = 0;
while (iter.hasNext()) {
sb.append("<tr class=\"" + (((i++ % 2) == 0) ? "" : "even")
+ "\">");
final SimpleFeature f = iter.next();
for (final String n : attributes) {
sb.append("<td>" + f.getAttribute(n) + "</td>");
}
sb.append("</tr>");
}
sb.append("</tbody>");
sb.append("</table>");
iter.close();
LOGGER.debug("Gemaakte HTML tabel:\n" + sb);
} else {
LOGGER.debug("Geen attribuut info voor deze locatie/zoomnivo");
return RESOURCES.getString("KEY_INFO_GEEN_FEATURES");
}
} catch (ParserConfigurationException | SAXException e) {
LOGGER.error("Fout tijdens parsen van GML. ", e);
} finally {
gmlStream.close();
}
return sb.toString();
}
|
diff --git a/src/org/objectweb/proactive/ic2d/gui/jobmonitor/NodeExploration.java b/src/org/objectweb/proactive/ic2d/gui/jobmonitor/NodeExploration.java
index 1310a7705..f25307a01 100644
--- a/src/org/objectweb/proactive/ic2d/gui/jobmonitor/NodeExploration.java
+++ b/src/org/objectweb/proactive/ic2d/gui/jobmonitor/NodeExploration.java
@@ -1,167 +1,168 @@
package org.objectweb.proactive.ic2d.gui.jobmonitor;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.body.rmi.RemoteBodyAdapter;
import org.objectweb.proactive.core.runtime.ProActiveRuntime;
import org.objectweb.proactive.core.runtime.rmi.*;
import org.objectweb.proactive.ic2d.gui.IC2DGUIController;
import org.objectweb.proactive.ic2d.gui.jobmonitor.data.DataAssociation;
import java.rmi.*;
import java.rmi.registry.*;
import java.util.*;
public class NodeExploration implements JobMonitorConstants {
private static final String PA_JVM = "PA_JVM";
private int maxDepth;
private DataAssociation asso;
private Vector filteredJobs;
private IC2DGUIController controller;
private Map aos;
private Set visitedVM;
public NodeExploration(DataAssociation asso, Vector filteredJobs,
IC2DGUIController controller) {
this.maxDepth = 1;
this.asso = asso;
this.filteredJobs = filteredJobs;
this.controller = controller;
this.aos = new HashMap();
}
public int getMaxDepth() {
return maxDepth;
}
public void setMaxDepth(int maxDepth) {
if (maxDepth > 0) {
this.maxDepth = maxDepth;
}
}
public void exploreHost(String hostname, int port) {
try {
visitedVM = new TreeSet();
Registry registry = LocateRegistry.getRegistry(hostname, port);
String[] list = registry.list();
for (int idx = 0; idx < list.length; ++idx) {
String id = list[idx];
if (id.indexOf(PA_JVM) != -1) {
RemoteProActiveRuntime r = (RemoteProActiveRuntime) registry.lookup(id);
List x = new ArrayList();
try {
ProActiveRuntime part = new RemoteProActiveRuntimeAdapter(r);
x.add(part);
ProActiveRuntime[] runtimes = r.getProActiveRuntimes();
x.addAll(Arrays.asList(runtimes));
for (int i = 0, size = x.size(); i < size; ++i) {
handleProActiveRuntime((ProActiveRuntime) x.get(i), 1);
}
} catch (ProActiveException e) {
// System.out.println ("Unexpected ProActive exception caught while obtaining runtime reference from the RemoteProActiveRuntime instance - The RMI reference might be dead: " + e);
// e.printStackTrace();
} catch (RemoteException e) {
// System.out.println ("Unexpected remote exception caught while getting proactive runtimes: " + e);
// e.printStackTrace();
}
}
}
} catch (RemoteException e) {
// System.out.println("Unexpected exception caught while getting registry reference: " + e);
// e.printStackTrace();
} catch (NotBoundException e) {
// System.out.println("Unexpected not bound exception caught while looking up object reference: " + e);
// e.printStackTrace();
} finally {
visitedVM = null;
}
}
private void handleProActiveRuntime(ProActiveRuntime pr, int depth)
throws ProActiveException {
if (pr instanceof RemoteProActiveRuntime && !(pr instanceof RemoteProActiveRuntimeAdapter))
pr = new RemoteProActiveRuntimeAdapter((RemoteProActiveRuntime) pr);
String vmName = pr.getVMInformation().getName();
if (isJobFiltered(pr.getJobID()) || visitedVM.contains(vmName))
return;
visitedVM.add(vmName);
String jobId = pr.getJobID();
String hostname = pr.getVMInformation().getInetAddress()
.getCanonicalHostName();
asso.addChild(JOB, jobId, vmName);
String[] nodes = pr.getLocalNodeNames();
// System.out.println ("Found " + nodes.length + " nodes on this runtime");
for (int i = 0; i < nodes.length; ++i) {
String nodeName = nodes[i];
String vnName = pr.getVNName(nodeName);
ArrayList activeObjects = null;
try {
activeObjects = pr.getActiveObjects(nodeName);
} catch (ProActiveException e) {
controller.log("Unexpected ProActive exception caught while obtaining the active objects list",
e);
}
asso.addChild(JVM, vmName, nodeName);
asso.addChild(HOST, hostname, JVM, vmName);
if (vnName != null) {
asso.addChild(VN, vnName, NODE, nodeName);
}
- handleActiveObjects(nodeName, activeObjects);
+ if (activeObjects != null)
+ handleActiveObjects(nodeName, activeObjects);
}
if (depth < maxDepth) {
ProActiveRuntime[] runtimes = pr.getProActiveRuntimes();
for (int i = 0; i < runtimes.length; ++i)
handleProActiveRuntime(runtimes[i], depth + 1);
}
}
private void handleActiveObjects(String nodeName, ArrayList activeObjects) {
for (int i = 0, size = activeObjects.size(); i < size; ++i) {
ArrayList aoWrapper = (ArrayList) activeObjects.get(i);
RemoteBodyAdapter rba = (RemoteBodyAdapter) aoWrapper.get(0);
// System.out.println ("Active object " + (i + 1) + " / " + size + " class: " + aoWrapper.get (1));
String className = (String) aoWrapper.get(1);
if (className.equalsIgnoreCase(
"org.objectweb.proactive.ic2d.spy.Spy")) {
continue;
}
className = className.substring(className.lastIndexOf(".") + 1);
String aoName = (String) aos.get(rba.getID());
if (aoName == null) {
aoName = className + "#" + (aos.size() + 1);
aos.put(rba.getID(), aoName);
}
asso.addChild(NODE, nodeName, aoName);
}
}
private boolean isJobFiltered(String jobId) {
for (int i = 0, size = filteredJobs.size(); i < size; ++i) {
String job = (String) filteredJobs.get(i);
if (job.equalsIgnoreCase(jobId)) {
return true;
}
}
return false;
}
}
| true | true | private void handleProActiveRuntime(ProActiveRuntime pr, int depth)
throws ProActiveException {
if (pr instanceof RemoteProActiveRuntime && !(pr instanceof RemoteProActiveRuntimeAdapter))
pr = new RemoteProActiveRuntimeAdapter((RemoteProActiveRuntime) pr);
String vmName = pr.getVMInformation().getName();
if (isJobFiltered(pr.getJobID()) || visitedVM.contains(vmName))
return;
visitedVM.add(vmName);
String jobId = pr.getJobID();
String hostname = pr.getVMInformation().getInetAddress()
.getCanonicalHostName();
asso.addChild(JOB, jobId, vmName);
String[] nodes = pr.getLocalNodeNames();
// System.out.println ("Found " + nodes.length + " nodes on this runtime");
for (int i = 0; i < nodes.length; ++i) {
String nodeName = nodes[i];
String vnName = pr.getVNName(nodeName);
ArrayList activeObjects = null;
try {
activeObjects = pr.getActiveObjects(nodeName);
} catch (ProActiveException e) {
controller.log("Unexpected ProActive exception caught while obtaining the active objects list",
e);
}
asso.addChild(JVM, vmName, nodeName);
asso.addChild(HOST, hostname, JVM, vmName);
if (vnName != null) {
asso.addChild(VN, vnName, NODE, nodeName);
}
handleActiveObjects(nodeName, activeObjects);
}
if (depth < maxDepth) {
ProActiveRuntime[] runtimes = pr.getProActiveRuntimes();
for (int i = 0; i < runtimes.length; ++i)
handleProActiveRuntime(runtimes[i], depth + 1);
}
}
| private void handleProActiveRuntime(ProActiveRuntime pr, int depth)
throws ProActiveException {
if (pr instanceof RemoteProActiveRuntime && !(pr instanceof RemoteProActiveRuntimeAdapter))
pr = new RemoteProActiveRuntimeAdapter((RemoteProActiveRuntime) pr);
String vmName = pr.getVMInformation().getName();
if (isJobFiltered(pr.getJobID()) || visitedVM.contains(vmName))
return;
visitedVM.add(vmName);
String jobId = pr.getJobID();
String hostname = pr.getVMInformation().getInetAddress()
.getCanonicalHostName();
asso.addChild(JOB, jobId, vmName);
String[] nodes = pr.getLocalNodeNames();
// System.out.println ("Found " + nodes.length + " nodes on this runtime");
for (int i = 0; i < nodes.length; ++i) {
String nodeName = nodes[i];
String vnName = pr.getVNName(nodeName);
ArrayList activeObjects = null;
try {
activeObjects = pr.getActiveObjects(nodeName);
} catch (ProActiveException e) {
controller.log("Unexpected ProActive exception caught while obtaining the active objects list",
e);
}
asso.addChild(JVM, vmName, nodeName);
asso.addChild(HOST, hostname, JVM, vmName);
if (vnName != null) {
asso.addChild(VN, vnName, NODE, nodeName);
}
if (activeObjects != null)
handleActiveObjects(nodeName, activeObjects);
}
if (depth < maxDepth) {
ProActiveRuntime[] runtimes = pr.getProActiveRuntimes();
for (int i = 0; i < runtimes.length; ++i)
handleProActiveRuntime(runtimes[i], depth + 1);
}
}
|
diff --git a/src/main/java/org/oneandone/idev/johanna/protocol/impl/VarReadRequest.java b/src/main/java/org/oneandone/idev/johanna/protocol/impl/VarReadRequest.java
index e5769af..c851195 100644
--- a/src/main/java/org/oneandone/idev/johanna/protocol/impl/VarReadRequest.java
+++ b/src/main/java/org/oneandone/idev/johanna/protocol/impl/VarReadRequest.java
@@ -1,29 +1,29 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.oneandone.idev.johanna.protocol.impl;
import java.util.logging.Logger;
import org.oneandone.idev.johanna.protocol.Response;
import org.oneandone.idev.johanna.store.AbstractSession;
import org.oneandone.idev.johanna.store.SessionStore;
/**
*
* @author kiesel
*/
public class VarReadRequest extends SessionKeyBasedRequest {
private static final Logger LOG = Logger.getLogger(VarReadRequest.class.getName());
public VarReadRequest(String command) {
super(command);
}
@Override
protected Response processSessionKey(SessionStore store, AbstractSession s, String name) {
if (!s.hasValue(name)) return Response.NOKEY;
- return new Response(true, name);
+ return new Response(true, s.getValue(name));
}
}
| true | true | protected Response processSessionKey(SessionStore store, AbstractSession s, String name) {
if (!s.hasValue(name)) return Response.NOKEY;
return new Response(true, name);
}
| protected Response processSessionKey(SessionStore store, AbstractSession s, String name) {
if (!s.hasValue(name)) return Response.NOKEY;
return new Response(true, s.getValue(name));
}
|
diff --git a/Curiosity/src/edu/kit/curiosity/behaviors/tape/ObstacleFound.java b/Curiosity/src/edu/kit/curiosity/behaviors/tape/ObstacleFound.java
index 5378162..87a231b 100644
--- a/Curiosity/src/edu/kit/curiosity/behaviors/tape/ObstacleFound.java
+++ b/Curiosity/src/edu/kit/curiosity/behaviors/tape/ObstacleFound.java
@@ -1,57 +1,57 @@
package edu.kit.curiosity.behaviors.tape;
import edu.kit.curiosity.Settings;
import lejos.nxt.LightSensor;
import lejos.nxt.TouchSensor;
import lejos.nxt.UltrasonicSensor;
import lejos.robotics.navigation.DifferentialPilot;
import lejos.robotics.subsumption.Behavior;
public class ObstacleFound implements Behavior {
private boolean suppressed = false;
TouchSensor touch_l = Settings.TOUCH_L;
TouchSensor touch_r = Settings.TOUCH_R;
DifferentialPilot pilot = Settings.PILOT;
UltrasonicSensor sensor = Settings.SONIC;
LightSensor light = Settings.LIGHT;
private final int distanceToWall = 12;
@Override
public boolean takeControl() {
return (Settings.obstacle || touch_l.isPressed() || touch_r.isPressed());
}
@Override
public void action() {
suppressed = false;
if (!Settings.obstacle) { //If not in obstacle mode - initialize obstacle mode
Settings.obstacle = true;
Settings.motorAAngle = 0;
- pilot.travel(-10, true); // TODO true?
- pilot.rotate(100, true); // TODO true?
+ pilot.travel(-10);
+ pilot.rotate(100);
}
while (!suppressed && light.getLightValue() < 50) { //arcs until line found
if (!pilot.isMoving() && sensor.getDistance() > (distanceToWall + 10)) {
pilot.arc(-15, -90, true);
} else if (!pilot.isMoving() && sensor.getDistance() < distanceToWall) {
pilot.arc(60, 20, true);
} else if (!pilot.isMoving() && sensor.getDistance() >= distanceToWall) {
pilot.arc(-60, -20, true);
}
}
if (light.getLightValue() > 50) { //if line found - leave obstacle mode
Settings.obstacle = false;
pilot.travel(-5);
Settings.motorAAngle = 90;
}
pilot.stop();
}
@Override
public void suppress() {
suppressed = true;
}
}
| true | true | public void action() {
suppressed = false;
if (!Settings.obstacle) { //If not in obstacle mode - initialize obstacle mode
Settings.obstacle = true;
Settings.motorAAngle = 0;
pilot.travel(-10, true); // TODO true?
pilot.rotate(100, true); // TODO true?
}
while (!suppressed && light.getLightValue() < 50) { //arcs until line found
if (!pilot.isMoving() && sensor.getDistance() > (distanceToWall + 10)) {
pilot.arc(-15, -90, true);
} else if (!pilot.isMoving() && sensor.getDistance() < distanceToWall) {
pilot.arc(60, 20, true);
} else if (!pilot.isMoving() && sensor.getDistance() >= distanceToWall) {
pilot.arc(-60, -20, true);
}
}
if (light.getLightValue() > 50) { //if line found - leave obstacle mode
Settings.obstacle = false;
pilot.travel(-5);
Settings.motorAAngle = 90;
}
pilot.stop();
}
| public void action() {
suppressed = false;
if (!Settings.obstacle) { //If not in obstacle mode - initialize obstacle mode
Settings.obstacle = true;
Settings.motorAAngle = 0;
pilot.travel(-10);
pilot.rotate(100);
}
while (!suppressed && light.getLightValue() < 50) { //arcs until line found
if (!pilot.isMoving() && sensor.getDistance() > (distanceToWall + 10)) {
pilot.arc(-15, -90, true);
} else if (!pilot.isMoving() && sensor.getDistance() < distanceToWall) {
pilot.arc(60, 20, true);
} else if (!pilot.isMoving() && sensor.getDistance() >= distanceToWall) {
pilot.arc(-60, -20, true);
}
}
if (light.getLightValue() > 50) { //if line found - leave obstacle mode
Settings.obstacle = false;
pilot.travel(-5);
Settings.motorAAngle = 90;
}
pilot.stop();
}
|
diff --git a/luaj-vm/src/core/org/luaj/lib/BaseLib.java b/luaj-vm/src/core/org/luaj/lib/BaseLib.java
index f00d69b..7dfc333 100644
--- a/luaj-vm/src/core/org/luaj/lib/BaseLib.java
+++ b/luaj-vm/src/core/org/luaj/lib/BaseLib.java
@@ -1,445 +1,448 @@
/**
*
*/
package org.luaj.lib;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import org.luaj.vm.CallInfo;
import org.luaj.vm.LClosure;
import org.luaj.vm.LFunction;
import org.luaj.vm.LInteger;
import org.luaj.vm.LNil;
import org.luaj.vm.LNumber;
import org.luaj.vm.LString;
import org.luaj.vm.LTable;
import org.luaj.vm.LValue;
import org.luaj.vm.Lua;
import org.luaj.vm.LuaState;
import org.luaj.vm.Platform;
public class BaseLib extends LFunction {
public static InputStream STDIN = null;
public static PrintStream STDOUT = System.out;
private static PrintStream stdout = System.out;
private static final String[] NAMES = {
"base",
"print",
"pairs",
"getmetatable",
"setmetatable",
"type",
"pcall",
"ipairs",
"error",
"assert",
"loadfile",
"tonumber",
"rawget",
"rawset",
"setfenv",
"select",
"collectgarbage",
"dofile",
"loadstring",
"load",
"tostring",
"unpack",
"next",
};
private static final int INSTALL = 0;
private static final int PRINT = 1;
private static final int PAIRS = 2;
private static final int GETMETATABLE = 3;
private static final int SETMETATABLE = 4;
private static final int TYPE = 5;
private static final int PCALL = 6;
private static final int IPAIRS = 7;
private static final int ERROR = 8;
private static final int ASSERT = 9;
private static final int LOADFILE = 10;
private static final int TONUMBER = 11;
private static final int RAWGET = 12;
private static final int RAWSET = 13;
private static final int SETFENV = 14;
private static final int SELECT = 15;
private static final int COLLECTGARBAGE = 16;
private static final int DOFILE = 17;
private static final int LOADSTRING = 18;
private static final int LOAD = 19;
private static final int TOSTRING = 20;
private static final int UNPACK = 21;
private static final int NEXT = 22;
public static void install(LTable globals) {
for ( int i=1; i<NAMES.length; i++ )
globals.put( NAMES[i], new BaseLib(i) );
}
private int id;
private BaseLib( int id ) {
this.id = id;
}
public String toString() {
return NAMES[id]+"()";
}
private static void setResult( LuaState vm, LValue value ) {
vm.settop(0);
vm.pushlvalue( value );
}
private static void setErrorResult( LuaState vm, String message ) {
vm.settop(0);
vm.pushnil();
vm.pushstring( message );
}
public boolean luaStackCall(LuaState vm) {
switch ( id ) {
case PRINT: {
int n = vm.gettop();
for ( int i=2; i<=n; i++ ) {
if ( i > 2 )
stdout.print( "\t" );
stdout.print( vm.tostring(i) );
}
stdout.println();
vm.settop(0);
break;
}
case PAIRS:
case IPAIRS: {
LValue v = vm.topointer(2);
LValue r = v.luaPairs(id==PAIRS);
vm.settop(0);
vm.pushlvalue( r );
break;
}
case GETMETATABLE: {
- int r = vm.getmetatable(2);
- vm.settop(0);
- vm.pushinteger(r);
+ if ( 0 == vm.getmetatable(2) )
+ vm.settop(0);
+ else {
+ vm.insert(1);
+ vm.settop(1);
+ }
break;
}
case SETMETATABLE: {
vm.setmetatable(2);
vm.remove(1);
break;
}
case TYPE: {
LValue v = vm.topointer(2);
vm.settop(0);
vm.pushlstring( v.luaGetTypeName() );
break;
}
case PCALL: {
int n = vm.gettop();
int s = vm.pcall( n-2, Lua.LUA_MULTRET, 0 );
if ( s == 0 ) { // success, results are on stack above the pcall
vm.remove( 1 );
vm.pushboolean( true );
vm.insert( 1 );
} else { // error, error message is on the stack
vm.pushboolean( false );
vm.insert( 1 );
}
break;
}
case ERROR: {
vm.error(vm.tostring(2), vm.gettop()>2? vm.tointeger(3): 1);
break;
}
case ASSERT: {
if ( ! vm.toboolean(2) )
vm.error( vm.gettop()>2? vm.tostring(3): "assertion failed!", 0 );
vm.remove(1);
break;
}
case LOADFILE:
loadfile(vm, vm.tostring(2));
break;
case TONUMBER: {
LValue input = vm.topointer(2);
vm.settop(0);
if ( input instanceof LNumber ) {
vm.pushlvalue(input);
} else if ( input instanceof LString ) {
int base = 10;
if ( vm.gettop()>=3 ) {
base = vm.tointeger(3);
}
vm.pushlvalue( ( (LString) input ).luaToNumber( base ) );
}
vm.pushnil();
break;
}
case RAWGET: {
LValue t = vm.topointer(2);
LValue k = vm.topointer(3);
vm.settop(0);
if ( t instanceof LTable ) {
vm.pushlvalue(( (LTable) t ).get( k ));
}
} break;
case RAWSET: {
LValue t = vm.topointer(2);
LValue k = vm.topointer(3);
LValue v = vm.topointer(4);
vm.settop(0);
if ( t instanceof LTable ) {
( (LTable) t ).put( k, v );
} else {
vm.error( "expected table" );
}
} break;
case SETFENV:
setfenv( (LuaState) vm );
break;
case SELECT:
select( vm );
break;
case COLLECTGARBAGE:
System.gc();
vm.settop(0);
break;
case DOFILE:
dofile(vm);
break;
case LOADSTRING:
loadstring(vm, vm.topointer(2), vm.tostring(3));
break;
case LOAD:
load(vm, vm.topointer(2), vm.tostring(3));
break;
case TOSTRING: {
LValue v = vm.topointer(2);
vm.settop(0);
vm.pushlvalue( v.luaAsString() );
break;
}
case UNPACK:
unpack(vm);
break;
case NEXT: {
setResult( vm, next(vm, vm.topointer(2), vm.tointeger(3)) );
break;
}
default:
luaUnsupportedOperation();
}
return false;
}
public static void redirectOutput( OutputStream newStdOut ) {
stdout = new PrintStream( newStdOut );
}
public static void restoreStandardOutput() {
stdout = System.out;
}
private void select( LuaState vm ) {
LValue arg = vm.topointer(2);
if ( arg instanceof LNumber ) {
final int start = Math.min(arg.toJavaInt(),vm.gettop());
for ( int i=0; i<=start; i++ )
vm.remove(1);
return;
} else if ( arg.toJavaString().equals( "#" ) ) {
setResult( vm, LInteger.valueOf( vm.gettop() - 2 ) );
}
}
private void setfenv( LuaState state ) {
LValue f = state.topointer(2);
LValue newenv = state.topointer(3);
LClosure c = null;
// Lua reference manual says that first argument, f, can be a "Lua
// function" or an integer. Lots of things extend LFunction, but only
// instances of Closure are "Lua functions".
if ( f instanceof LClosure ) {
c = (LClosure) f;
} else {
int callStackDepth = f.toJavaInt();
if ( callStackDepth > 0 ) {
CallInfo frame = state.getStackFrame( callStackDepth );
if ( frame != null ) {
c = frame.closure;
}
} else {
// This is supposed to set the environment of the current
// "thread". But, we have not implemented coroutines yet.
throw new RuntimeException( "not implemented" );
}
}
if ( c != null ) {
if ( newenv instanceof LTable ) {
c.env = (LTable) newenv;
}
state.settop(0);
state.pushlvalue( c );
return;
}
state.settop(0);
return;
}
// closes the input stream, provided its not null or System.in
private static void closeSafely(InputStream is) {
try {
if ( is != null && is != STDIN )
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// closes the output stream, provided its not null or STDOUT
private static void closeSafely(OutputStream os) {
try {
if ( os != null && os != STDOUT )
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// return true if laoded, false if error put onto the stack
private static boolean loadis(LuaState vm, InputStream is, String chunkname ) {
try {
vm.settop(0);
if ( 0 != vm.load(is, chunkname) ) {
setErrorResult( vm, "cannot load "+chunkname+": "+vm.topointer(-1) );
return false;
} else {
return true;
}
} finally {
closeSafely( is );
}
}
// return true if loaded, false if error put onto stack
public static boolean loadfile( LuaState vm, String fileName ) {
InputStream is;
String script;
if ( ! "".equals(fileName) ) {
script = fileName;
is = Platform.getInstance().openFile(fileName);
if ( is == null ) {
setErrorResult( vm, "cannot open "+fileName+": No such file or directory" );
return false;
}
} else {
is = STDIN;
script = "-";
}
// use vm to load the script
return loadis( vm, is, script );
}
// if load succeeds, return 0 for success, 1 for error (as per lua spec)
private void dofile( LuaState vm ) {
String filename = vm.tostring(2);
if ( loadfile( vm, filename ) ) {
int s = vm.pcall(1, 0, 0);
setResult( vm, LInteger.valueOf( s!=0? 1: 0 ) );
} else {
vm.error("cannot open "+filename);
}
}
// return true if loaded, false if error put onto stack
private boolean loadstring(LuaState vm, LValue string, String chunkname) {
return loadis( vm,
string.luaAsString().toInputStream(),
("".equals(chunkname)? "(string)": chunkname) );
}
// return true if loaded, false if error put onto stack
private boolean load(LuaState vm, LValue chunkPartLoader, String chunkname) {
if ( ! (chunkPartLoader instanceof LClosure) ) {
vm.error("not a closure: "+chunkPartLoader);
}
// load all the parts
LClosure c = (LClosure) chunkPartLoader;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
while ( true ) {
setResult(vm,c);
if ( 0 != vm.pcall(0, 1, 0) ) {
setErrorResult(vm, vm.tostring(2));
return false;
}
LValue v = vm.topointer(2);
if ( v == LNil.NIL )
break;
LString s = v.luaAsString();
s.write(baos, 0, s.length());
}
// load the chunk
return loadis( vm,
new ByteArrayInputStream( baos.toByteArray() ),
("".equals(chunkname)? "=(load)": chunkname) );
} catch (IOException ioe) {
setErrorResult(vm, ioe.getMessage());
return false;
} finally {
closeSafely( baos );
}
}
/** unpack (list [, i [, j]])
*
* Returns the elements from the given table. This function is equivalent to
* return list[i], list[i+1], ···, list[j]
*
* except that the above code can be written only for a fixed number of elements.
* By default, i is 1 and j is the length of the list, as defined by the length operator (see §2.5.5).
*/
private void unpack(LuaState vm) {
LValue v = vm.topointer(2);
int i = vm.tointeger(3);
int j = vm.tointeger(4);
LTable list = (LTable) v;
if ( i == 0 )
i = 1;
if ( j == 0 )
j = list.luaLength();
vm.settop(0);
for ( int k=i; k<=j; k++ )
vm.pushlvalue( list.get(k) );
}
private LValue next(LuaState vm, LValue table, int index) {
throw new java.lang.RuntimeException("next() not supported yet");
}
}
| true | true | public boolean luaStackCall(LuaState vm) {
switch ( id ) {
case PRINT: {
int n = vm.gettop();
for ( int i=2; i<=n; i++ ) {
if ( i > 2 )
stdout.print( "\t" );
stdout.print( vm.tostring(i) );
}
stdout.println();
vm.settop(0);
break;
}
case PAIRS:
case IPAIRS: {
LValue v = vm.topointer(2);
LValue r = v.luaPairs(id==PAIRS);
vm.settop(0);
vm.pushlvalue( r );
break;
}
case GETMETATABLE: {
int r = vm.getmetatable(2);
vm.settop(0);
vm.pushinteger(r);
break;
}
case SETMETATABLE: {
vm.setmetatable(2);
vm.remove(1);
break;
}
case TYPE: {
LValue v = vm.topointer(2);
vm.settop(0);
vm.pushlstring( v.luaGetTypeName() );
break;
}
case PCALL: {
int n = vm.gettop();
int s = vm.pcall( n-2, Lua.LUA_MULTRET, 0 );
if ( s == 0 ) { // success, results are on stack above the pcall
vm.remove( 1 );
vm.pushboolean( true );
vm.insert( 1 );
} else { // error, error message is on the stack
vm.pushboolean( false );
vm.insert( 1 );
}
break;
}
case ERROR: {
vm.error(vm.tostring(2), vm.gettop()>2? vm.tointeger(3): 1);
break;
}
case ASSERT: {
if ( ! vm.toboolean(2) )
vm.error( vm.gettop()>2? vm.tostring(3): "assertion failed!", 0 );
vm.remove(1);
break;
}
case LOADFILE:
loadfile(vm, vm.tostring(2));
break;
case TONUMBER: {
LValue input = vm.topointer(2);
vm.settop(0);
if ( input instanceof LNumber ) {
vm.pushlvalue(input);
} else if ( input instanceof LString ) {
int base = 10;
if ( vm.gettop()>=3 ) {
base = vm.tointeger(3);
}
vm.pushlvalue( ( (LString) input ).luaToNumber( base ) );
}
vm.pushnil();
break;
}
case RAWGET: {
LValue t = vm.topointer(2);
LValue k = vm.topointer(3);
vm.settop(0);
if ( t instanceof LTable ) {
vm.pushlvalue(( (LTable) t ).get( k ));
}
} break;
case RAWSET: {
LValue t = vm.topointer(2);
LValue k = vm.topointer(3);
LValue v = vm.topointer(4);
vm.settop(0);
if ( t instanceof LTable ) {
( (LTable) t ).put( k, v );
} else {
vm.error( "expected table" );
}
} break;
case SETFENV:
setfenv( (LuaState) vm );
break;
case SELECT:
select( vm );
break;
case COLLECTGARBAGE:
System.gc();
vm.settop(0);
break;
case DOFILE:
dofile(vm);
break;
case LOADSTRING:
loadstring(vm, vm.topointer(2), vm.tostring(3));
break;
case LOAD:
load(vm, vm.topointer(2), vm.tostring(3));
break;
case TOSTRING: {
LValue v = vm.topointer(2);
vm.settop(0);
vm.pushlvalue( v.luaAsString() );
break;
}
case UNPACK:
unpack(vm);
break;
case NEXT: {
setResult( vm, next(vm, vm.topointer(2), vm.tointeger(3)) );
break;
}
default:
luaUnsupportedOperation();
}
return false;
}
| public boolean luaStackCall(LuaState vm) {
switch ( id ) {
case PRINT: {
int n = vm.gettop();
for ( int i=2; i<=n; i++ ) {
if ( i > 2 )
stdout.print( "\t" );
stdout.print( vm.tostring(i) );
}
stdout.println();
vm.settop(0);
break;
}
case PAIRS:
case IPAIRS: {
LValue v = vm.topointer(2);
LValue r = v.luaPairs(id==PAIRS);
vm.settop(0);
vm.pushlvalue( r );
break;
}
case GETMETATABLE: {
if ( 0 == vm.getmetatable(2) )
vm.settop(0);
else {
vm.insert(1);
vm.settop(1);
}
break;
}
case SETMETATABLE: {
vm.setmetatable(2);
vm.remove(1);
break;
}
case TYPE: {
LValue v = vm.topointer(2);
vm.settop(0);
vm.pushlstring( v.luaGetTypeName() );
break;
}
case PCALL: {
int n = vm.gettop();
int s = vm.pcall( n-2, Lua.LUA_MULTRET, 0 );
if ( s == 0 ) { // success, results are on stack above the pcall
vm.remove( 1 );
vm.pushboolean( true );
vm.insert( 1 );
} else { // error, error message is on the stack
vm.pushboolean( false );
vm.insert( 1 );
}
break;
}
case ERROR: {
vm.error(vm.tostring(2), vm.gettop()>2? vm.tointeger(3): 1);
break;
}
case ASSERT: {
if ( ! vm.toboolean(2) )
vm.error( vm.gettop()>2? vm.tostring(3): "assertion failed!", 0 );
vm.remove(1);
break;
}
case LOADFILE:
loadfile(vm, vm.tostring(2));
break;
case TONUMBER: {
LValue input = vm.topointer(2);
vm.settop(0);
if ( input instanceof LNumber ) {
vm.pushlvalue(input);
} else if ( input instanceof LString ) {
int base = 10;
if ( vm.gettop()>=3 ) {
base = vm.tointeger(3);
}
vm.pushlvalue( ( (LString) input ).luaToNumber( base ) );
}
vm.pushnil();
break;
}
case RAWGET: {
LValue t = vm.topointer(2);
LValue k = vm.topointer(3);
vm.settop(0);
if ( t instanceof LTable ) {
vm.pushlvalue(( (LTable) t ).get( k ));
}
} break;
case RAWSET: {
LValue t = vm.topointer(2);
LValue k = vm.topointer(3);
LValue v = vm.topointer(4);
vm.settop(0);
if ( t instanceof LTable ) {
( (LTable) t ).put( k, v );
} else {
vm.error( "expected table" );
}
} break;
case SETFENV:
setfenv( (LuaState) vm );
break;
case SELECT:
select( vm );
break;
case COLLECTGARBAGE:
System.gc();
vm.settop(0);
break;
case DOFILE:
dofile(vm);
break;
case LOADSTRING:
loadstring(vm, vm.topointer(2), vm.tostring(3));
break;
case LOAD:
load(vm, vm.topointer(2), vm.tostring(3));
break;
case TOSTRING: {
LValue v = vm.topointer(2);
vm.settop(0);
vm.pushlvalue( v.luaAsString() );
break;
}
case UNPACK:
unpack(vm);
break;
case NEXT: {
setResult( vm, next(vm, vm.topointer(2), vm.tointeger(3)) );
break;
}
default:
luaUnsupportedOperation();
}
return false;
}
|
diff --git a/src/org/antlr/codegen/RubyTarget.java b/src/org/antlr/codegen/RubyTarget.java
index bc08e11..d40a74b 100644
--- a/src/org/antlr/codegen/RubyTarget.java
+++ b/src/org/antlr/codegen/RubyTarget.java
@@ -1,73 +1,73 @@
/*
[The "BSD licence"]
Copyright (c) 2005 Martin Traverso
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 org.antlr.codegen;
public class RubyTarget
extends Target
{
public String getTargetCharLiteralFromANTLRCharLiteral(
CodeGenerator generator,
String literal)
{
literal = literal.substring(1, literal.length() - 1);
- String result = "";
+ String result = "?";
if (literal.equals("\\")) {
result += "\\\\";
}
else if (literal.equals(" ")) {
result += "\\s";
}
else if (literal.startsWith("\\u")) {
result = "0x" + literal.substring(2);
}
else {
result += literal;
}
return result;
}
public int getMaxCharValue(CodeGenerator generator)
{
// we don't support unicode, yet.
return 0xFF;
}
public String getTokenTypeAsTargetLabel(CodeGenerator generator, int ttype)
{
String name = generator.grammar.getTokenDisplayName(ttype);
// If name is a literal, return the token type instead
if ( name.charAt(0)=='\'' ) {
return generator.grammar.computeTokenNameFromLiteral(ttype, name);
}
return name;
}
}
| true | true | public String getTargetCharLiteralFromANTLRCharLiteral(
CodeGenerator generator,
String literal)
{
literal = literal.substring(1, literal.length() - 1);
String result = "";
if (literal.equals("\\")) {
result += "\\\\";
}
else if (literal.equals(" ")) {
result += "\\s";
}
else if (literal.startsWith("\\u")) {
result = "0x" + literal.substring(2);
}
else {
result += literal;
}
return result;
}
| public String getTargetCharLiteralFromANTLRCharLiteral(
CodeGenerator generator,
String literal)
{
literal = literal.substring(1, literal.length() - 1);
String result = "?";
if (literal.equals("\\")) {
result += "\\\\";
}
else if (literal.equals(" ")) {
result += "\\s";
}
else if (literal.startsWith("\\u")) {
result = "0x" + literal.substring(2);
}
else {
result += literal;
}
return result;
}
|
diff --git a/src/org/encog/neural/networks/structure/NeuralStructure.java b/src/org/encog/neural/networks/structure/NeuralStructure.java
index f7de78b5c..d2d5538c0 100644
--- a/src/org/encog/neural/networks/structure/NeuralStructure.java
+++ b/src/org/encog/neural/networks/structure/NeuralStructure.java
@@ -1,805 +1,805 @@
/*
* Encog(tm) Core v2.5 - Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2010 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.neural.networks.structure;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.encog.engine.network.activation.ActivationFunction;
import org.encog.engine.network.activation.ActivationLinear;
import org.encog.engine.network.flat.FlatLayer;
import org.encog.engine.network.flat.FlatNetwork;
import org.encog.engine.network.flat.FlatNetworkRBF;
import org.encog.engine.util.EngineArray;
import org.encog.engine.util.ObjectPair;
import org.encog.mathutil.matrices.Matrix;
import org.encog.neural.NeuralNetworkError;
import org.encog.neural.networks.BasicNetwork;
import org.encog.neural.networks.layers.BasicLayer;
import org.encog.neural.networks.layers.ContextLayer;
import org.encog.neural.networks.layers.Layer;
import org.encog.neural.networks.layers.RadialBasisFunctionLayer;
import org.encog.neural.networks.logic.FeedforwardLogic;
import org.encog.neural.networks.logic.SimpleRecurrentLogic;
import org.encog.neural.networks.synapse.Synapse;
import org.encog.util.obj.ReflectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Holds "cached" information about the structure of the neural network. This is
* a very good performance boost since the neural network does not need to
* traverse itself each time a complete collection of layers or synapses is
* needed.
*
* @author jheaton
*
*/
public class NeuralStructure implements Serializable {
/**
* The serial ID.
*/
private static final long serialVersionUID = -2929683885395737817L;
/**
* The logging object.
*/
private static final transient Logger LOGGER = LoggerFactory
.getLogger(NeuralStructure.class);
/**
* The layers in this neural network.
*/
private final List<Layer> layers = new ArrayList<Layer>();
/**
* The synapses in this neural network.
*/
private final List<Synapse> synapses = new ArrayList<Synapse>();
/**
* The neural network this class belongs to.
*/
private final BasicNetwork network;
/**
* The limit, below which a connection is treated as zero.
*/
private double connectionLimit;
/**
* Are connections limited?
*/
private boolean connectionLimited;
/**
* The next ID to be assigned to a layer.
*/
private int nextID = 1;
/**
* The flattened form of the network.
*/
private transient FlatNetwork flat;
/**
* What type of update is needed to the flat network.
*/
private transient FlatUpdateNeeded flatUpdate;
/**
* Construct a structure object for the specified network.
*
* @param network
* The network to construct a structure for.
*/
public NeuralStructure(final BasicNetwork network) {
this.network = network;
this.flatUpdate = FlatUpdateNeeded.None;
}
/**
* Assign an ID to every layer that does not already have one.
*/
public void assignID() {
for (final Layer layer : this.layers) {
assignID(layer);
}
sort();
}
/**
* Assign an ID to the specified layer.
*
* @param layer
* The layer to get an ID assigned.
*/
public void assignID(final Layer layer) {
if (layer.getID() == -1) {
layer.setID(getNextID());
}
}
/**
* Calculate the size that an array should be to hold all of the weights and
* bias values.
*
* @return The size of the calculated array.
*/
public int calculateSize() {
return NetworkCODEC.networkSize(this.network);
}
/**
* Determine if the network contains a layer of the specified type.
*
* @param type
* The layer type we are looking for.
* @return True if this layer type is present.
*/
public boolean containsLayerType(final Class<?> type) {
for (final Layer layer : this.layers) {
if (ReflectionUtil.isInstanceOf(layer.getClass(), type)) {
return true;
}
}
return false;
}
/**
* Count the number of non-context layers.
*
* @return The number of non-context layers.
*/
private int countNonContext() {
int result = 0;
for (final Layer layer : this.getLayers()) {
if (layer.getClass() != ContextLayer.class) {
result++;
}
}
return result;
}
/**
* Enforce that all connections are above the connection limit. Any
* connections below this limit will be severed.
*/
public void enforceLimit() {
if (!this.connectionLimited) {
return;
}
for (final Synapse synapse : this.synapses) {
final Matrix matrix = synapse.getMatrix();
if (matrix != null) {
for (int row = 0; row < matrix.getRows(); row++) {
for (int col = 0; col < matrix.getCols(); col++) {
final double value = matrix.get(row, col);
if (Math.abs(value) < this.connectionLimit) {
matrix.set(row, col, 0);
}
}
}
}
}
}
/**
* Build the layer structure.
*/
private void finalizeLayers() {
// no bias values on the input layer for feedforward/srn
if ((this.network.getLogic().getClass() == FeedforwardLogic.class)
|| (this.network.getLogic().getClass() == SimpleRecurrentLogic.class)) {
final Layer inputLayer = this.network
.getLayer(BasicNetwork.TAG_INPUT);
inputLayer.setBiasWeights(null);
}
final List<Layer> result = new ArrayList<Layer>();
this.layers.clear();
for (final Layer layer : this.network.getLayerTags().values()) {
getLayers(result, layer);
}
this.layers.addAll(result);
// make sure that the current ID is not going to cause a repeat
for (final Layer layer : this.layers) {
if (layer.getID() >= this.nextID) {
this.nextID = layer.getID() + 1;
}
}
sort();
}
/**
* Parse/finalize the limit value for connections.
*/
private void finalizeLimit() {
// see if there is a connection limit imposed
final String limit = this.network
.getPropertyString(BasicNetwork.TAG_LIMIT);
if (limit != null) {
try {
this.connectionLimited = true;
this.connectionLimit = Double.parseDouble(limit);
} catch (final NumberFormatException e) {
throw new NeuralNetworkError("Invalid property("
+ BasicNetwork.TAG_LIMIT + "):" + limit);
}
} else {
this.connectionLimited = false;
this.connectionLimit = 0;
}
}
/**
* Build the synapse and layer structure. This method should be called after
* you are done adding layers to a network, or change the network's logic
* property.
*/
public void finalizeStructure() {
finalizeLayers();
finalizeSynapses();
finalizeLimit();
Collections.sort(this.layers);
assignID();
this.network.getLogic().init(this.network);
enforceLimit();
flatten();
}
/**
* Build the synapse structure.
*/
private void finalizeSynapses() {
final Set<Synapse> result = new HashSet<Synapse>();
for (final Layer layer : getLayers()) {
for (final Synapse synapse : layer.getNext()) {
result.add(synapse);
}
}
this.synapses.clear();
this.synapses.addAll(result);
}
/**
* Find the next bias.
*
* @param layer
* The layer to search from.
* @return The next bias.
*/
private double findNextBias(final Layer layer) {
double bias = FlatNetwork.NO_BIAS_ACTIVATION;
if (layer.getNext().size() > 0) {
final Synapse synapse = this.network.getStructure()
.findNextSynapseByLayerType(layer, BasicLayer.class);
if (synapse != null) {
final Layer nextLayer = synapse.getToLayer();
if (nextLayer.hasBias()) {
bias = nextLayer.getBiasActivation();
}
}
}
return bias;
}
/**
* Find the next synapse by layer type.
*
* @param layer
* The layer to search from.
* @param type
* The synapse type to look for.
* @return The synapse found, or null.
*/
public Synapse findNextSynapseByLayerType(final Layer layer,
final Class<? extends Layer> type) {
for (final Synapse synapse : layer.getNext()) {
if (synapse.getToLayer().getClass() == type) {
return synapse;
}
}
return null;
}
/**
* Find previous synapse by layer type.
*
* @param layer
* The layer to start from.
* @param type
* The type of layer.
* @return The synapse found.
*/
public Synapse findPreviousSynapseByLayerType(final Layer layer,
final Class<? extends Layer> type) {
for (final Synapse synapse : getPreviousSynapses(layer)) {
if (synapse.getFromLayer().getClass() == type) {
return synapse;
}
}
return null;
}
/**
* Find the specified synapse, throw an error if it is required.
*
* @param fromLayer
* The from layer.
* @param toLayer
* The to layer.
* @param required
* Is this required?
* @return The synapse, if it exists, otherwise null.
*/
public Synapse findSynapse(final Layer fromLayer, final Layer toLayer,
final boolean required) {
Synapse result = null;
for (final Synapse synapse : getSynapses()) {
if ((synapse.getFromLayer() == fromLayer)
&& (synapse.getToLayer() == toLayer)) {
result = synapse;
break;
}
}
if (required && (result == null)) {
final String str = "This operation requires a network with a synapse between the "
+ nameLayer(fromLayer)
+ " layer to the "
+ nameLayer(toLayer) + " layer.";
if (NeuralStructure.LOGGER.isErrorEnabled()) {
NeuralStructure.LOGGER.error(str);
}
throw new NeuralNetworkError(str);
}
return result;
}
/**
* Flatten the network. Generate the flat network.
*/
public void flatten() {
final boolean isRBF = false;
final Map<Layer, FlatLayer> regular2flat = new HashMap<Layer, FlatLayer>();
final Map<FlatLayer, Layer> flat2regular = new HashMap<FlatLayer, Layer>();
final List<ObjectPair<Layer, Layer>> contexts = new ArrayList<ObjectPair<Layer, Layer>>();
this.flat = null;
final ValidateForFlat val = new ValidateForFlat();
if (val.isValid(this.network) == null) {
if ((this.layers.size() == 3)
&& (this.layers.get(1) instanceof RadialBasisFunctionLayer)) {
final RadialBasisFunctionLayer rbf = (RadialBasisFunctionLayer) this.layers
.get(1);
this.flat = new FlatNetworkRBF(this.network.getInputCount(),
rbf.getNeuronCount(), this.network.getOutputCount(),
rbf.getRadialBasisFunction());
flattenWeights();
this.flatUpdate = FlatUpdateNeeded.None;
return;
}
int flatLayerCount = countNonContext();
final FlatLayer[] flatLayers = new FlatLayer[flatLayerCount];
int index = flatLayers.length - 1;
for (final Layer layer : this.layers) {
if (layer instanceof ContextLayer) {
final Synapse inboundSynapse = this.network.getStructure()
.findPreviousSynapseByLayerType(layer,
BasicLayer.class);
final Synapse outboundSynapse = this.network
.getStructure()
.findNextSynapseByLayerType(layer, BasicLayer.class);
if (inboundSynapse == null) {
throw new NeuralNetworkError(
"Context layer must be connected to by one BasicLayer.");
}
if (outboundSynapse == null) {
throw new NeuralNetworkError(
"Context layer must connect to by one BasicLayer.");
}
final Layer inbound = inboundSynapse.getFromLayer();
final Layer outbound = outboundSynapse.getToLayer();
contexts
.add(new ObjectPair<Layer, Layer>(inbound, outbound));
} else {
final double bias = findNextBias(layer);
ActivationFunction activationType;
double[] params = new double[1];
if (layer.getActivationFunction() == null) {
activationType = new ActivationLinear();
params = new double[1];
params[0] = 1;
} else {
activationType = layer.getActivationFunction();
params = layer.getActivationFunction().getParams();
}
final FlatLayer flatLayer = new FlatLayer(activationType,
layer.getNeuronCount(), bias, params);
regular2flat.put(layer, flatLayer);
flat2regular.put(flatLayer, layer);
flatLayers[index--] = flatLayer;
}
}
// now link up the context layers
for (final ObjectPair<Layer, Layer> context : contexts) {
final Layer layer = context.getB();
final Synapse synapse = this.network
.getStructure()
.findPreviousSynapseByLayerType(layer, BasicLayer.class);
final FlatLayer from = regular2flat.get(context.getA());
final FlatLayer to = regular2flat.get(synapse.getFromLayer());
to.setContextFedBy(from);
}
this.flat = new FlatNetwork(flatLayers);
// update the context indexes on the non-flat network
for (int i = 0; i < flatLayerCount; i++) {
FlatLayer fedBy = flatLayers[i].getContextFedBy();
if (fedBy != null) {
- Layer fedBy2 = flat2regular.get(fedBy);
+ Layer fedBy2 = flat2regular.get(flatLayers[i+1]);
Synapse synapse = findPreviousSynapseByLayerType(fedBy2,
ContextLayer.class);
if (synapse == null)
throw new NeuralNetworkError(
"Can't find parent synapse to context layer.");
ContextLayer context = (ContextLayer) synapse
.getFromLayer();
// find fedby index
int fedByIndex = -1;
for (int j = 0; j < flatLayerCount; j++) {
if (flatLayers[j] == fedBy) {
fedByIndex = j;
break;
}
}
if (fedByIndex == -1)
throw new NeuralNetworkError(
"Can't find layer feeding context.");
context.setFlatContextIndex(this.flat
.getContextTargetOffset()[fedByIndex]);
}
}
// RBF networks will not train every layer
if (isRBF) {
this.flat.setEndTraining(flatLayers.length - 1);
}
flattenWeights();
this.flatUpdate = FlatUpdateNeeded.None;
} else {
this.flatUpdate = FlatUpdateNeeded.Never;
}
}
/**
* Flatten the weights, do not restructure.
*/
public void flattenWeights() {
if (this.flat != null) {
this.flatUpdate = FlatUpdateNeeded.Flatten;
final double[] targetWeights = this.flat.getWeights();
final double[] sourceWeights = NetworkCODEC
.networkToArray(this.network);
EngineArray.arrayCopy(sourceWeights, targetWeights);
this.flatUpdate = FlatUpdateNeeded.None;
// update context layers
for (Layer layer : this.layers) {
if (layer instanceof ContextLayer) {
ContextLayer context = (ContextLayer) layer;
if (context.getFlatContextIndex() != -1) {
EngineArray.arrayCopy(context.getContext().getData(),
0, this.flat.getLayerOutput(), context
.getFlatContextIndex(), context
.getContext().size());
}
}
}
// handle limited connection networks
if (this.connectionLimited) {
this.flat.setConnectionLimit(this.connectionLimit);
} else {
this.flat.clearConnectionLimit();
}
}
}
/**
* @return The connection limit.
*/
public double getConnectionLimit() {
return this.connectionLimit;
}
/**
* @return The flat network.
*/
public FlatNetwork getFlat() {
return this.flat;
}
/**
* @return The type of update currently needed.
*/
public FlatUpdateNeeded getFlatUpdate() {
return this.flatUpdate;
}
/**
* @return The layers in this neural network.
*/
public List<Layer> getLayers() {
return this.layers;
}
/**
* Called to help build the layer structure.
*
* @param result
* The layer list.
* @param layer
* The current layer being processed.
*/
private void getLayers(final List<Layer> result, final Layer layer) {
if (!result.contains(layer)) {
result.add(layer);
}
for (final Synapse synapse : layer.getNext()) {
final Layer nextLayer = synapse.getToLayer();
if (!result.contains(nextLayer)) {
getLayers(result, nextLayer);
}
}
}
/**
* @return The network this structure belongs to.
*/
public BasicNetwork getNetwork() {
return this.network;
}
/**
* Get the next layer id.
*
* @return The next layer id.
*/
public int getNextID() {
return this.nextID++;
}
/**
* Get the previous layers from the specified layer.
*
* @param targetLayer
* The target layer.
* @return The previous layers.
*/
public Collection<Layer> getPreviousLayers(final Layer targetLayer) {
final Collection<Layer> result = new HashSet<Layer>();
for (final Layer layer : this.getLayers()) {
for (final Synapse synapse : layer.getNext()) {
if (synapse.getToLayer() == targetLayer) {
result.add(synapse.getFromLayer());
}
}
}
return result;
}
/**
* Get the previous synapses.
*
* @param targetLayer
* The layer to get the previous layers from.
* @return A collection of synapses.
*/
public List<Synapse> getPreviousSynapses(final Layer targetLayer) {
final List<Synapse> result = new ArrayList<Synapse>();
for (final Synapse synapse : this.synapses) {
if (synapse.getToLayer() == targetLayer) {
if (!result.contains(synapse)) {
result.add(synapse);
}
}
}
return result;
}
/**
* @return All synapses in the neural network.
*/
public List<Synapse> getSynapses() {
return this.synapses;
}
/**
* @return True if this is not a fully connected feedforward network.
*/
public boolean isConnectionLimited() {
return this.connectionLimited;
}
/**
* @return Are there any context layers.
*/
public boolean isRecurrent() {
for (final Layer layer : this.getLayers()) {
if (layer instanceof ContextLayer) {
return true;
}
}
return false;
}
/**
* Obtain a name for the specified layer.
*
* @param layer
* The layer to name.
* @return The name of this layer.
*/
public List<String> nameLayer(final Layer layer) {
final List<String> result = new ArrayList<String>();
for (final Entry<String, Layer> entry : this.network.getLayerTags()
.entrySet()) {
if (entry.getValue() == layer) {
result.add(entry.getKey());
}
}
return result;
}
/**
* Set the type of flat update needed.
*
* @param flatUpdate
* The type of flat update needed.
*/
public void setFlatUpdate(final FlatUpdateNeeded flatUpdate) {
this.flatUpdate = flatUpdate;
}
/**
* Sort the layers and synapses.
*/
public void sort() {
Collections.sort(this.layers, new LayerComparator(this));
Collections.sort(this.synapses, new SynapseComparator(this));
}
/**
* Unflatten the weights.
*/
public void unflattenWeights() {
if (flat != null) {
double[] sourceWeights = flat.getWeights();
NetworkCODEC.arrayToNetwork(sourceWeights, network);
this.flatUpdate = FlatUpdateNeeded.None;
// update context layers
for (Layer layer : this.layers) {
if (layer instanceof ContextLayer) {
ContextLayer context = (ContextLayer) layer;
if (context.getFlatContextIndex() != -1) {
EngineArray.arrayCopy(this.flat.getLayerOutput(),
context.getFlatContextIndex(), context
.getContext().getData(), 0, context
.getContext().size());
}
}
}
}
}
/**
* Update the flat network.
*/
public void updateFlatNetwork() {
// if flatUpdate is null, the network was likely just loaded from a
// serialized file
if (this.flatUpdate == null) {
flattenWeights();
this.flatUpdate = FlatUpdateNeeded.None;
}
switch (this.flatUpdate) {
case Flatten:
flattenWeights();
break;
case Unflatten:
unflattenWeights();
break;
case None:
case Never:
return;
}
this.flatUpdate = FlatUpdateNeeded.None;
}
}
| true | true | public void flatten() {
final boolean isRBF = false;
final Map<Layer, FlatLayer> regular2flat = new HashMap<Layer, FlatLayer>();
final Map<FlatLayer, Layer> flat2regular = new HashMap<FlatLayer, Layer>();
final List<ObjectPair<Layer, Layer>> contexts = new ArrayList<ObjectPair<Layer, Layer>>();
this.flat = null;
final ValidateForFlat val = new ValidateForFlat();
if (val.isValid(this.network) == null) {
if ((this.layers.size() == 3)
&& (this.layers.get(1) instanceof RadialBasisFunctionLayer)) {
final RadialBasisFunctionLayer rbf = (RadialBasisFunctionLayer) this.layers
.get(1);
this.flat = new FlatNetworkRBF(this.network.getInputCount(),
rbf.getNeuronCount(), this.network.getOutputCount(),
rbf.getRadialBasisFunction());
flattenWeights();
this.flatUpdate = FlatUpdateNeeded.None;
return;
}
int flatLayerCount = countNonContext();
final FlatLayer[] flatLayers = new FlatLayer[flatLayerCount];
int index = flatLayers.length - 1;
for (final Layer layer : this.layers) {
if (layer instanceof ContextLayer) {
final Synapse inboundSynapse = this.network.getStructure()
.findPreviousSynapseByLayerType(layer,
BasicLayer.class);
final Synapse outboundSynapse = this.network
.getStructure()
.findNextSynapseByLayerType(layer, BasicLayer.class);
if (inboundSynapse == null) {
throw new NeuralNetworkError(
"Context layer must be connected to by one BasicLayer.");
}
if (outboundSynapse == null) {
throw new NeuralNetworkError(
"Context layer must connect to by one BasicLayer.");
}
final Layer inbound = inboundSynapse.getFromLayer();
final Layer outbound = outboundSynapse.getToLayer();
contexts
.add(new ObjectPair<Layer, Layer>(inbound, outbound));
} else {
final double bias = findNextBias(layer);
ActivationFunction activationType;
double[] params = new double[1];
if (layer.getActivationFunction() == null) {
activationType = new ActivationLinear();
params = new double[1];
params[0] = 1;
} else {
activationType = layer.getActivationFunction();
params = layer.getActivationFunction().getParams();
}
final FlatLayer flatLayer = new FlatLayer(activationType,
layer.getNeuronCount(), bias, params);
regular2flat.put(layer, flatLayer);
flat2regular.put(flatLayer, layer);
flatLayers[index--] = flatLayer;
}
}
// now link up the context layers
for (final ObjectPair<Layer, Layer> context : contexts) {
final Layer layer = context.getB();
final Synapse synapse = this.network
.getStructure()
.findPreviousSynapseByLayerType(layer, BasicLayer.class);
final FlatLayer from = regular2flat.get(context.getA());
final FlatLayer to = regular2flat.get(synapse.getFromLayer());
to.setContextFedBy(from);
}
this.flat = new FlatNetwork(flatLayers);
// update the context indexes on the non-flat network
for (int i = 0; i < flatLayerCount; i++) {
FlatLayer fedBy = flatLayers[i].getContextFedBy();
if (fedBy != null) {
Layer fedBy2 = flat2regular.get(fedBy);
Synapse synapse = findPreviousSynapseByLayerType(fedBy2,
ContextLayer.class);
if (synapse == null)
throw new NeuralNetworkError(
"Can't find parent synapse to context layer.");
ContextLayer context = (ContextLayer) synapse
.getFromLayer();
// find fedby index
int fedByIndex = -1;
for (int j = 0; j < flatLayerCount; j++) {
if (flatLayers[j] == fedBy) {
fedByIndex = j;
break;
}
}
if (fedByIndex == -1)
throw new NeuralNetworkError(
"Can't find layer feeding context.");
context.setFlatContextIndex(this.flat
.getContextTargetOffset()[fedByIndex]);
}
}
// RBF networks will not train every layer
if (isRBF) {
this.flat.setEndTraining(flatLayers.length - 1);
}
flattenWeights();
this.flatUpdate = FlatUpdateNeeded.None;
} else {
this.flatUpdate = FlatUpdateNeeded.Never;
}
}
| public void flatten() {
final boolean isRBF = false;
final Map<Layer, FlatLayer> regular2flat = new HashMap<Layer, FlatLayer>();
final Map<FlatLayer, Layer> flat2regular = new HashMap<FlatLayer, Layer>();
final List<ObjectPair<Layer, Layer>> contexts = new ArrayList<ObjectPair<Layer, Layer>>();
this.flat = null;
final ValidateForFlat val = new ValidateForFlat();
if (val.isValid(this.network) == null) {
if ((this.layers.size() == 3)
&& (this.layers.get(1) instanceof RadialBasisFunctionLayer)) {
final RadialBasisFunctionLayer rbf = (RadialBasisFunctionLayer) this.layers
.get(1);
this.flat = new FlatNetworkRBF(this.network.getInputCount(),
rbf.getNeuronCount(), this.network.getOutputCount(),
rbf.getRadialBasisFunction());
flattenWeights();
this.flatUpdate = FlatUpdateNeeded.None;
return;
}
int flatLayerCount = countNonContext();
final FlatLayer[] flatLayers = new FlatLayer[flatLayerCount];
int index = flatLayers.length - 1;
for (final Layer layer : this.layers) {
if (layer instanceof ContextLayer) {
final Synapse inboundSynapse = this.network.getStructure()
.findPreviousSynapseByLayerType(layer,
BasicLayer.class);
final Synapse outboundSynapse = this.network
.getStructure()
.findNextSynapseByLayerType(layer, BasicLayer.class);
if (inboundSynapse == null) {
throw new NeuralNetworkError(
"Context layer must be connected to by one BasicLayer.");
}
if (outboundSynapse == null) {
throw new NeuralNetworkError(
"Context layer must connect to by one BasicLayer.");
}
final Layer inbound = inboundSynapse.getFromLayer();
final Layer outbound = outboundSynapse.getToLayer();
contexts
.add(new ObjectPair<Layer, Layer>(inbound, outbound));
} else {
final double bias = findNextBias(layer);
ActivationFunction activationType;
double[] params = new double[1];
if (layer.getActivationFunction() == null) {
activationType = new ActivationLinear();
params = new double[1];
params[0] = 1;
} else {
activationType = layer.getActivationFunction();
params = layer.getActivationFunction().getParams();
}
final FlatLayer flatLayer = new FlatLayer(activationType,
layer.getNeuronCount(), bias, params);
regular2flat.put(layer, flatLayer);
flat2regular.put(flatLayer, layer);
flatLayers[index--] = flatLayer;
}
}
// now link up the context layers
for (final ObjectPair<Layer, Layer> context : contexts) {
final Layer layer = context.getB();
final Synapse synapse = this.network
.getStructure()
.findPreviousSynapseByLayerType(layer, BasicLayer.class);
final FlatLayer from = regular2flat.get(context.getA());
final FlatLayer to = regular2flat.get(synapse.getFromLayer());
to.setContextFedBy(from);
}
this.flat = new FlatNetwork(flatLayers);
// update the context indexes on the non-flat network
for (int i = 0; i < flatLayerCount; i++) {
FlatLayer fedBy = flatLayers[i].getContextFedBy();
if (fedBy != null) {
Layer fedBy2 = flat2regular.get(flatLayers[i+1]);
Synapse synapse = findPreviousSynapseByLayerType(fedBy2,
ContextLayer.class);
if (synapse == null)
throw new NeuralNetworkError(
"Can't find parent synapse to context layer.");
ContextLayer context = (ContextLayer) synapse
.getFromLayer();
// find fedby index
int fedByIndex = -1;
for (int j = 0; j < flatLayerCount; j++) {
if (flatLayers[j] == fedBy) {
fedByIndex = j;
break;
}
}
if (fedByIndex == -1)
throw new NeuralNetworkError(
"Can't find layer feeding context.");
context.setFlatContextIndex(this.flat
.getContextTargetOffset()[fedByIndex]);
}
}
// RBF networks will not train every layer
if (isRBF) {
this.flat.setEndTraining(flatLayers.length - 1);
}
flattenWeights();
this.flatUpdate = FlatUpdateNeeded.None;
} else {
this.flatUpdate = FlatUpdateNeeded.Never;
}
}
|
diff --git a/FileDuplicateFinderUI/src/main/groovy/com/sleepcamel/fileduplicatefinder/ui/components/SizeWidget.java b/FileDuplicateFinderUI/src/main/groovy/com/sleepcamel/fileduplicatefinder/ui/components/SizeWidget.java
index f5413d8..1bc72c3 100644
--- a/FileDuplicateFinderUI/src/main/groovy/com/sleepcamel/fileduplicatefinder/ui/components/SizeWidget.java
+++ b/FileDuplicateFinderUI/src/main/groovy/com/sleepcamel/fileduplicatefinder/ui/components/SizeWidget.java
@@ -1,50 +1,49 @@
package com.sleepcamel.fileduplicatefinder.ui.components;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Spinner;
import com.sleepcamel.fileduplicatefinder.ui.utils.FileSize;
public class SizeWidget extends Composite {
private ComboViewer combo;
private Spinner spinner;
public SizeWidget(Composite parent, int style) {
super(parent, SWT.NONE);
RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
rowLayout.justify = true;
rowLayout.fill = true;
rowLayout.center = true;
setLayout(rowLayout);
spinner = new Spinner(this, SWT.BORDER);
spinner.setMaximum(Integer.MAX_VALUE - 1);
spinner.setLayoutData(new RowData(50, SWT.DEFAULT));
combo = new ComboViewer(this, SWT.BORDER | SWT.READ_ONLY);
combo.setContentProvider(ArrayContentProvider.getInstance());
combo.setLabelProvider(new LabelProvider() {
public String getText(Object element) {
FileSize f = (FileSize) element;
return ((element == null) ? "" : f.getFriendlyName());
}
});
combo.setInput(FileSize.values());
- combo.getCombo().setLayoutData(new RowData(28, SWT.DEFAULT));
combo.getCombo().select(0);
}
public Object getData() {
StructuredSelection selection = (StructuredSelection) combo.getSelection();
FileSize selectedElement = (FileSize) selection.getFirstElement();
return selectedElement.toBytes(spinner.getSelection());
}
}
| true | true | public SizeWidget(Composite parent, int style) {
super(parent, SWT.NONE);
RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
rowLayout.justify = true;
rowLayout.fill = true;
rowLayout.center = true;
setLayout(rowLayout);
spinner = new Spinner(this, SWT.BORDER);
spinner.setMaximum(Integer.MAX_VALUE - 1);
spinner.setLayoutData(new RowData(50, SWT.DEFAULT));
combo = new ComboViewer(this, SWT.BORDER | SWT.READ_ONLY);
combo.setContentProvider(ArrayContentProvider.getInstance());
combo.setLabelProvider(new LabelProvider() {
public String getText(Object element) {
FileSize f = (FileSize) element;
return ((element == null) ? "" : f.getFriendlyName());
}
});
combo.setInput(FileSize.values());
combo.getCombo().setLayoutData(new RowData(28, SWT.DEFAULT));
combo.getCombo().select(0);
}
| public SizeWidget(Composite parent, int style) {
super(parent, SWT.NONE);
RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
rowLayout.justify = true;
rowLayout.fill = true;
rowLayout.center = true;
setLayout(rowLayout);
spinner = new Spinner(this, SWT.BORDER);
spinner.setMaximum(Integer.MAX_VALUE - 1);
spinner.setLayoutData(new RowData(50, SWT.DEFAULT));
combo = new ComboViewer(this, SWT.BORDER | SWT.READ_ONLY);
combo.setContentProvider(ArrayContentProvider.getInstance());
combo.setLabelProvider(new LabelProvider() {
public String getText(Object element) {
FileSize f = (FileSize) element;
return ((element == null) ? "" : f.getFriendlyName());
}
});
combo.setInput(FileSize.values());
combo.getCombo().select(0);
}
|
diff --git a/test/com/dmdirc/config/prefs/validator/URLProtocolValidatorTest.java b/test/com/dmdirc/config/prefs/validator/URLProtocolValidatorTest.java
index 29ce4fc04..b493bfdd1 100644
--- a/test/com/dmdirc/config/prefs/validator/URLProtocolValidatorTest.java
+++ b/test/com/dmdirc/config/prefs/validator/URLProtocolValidatorTest.java
@@ -1,47 +1,46 @@
/*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.config.prefs.validator;
import com.dmdirc.config.IdentityManager;
import org.junit.Test;
import static org.junit.Assert.*;
public class URLProtocolValidatorTest extends junit.framework.TestCase {
public URLProtocolValidatorTest(String testName) {
super(testName);
}
@Test
public void testValidate() {
IdentityManager.load();
+ IdentityManager.getConfigIdentity().setOption("protocol", "http", "BROWSER");
final URLProtocolValidator validator = new URLProtocolValidator();
assertTrue(validator.validate(null).isFailure());
assertTrue(validator.validate("").isFailure());
assertTrue(validator.validate("http").isFailure());
- assertTrue(validator.validate("https").isFailure());
- assertTrue(validator.validate("irc").isFailure());
assertFalse(validator.validate("steam").isFailure());
}
}
| false | true | public void testValidate() {
IdentityManager.load();
final URLProtocolValidator validator = new URLProtocolValidator();
assertTrue(validator.validate(null).isFailure());
assertTrue(validator.validate("").isFailure());
assertTrue(validator.validate("http").isFailure());
assertTrue(validator.validate("https").isFailure());
assertTrue(validator.validate("irc").isFailure());
assertFalse(validator.validate("steam").isFailure());
}
| public void testValidate() {
IdentityManager.load();
IdentityManager.getConfigIdentity().setOption("protocol", "http", "BROWSER");
final URLProtocolValidator validator = new URLProtocolValidator();
assertTrue(validator.validate(null).isFailure());
assertTrue(validator.validate("").isFailure());
assertTrue(validator.validate("http").isFailure());
assertFalse(validator.validate("steam").isFailure());
}
|
diff --git a/v9t9/v9t9-java/v9t9-engine/src/v9t9/engine/memory/MemoryEntryFactory.java b/v9t9/v9t9-java/v9t9-engine/src/v9t9/engine/memory/MemoryEntryFactory.java
index fd6ca84cd..f27b490eb 100644
--- a/v9t9/v9t9-java/v9t9-engine/src/v9t9/engine/memory/MemoryEntryFactory.java
+++ b/v9t9/v9t9-java/v9t9-engine/src/v9t9/engine/memory/MemoryEntryFactory.java
@@ -1,380 +1,380 @@
/**
*
*/
package v9t9.engine.memory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Element;
import ejs.base.settings.ISettingSection;
import ejs.base.utils.HexUtils;
import ejs.base.utils.XMLUtils;
import v9t9.common.client.ISettingsHandler;
import v9t9.common.files.IPathFileLocator;
import v9t9.common.memory.IMemory;
import v9t9.common.memory.IMemoryDomain;
import v9t9.common.memory.IMemoryEntry;
import v9t9.common.memory.IMemoryEntryFactory;
import v9t9.common.memory.MemoryEntryInfo;
import v9t9.common.memory.StoredMemoryEntryInfo;
import v9t9.common.modules.ModuleDatabase;
/**
* This factory assists in creating {@link IMemoryEntry} instances.
* @author ejs
*
*/
public class MemoryEntryFactory implements IMemoryEntryFactory {
private IPathFileLocator locator;
private final IMemory memory;
private final ISettingsHandler settings;
public MemoryEntryFactory(ISettingsHandler settings, IMemory memory, IPathFileLocator locator) {
this.settings = settings;
this.memory = memory;
this.locator = locator;
}
/* (non-Javadoc)
* @see v9t9.engine.memory.IMemoryEntryFactory#newMemoryEntry(v9t9.common.modules.MemoryEntryInfo)
*/
@Override
public IMemoryEntry newMemoryEntry(MemoryEntryInfo info) throws IOException {
if (!info.isBanked())
return newSimpleMemoryEntry(info);
else
return newBankedMemoryFromFile(info);
}
/**
* @param info
* @return
* @throws IOException
*/
protected IMemoryEntry newSimpleMemoryEntry(MemoryEntryInfo info)
throws IOException {
MemoryArea area;
IMemoryEntry entry;
if (info.getFilename() != null) {
if (info.isByteSized())
area = new ByteMemoryArea();
else
area = new WordMemoryArea();
entry = newFromFile(info, area);
}
else {
int size = Math.abs(info.getSize());
if (info.isByteSized())
area = new ByteMemoryArea(info.getDomain(memory).getLatency(info.getAddress()),
new byte[size]
);
else
area = new WordMemoryArea(info.getDomain(memory).getLatency(info.getAddress()),
new short[size / 2]
);
entry = new MemoryEntry(info.getName(), info.getDomain(memory),
info.getAddress(), size, area);
}
return entry;
}
/**
* Create a memory entry for banked (ROM) memory.
* @param klass
* @param addr
* @param size
* @param memory
* @param name
* @param domain
* @param filepath
* @param fileoffs
* @param filepath2
* @param fileoffs2
* @return
* @throws IOException
*/
private BankedMemoryEntry newBankedMemoryFromFile(MemoryEntryInfo info) throws IOException {
@SuppressWarnings("unchecked")
Class<? extends BankedMemoryEntry> klass = (Class<? extends BankedMemoryEntry>) info.getBankedClass();
IMemoryEntry bank0 = newFromFile(info, info.getName() + " (bank 0)",
info.getFilename(), info.getOffset(), MemoryAreaFactory.createMemoryArea(memory, info));
IMemoryEntry bank1 = newFromFile(info, info.getName() + " (bank 1)",
info.getFilename2(), info.getOffset2(), MemoryAreaFactory.createMemoryArea(memory, info));
IMemoryEntry[] entries = new IMemoryEntry[] { bank0, bank1 };
BankedMemoryEntry bankedMemoryEntry;
try {
bankedMemoryEntry = klass.getConstructor(
ISettingsHandler.class,
IMemory.class, String.class, entries.getClass()).newInstance(
settings, memory, info.getName(), entries);
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw (IOException) new IOException().initCause(e);
} catch (Exception e) {
throw (IOException) new IOException().initCause(e);
}
return bankedMemoryEntry;
}
/** Construct a DiskMemoryEntry based on the file length.
* @throws IOException if the memory cannot be read and is not stored
*/
private DiskMemoryEntry newFromFile(MemoryEntryInfo info, MemoryArea area) throws IOException {
return newFromFile(info, info.getName(), info.getFilename(), info.getOffset(), area);
}
/** Construct a DiskMemoryEntry based on the file length.
* @return the entry
* @throws IOException if the memory cannot be read and is not stored
*/
private DiskMemoryEntry newFromFile(MemoryEntryInfo info, String name, String filename, int offset, MemoryArea area) throws IOException {
StoredMemoryEntryInfo storedInfo = resolveMemoryEntry(info, name, filename, offset);
DiskMemoryEntry entry = new DiskMemoryEntry(info, name, area, storedInfo);
//info.getProperties().put(MemoryEntryInfo.SIZE, entry.getSize());
entry.setArea(MemoryAreaFactory.createMemoryArea(memory, info));
return entry;
}
/* (non-Javadoc)
* @see v9t9.engine.memory.IMemoryEntryFactory#resolveMemoryEntry(v9t9.common.modules.MemoryEntryInfo, java.lang.String, java.lang.String, int)
*/
@Override
public StoredMemoryEntryInfo resolveMemoryEntry(
MemoryEntryInfo info,
String name,
String filename,
int fileoffs) throws IOException {
return StoredMemoryEntryInfo.createStoredMemoryEntryInfo(
locator, settings, memory,
info, name, filename, fileoffs);
}
/**
* Create a memory entry from storage
* @param entryStore
* @return
*/
public IMemoryEntry createEntry(IMemoryDomain domain, ISettingSection entryStore) {
MemoryEntry entry = null;
String klazzName = entryStore.get("Class");
if (klazzName != null) {
Class<?> klass;
try {
klass = Class.forName(klazzName);
entry = (MemoryEntry) klass.newInstance();
} catch (Exception e) {
// in case packages change...
if (klazzName.endsWith(".DiskMemoryEntry")) {
klass = DiskMemoryEntry.class;
} else if (klazzName.endsWith(".MemoryEntry")) {
klass = MemoryEntry.class;
} else if (klazzName.endsWith(".MultiBankedMemoryEntry")) {
klass = MultiBankedMemoryEntry.class;
} else if (klazzName.endsWith(".WindowBankedMemoryEntry")) {
klass = WindowBankedMemoryEntry.class;
} else {
e.printStackTrace();
return null;
}
}
entry.setLocator(locator);
entry.setDomain(domain);
entry.setWordAccess(domain.getIdentifier().equals(IMemoryDomain.NAME_CPU)); // TODO
int latency = domain.getLatency(entryStore.getInt("Address"));
if (entry.isWordAccess())
entry.setArea(new WordMemoryArea(latency));
else
entry.setArea(new ByteMemoryArea(latency));
entry.setMemory(domain.getMemory());
entry.loadState(entryStore);
}
return entry;
}
public List<MemoryEntryInfo> loadEntriesFrom(String name, Element root) {
List<MemoryEntryInfo> memoryEntries = new ArrayList<MemoryEntryInfo>();
Element[] entries;
entries = XMLUtils.getChildElementsNamed(root, "memoryEntries");
for (Element entry : entries) {
for (Element el : XMLUtils.getChildElements(entry)) {
MemoryEntryInfo info = new MemoryEntryInfo();
Map<String, Object> properties = info.getProperties();
properties.put(MemoryEntryInfo.NAME, name);
// helpers
if (el.getNodeName().equals("romModuleEntry")) {
properties.put(MemoryEntryInfo.DOMAIN, IMemoryDomain.NAME_CPU);
properties.put(MemoryEntryInfo.ADDRESS, 0x6000);
properties.put(MemoryEntryInfo.SIZE, 0x2000);
}
else if (el.getNodeName().equals("gromModuleEntry")) {
properties.put(MemoryEntryInfo.DOMAIN, IMemoryDomain.NAME_GRAPHICS);
properties.put(MemoryEntryInfo.ADDRESS, 0x6000);
properties.put(MemoryEntryInfo.SIZE, -0xA000);
}
else if (el.getNodeName().equals("bankedModuleEntry")) {
properties.put(MemoryEntryInfo.DOMAIN, IMemoryDomain.NAME_CPU);
properties.put(MemoryEntryInfo.ADDRESS, 0x6000);
properties.put(MemoryEntryInfo.SIZE, -0x2000);
if ("true".equals(el.getAttribute("custom"))) {
properties.put(MemoryEntryInfo.CLASS, BankedMemoryEntry.class);
} else {
properties.put(MemoryEntryInfo.CLASS, StdMultiBankedMemoryEntry.class);
}
}
else if (!el.getNodeName().equals("memoryEntry")) {
System.err.println("Unknown entry: " + el.getNodeName());
continue;
}
getStringAttribute(el, MemoryEntryInfo.FILENAME, info);
getStringAttribute(el, MemoryEntryInfo.FILENAME2, info);
getStringAttribute(el, MemoryEntryInfo.DOMAIN, info);
getIntAttribute(el, MemoryEntryInfo.ADDRESS, info);
getIntAttribute(el, MemoryEntryInfo.SIZE, info);
getIntAttribute(el, MemoryEntryInfo.OFFSET, info);
getBooleanAttribute(el, MemoryEntryInfo.STORED, info);
getClassAttribute(el, MemoryEntryInfo.CLASS, MemoryEntry.class, info);
memoryEntries.add(info);
}
}
return memoryEntries;
}
public void saveEntriesTo(Collection<MemoryEntryInfo> memoryEntries, Element root) {
Element memoryEntriesEl = root.getOwnerDocument().createElement("memoryEntries");
root.appendChild(memoryEntriesEl);
for (MemoryEntryInfo info : memoryEntries) {
Map<String, Object> properties = info.getProperties();
Element entry = null;
// helpers
boolean needAddress = true;
boolean needSize = true;
boolean needDomain = true;
if (IMemoryDomain.NAME_CPU.equals(properties.get(MemoryEntryInfo.DOMAIN))
&& (Integer) properties.get(MemoryEntryInfo.ADDRESS) == 0x6000
&& (Integer) properties.get(MemoryEntryInfo.SIZE) == 0x2000) {
entry = root.getOwnerDocument().createElement("romModuleEntry");
needAddress = needSize = needDomain = false;
}
else if (IMemoryDomain.NAME_GRAPHICS.equals(properties.get(MemoryEntryInfo.DOMAIN))
&& (Integer) properties.get(MemoryEntryInfo.ADDRESS) == 0x6000) {
entry = root.getOwnerDocument().createElement("gromModuleEntry");
needAddress = needSize = needDomain = false;
}
else if (IMemoryDomain.NAME_CPU.equals(properties.get(MemoryEntryInfo.DOMAIN))
&& (Integer) properties.get(MemoryEntryInfo.ADDRESS) == 0x6000
&& BankedMemoryEntry.class.isAssignableFrom((Class<?>)properties.get(MemoryEntryInfo.CLASS))) {
entry = root.getOwnerDocument().createElement("bankedModuleEntry");
needAddress = needSize = needDomain = false;
if (BankedMemoryEntry.class.equals((Class<?>)properties.get(MemoryEntryInfo.CLASS)))
entry.setAttribute("custom", "true");
}
else {
entry = root.getOwnerDocument().createElement("memoryEntry");
}
if (needDomain) {
entry.setAttribute(MemoryEntryInfo.DOMAIN, ""+properties.get(MemoryEntryInfo.DOMAIN));
}
if (needAddress) {
entry.setAttribute(MemoryEntryInfo.ADDRESS,
- HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.ADDRESS)).intValue()));
+ "0x" + HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.ADDRESS)).intValue()));
}
if (needSize) {
entry.setAttribute(MemoryEntryInfo.SIZE,
- HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.SIZE)).intValue()));
+ "0x" + HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.SIZE)).intValue()));
}
entry.setAttribute(MemoryEntryInfo.FILENAME, properties.get(MemoryEntryInfo.FILENAME).toString());
if (properties.containsKey(MemoryEntryInfo.FILENAME2))
entry.setAttribute(MemoryEntryInfo.FILENAME2, properties.get(MemoryEntryInfo.FILENAME2).toString());
if (properties.containsKey(MemoryEntryInfo.OFFSET) && ((Number) properties.get(MemoryEntryInfo.OFFSET)).intValue() != 0)
entry.setAttribute(MemoryEntryInfo.OFFSET,
- HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.OFFSET)).intValue()));
+ "0x" + HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.OFFSET)).intValue()));
if (info.isStored())
entry.setAttribute(MemoryEntryInfo.STORED, "true");
memoryEntriesEl.appendChild(entry);
}
}
private void getClassAttribute(Element el, String name, Class<?> baseKlass,
MemoryEntryInfo info) {
if (el.hasAttribute(name)) {
Class<?> klass;
String klassName = el.getAttribute(name);
try {
klass = ModuleDatabase.class.getClassLoader().loadClass(klassName);
if (!baseKlass.isAssignableFrom(klass)) {
throw new AssertionError("Illegal class: wanted instance of " + baseKlass + " but got " + klass);
} else {
info.getProperties().put(name, klass);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public void getStringAttribute(Element el, String name, MemoryEntryInfo info) {
if (el.hasAttribute(name)) {
String attr = el.getAttribute(name);
info.getProperties().put(name, attr);
}
}
public void getIntAttribute(Element el, String name, MemoryEntryInfo info) {
if (el.hasAttribute(name)) {
String attr = el.getAttribute(name);
info.getProperties().put(name, HexUtils.parseInt(attr));
}
}
public void getBooleanAttribute(Element el, String name, MemoryEntryInfo info) {
if (el.hasAttribute(name)) {
String attr = el.getAttribute(name);
info.getProperties().put(name, "true".equals(attr));
}
}
}
| false | true | public void saveEntriesTo(Collection<MemoryEntryInfo> memoryEntries, Element root) {
Element memoryEntriesEl = root.getOwnerDocument().createElement("memoryEntries");
root.appendChild(memoryEntriesEl);
for (MemoryEntryInfo info : memoryEntries) {
Map<String, Object> properties = info.getProperties();
Element entry = null;
// helpers
boolean needAddress = true;
boolean needSize = true;
boolean needDomain = true;
if (IMemoryDomain.NAME_CPU.equals(properties.get(MemoryEntryInfo.DOMAIN))
&& (Integer) properties.get(MemoryEntryInfo.ADDRESS) == 0x6000
&& (Integer) properties.get(MemoryEntryInfo.SIZE) == 0x2000) {
entry = root.getOwnerDocument().createElement("romModuleEntry");
needAddress = needSize = needDomain = false;
}
else if (IMemoryDomain.NAME_GRAPHICS.equals(properties.get(MemoryEntryInfo.DOMAIN))
&& (Integer) properties.get(MemoryEntryInfo.ADDRESS) == 0x6000) {
entry = root.getOwnerDocument().createElement("gromModuleEntry");
needAddress = needSize = needDomain = false;
}
else if (IMemoryDomain.NAME_CPU.equals(properties.get(MemoryEntryInfo.DOMAIN))
&& (Integer) properties.get(MemoryEntryInfo.ADDRESS) == 0x6000
&& BankedMemoryEntry.class.isAssignableFrom((Class<?>)properties.get(MemoryEntryInfo.CLASS))) {
entry = root.getOwnerDocument().createElement("bankedModuleEntry");
needAddress = needSize = needDomain = false;
if (BankedMemoryEntry.class.equals((Class<?>)properties.get(MemoryEntryInfo.CLASS)))
entry.setAttribute("custom", "true");
}
else {
entry = root.getOwnerDocument().createElement("memoryEntry");
}
if (needDomain) {
entry.setAttribute(MemoryEntryInfo.DOMAIN, ""+properties.get(MemoryEntryInfo.DOMAIN));
}
if (needAddress) {
entry.setAttribute(MemoryEntryInfo.ADDRESS,
HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.ADDRESS)).intValue()));
}
if (needSize) {
entry.setAttribute(MemoryEntryInfo.SIZE,
HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.SIZE)).intValue()));
}
entry.setAttribute(MemoryEntryInfo.FILENAME, properties.get(MemoryEntryInfo.FILENAME).toString());
if (properties.containsKey(MemoryEntryInfo.FILENAME2))
entry.setAttribute(MemoryEntryInfo.FILENAME2, properties.get(MemoryEntryInfo.FILENAME2).toString());
if (properties.containsKey(MemoryEntryInfo.OFFSET) && ((Number) properties.get(MemoryEntryInfo.OFFSET)).intValue() != 0)
entry.setAttribute(MemoryEntryInfo.OFFSET,
HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.OFFSET)).intValue()));
if (info.isStored())
entry.setAttribute(MemoryEntryInfo.STORED, "true");
memoryEntriesEl.appendChild(entry);
}
}
| public void saveEntriesTo(Collection<MemoryEntryInfo> memoryEntries, Element root) {
Element memoryEntriesEl = root.getOwnerDocument().createElement("memoryEntries");
root.appendChild(memoryEntriesEl);
for (MemoryEntryInfo info : memoryEntries) {
Map<String, Object> properties = info.getProperties();
Element entry = null;
// helpers
boolean needAddress = true;
boolean needSize = true;
boolean needDomain = true;
if (IMemoryDomain.NAME_CPU.equals(properties.get(MemoryEntryInfo.DOMAIN))
&& (Integer) properties.get(MemoryEntryInfo.ADDRESS) == 0x6000
&& (Integer) properties.get(MemoryEntryInfo.SIZE) == 0x2000) {
entry = root.getOwnerDocument().createElement("romModuleEntry");
needAddress = needSize = needDomain = false;
}
else if (IMemoryDomain.NAME_GRAPHICS.equals(properties.get(MemoryEntryInfo.DOMAIN))
&& (Integer) properties.get(MemoryEntryInfo.ADDRESS) == 0x6000) {
entry = root.getOwnerDocument().createElement("gromModuleEntry");
needAddress = needSize = needDomain = false;
}
else if (IMemoryDomain.NAME_CPU.equals(properties.get(MemoryEntryInfo.DOMAIN))
&& (Integer) properties.get(MemoryEntryInfo.ADDRESS) == 0x6000
&& BankedMemoryEntry.class.isAssignableFrom((Class<?>)properties.get(MemoryEntryInfo.CLASS))) {
entry = root.getOwnerDocument().createElement("bankedModuleEntry");
needAddress = needSize = needDomain = false;
if (BankedMemoryEntry.class.equals((Class<?>)properties.get(MemoryEntryInfo.CLASS)))
entry.setAttribute("custom", "true");
}
else {
entry = root.getOwnerDocument().createElement("memoryEntry");
}
if (needDomain) {
entry.setAttribute(MemoryEntryInfo.DOMAIN, ""+properties.get(MemoryEntryInfo.DOMAIN));
}
if (needAddress) {
entry.setAttribute(MemoryEntryInfo.ADDRESS,
"0x" + HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.ADDRESS)).intValue()));
}
if (needSize) {
entry.setAttribute(MemoryEntryInfo.SIZE,
"0x" + HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.SIZE)).intValue()));
}
entry.setAttribute(MemoryEntryInfo.FILENAME, properties.get(MemoryEntryInfo.FILENAME).toString());
if (properties.containsKey(MemoryEntryInfo.FILENAME2))
entry.setAttribute(MemoryEntryInfo.FILENAME2, properties.get(MemoryEntryInfo.FILENAME2).toString());
if (properties.containsKey(MemoryEntryInfo.OFFSET) && ((Number) properties.get(MemoryEntryInfo.OFFSET)).intValue() != 0)
entry.setAttribute(MemoryEntryInfo.OFFSET,
"0x" + HexUtils.toHex4(((Number) properties.get(MemoryEntryInfo.OFFSET)).intValue()));
if (info.isStored())
entry.setAttribute(MemoryEntryInfo.STORED, "true");
memoryEntriesEl.appendChild(entry);
}
}
|
diff --git a/javasrc/src/org/ccnx/ccn/impl/repo/PolicyXML.java b/javasrc/src/org/ccnx/ccn/impl/repo/PolicyXML.java
index 55d4cc855..88dce1b08 100644
--- a/javasrc/src/org/ccnx/ccn/impl/repo/PolicyXML.java
+++ b/javasrc/src/org/ccnx/ccn/impl/repo/PolicyXML.java
@@ -1,260 +1,259 @@
/**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* 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., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.impl.repo;
import java.io.IOException;
import java.util.ArrayList;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.encoding.GenericXMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLDecoder;
import org.ccnx.ccn.impl.encoding.XMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLEncoder;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.content.CCNEncodableObject;
import org.ccnx.ccn.io.content.ContentDecodingException;
import org.ccnx.ccn.io.content.ContentEncodingException;
import org.ccnx.ccn.io.content.ContentGoneException;
import org.ccnx.ccn.io.content.ContentNotReadyException;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
/**
* Represents repo policy data
*/
public class PolicyXML extends GenericXMLEncodable implements XMLEncodable {
public static class PolicyObject extends CCNEncodableObject<PolicyXML> {
protected RepositoryStore _repo = null; // Non null if we are saving from within a repository
public PolicyObject(ContentName name, PolicyXML data, CCNHandle handle, RepositoryStore repo) throws IOException {
super(PolicyXML.class, true, name, data, handle);
_repo = repo;
}
public PolicyObject(ContentName name, PolicyXML data, CCNHandle handle) throws IOException {
this(name, data, handle, null);
}
public PolicyObject(ContentName name, CCNHandle handle)
throws ContentDecodingException, IOException {
super(PolicyXML.class, true, name, handle);
}
public PolicyXML policyXML() throws ContentNotReadyException, ContentGoneException {
return data();
}
protected synchronized void createFlowController() throws IOException {
if (null != _repo)
_flowControl = new RepositoryInternalFlowControl(_repo, _handle);
super.createFlowController();
}
}
protected static final String POLICY_OBJECT_ELEMENT = "Policy";
/**
* The following interface and enumeration allow user created policy files with the
* data in any order. The encoder goes through the user's names, checks for matches with
* the names from the enumeration and encodes the name it sees appropriately
*/
private interface ElementPutter {
public void put(PolicyXML pxml, String value) throws MalformedContentNameStringException;
}
private enum PolicyElement {
VERSION (POLICY_VERSION, new VersionPutter()),
NAMESPACE (POLICY_NAMESPACE, new NameSpacePutter()),
LOCALNAME (POLICY_LOCALNAME, new LocalNamePutter()),
GLOBALPREFIX (POLICY_GLOBALPREFIX, new GlobalPrefixPutter());
private String _stringValue;
private ElementPutter _putter;
PolicyElement(String stringValue, ElementPutter putter) {
_stringValue = stringValue;
_putter = putter;
}
}
private static class VersionPutter implements ElementPutter {
public void put(PolicyXML pxml, String value) throws MalformedContentNameStringException {
pxml._version = value.trim();
}
}
private static class GlobalPrefixPutter implements ElementPutter {
public void put(PolicyXML pxml, String value) throws MalformedContentNameStringException {
pxml.setGlobalPrefix(value.trim());
}
}
private static class LocalNamePutter implements ElementPutter {
public void put(PolicyXML pxml, String value) throws MalformedContentNameStringException {
pxml._localName = value.trim();
}
}
private static class NameSpacePutter implements ElementPutter {
public void put(PolicyXML pxml, String value) throws MalformedContentNameStringException {
if (null == pxml._namespace)
pxml._namespace = new ArrayList<ContentName>();
pxml._namespace.add(ContentName.fromNative(value.trim()));
}
}
protected static final String POLICY_VERSION = "PolicyVersion";
protected static final String POLICY_NAMESPACE = "Namespace";
protected static final String POLICY_GLOBALPREFIX = "GlobalPrefix";
protected static final String POLICY_LOCALNAME = "LocalName";
protected String _version = null;
protected ContentName _globalPrefix = null;
protected String _localName = null;
protected ArrayList<ContentName> _namespace = new ArrayList<ContentName>();
@Override
public void decode(XMLDecoder decoder) throws ContentDecodingException {
decoder.readStartElement(getElementLabel());
PolicyElement foundElement;
do {
foundElement = null;
for (PolicyElement element : PolicyElement.values()) {
if (decoder.peekStartElement(element._stringValue)) {
foundElement = element;
break;
}
}
if (null != foundElement) {
String value = decoder.readUTF8Element(foundElement._stringValue);
try {
foundElement._putter.put(this, value);
} catch (MalformedContentNameStringException e) {
throw new ContentDecodingException(e.getMessage());
}
Log.fine("Found policy element {0} with value {1}", foundElement._stringValue, value);
}
} while (null != foundElement);
- decoder.readEndElement();
}
@Override
public void encode(XMLEncoder encoder) throws ContentEncodingException {
if (!validate()) {
throw new ContentEncodingException("Cannot encode " + this.getClass().getName() + ": field values missing.");
}
encoder.writeStartElement(getElementLabel());
encoder.writeElement(POLICY_VERSION, _version);
encoder.writeElement(POLICY_LOCALNAME, _localName);
encoder.writeElement(POLICY_GLOBALPREFIX, _globalPrefix.toString());
if (null != _namespace) {
synchronized (_namespace) {
for (ContentName name : _namespace)
encoder.writeElement(POLICY_NAMESPACE, name.toString());
}
}
encoder.writeEndElement();
}
@Override
public String getElementLabel() {
return POLICY_OBJECT_ELEMENT;
}
@Override
public boolean validate() {
return null != _version;
}
public ArrayList<ContentName> getNamespace() {
return _namespace;
}
public void setNamespace(ArrayList<ContentName> namespace) {
_namespace = namespace;
}
public void addNamespace(ContentName name) {
if (null == _namespace)
_namespace = new ArrayList<ContentName>();
_namespace.add(name);
}
public void removeNamespace(ContentName name) {
if (null != _namespace)
_namespace.remove(name);
}
public void setLocalName(String localName) {
_localName = localName;
}
public String getLocalName() {
return _localName;
}
public void setGlobalPrefix(String globalPrefix) throws MalformedContentNameStringException {
// Note - need to synchronize on "this" to synchronize with events reading
// the name space in the policy clients which have access only to this object
synchronized (this) {
if (null != _globalPrefix)
_namespace.remove(_globalPrefix);
_globalPrefix = ContentName.fromNative(fixSlash(globalPrefix));
addNamespace(_globalPrefix);
}
}
/**
* This is a special case for transferring one policyXML to another (so we already have the
* namespace setup correctly).
*
* @param globalPrefix
*/
public void setGlobalPrefixOnly(ContentName globalPrefix) {
_globalPrefix = globalPrefix;
}
public ContentName getGlobalPrefix() {
return _globalPrefix;
}
public void setVersion(String version) {
_version = version;
}
public String getVersion() {
return _version;
}
/**
* Global prefix names are not required to start with a slash. Just add one
* here if it doesn't
* @param name - the test name
* @return
*/
public static String fixSlash(String name) {
if (!name.startsWith("/"))
name = "/" + name;
return name;
}
}
| true | true | public void decode(XMLDecoder decoder) throws ContentDecodingException {
decoder.readStartElement(getElementLabel());
PolicyElement foundElement;
do {
foundElement = null;
for (PolicyElement element : PolicyElement.values()) {
if (decoder.peekStartElement(element._stringValue)) {
foundElement = element;
break;
}
}
if (null != foundElement) {
String value = decoder.readUTF8Element(foundElement._stringValue);
try {
foundElement._putter.put(this, value);
} catch (MalformedContentNameStringException e) {
throw new ContentDecodingException(e.getMessage());
}
Log.fine("Found policy element {0} with value {1}", foundElement._stringValue, value);
}
} while (null != foundElement);
decoder.readEndElement();
}
| public void decode(XMLDecoder decoder) throws ContentDecodingException {
decoder.readStartElement(getElementLabel());
PolicyElement foundElement;
do {
foundElement = null;
for (PolicyElement element : PolicyElement.values()) {
if (decoder.peekStartElement(element._stringValue)) {
foundElement = element;
break;
}
}
if (null != foundElement) {
String value = decoder.readUTF8Element(foundElement._stringValue);
try {
foundElement._putter.put(this, value);
} catch (MalformedContentNameStringException e) {
throw new ContentDecodingException(e.getMessage());
}
Log.fine("Found policy element {0} with value {1}", foundElement._stringValue, value);
}
} while (null != foundElement);
}
|
diff --git a/resources/tests/src/test/java/org/jboss/forge/addon/resource/monitor/ResourceMonitorTest.java b/resources/tests/src/test/java/org/jboss/forge/addon/resource/monitor/ResourceMonitorTest.java
index 500fc3d3e..45c84d584 100644
--- a/resources/tests/src/test/java/org/jboss/forge/addon/resource/monitor/ResourceMonitorTest.java
+++ b/resources/tests/src/test/java/org/jboss/forge/addon/resource/monitor/ResourceMonitorTest.java
@@ -1,667 +1,665 @@
/**
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.resource.monitor;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import java.io.File;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.addon.resource.DirectoryResource;
import org.jboss.forge.addon.resource.FileResource;
import org.jboss.forge.addon.resource.Resource;
import org.jboss.forge.addon.resource.ResourceFactory;
import org.jboss.forge.addon.resource.ResourceFilter;
import org.jboss.forge.addon.resource.URLResource;
import org.jboss.forge.addon.resource.events.ResourceCreated;
import org.jboss.forge.addon.resource.events.ResourceDeleted;
import org.jboss.forge.addon.resource.events.ResourceEvent;
import org.jboss.forge.addon.resource.events.ResourceModified;
import org.jboss.forge.arquillian.AddonDependency;
import org.jboss.forge.arquillian.Dependencies;
import org.jboss.forge.arquillian.archive.ForgeArchive;
import org.jboss.forge.furnace.repositories.AddonDependencyEntry;
import org.jboss.forge.furnace.util.Callables;
import org.jboss.forge.furnace.util.OperatingSystemUtils;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author <a href="[email protected]">George Gastaldi</a>
*/
@RunWith(Arquillian.class)
public class ResourceMonitorTest
{
@Deployment
@Dependencies({
@AddonDependency(name = "org.jboss.forge.addon:facets"),
@AddonDependency(name = "org.jboss.forge.addon:resources") })
public static ForgeArchive getDeployment()
{
ForgeArchive archive = ShrinkWrap.create(ForgeArchive.class)
.addBeansXML()
.addAsAddonDependencies(
AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi"),
AddonDependencyEntry.create("org.jboss.forge.addon:facets"),
AddonDependencyEntry.create("org.jboss.forge.addon:resources")
);
return archive;
}
@Inject
private ResourceFactory resourceFactory;
private ResourceMonitor monitor;
@After
public void cancelMonitor()
{
if (monitor != null)
{
monitor.cancel();
monitor = null;
}
}
@Test(expected = IllegalArgumentException.class)
public void testResourceMonitorShouldThrowIllegalArgumentOnNull() throws Exception
{
monitor = resourceFactory.monitor(null);
}
@Test(expected = IllegalArgumentException.class)
public void testResourceMonitorShouldThrowIllegalArgumentOnUnsupportedResource() throws Exception
{
URLResource resource = resourceFactory.create(URLResource.class, new URL("http://forge.jboss.org"));
Assert.assertNotNull(resource);
monitor = resourceFactory.monitor(resource);
}
@Test(expected = IllegalStateException.class)
public void testResourceMonitorInexistentResourceShouldThrowIllegalStateException() throws Exception
{
File tempDir = OperatingSystemUtils.createTempDir();
tempDir.delete();
DirectoryResource tempDirResource = resourceFactory.create(DirectoryResource.class, tempDir);
monitor = resourceFactory.monitor(tempDirResource);
}
@Test
public void testResourceMonitorDirectory() throws Exception
{
Assume.assumeFalse("FORGE-1679", OperatingSystemUtils.isWindows());
File tempDir = OperatingSystemUtils.createTempDir();
DirectoryResource tempDirResource = resourceFactory.create(DirectoryResource.class, tempDir);
monitor = resourceFactory.monitor(tempDirResource);
final Set<ResourceEvent> eventCollector = new LinkedHashSet<>();
monitor.addResourceListener(new ResourceListener()
{
@Override
public void processEvent(ResourceEvent event)
{
eventCollector.add(event);
}
});
final DirectoryResource childDir = tempDirResource.getChildDirectory("child_dir");
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceCreated
childDir.mkdir();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 1;
}
}, 5, TimeUnit.SECONDS);
final FileResource<?> childFile = childDir.getChild("child_file.txt").reify(FileResource.class);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceCreated
childFile.createNewFile();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 2;
}
}, 5, TimeUnit.SECONDS);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceDeleted
childFile.delete();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 3;
}
}, 5, TimeUnit.SECONDS);
Assert.assertEquals(3, eventCollector.size());
Iterator<ResourceEvent> iterator = eventCollector.iterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceCreated.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceCreated.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceDeleted.class)));
}
@Test
public void testResourceMonitorDirectoryWindows() throws Exception
{
Assume.assumeTrue("FORGE-1679", OperatingSystemUtils.isWindows());
File tempDir = OperatingSystemUtils.createTempDir();
DirectoryResource tempDirResource = resourceFactory.create(DirectoryResource.class, tempDir);
monitor = resourceFactory.monitor(tempDirResource);
final Set<ResourceEvent> eventCollector = new LinkedHashSet<>();
monitor.addResourceListener(new ResourceListener()
{
@Override
public void processEvent(ResourceEvent event)
{
eventCollector.add(event);
}
});
final DirectoryResource childDir = tempDirResource.getChildDirectory("child_dir");
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceCreated
childDir.mkdir();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 1;
}
}, 5, TimeUnit.SECONDS);
final FileResource<?> childFile = childDir.getChild("child_file.txt").reify(FileResource.class);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceCreated
childFile.createNewFile();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 2;
}
}, 5, TimeUnit.SECONDS);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceDeleted
childFile.delete();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
- return eventCollector.size() == 5;
+ return eventCollector.size() == 4;
}
}, 5, TimeUnit.SECONDS);
- Assert.assertEquals(5, eventCollector.size());
+ Assert.assertEquals(4, eventCollector.size());
Iterator<ResourceEvent> iterator = eventCollector.iterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceCreated.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceCreated.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceModified.class)));
Assert.assertTrue(iterator.hasNext());
- Assert.assertThat(iterator.next(), is(instanceOf(ResourceModified.class)));
- Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceDeleted.class)));
}
@Test
@SuppressWarnings("unchecked")
public void testResourceMonitorFile() throws Exception
{
File tempDir = OperatingSystemUtils.createTempDir();
File tempFile = File.createTempFile("resource_monitor", ".tmp", tempDir);
final FileResource<?> resource = resourceFactory.create(FileResource.class, tempFile);
monitor = resource.monitor();
final Set<ResourceEvent> eventCollector = new LinkedHashSet<>();
monitor.addResourceListener(new ResourceListener()
{
@Override
public void processEvent(ResourceEvent event)
{
eventCollector.add(event);
}
});
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceModified
resource.setContents("TEST");
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 1;
}
}, 10, TimeUnit.SECONDS);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceDeleted
resource.delete();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 2;
}
}, 10, TimeUnit.SECONDS);
Assert.assertEquals(2, eventCollector.size());
Iterator<ResourceEvent> it = eventCollector.iterator();
Assert.assertTrue(it.hasNext());
Assert.assertThat(it.next(), is(instanceOf(ResourceModified.class)));
Assert.assertTrue(it.hasNext());
Assert.assertThat(it.next(), is(instanceOf(ResourceDeleted.class)));
}
@Test
public void testResourceMonitorDirectoryWithFilter() throws Exception
{
Assume.assumeFalse("FORGE-1679", OperatingSystemUtils.isWindows());
File tempDir = OperatingSystemUtils.createTempDir();
DirectoryResource tempDirResource = resourceFactory.create(DirectoryResource.class, tempDir);
monitor = resourceFactory.monitor(tempDirResource, new ResourceFilter()
{
@Override
public boolean accept(Resource<?> resource)
{
return "foo.txt".equals(resource.getName());
}
});
final Set<ResourceEvent> eventCollector = new LinkedHashSet<>();
monitor.addResourceListener(new ResourceListener()
{
@Override
public void processEvent(ResourceEvent event)
{
eventCollector.add(event);
}
});
final FileResource<?> childFile1 = tempDirResource.getChild("child_file.txt").reify(FileResource.class);
// NEW EVENT: ResourceCreated
childFile1.createNewFile();
final FileResource<?> childFile2 = tempDirResource.getChild("foo.txt").reify(FileResource.class);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceCreated of parent dir
childFile2.createNewFile();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 1;
}
}, 5, TimeUnit.SECONDS);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceDeleted
childFile2.delete();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 2;
}
}, 5, TimeUnit.SECONDS);
Assert.assertEquals(2, eventCollector.size());
Iterator<ResourceEvent> iterator = eventCollector.iterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceCreated.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceDeleted.class)));
}
@Test
public void testResourceMonitorDirectoryWithFilterWindows() throws Exception
{
Assume.assumeTrue("FORGE-1679", OperatingSystemUtils.isWindows());
File tempDir = OperatingSystemUtils.createTempDir();
DirectoryResource tempDirResource = resourceFactory.create(DirectoryResource.class, tempDir);
monitor = resourceFactory.monitor(tempDirResource, new ResourceFilter()
{
@Override
public boolean accept(Resource<?> resource)
{
return "foo.txt".equals(resource.getName());
}
});
final Set<ResourceEvent> eventCollector = new LinkedHashSet<>();
monitor.addResourceListener(new ResourceListener()
{
@Override
public void processEvent(ResourceEvent event)
{
eventCollector.add(event);
}
});
final FileResource<?> childFile1 = tempDirResource.getChild("child_file.txt").reify(FileResource.class);
// NEW EVENT: ResourceCreated
childFile1.createNewFile();
final FileResource<?> childFile2 = tempDirResource.getChild("foo.txt").reify(FileResource.class);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceCreated of parent dir
childFile2.createNewFile();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 1;
}
}, 5, TimeUnit.SECONDS);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
//Windows 7 adds ResourceModified
// NEW EVENT: ResourceDeleted
childFile2.delete();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 3;
}
}, 5, TimeUnit.SECONDS);
Assert.assertEquals(3, eventCollector.size());
Iterator<ResourceEvent> iterator = eventCollector.iterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceCreated.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceModified.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceDeleted.class)));
}
@Test
@SuppressWarnings("unchecked")
public void testResourceMonitorFileWithFilter() throws Exception
{
Assume.assumeFalse("FORGE-1679", OperatingSystemUtils.isWindows());
File tempDir = OperatingSystemUtils.createTempDir();
File tempFile = File.createTempFile("resource_monitor", ".tmp", tempDir);
final FileResource<?> resource = resourceFactory.create(FileResource.class, tempFile);
monitor = resourceFactory.monitor(resource, new ResourceFilter()
{
@Override
public boolean accept(Resource<?> resource)
{
return resource.getName().startsWith("resource_monitor");
}
});
final Set<ResourceEvent> eventCollector = new LinkedHashSet<>();
monitor.addResourceListener(new ResourceListener()
{
@Override
public void processEvent(ResourceEvent event)
{
eventCollector.add(event);
}
});
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceModified
resource.setContents("TEST");
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 1;
}
}, 5, TimeUnit.SECONDS);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceDeleted
resource.delete();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 2;
}
}, 5, TimeUnit.SECONDS);
Assert.assertEquals(2, eventCollector.size());
Iterator<ResourceEvent> iterator = eventCollector.iterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceModified.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceDeleted.class)));
}
@Test
@SuppressWarnings("unchecked")
public void testResourceMonitorFileWithFilterWindows() throws Exception
{
Assume.assumeTrue("FORGE-1679", OperatingSystemUtils.isWindows());
File tempDir = OperatingSystemUtils.createTempDir();
File tempFile = File.createTempFile("resource_monitor", ".tmp", tempDir);
final FileResource<?> resource = resourceFactory.create(FileResource.class, tempFile);
monitor = resourceFactory.monitor(resource, new ResourceFilter()
{
@Override
public boolean accept(Resource<?> resource)
{
return resource.getName().startsWith("resource_monitor");
}
});
final Set<ResourceEvent> eventCollector = new LinkedHashSet<>();
monitor.addResourceListener(new ResourceListener()
{
@Override
public void processEvent(ResourceEvent event)
{
eventCollector.add(event);
}
});
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceModified
resource.setContents("TEST");
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 1;
}
}, 5, TimeUnit.SECONDS);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceDeleted
resource.delete();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 2;
}
}, 5, TimeUnit.SECONDS);
Assert.assertEquals(2, eventCollector.size());
Iterator<ResourceEvent> iterator = eventCollector.iterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceModified.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceDeleted.class)));
}
private void waitForMonitor(Callable<Void> task, Callable<Boolean> status, int quantity, TimeUnit unit)
throws TimeoutException
{
try
{
task.call();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
long start = System.currentTimeMillis();
while (!Callables.call(status))
{
if (System.currentTimeMillis() >= (start + TimeUnit.MILLISECONDS.convert(quantity, unit))
&& !Callables.call(status))
{
throw new TimeoutException("Timeout occurred while waiting for status.");
}
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
throw new RuntimeException("Interrupted while waiting for status.", e);
}
}
}
}
| false | true | public void testResourceMonitorDirectoryWindows() throws Exception
{
Assume.assumeTrue("FORGE-1679", OperatingSystemUtils.isWindows());
File tempDir = OperatingSystemUtils.createTempDir();
DirectoryResource tempDirResource = resourceFactory.create(DirectoryResource.class, tempDir);
monitor = resourceFactory.monitor(tempDirResource);
final Set<ResourceEvent> eventCollector = new LinkedHashSet<>();
monitor.addResourceListener(new ResourceListener()
{
@Override
public void processEvent(ResourceEvent event)
{
eventCollector.add(event);
}
});
final DirectoryResource childDir = tempDirResource.getChildDirectory("child_dir");
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceCreated
childDir.mkdir();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 1;
}
}, 5, TimeUnit.SECONDS);
final FileResource<?> childFile = childDir.getChild("child_file.txt").reify(FileResource.class);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceCreated
childFile.createNewFile();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 2;
}
}, 5, TimeUnit.SECONDS);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceDeleted
childFile.delete();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 5;
}
}, 5, TimeUnit.SECONDS);
Assert.assertEquals(5, eventCollector.size());
Iterator<ResourceEvent> iterator = eventCollector.iterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceCreated.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceCreated.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceModified.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceModified.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceDeleted.class)));
}
| public void testResourceMonitorDirectoryWindows() throws Exception
{
Assume.assumeTrue("FORGE-1679", OperatingSystemUtils.isWindows());
File tempDir = OperatingSystemUtils.createTempDir();
DirectoryResource tempDirResource = resourceFactory.create(DirectoryResource.class, tempDir);
monitor = resourceFactory.monitor(tempDirResource);
final Set<ResourceEvent> eventCollector = new LinkedHashSet<>();
monitor.addResourceListener(new ResourceListener()
{
@Override
public void processEvent(ResourceEvent event)
{
eventCollector.add(event);
}
});
final DirectoryResource childDir = tempDirResource.getChildDirectory("child_dir");
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceCreated
childDir.mkdir();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 1;
}
}, 5, TimeUnit.SECONDS);
final FileResource<?> childFile = childDir.getChild("child_file.txt").reify(FileResource.class);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceCreated
childFile.createNewFile();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 2;
}
}, 5, TimeUnit.SECONDS);
waitForMonitor(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// NEW EVENT: ResourceDeleted
childFile.delete();
return null;
}
}, new Callable<Boolean>()
{
@Override
public Boolean call() throws Exception
{
return eventCollector.size() == 4;
}
}, 5, TimeUnit.SECONDS);
Assert.assertEquals(4, eventCollector.size());
Iterator<ResourceEvent> iterator = eventCollector.iterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceCreated.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceCreated.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceModified.class)));
Assert.assertTrue(iterator.hasNext());
Assert.assertThat(iterator.next(), is(instanceOf(ResourceDeleted.class)));
}
|
diff --git a/jetty/src/main/java/org/mortbay/jetty/handler/DefaultHandler.java b/jetty/src/main/java/org/mortbay/jetty/handler/DefaultHandler.java
index d5608352a..1bf26e570 100644
--- a/jetty/src/main/java/org/mortbay/jetty/handler/DefaultHandler.java
+++ b/jetty/src/main/java/org/mortbay/jetty/handler/DefaultHandler.java
@@ -1,179 +1,179 @@
// ========================================================================
// Copyright 1999-2005 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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.mortbay.jetty.handler;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.io.IO;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.HttpHeaders;
import org.mortbay.jetty.HttpMethods;
import org.mortbay.jetty.MimeTypes;
import org.mortbay.jetty.Server;
import org.mortbay.log.Log;
import org.mortbay.util.ByteArrayISO8859Writer;
import org.mortbay.util.StringUtil;
/* ------------------------------------------------------------ */
/** Default Handler.
*
* This handle will deal with unhandled requests in the server.
* For requests for favicon.ico, the Jetty icon is served.
* For reqests to '/' a 404 with a list of known contexts is served.
* For all other requests a normal 404 is served.
* TODO Implement OPTIONS and TRACE methods for the server.
*
* @author Greg Wilkins (gregw)
* @org.apache.xbean.XBean
*/
public class DefaultHandler extends AbstractHandler
{
long _faviconModified=(System.currentTimeMillis()/1000)*1000;
byte[] _favicon;
boolean _serveIcon=true;
public DefaultHandler()
{
try
{
URL fav = this.getClass().getClassLoader().getResource("org/mortbay/jetty/favicon.ico");
if (fav!=null)
_favicon=IO.readBytes(fav.openStream());
}
catch(Exception e)
{
Log.warn(e);
}
}
/* ------------------------------------------------------------ */
/*
* @see org.mortbay.jetty.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
*/
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException
{
if (response.isCommitted() || HttpConnection.getCurrentConnection().getRequest().isHandled())
return;
String method=request.getMethod();
// little cheat for common request
if (_serveIcon && _favicon!=null && method.equals(HttpMethods.GET) && request.getRequestURI().equals("/favicon.ico"))
{
if (request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)==_faviconModified)
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
else
{
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("image/x-icon");
response.setContentLength(_favicon.length);
response.setDateHeader(HttpHeaders.LAST_MODIFIED, _faviconModified);
response.getOutputStream().write(_favicon);
}
return;
}
if (!method.equals(HttpMethods.GET) || !request.getRequestURI().equals("/"))
{
- response.sendError(HttpServletResponse.SC_OK);
+ response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
- response.setStatus(HttpServletResponse.SC_OK);
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.setContentType(MimeTypes.TEXT_HTML);
ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);
String uri=request.getRequestURI();
uri=StringUtil.replace(uri,"<","<");
uri=StringUtil.replace(uri,">",">");
writer.write("<HTML>\n<HEAD>\n<TITLE>Error 404 - Not Found");
writer.write("</TITLE>\n<BODY>\n<H2>Error 404 - Not Found.</H2>\n");
writer.write("No context on this server matched or handled this request.<BR>");
writer.write("Contexts known to this server are: <ul>");
Server server = getServer();
Handler[] handlers = server==null?null:server.getChildHandlersByClass(ContextHandler.class);
for (int i=0;handlers!=null && i<handlers.length;i++)
{
ContextHandler context = (ContextHandler)handlers[i];
if (context.isRunning())
{
writer.write("<li><a href=\"");
writer.write(context.getContextPath());
writer.write("/\">");
writer.write(context.getContextPath());
writer.write(" ---> ");
writer.write(context.toString());
writer.write("</a></li>\n");
}
else
{
writer.write("<li>");
writer.write(context.getContextPath());
writer.write(" ---> ");
writer.write(context.toString());
writer.write(" [stopped]");
writer.write("</li>\n");
}
}
writer.write("</ul><small><I>The links above may not work if a virtual host is configured</I></small>");
for (int i=0;i<10;i++)
writer.write("\n<!-- Padding for IE -->");
writer.write("\n</BODY>\n</HTML>\n");
writer.flush();
response.setContentLength(writer.size());
OutputStream out=response.getOutputStream();
writer.writeTo(out);
out.close();
return;
}
/* ------------------------------------------------------------ */
/**
* @return Returns true if the handle can server the jetty favicon.ico
*/
public boolean getServeIcon()
{
return _serveIcon;
}
/* ------------------------------------------------------------ */
/**
* @param serveIcon true if the handle can server the jetty favicon.ico
*/
public void setServeIcon(boolean serveIcon)
{
_serveIcon = serveIcon;
}
}
| false | true | public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException
{
if (response.isCommitted() || HttpConnection.getCurrentConnection().getRequest().isHandled())
return;
String method=request.getMethod();
// little cheat for common request
if (_serveIcon && _favicon!=null && method.equals(HttpMethods.GET) && request.getRequestURI().equals("/favicon.ico"))
{
if (request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)==_faviconModified)
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
else
{
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("image/x-icon");
response.setContentLength(_favicon.length);
response.setDateHeader(HttpHeaders.LAST_MODIFIED, _faviconModified);
response.getOutputStream().write(_favicon);
}
return;
}
if (!method.equals(HttpMethods.GET) || !request.getRequestURI().equals("/"))
{
response.sendError(HttpServletResponse.SC_OK);
return;
}
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(MimeTypes.TEXT_HTML);
ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);
String uri=request.getRequestURI();
uri=StringUtil.replace(uri,"<","<");
uri=StringUtil.replace(uri,">",">");
writer.write("<HTML>\n<HEAD>\n<TITLE>Error 404 - Not Found");
writer.write("</TITLE>\n<BODY>\n<H2>Error 404 - Not Found.</H2>\n");
writer.write("No context on this server matched or handled this request.<BR>");
writer.write("Contexts known to this server are: <ul>");
Server server = getServer();
Handler[] handlers = server==null?null:server.getChildHandlersByClass(ContextHandler.class);
for (int i=0;handlers!=null && i<handlers.length;i++)
{
ContextHandler context = (ContextHandler)handlers[i];
if (context.isRunning())
{
writer.write("<li><a href=\"");
writer.write(context.getContextPath());
writer.write("/\">");
writer.write(context.getContextPath());
writer.write(" ---> ");
writer.write(context.toString());
writer.write("</a></li>\n");
}
else
{
writer.write("<li>");
writer.write(context.getContextPath());
writer.write(" ---> ");
writer.write(context.toString());
writer.write(" [stopped]");
writer.write("</li>\n");
}
}
writer.write("</ul><small><I>The links above may not work if a virtual host is configured</I></small>");
for (int i=0;i<10;i++)
writer.write("\n<!-- Padding for IE -->");
writer.write("\n</BODY>\n</HTML>\n");
writer.flush();
response.setContentLength(writer.size());
OutputStream out=response.getOutputStream();
writer.writeTo(out);
out.close();
return;
}
| public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException
{
if (response.isCommitted() || HttpConnection.getCurrentConnection().getRequest().isHandled())
return;
String method=request.getMethod();
// little cheat for common request
if (_serveIcon && _favicon!=null && method.equals(HttpMethods.GET) && request.getRequestURI().equals("/favicon.ico"))
{
if (request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)==_faviconModified)
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
else
{
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("image/x-icon");
response.setContentLength(_favicon.length);
response.setDateHeader(HttpHeaders.LAST_MODIFIED, _faviconModified);
response.getOutputStream().write(_favicon);
}
return;
}
if (!method.equals(HttpMethods.GET) || !request.getRequestURI().equals("/"))
{
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.setContentType(MimeTypes.TEXT_HTML);
ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);
String uri=request.getRequestURI();
uri=StringUtil.replace(uri,"<","<");
uri=StringUtil.replace(uri,">",">");
writer.write("<HTML>\n<HEAD>\n<TITLE>Error 404 - Not Found");
writer.write("</TITLE>\n<BODY>\n<H2>Error 404 - Not Found.</H2>\n");
writer.write("No context on this server matched or handled this request.<BR>");
writer.write("Contexts known to this server are: <ul>");
Server server = getServer();
Handler[] handlers = server==null?null:server.getChildHandlersByClass(ContextHandler.class);
for (int i=0;handlers!=null && i<handlers.length;i++)
{
ContextHandler context = (ContextHandler)handlers[i];
if (context.isRunning())
{
writer.write("<li><a href=\"");
writer.write(context.getContextPath());
writer.write("/\">");
writer.write(context.getContextPath());
writer.write(" ---> ");
writer.write(context.toString());
writer.write("</a></li>\n");
}
else
{
writer.write("<li>");
writer.write(context.getContextPath());
writer.write(" ---> ");
writer.write(context.toString());
writer.write(" [stopped]");
writer.write("</li>\n");
}
}
writer.write("</ul><small><I>The links above may not work if a virtual host is configured</I></small>");
for (int i=0;i<10;i++)
writer.write("\n<!-- Padding for IE -->");
writer.write("\n</BODY>\n</HTML>\n");
writer.flush();
response.setContentLength(writer.size());
OutputStream out=response.getOutputStream();
writer.writeTo(out);
out.close();
return;
}
|
diff --git a/modules/org.restlet/src/org/restlet/resource/Finder.java b/modules/org.restlet/src/org/restlet/resource/Finder.java
index af1e6aa50..5f9366972 100644
--- a/modules/org.restlet/src/org/restlet/resource/Finder.java
+++ b/modules/org.restlet/src/org/restlet/resource/Finder.java
@@ -1,511 +1,512 @@
/**
* Copyright 2005-2009 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.resource;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.data.Method;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
/**
* Restlet that can find the target server resource or handler that will
* effectively handle the call. Based on a given {@link ServerResource} or
* {@link Handler} subclass, it is also capable of instantiating the target with
* the context, request and response without requiring the usage of a Finder
* subclass. It will use the default constructor then invoke the
* {@link ServerResource#init(Context, Request, Response)} method.<br>
* <br>
* Once the target has been found, the call is automatically dispatched to the
* appropriate {@link ServerResource#handle()} method or for {@link Handler}
* subclasses to the handle*() method (where the '*' character corresponds to
* the method name) if the corresponding allow*() method returns true.<br>
* <br>
* For example, if you want to support a MOVE method for a WebDAV server, you
* just have to add a handleMove() method in your subclass of Handler and it
* will be automatically be used by the Finder instance at runtime.<br>
* <br>
* If no matching handle*() method is found, then a
* Status.CLIENT_ERROR_METHOD_NOT_ALLOWED is returned.<br>
* <br>
* Once the call is handled, the {@link ServerResource#destroy()} method is
* invoked to permit clean-up actions.<br>
* <br>
* Concurrency note: instances of this class or its subclasses can be invoked by
* several threads at the same time and therefore must be thread-safe. You
* should be especially careful when storing state in member variables.
*
* @see <a
* href="http://www.restlet.org/documentation/1.1/tutorial#part12">Tutorial:
* Reaching target Resources</a>
* @author Jerome Louvel
*/
public class Finder extends Restlet {
/** Target {@link Handler} or {@link ServerResource} subclass. */
private volatile Class<?> targetClass;
/**
* Constructor.
*/
public Finder() {
this(null);
}
/**
* Constructor.
*
* @param context
* The context.
*/
public Finder(Context context) {
super(context);
this.targetClass = null;
}
/**
* Constructor.
*
* @param context
* The context.
* @param targetClass
* The target handler class. It must be either a subclass of
* {@link Handler} or of {@link ServerResource}.
*/
public Finder(Context context, Class<?> targetClass) {
super(context);
this.targetClass = targetClass;
}
/**
* Indicates if a method is allowed on a target handler.
*
* @param method
* The method to test.
* @param target
* The target handler.
* @return True if a method is allowed on a target handler.
*/
private boolean allow(Method method, Handler target) {
boolean result = false;
if (target != null) {
if (method.equals(Method.GET)) {
result = target.allowGet();
} else if (method.equals(Method.POST)) {
result = target.allowPost();
} else if (method.equals(Method.PUT)) {
result = target.allowPut();
} else if (method.equals(Method.DELETE)) {
result = target.allowDelete();
} else if (method.equals(Method.HEAD)) {
result = target.allowHead();
} else if (method.equals(Method.OPTIONS)) {
result = target.allowOptions();
} else {
// Dynamically introspect the target handler to detect a
// matching "allow" method.
final java.lang.reflect.Method allowMethod = getAllowMethod(
method, target);
if (allowMethod != null) {
result = (Boolean) invoke(target, allowMethod);
}
}
}
return result;
}
/**
* Creates a new instance of a given {@link ServerResource} subclass. Note
* that Error and RuntimeException thrown by {@link ServerResource}
* constructors are re-thrown by this method. Other exception are caught and
* logged.
*
* @param request
* The request to handle.
* @param response
* The response to update.
* @return The created handler or null.
*/
public ServerResource create(Class<? extends ServerResource> targetClass,
Request request, Response response) {
ServerResource result = null;
if (targetClass != null) {
try {
// Invoke the constructor with Context, Request and Response
// parameters
result = targetClass.newInstance();
} catch (Exception e) {
getLogger()
.log(
Level.WARNING,
"Exception while instantiating the target server resource.",
e);
}
}
return result;
}
/**
* Creates a new instance of the {@link ServerResource} subclass designated
* by the "targetClass" property. The default behavior is to invoke the
* {@link #create(Class, Request, Response)} with the "targetClass" property
* as a parameter.
*
* @param request
* The request to handle.
* @param response
* The response to update.
* @return The created handler or null.
*/
@SuppressWarnings("unchecked")
public ServerResource create(Request request, Response response) {
return create((Class<? extends ServerResource>) getTargetClass(),
request, response);
}
/**
* Creates a new instance of a given handler class. Note that Error and
* RuntimeException thrown by Handler constructors are re-thrown by this
* method. Other exception are caught and logged.
*
* @param request
* The request to handle.
* @param response
* The response to update.
* @return The created handler or null.
*/
protected Handler createTarget(Class<? extends Handler> targetClass,
Request request, Response response) {
Handler result = null;
if (targetClass != null) {
try {
Constructor<?> constructor;
try {
// Invoke the constructor with Context, Request and Response
// parameters
constructor = targetClass.getConstructor(Context.class,
Request.class, Response.class);
result = (Handler) constructor.newInstance(getContext(),
request, response);
} catch (NoSuchMethodException nsme) {
// Invoke the default constructor then the init(Context,
// Request, Response) method.
constructor = targetClass.getConstructor();
if (constructor != null) {
result = (Handler) constructor.newInstance();
result.init(getContext(), request, response);
}
}
} catch (InvocationTargetException e) {
if (e.getCause() instanceof Error) {
throw (Error) e.getCause();
} else if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
} else {
getLogger()
.log(
Level.WARNING,
"Exception while instantiating the target handler.",
e);
}
} catch (Exception e) {
getLogger().log(Level.WARNING,
"Exception while instantiating the target handler.", e);
}
}
return result;
}
/**
* Creates a new instance of the handler class designated by the
* "targetClass" property. The default behavior is to invoke the
* {@link #createTarget(Class, Request, Response)} with the "targetClass"
* property as a parameter.
*
* @param request
* The request to handle.
* @param response
* The response to update.
* @return The created handler or null.
*/
@SuppressWarnings("unchecked")
protected Handler createTarget(Request request, Response response) {
return createTarget((Class<? extends Handler>) getTargetClass(),
request, response);
}
/**
* Finds the target {@link ServerResource} if available. The default
* behavior is to invoke the {@link #create(Request, Response)} method.
*
* @param request
* The request to handle.
* @param response
* The response to update.
* @return The target handler if available or null.
*/
public ServerResource find(Request request, Response response) {
return create(request, response);
}
/**
* Finds the target {@link Handler} if available. The default behavior is to
* invoke the {@link #createTarget(Request, Response)} method.
*
* @param request
* The request to handle.
* @param response
* The response to update.
* @return The target handler if available or null.
*/
public Handler findTarget(Request request, Response response) {
return createTarget(request, response);
}
/**
* Returns the allow method matching the given method name.
*
* @param method
* The method to match.
* @param target
* The target handler.
* @return The allow method matching the given method name.
*/
private java.lang.reflect.Method getAllowMethod(Method method,
Handler target) {
return getMethod("allow", method, target);
}
/**
* Returns the handle method matching the given method name.
*
* @param method
* The method to match.
* @return The handle method matching the given method name.
*/
private java.lang.reflect.Method getHandleMethod(Handler target,
Method method) {
return getMethod("handle", method, target);
}
/**
* Returns the method matching the given prefix and method name.
*
* @param prefix
* The method prefix to match (ex: "allow" or "handle").
* @param method
* The method to match.
* @return The method matching the given prefix and method name.
*/
private java.lang.reflect.Method getMethod(String prefix, Method method,
Object target, Class<?>... classes) {
java.lang.reflect.Method result = null;
final StringBuilder sb = new StringBuilder();
final String methodName = method.getName().toLowerCase();
if ((methodName != null) && (methodName.length() > 0)) {
sb.append(prefix);
sb.append(Character.toUpperCase(methodName.charAt(0)));
sb.append(methodName.substring(1));
}
try {
result = target.getClass().getMethod(sb.toString(), classes);
} catch (SecurityException e) {
getLogger().log(
Level.WARNING,
"Couldn't access the " + prefix + " method for \"" + method
+ "\"", e);
} catch (NoSuchMethodException e) {
getLogger().log(
Level.INFO,
"Couldn't find the " + prefix + " method for \"" + method
+ "\"", e);
}
return result;
}
/**
* Returns the target Handler class. It will be either a subclass of
* {@link Handler} or of {@link ServerResource}.
*
* @return the target Handler class.
*/
public Class<?> getTargetClass() {
return this.targetClass;
}
/**
* Handles a call.
*
* @param request
* The request to handle.
* @param response
* The response to update.
*/
@SuppressWarnings("unchecked")
@Override
public void handle(Request request, Response response) {
super.handle(request, response);
if (isStarted()) {
if (getTargetClass() == null) {
getLogger().warning(
"No target class was defined for this finder: "
+ toString());
} else {
- if (Handler.class
- .isAssignableFrom((Class<? extends Handler>) getTargetClass())) {
+ if ((getTargetClass() == null)
+ | Handler.class
+ .isAssignableFrom((Class<? extends Handler>) getTargetClass())) {
final Handler targetHandler = findTarget(request, response);
if (!response.getStatus().equals(Status.SUCCESS_OK)) {
// Probably during the instantiation of the target
// handler,
// or earlier the status was changed from the default
// one.
// Don't go further.
} else {
final Method method = request.getMethod();
if (method == null) {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST,
"No method specified");
} else {
if (!allow(method, targetHandler)) {
response
.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
targetHandler.updateAllowedMethods();
} else {
if (method.equals(Method.GET)) {
targetHandler.handleGet();
} else if (method.equals(Method.HEAD)) {
targetHandler.handleHead();
} else if (method.equals(Method.POST)) {
targetHandler.handlePost();
} else if (method.equals(Method.PUT)) {
targetHandler.handlePut();
} else if (method.equals(Method.DELETE)) {
targetHandler.handleDelete();
} else if (method.equals(Method.OPTIONS)) {
targetHandler.handleOptions();
} else {
final java.lang.reflect.Method handleMethod = getHandleMethod(
targetHandler, method);
if (handleMethod != null) {
invoke(targetHandler, handleMethod);
} else {
response
.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
}
}
}
}
} else {
final ServerResource targetResource = find(request,
response);
targetResource.init(getContext(), request, response);
if (!response.getStatus().equals(Status.SUCCESS_OK)) {
// Probably during the instantiation of the target
// server
// resource, or earlier the status was changed from the
// default one. Don't go further.
} else if (targetResource == null) {
// If the current status is a success but we couldn't
// find
// the target handler for the request's resource URI,
// then
// we set the response status to 404 (Not Found).
response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
targetResource.handle();
}
targetResource.release();
}
}
}
}
/**
* Invokes a method with the given arguments.
*
* @param target
* The target object.
* @param method
* The method to invoke.
* @param args
* The arguments to pass.
* @return Invocation result.
*/
private Object invoke(Object target, java.lang.reflect.Method method,
Object... args) {
Object result = null;
if (method != null) {
try {
result = method.invoke(target, args);
} catch (Exception e) {
getLogger().log(
Level.WARNING,
"Couldn't invoke the handle method for \"" + method
+ "\"", e);
}
}
return result;
}
/**
* Sets the target Handler class.
*
* @param targetClass
* The target Handler class. It must be either a subclass of
* {@link Handler} or of {@link ServerResource}.
*/
public void setTargetClass(Class<?> targetClass) {
this.targetClass = targetClass;
}
}
| true | true | public void handle(Request request, Response response) {
super.handle(request, response);
if (isStarted()) {
if (getTargetClass() == null) {
getLogger().warning(
"No target class was defined for this finder: "
+ toString());
} else {
if (Handler.class
.isAssignableFrom((Class<? extends Handler>) getTargetClass())) {
final Handler targetHandler = findTarget(request, response);
if (!response.getStatus().equals(Status.SUCCESS_OK)) {
// Probably during the instantiation of the target
// handler,
// or earlier the status was changed from the default
// one.
// Don't go further.
} else {
final Method method = request.getMethod();
if (method == null) {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST,
"No method specified");
} else {
if (!allow(method, targetHandler)) {
response
.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
targetHandler.updateAllowedMethods();
} else {
if (method.equals(Method.GET)) {
targetHandler.handleGet();
} else if (method.equals(Method.HEAD)) {
targetHandler.handleHead();
} else if (method.equals(Method.POST)) {
targetHandler.handlePost();
} else if (method.equals(Method.PUT)) {
targetHandler.handlePut();
} else if (method.equals(Method.DELETE)) {
targetHandler.handleDelete();
} else if (method.equals(Method.OPTIONS)) {
targetHandler.handleOptions();
} else {
final java.lang.reflect.Method handleMethod = getHandleMethod(
targetHandler, method);
if (handleMethod != null) {
invoke(targetHandler, handleMethod);
} else {
response
.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
}
}
}
}
} else {
final ServerResource targetResource = find(request,
response);
targetResource.init(getContext(), request, response);
if (!response.getStatus().equals(Status.SUCCESS_OK)) {
// Probably during the instantiation of the target
// server
// resource, or earlier the status was changed from the
// default one. Don't go further.
} else if (targetResource == null) {
// If the current status is a success but we couldn't
// find
// the target handler for the request's resource URI,
// then
// we set the response status to 404 (Not Found).
response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
targetResource.handle();
}
targetResource.release();
}
}
}
}
| public void handle(Request request, Response response) {
super.handle(request, response);
if (isStarted()) {
if (getTargetClass() == null) {
getLogger().warning(
"No target class was defined for this finder: "
+ toString());
} else {
if ((getTargetClass() == null)
| Handler.class
.isAssignableFrom((Class<? extends Handler>) getTargetClass())) {
final Handler targetHandler = findTarget(request, response);
if (!response.getStatus().equals(Status.SUCCESS_OK)) {
// Probably during the instantiation of the target
// handler,
// or earlier the status was changed from the default
// one.
// Don't go further.
} else {
final Method method = request.getMethod();
if (method == null) {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST,
"No method specified");
} else {
if (!allow(method, targetHandler)) {
response
.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
targetHandler.updateAllowedMethods();
} else {
if (method.equals(Method.GET)) {
targetHandler.handleGet();
} else if (method.equals(Method.HEAD)) {
targetHandler.handleHead();
} else if (method.equals(Method.POST)) {
targetHandler.handlePost();
} else if (method.equals(Method.PUT)) {
targetHandler.handlePut();
} else if (method.equals(Method.DELETE)) {
targetHandler.handleDelete();
} else if (method.equals(Method.OPTIONS)) {
targetHandler.handleOptions();
} else {
final java.lang.reflect.Method handleMethod = getHandleMethod(
targetHandler, method);
if (handleMethod != null) {
invoke(targetHandler, handleMethod);
} else {
response
.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
}
}
}
}
} else {
final ServerResource targetResource = find(request,
response);
targetResource.init(getContext(), request, response);
if (!response.getStatus().equals(Status.SUCCESS_OK)) {
// Probably during the instantiation of the target
// server
// resource, or earlier the status was changed from the
// default one. Don't go further.
} else if (targetResource == null) {
// If the current status is a success but we couldn't
// find
// the target handler for the request's resource URI,
// then
// we set the response status to 404 (Not Found).
response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
targetResource.handle();
}
targetResource.release();
}
}
}
}
|
diff --git a/src/edu/isi/pegasus/common/util/CondorVersion.java b/src/edu/isi/pegasus/common/util/CondorVersion.java
index aec457499..fb7e95dbb 100644
--- a/src/edu/isi/pegasus/common/util/CondorVersion.java
+++ b/src/edu/isi/pegasus/common/util/CondorVersion.java
@@ -1,247 +1,246 @@
/**
* Copyright 2007-2008 University Of Southern California
*
* 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 edu.isi.pegasus.common.util;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.common.logging.LogManagerFactory;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.griphyn.cPlanner.common.StreamGobbler;
import org.griphyn.cPlanner.common.StreamGobblerCallback;
/**
* A utility class that allows us to determine condor version.
*
* @author Karan Vahi
*/
public class CondorVersion {
/**
* The condor version command to be executed.
*/
public static final String CONDOR_VERSION_COMMAND = "condor_version";
/**
* Store the regular expressions necessary to parse the output of
* condor_version
* e.g. $CondorVersion: 7.1.0 Apr 1 2008 BuildID: 80895
*/
private static final String mRegexExpression =
"\\$CondorVersion:\\s*([0-9][.][0-9][.][0-9])[a-zA-Z:0-9\\s]*\\$";
/**
* Stores compiled patterns at first use, quasi-Singleton.
*/
private static Pattern mPattern = null;
/**
* Converts a string into the corresponding integer value.
*
* @param version
*
* @return int value of the version, else -1 in case of null version
* or incorrect formatted string
*/
public static int intValue( String version ){
int result = 0;
if( version == null ){
return -1;
}
//split on .
try{
String[] subs = version.split( "\\." );
int index = subs.length;
for( int i = 0, y = subs.length - 1; y >= 0; y--,i++){
result += (int) (Math.pow(10, y) * (Integer.parseInt(subs[i])));
}
}
catch( NumberFormatException nfe ){
result = -1;
}
return result;
}
/**
* The default logger.
*/
private LogManager mLogger;
/**
* Factory method to instantiate the class.
*/
public static CondorVersion getInstance( ){
return getInstance( null );
}
/**
* Factory method to instantiate the class.
*
*
* @param logger the logger object
*/
public static CondorVersion getInstance( LogManager logger ){
if( logger == null ){
logger = LogManagerFactory.loadSingletonInstance();
}
return new CondorVersion( logger );
}
/**
* The default constructor.
*
* @param logger the logger object
*/
private CondorVersion( LogManager logger ){
mLogger = logger;
if( mPattern == null ){
mPattern = Pattern.compile( mRegexExpression );
}
}
/**
* Returns the condor version parsed by executing the condor_version
* command.
*
* @return the version number as int else -1 if unable to determine.
*/
public int versionAsInt(){
return CondorVersion.intValue( version() );
}
/**
* Returns the condor version parsed by executing the condor_version
* command.
*
* @return the version number as String else null if unable to determine.
*/
public String version(){
String version = null;
try{
//set the callback and run the grep command
CondorVersionCallback c = new CondorVersionCallback( );
Runtime r = Runtime.getRuntime();
Process p = r.exec( CONDOR_VERSION_COMMAND );
//Process p = r.exec( CONDOR_VERSION_COMMAND );
//spawn off the gobblers
StreamGobbler ips = new StreamGobbler(p.getInputStream(), c);
StreamGobbler eps = new StreamGobbler(p.getErrorStream(),
new StreamGobblerCallback(){
//we cannot log to any of the default stream
LogManager mLogger = this.mLogger;
public void work(String s){
mLogger.log("Output on stream gobller error stream " +
s,LogManager.DEBUG_MESSAGE_LEVEL);
}
});
ips.start();
eps.start();
//wait for the threads to finish off
ips.join();
version = c.getVersion();
eps.join();
//get the status
int status = p.waitFor();
if( status != 0){
mLogger.log("Command " + CONDOR_VERSION_COMMAND + " exited with status " + status,
LogManager.WARNING_MESSAGE_LEVEL);
}
}
catch(IOException ioe){
mLogger.log("IOException while determining condor_version ", ioe,
LogManager.ERROR_MESSAGE_LEVEL);
- ioe.printStackTrace();
}
catch( InterruptedException ie){
//ignore
}
return version;
}
/**
* An inner class, that implements the StreamGobblerCallback to determine
* the version of Condor being used.
*
*/
private class CondorVersionCallback implements StreamGobblerCallback{
/**
* The version detected.
*/
private String mVersion;
/**
* The Default Constructor
*/
public CondorVersionCallback( ){
mVersion = null;
}
/**
* Callback whenever a line is read from the stream by the StreamGobbler.
* Counts the occurences of the word that are in the line, and
* increments to the global counter.
*
* @param line the line that is read.
*/
public void work( String line ){
Matcher matcher = mPattern.matcher( line );
if( matcher.matches( ) ){
mVersion = matcher.group( 1 );
}
}
/**
* Returns the condor version detected.
*
* @return the condor version else null
*/
public String getVersion(){
return mVersion;
}
}
public static void main( String[] args ){
LogManager logger = LogManagerFactory.loadSingletonInstance();
CondorVersion cv = CondorVersion.getInstance();
logger.logEventStart( "CondorVersion", "CondorVersion", "Version");
System.out.println( "Condor Version is " + cv.version() );
System.out.println( CondorVersion.intValue( "7.1.2") );
System.out.println( CondorVersion.intValue( "7.1.5s" ) );
logger.logEventCompletion();
}
}
| true | true | public String version(){
String version = null;
try{
//set the callback and run the grep command
CondorVersionCallback c = new CondorVersionCallback( );
Runtime r = Runtime.getRuntime();
Process p = r.exec( CONDOR_VERSION_COMMAND );
//Process p = r.exec( CONDOR_VERSION_COMMAND );
//spawn off the gobblers
StreamGobbler ips = new StreamGobbler(p.getInputStream(), c);
StreamGobbler eps = new StreamGobbler(p.getErrorStream(),
new StreamGobblerCallback(){
//we cannot log to any of the default stream
LogManager mLogger = this.mLogger;
public void work(String s){
mLogger.log("Output on stream gobller error stream " +
s,LogManager.DEBUG_MESSAGE_LEVEL);
}
});
ips.start();
eps.start();
//wait for the threads to finish off
ips.join();
version = c.getVersion();
eps.join();
//get the status
int status = p.waitFor();
if( status != 0){
mLogger.log("Command " + CONDOR_VERSION_COMMAND + " exited with status " + status,
LogManager.WARNING_MESSAGE_LEVEL);
}
}
catch(IOException ioe){
mLogger.log("IOException while determining condor_version ", ioe,
LogManager.ERROR_MESSAGE_LEVEL);
ioe.printStackTrace();
}
catch( InterruptedException ie){
//ignore
}
return version;
}
| public String version(){
String version = null;
try{
//set the callback and run the grep command
CondorVersionCallback c = new CondorVersionCallback( );
Runtime r = Runtime.getRuntime();
Process p = r.exec( CONDOR_VERSION_COMMAND );
//Process p = r.exec( CONDOR_VERSION_COMMAND );
//spawn off the gobblers
StreamGobbler ips = new StreamGobbler(p.getInputStream(), c);
StreamGobbler eps = new StreamGobbler(p.getErrorStream(),
new StreamGobblerCallback(){
//we cannot log to any of the default stream
LogManager mLogger = this.mLogger;
public void work(String s){
mLogger.log("Output on stream gobller error stream " +
s,LogManager.DEBUG_MESSAGE_LEVEL);
}
});
ips.start();
eps.start();
//wait for the threads to finish off
ips.join();
version = c.getVersion();
eps.join();
//get the status
int status = p.waitFor();
if( status != 0){
mLogger.log("Command " + CONDOR_VERSION_COMMAND + " exited with status " + status,
LogManager.WARNING_MESSAGE_LEVEL);
}
}
catch(IOException ioe){
mLogger.log("IOException while determining condor_version ", ioe,
LogManager.ERROR_MESSAGE_LEVEL);
}
catch( InterruptedException ie){
//ignore
}
return version;
}
|
diff --git a/source/yacy.java b/source/yacy.java
index 97c19f7bf..0cfc8e13b 100644
--- a/source/yacy.java
+++ b/source/yacy.java
@@ -1,837 +1,837 @@
//yacy.java
//-----------------------
//(C) by Michael Peter Christen; [email protected]
//first published on http://www.yacy.net
//Frankfurt, Germany, 2004, 2005
//last major change: 24.03.2005
//
//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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//Using this software in any meaning (reading, learning, copying, compiling,
//running) means that you agree that the Author(s) is (are) not responsible
//for cost, loss of data or any harm that may be caused directly or indirectly
//by usage of this softare or this documentation. The usage of this software
//is on your own risk. The installation and usage (starting/running) of this
//software may allow other people or application to access your computer and
//any attached devices and is highly dependent on the configuration of the
//software which must be done by the user of the software; the author(s) is
//(are) also not responsible for proper configuration and usage of the
//software, even if provoked by documentation provided together with
//the software.
//
//Any changes to this file according to the GPL as documented in the file
//gpl.txt aside this file in the shipment you received can be done to the
//lines that follows this copyright notice here, but changes must not be
//done inside the copyright notive above. A re-distribution must contain
//the intact and unchanged copyright notice.
//Contributions and changes to the program code must be marked as such.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.anomic.data.translator;
import de.anomic.http.httpHeader;
import de.anomic.http.httpc;
import de.anomic.http.httpd;
import de.anomic.http.httpdFileHandler;
import de.anomic.http.httpdProxyHandler;
import de.anomic.kelondro.kelondroMScoreCluster;
import de.anomic.kelondro.kelondroTree;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaURL;
import de.anomic.plasma.plasmaWordIndex;
import de.anomic.plasma.plasmaWordIndexEntity;
import de.anomic.plasma.plasmaWordIndexEntry;
import de.anomic.plasma.plasmaWordIndexEntryContainer;
import de.anomic.plasma.plasmaWordIndexClassicDB;
import de.anomic.plasma.plasmaWordIndexCache;
import de.anomic.server.serverCodings;
import de.anomic.server.serverCore;
import de.anomic.server.serverFileUtils;
import de.anomic.server.serverSystem;
import de.anomic.server.logging.serverLog;
import de.anomic.tools.enumerateFiles;
import de.anomic.yacy.yacyCore;
/**
* This is the main class of the proxy. Several threads are started from here:
* <ul>
* <li>one single instance of the plasmaSwitchboard is generated, which itself
* starts a thread with a plasmaHTMLCache object. This object simply counts
* files sizes in the cache and terminates them. It also generates a
* plasmaCrawlerLoader object, which may itself start some more httpc-calling
* threads to load web pages. They terminate automatically when a page has
* loaded.
* <li>one serverCore - thread is started, which implements a multi-threaded
* server. The process may start itself many more processes that handle
* connections.
* <li>finally, all idle-dependent processes are written in a queue in
* plasmaSwitchboard which are worked off inside an idle-sensitive loop of the
* main process. (here)
* </ul>
*
* On termination, the following must be done:
* <ul>
* <li>stop feeding of the crawling process because it othervise fills the
* indexing queue.
* <li>say goodbye to connected peers and disable new connections. Don't wait for
* success.
* <li>first terminate the serverCore thread. This prevents that new cache
* objects are queued.
* <li>wait that the plasmaHTMLCache terminates (it should be normal that this
* process already has terminated).
* <li>then wait for termination of all loader process of the
* plasmaCrawlerLoader.
* <li>work off the indexing and cache storage queue. These values are inside a
* RAM cache and would be lost otherwise.
* <li>write all settings.
* <li>terminate.
* </ul>
*/
public final class yacy {
// static objects
private static String vString = "@REPL_VERSION@";
private static float version = (float) 0.1;
private static final String vDATE = "@REPL_DATE@";
private static final String copyright = "[ YACY Proxy v" + vString + ", build " + vDATE + " by Michael Christen / www.yacy.net ]";
private static final String hline = "-------------------------------------------------------------------------------";
/**
* Convert the combined versionstring into a pretty string.
* FIXME: Why is this so complicated?
*
* @param s Combined version string
* @return Pretty string where version and svn-Version are separated by an
* slash
*/
public static String combinedVersionString2PrettyString(String s) {
long svn;
try {svn = (long) (100000000.0 * Double.parseDouble(s));} catch (NumberFormatException ee) {svn = 0;}
double version = (Math.floor((double) svn / (double) 100000) / (double) 1000);
String vStr = (version < 0.11) ? "dev" : Double.toString(version);
//while (vStr.length() < 5) vStr = vStr + "0";
svn = svn % 100000;
if (svn > 4000) svn=svn / 10; // fix a previous bug online
String svnStr = Long.toString(svn);
while (svnStr.length() < 5) svnStr = "0" + svnStr;
return vStr + "/" + svnStr;
}
/**
* Combines the version of the proxy with the versionnumber from svn to a
* combined Version
*
* @param version Current given version for this proxy.
* @param svn Current version given from svn.
* @return String with the combined version
*/
public static float versvn2combinedVersion(float version, int svn) {
return (float) (((double) version * 100000000.0 + ((double) svn)) / 100000000.0);
}
/**
* Starts up the whole application. Sets up all datastructures and starts
* the main threads.
*
* @param homePath Root-path where all information is to be found.
*/
private static void startup(String homePath) {
long startup = yacyCore.universalTime();
try {
// start up
System.out.println(copyright);
System.out.println(hline);
// check java version
try {
String[] check = "a,b".split(","); // split needs java 1.4
} catch (NoSuchMethodError e) {
System.err.println("STARTUP: Java Version too low. You need at least Java 1.4.2 to run YACY");
Thread.currentThread().sleep(3000);
System.exit(-1);
}
// setting up logging
try {
serverLog.configureLogging(new File(homePath, "yacy.logging"));
} catch (IOException e) {
System.out.println("could not find logging properties in homePath=" + homePath);
e.printStackTrace();
}
serverLog.logSystem("STARTUP", copyright);
serverLog.logSystem("STARTUP", hline);
serverLog.logSystem("STARTUP", "java version " + System.getProperty("java.version", "no-java-version"));
serverLog.logSystem("STARTUP", "Application Root Path: " + homePath.toString());
// create data folder
File dataFolder = new File(homePath, "DATA");
if (!(dataFolder.exists())) dataFolder.mkdir();
plasmaSwitchboard sb = new plasmaSwitchboard(homePath, "yacy.init", "DATA/SETTINGS/httpProxy.conf");
// hardcoded, forced, temporary value-migration
sb.setConfig("htTemplatePath", "htroot/env/templates");
sb.setConfig("parseableExt", "html,htm,txt,php,shtml,asp");
// if we are running an SVN version, we try to detect the used svn revision now ...
Properties buildProp = new Properties();
File buildPropFile = null;
try {
buildPropFile = new File(homePath,"build.properties");
buildProp.load(new FileInputStream(buildPropFile));
} catch (Exception e) {
System.err.println("ERROR: " + buildPropFile.toString() + " not found in settings path");
}
try {
if (buildProp.containsKey("releaseNr")) {
// this normally looks like this: $Revision: 181 $
String svnReleaseNrStr = buildProp.getProperty("releaseNr");
Pattern pattern = Pattern.compile("\\$Revision:\\s(.*)\\s\\$",Pattern.DOTALL+Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(svnReleaseNrStr);
if (matcher.find()) {
String svrReleaseNr = matcher.group(1);
try {
try {version = Float.parseFloat(vString);} catch (NumberFormatException e) {version = (float) 0.1;}
version = versvn2combinedVersion(version, Integer.parseInt(svrReleaseNr));
} catch (NumberFormatException e) {}
sb.setConfig("svnRevision", svrReleaseNr);
}
}
} catch (Exception e) {
System.err.println("Unable to determine the currently used SVN revision number.");
}
sb.setConfig("version", Float.toString(version));
sb.setConfig("vdate", vDATE);
sb.setConfig("applicationRoot", homePath);
sb.setConfig("startupTime", Long.toString(startup));
serverLog.logSystem("STARTUP", "YACY Version: " + version + ", Built " + vDATE);
yacyCore.latestVersion = (float) version;
// read environment
//new
int port = Integer.parseInt(sb.getConfig("port", "8080"));
int timeout = Integer.parseInt(sb.getConfig("httpdTimeout", "60000"));
if (timeout < 60000) timeout = 60000;
// create some directories
File htRootPath = new File(sb.getRootPath(), sb.getConfig("htRootPath", "htroot"));
File htDocsPath = new File(sb.getRootPath(), sb.getConfig("htDocsPath", "DATA/HTDOCS"));
File htTemplatePath = new File(sb.getRootPath(), sb.getConfig("htTemplatePath","htdocs"));
// create default notifier picture
- if (!((new File(htRootPath, "env/pictures/notifier.gif")).exists())) try {
- serverFileUtils.copy(new File(htRootPath, "env/pictures/empty.gif"),
- new File(htRootPath, "env/pictures/notifier.gif"));
+ if (!((new File(htRootPath, "env/grafics/notifier.gif")).exists())) try {
+ serverFileUtils.copy(new File(htRootPath, "env/grafics/empty.gif"),
+ new File(htRootPath, "env/grafics/notifier.gif"));
} catch (IOException e) {}
if (!(htDocsPath.exists())) htDocsPath.mkdir();
File htdocsDefaultReadme = new File(htDocsPath, "readme.txt");
if (!(htdocsDefaultReadme.exists())) try {serverFileUtils.write((
"This is your root directory for individual Web Content\r\n" +
"\r\n" +
"Please place your html files into the www subdirectory.\r\n" +
"The URL of that path is either\r\n" +
"http://www.<your-peer-name>.yacy or\r\n" +
"http://<your-ip>:<your-port>/www\r\n" +
"\r\n" +
"Other subdirectories may be created; they map to corresponding sub-domains.\r\n" +
"This directory shares it's content with the applications htroot path, so you\r\n" +
"may access your yacy search page with\r\n" +
"http://<your-peer-name>.yacy/\r\n" +
"\r\n").getBytes(), htdocsDefaultReadme);} catch (IOException e) {
System.out.println("Error creating htdocs readme: " + e.getMessage());
}
File wwwDefaultPath = new File(htDocsPath, "www");
if (!(wwwDefaultPath.exists())) wwwDefaultPath.mkdir();
File wwwDefaultClass = new File(wwwDefaultPath, "welcome.class");
//if ((!(wwwDefaultClass.exists())) || (wwwDefaultClass.length() != (new File(htRootPath, "htdocsdefault/welcome.class")).length())) try {
if((new File(htRootPath, "htdocsdefault/welcome.java")).exists())
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/welcome.java"), new File(wwwDefaultPath, "welcome.java"));
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/welcome.class"), wwwDefaultClass);
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/welcome.html"), new File(wwwDefaultPath, "welcome.html"));
//} catch (IOException e) {}
File shareDefaultPath = new File(htDocsPath, "share");
if (!(shareDefaultPath.exists())) shareDefaultPath.mkdir();
File shareDefaultClass = new File(shareDefaultPath, "dir.class");
//if ((!(shareDefaultClass.exists())) || (shareDefaultClass.length() != (new File(htRootPath, "htdocsdefault/dir.class")).length())) try {
if((new File(htRootPath, "htdocsdefault/dir.java")).exists())
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/dir.java"), new File(shareDefaultPath, "dir.java"));
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/dir.class"), shareDefaultClass);
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/dir.html"), new File(shareDefaultPath, "dir.html"));
//} catch (IOException e) {}
// set preset accounts/passwords
String acc;
if ((acc = sb.getConfig("proxyAccount", "")).length() > 0) {
sb.setConfig("proxyAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(serverCodings.standardCoder.encodeBase64String(acc)));
sb.setConfig("proxyAccount", "");
}
if ((acc = sb.getConfig("serverAccount", "")).length() > 0) {
sb.setConfig("serverAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(serverCodings.standardCoder.encodeBase64String(acc)));
sb.setConfig("serverAccount", "");
}
if ((acc = sb.getConfig("adminAccount", "")).length() > 0) {
sb.setConfig("adminAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(serverCodings.standardCoder.encodeBase64String(acc)));
sb.setConfig("adminAccount", "");
}
// fix unsafe old passwords
if ((acc = sb.getConfig("proxyAccountBase64", "")).length() > 0) {
sb.setConfig("proxyAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("proxyAccountBase64", "");
}
if ((acc = sb.getConfig("serverAccountBase64", "")).length() > 0) {
sb.setConfig("serverAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("serverAccountBase64", "");
}
if ((acc = sb.getConfig("adminAccountBase64", "")).length() > 0) {
sb.setConfig("adminAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("adminAccountBase64", "");
}
if ((acc = sb.getConfig("uploadAccountBase64", "")).length() > 0) {
sb.setConfig("uploadAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("uploadAccountBase64", "");
}
if ((acc = sb.getConfig("downloadAccountBase64", "")).length() > 0) {
sb.setConfig("downloadAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("downloadAccountBase64", "");
}
// start main threads
try {
httpd protocolHandler = new httpd(sb, new httpdFileHandler(sb), new httpdProxyHandler(sb));
serverCore server = new serverCore(port,
timeout /*control socket timeout in milliseconds*/,
true /* block attacks (wrong protocol) */,
protocolHandler /*command class*/,
sb,
30000 /*command max length incl. GET args*/);
server.setName("httpd:"+port);
server.setPriority(Thread.MAX_PRIORITY);
if (server == null) {
serverLog.logFailure("STARTUP", "Failed to start server. Probably port " + port + " already in use.");
} else {
// first start the server
sb.deployThread("10_httpd", "HTTPD Server/Proxy", "the HTTPD, used as web server and proxy", null, server, 0, 0, 0, 0);
//server.start();
// open the browser window
boolean browserPopUpTrigger = sb.getConfig("browserPopUpTrigger", "true").equals("true");
if (browserPopUpTrigger) {
String browserPopUpPage = sb.getConfig("browserPopUpPage", "Status.html");
String browserPopUpApplication = sb.getConfig("browserPopUpApplication", "netscape");
serverSystem.openBrowser("http://localhost:" + port + "/" + browserPopUpPage, browserPopUpApplication);
}
//Copy the shipped locales into DATA
File localesPath = new File(sb.getRootPath(), sb.getConfig("localesPath", "DATA/LOCALE"));
File defaultLocalesPath = new File(sb.getRootPath(), "locales");
try{
File[] defaultLocales = defaultLocalesPath.listFiles();
localesPath.mkdirs();
for(int i=0;i < defaultLocales.length; i++){
if(defaultLocales[i].getName().endsWith(".lng"))
serverFileUtils.copy(defaultLocales[i], new File(localesPath, defaultLocales[i].getName()));
}
serverLog.logInfo("STARTUP", "Copied the default lokales to DATA/LOCALE");
}catch(NullPointerException e){
serverLog.logError("STARTUP", "Nullpointer Exception while copying the default Locales");
}
//regenerate Locales from Translationlist, if needed
String lang = sb.getConfig("htLocaleSelection", "");
if(! lang.equals("") && ! lang.equals("default") ){ //locale is used
String currentRev = "";
try{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File( sb.getConfig("htRootPath", "htroot"), "locale/"+lang+"/version" ))));
currentRev = br.readLine();
br.close();
}catch(IOException e){
//Error
}
try{ //seperate try, because we want this, even when the File "version2 does not exist.
if(! currentRev.equals(sb.getConfig("svnRevision", "")) ){ //is this another version?!
File sourceDir = new File(sb.getConfig("htRootPath", "htroot"));
File destDir = new File(sourceDir, "locale/"+lang);
if(translator.translateFiles(sourceDir, destDir, new File("DATA/LOCALE/"+lang+".lng"), "html")){ //translate it
//write the new Versionnumber
BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(new File(destDir, "version"))));
bw.write(sb.getConfig("svnRevision", "Error getting Version"));
bw.close();
}
}
}catch(IOException e){
//Error
}
}
// registering shutdown hook
serverLog.logSystem("STARTUP", "Registering Shutdown Hook");
Runtime run = Runtime.getRuntime();
run.addShutdownHook(new shutdownHookThread(Thread.currentThread(), sb));
// wait for server shutdown
try {
sb.waitForShutdown();
} catch (Exception e) {
serverLog.logError("MAIN CONTROL LOOP", "PANIK: " + e.getMessage(),e);
}
// shut down
serverLog.logSystem("SHUTDOWN", "caught termination signal");
server.terminate(false);
server.interrupt();
if (server.isAlive()) try {
httpc.wget(new URL("http://localhost:" + port), 1000, null, null, null, 0); // kick server
serverLog.logSystem("SHUTDOWN", "sent termination signal to server socket");
} catch (IOException ee) {
serverLog.logSystem("SHUTDOWN", "termination signal to server socket missed (server shutdown, ok)");
}
// idle until the processes are down
while (server.isAlive()) {
Thread.currentThread().sleep(2000); // wait a while
}
serverLog.logSystem("SHUTDOWN", "server has terminated");
sb.close();
}
} catch (Exception e) {
serverLog.logError("STARTUP", "Unexpected Error: " + e.getClass().getName(),e);
//System.exit(1);
}
} catch (Exception ee) {
serverLog.logFailure("STARTUP", "FATAL ERROR: " + ee.getMessage(),ee);
ee.printStackTrace();
}
serverLog.logSystem("SHUTDOWN", "goodbye. (this is the last line)");
try {
System.exit(0);
} catch (Exception e) {} // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790)
}
/**
* Loads the configuration from the data-folder.
* FIXME: Why is this called over and over again from every method, instead
* of setting the configurationdata once for this class in main?
*
* @param mes Where are we called from, so that the errormessages can be
* more descriptive.
* @param homePath Root-path where all the information is to be found.
* @return Properties read from the configurationfile.
*/
private static Properties configuration(String mes, String homePath) {
serverLog.logSystem(mes, "Application Root Path: " + homePath.toString());
// read data folder
File dataFolder = new File(homePath, "DATA");
if (!(dataFolder.exists())) {
serverLog.logError(mes, "Application was never started or root path wrong.");
System.exit(-1);
}
Properties config = new Properties();
try {
config.load(new FileInputStream(new File(homePath, "DATA/SETTINGS/httpProxy.conf")));
} catch (FileNotFoundException e) {
serverLog.logError(mes, "could not find configuration file.");
System.exit(-1);
} catch (IOException e) {
serverLog.logError(mes, "could not read configuration file.");
System.exit(-1);
}
return config;
}
/**
* Call the shutdown-page from yacy to tell it to shut down. This method is
* called if you start yacy with the argument -shutdown.
*
* @param homePath Root-path where all the information is to be found.
*/
static void shutdown(String homePath) {
// start up
System.out.println(copyright);
System.out.println(hline);
Properties config = configuration("REMOTE-SHUTDOWN", homePath);
// read port
int port = Integer.parseInt((String) config.get("port"));
// read password
String encodedPassword = (String) config.get("adminAccountBase64MD5");
if (encodedPassword == null) encodedPassword = ""; // not defined
// send 'wget' to web interface
httpHeader requestHeader = new httpHeader();
requestHeader.put("Authorization", "realm=" + encodedPassword); // for http-authentify
try {
httpc con = httpc.getInstance("localhost", port, 10000, false);
httpc.response res = con.GET("Steering.html?shutdown=", requestHeader);
// read response
if (res.status.startsWith("2")) {
serverLog.logSystem("REMOTE-SHUTDOWN", "YACY accepted shutdown command.");
serverLog.logSystem("REMOTE-SHUTDOWN", "Stand by for termination, which may last some seconds.");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
res.writeContent(bos, null);
con.close();
} else {
serverLog.logError("REMOTE-SHUTDOWN", "error response from YACY socket: " + res.status);
System.exit(-1);
}
} catch (IOException e) {
serverLog.logError("REMOTE-SHUTDOWN", "could not establish connection to YACY socket: " + e.getMessage());
System.exit(-1);
}
// finished
serverLog.logSystem("REMOTE-SHUTDOWN", "SUCCESSFULLY FINISHED remote-shutdown:");
serverLog.logSystem("REMOTE-SHUTDOWN", "YACY will terminate after working off all enqueued tasks.");
}
/**
* This method gets all found words and outputs a statistic about the score
* of the words. The output of this method can be used to create stop-word
* lists. This method will be called if you start yacy with the argument
* -genwordstat.
* FIXME: How can stop-word list be created from this output? What type of
* score is output?
*
* @param homePath Root-Path where all the information is to be found.
*/
private static void genWordstat(String homePath) {
// start up
System.out.println(copyright);
System.out.println(hline);
Properties config = configuration("GEN-WORDSTAT", homePath);
// load words
serverLog.logInfo("GEN-WORDSTAT", "loading words...");
HashMap words = loadWordMap(new File(homePath, "yacy.words"));
// find all hashes
serverLog.logInfo("GEN-WORDSTAT", "searching all word-hash databases...");
File dbRoot = new File(homePath, config.getProperty("dbPath"));
enumerateFiles ef = new enumerateFiles(new File(dbRoot, "WORDS"), true, false, true, true);
File f;
String h;
kelondroMScoreCluster hs = new kelondroMScoreCluster();
while (ef.hasMoreElements()) {
f = (File) ef.nextElement();
h = f.getName().substring(0, plasmaURL.urlHashLength);
hs.addScore(h, (int) f.length());
}
// list the hashes in reverse order
serverLog.logInfo("GEN-WORDSTAT", "listing words in reverse size order...");
String w;
Iterator i = hs.scores(false);
while (i.hasNext()) {
h = (String) i.next();
w = (String) words.get(h);
if (w == null) System.out.print("# " + h); else System.out.print(w);
System.out.println(" - " + hs.getScore(h));
}
// finished
serverLog.logSystem("GEN-WORDSTAT", "FINISHED");
}
/**
* Migrates the PLASMA WORDS structure to the assortment cache if possible.
* This method will be called if you start yacy with the argument
* -migratewords.
* Caution: This might take a long time to finish. Don't interrupt it!
* FIXME: Shouldn't this method be private?
*
* @param homePath Root-path where all the information is to be found.
*/
public static void migrateWords(String homePath) {
// run with "java -classpath classes yacy -migratewords"
try {serverLog.configureLogging(new File(homePath, "yacy.logging"));} catch (Exception e) {}
File dbroot = new File(new File(homePath), "DATA/PLASMADB");
try {
serverLog log = new serverLog("WORDMIGRATION");
log.logInfo("STARTING MIGRATION");
plasmaWordIndexCache wordIndexCache = new plasmaWordIndexCache(dbroot, new plasmaWordIndexClassicDB(dbroot, log), 20000, log);
enumerateFiles words = new enumerateFiles(new File(dbroot, "WORDS"), true, false, true, true);
String wordhash;
File wordfile;
int migration;
while (words.hasMoreElements()) try {
wordfile = (File) words.nextElement();
wordhash = wordfile.getName().substring(0, 12);
migration = wordIndexCache.migrateWords2Assortment(wordhash);
if (migration == 0)
log.logInfo("SKIPPED " + wordhash + ": too big");
else if (migration > 0)
log.logInfo("MIGRATED " + wordhash + ": " + migration + " entries");
else
log.logInfo("REVERSED " + wordhash + ": " + (-migration) + " entries");
} catch (Exception e) {
e.printStackTrace();
}
log.logInfo("FINISHED MIGRATION JOB, WAIT FOR DUMP");
wordIndexCache.close(60);
log.logInfo("TERMINATED MIGRATION");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Reads all words from the given file and creates a hashmap, where key is
* the plasma word hash and value is the word itself.
*
* @param wordlist File where the words are stored.
* @return HashMap with the hash-word - relation.
*/
private static HashMap loadWordMap(File wordlist) {
// returns a hash-word - Relation
HashMap wordmap = new HashMap();
try {
String word;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(wordlist)));
while ((word = br.readLine()) != null) wordmap.put(plasmaWordIndexEntry.word2hash(word),word);
br.close();
} catch (IOException e) {}
return wordmap;
}
/**
* Reads all words from the given file and creats as HashSet, which contains
* all found words.
*
* @param wordlist File where the words are stored.
* @return HashSet with the words
*/
private static HashSet loadWordSet(File wordlist) {
// returns a set of words
HashSet wordset = new HashSet();
try {
String word;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(wordlist)));
while ((word = br.readLine()) != null) wordset.add(word);
br.close();
} catch (IOException e) {}
return wordset;
}
/**
* Cleans a wordlist in a file according to the length of the words. The
* file with the given filename is read and then only the words in the given
* length-range are written back to the file.
*
* @param wordlist Name of the file the words are stored in.
* @param minlength Minimal needed length for each word to be stored.
* @param maxlength Maximal allowed length for each word to be stored.
*/
private static void cleanwordlist(String wordlist, int minlength, int maxlength) {
// start up
System.out.println(copyright);
System.out.println(hline);
serverLog.logSystem("CLEAN-WORDLIST", "START");
String word;
TreeSet wordset = new TreeSet();
int count = 0;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(wordlist)));
String seps = "' .,:/-&";
while ((word = br.readLine()) != null) {
word = word.toLowerCase().trim();
for (int i = 0; i < seps.length(); i++) {
if (word.indexOf(seps.charAt(i)) >= 0) word = word.substring(0, word.indexOf(seps.charAt(i)));
}
if ((word.length() >= minlength) && (word.length() <= maxlength)) wordset.add(word);
count++;
}
br.close();
if (wordset.size() != count) {
count = count - wordset.size();
BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(wordlist)));
while (wordset.size() > 0) {
word = (String) wordset.first();
bw.write(word + "\n");
wordset.remove(word);
}
bw.close();
serverLog.logInfo("CLEAN-WORDLIST", "shrinked wordlist by " + count + " words.");
} else {
serverLog.logInfo("CLEAN-WORDLIST", "not necessary to change wordlist");
}
} catch (IOException e) {
serverLog.logError("CLEAN-WORDLIST", "ERROR: " + e.getMessage());
System.exit(-1);
}
// finished
serverLog.logSystem("CLEAN-WORDLIST", "FINISHED");
}
/**
* Gets all words from the stopword-list and removes them in the databases.
* FIXME: Really? Don't know if I read this correctly.
*
* @param homePath Root-Path where all information is to be found.
*/
private static void deleteStopwords(String homePath) {
// start up
System.out.println(copyright);
System.out.println(hline);
serverLog.logSystem("DELETE-STOPWORDS", "START");
Properties config = configuration("DELETE-STOPWORDS", homePath);
File dbRoot = new File(homePath, config.getProperty("dbPath"));
// load stopwords
HashSet stopwords = loadWordSet(new File(homePath, "yacy.stopwords"));
serverLog.logInfo("DELETE-STOPWORDS", "loaded stopwords, " + stopwords.size() + " entries in list, starting scanning");
// find all hashes
File f;
String w;
int count = 0;
long thisamount, totalamount = 0;
Iterator i = stopwords.iterator();
while (i.hasNext()) {
w = (String) i.next();
f = plasmaWordIndexEntity.wordHash2path(dbRoot, plasmaWordIndexEntry.word2hash(w));
if (f.exists()) {
thisamount = f.length();
if (f.delete()) {
count++;
totalamount += thisamount;
serverLog.logInfo("DELETE-STOPWORDS", "deleted index for word '" + w + "', " + thisamount + " bytes");
}
}
}
serverLog.logInfo("DELETE-STOPWORDS", "TOTALS: deleted " + count + " indexes; " + (totalamount / 1024) + " kbytes");
// finished
serverLog.logSystem("DELETE-STOPWORDS", "FINISHED");
}
/**
* Main-method which is started by java. Checks for special arguments or
* starts up the application.
*
* @param args Given arguments from the command line.
*/
public static void main(String args[]) {
String applicationRoot = System.getProperty("user.dir");
//System.out.println("args.length=" + args.length);
//System.out.print("args=["); for (int i = 0; i < args.length; i++) System.out.print(args[i] + ", "); System.out.println("]");
if ((args.length >= 1) && ((args[0].equals("-startup")) || (args[0].equals("-start")))) {
// normal start-up of yacy
if (args.length == 2) applicationRoot= args[1];
startup(applicationRoot);
} else if ((args.length >= 1) && ((args[0].equals("-shutdown")) || (args[0].equals("-stop")))) {
// normal shutdown of yacy
if (args.length == 2) applicationRoot= args[1];
shutdown(applicationRoot);
} else if ((args.length >= 1) && (args[0].equals("-migratewords"))) {
// migrate words from DATA/PLASMADB/WORDS path to assortment cache, if possible
// attention: this may run long and should not be interrupted!
if (args.length == 2) applicationRoot= args[1];
migrateWords(applicationRoot);
} else if ((args.length >= 1) && (args[0].equals("-deletestopwords"))) {
// delete those words in the index that are listed in the stopwords file
if (args.length == 2) applicationRoot= args[1];
deleteStopwords(applicationRoot);
} else if ((args.length >= 1) && (args[0].equals("-genwordstat"))) {
// this can help to create a stop-word list
// to use this, you need a 'yacy.words' file in the root path
// start this with "java -classpath classes yacy -genwordstat [<rootdir>]"
if (args.length == 2) applicationRoot= args[1];
genWordstat(applicationRoot);
} else if ((args.length == 4) && (args[0].equals("-cleanwordlist"))) {
// this can be used to organize and clean a word-list
// start this with "java -classpath classes yacy -cleanwordlist <word-file> <minlength> <maxlength>"
int minlength = Integer.parseInt(args[2]);
int maxlength = Integer.parseInt(args[3]);
cleanwordlist(args[1], minlength, maxlength);
} else {
if (args.length == 1) applicationRoot= args[0];
startup(applicationRoot);
}
}
}
/**
* This class is a helper class whose instance is started, when the java virtual
* machine shuts down. Signals the plasmaSwitchboard to shut down.
*/
class shutdownHookThread extends Thread {
private plasmaSwitchboard sb = null;
private Thread mainThread = null;
public shutdownHookThread(Thread mainThread, plasmaSwitchboard sb) {
this.sb = sb;
this.mainThread = mainThread;
}
public void run() {
try {
if (!this.sb.isTerminated()) {
serverLog.logSystem("SHUTDOWN","Shutdown via shutdown hook.");
// sending the yacy main thread a shutdown signal
this.sb.terminate();
// waiting for the yacy thread to finish execution
this.mainThread.join();
}
} catch (Exception e) {
serverLog.logFailure("SHUTDOWN","Unexpected error. " + e.getClass().getName(),e);
}
}
}
| true | true | private static void startup(String homePath) {
long startup = yacyCore.universalTime();
try {
// start up
System.out.println(copyright);
System.out.println(hline);
// check java version
try {
String[] check = "a,b".split(","); // split needs java 1.4
} catch (NoSuchMethodError e) {
System.err.println("STARTUP: Java Version too low. You need at least Java 1.4.2 to run YACY");
Thread.currentThread().sleep(3000);
System.exit(-1);
}
// setting up logging
try {
serverLog.configureLogging(new File(homePath, "yacy.logging"));
} catch (IOException e) {
System.out.println("could not find logging properties in homePath=" + homePath);
e.printStackTrace();
}
serverLog.logSystem("STARTUP", copyright);
serverLog.logSystem("STARTUP", hline);
serverLog.logSystem("STARTUP", "java version " + System.getProperty("java.version", "no-java-version"));
serverLog.logSystem("STARTUP", "Application Root Path: " + homePath.toString());
// create data folder
File dataFolder = new File(homePath, "DATA");
if (!(dataFolder.exists())) dataFolder.mkdir();
plasmaSwitchboard sb = new plasmaSwitchboard(homePath, "yacy.init", "DATA/SETTINGS/httpProxy.conf");
// hardcoded, forced, temporary value-migration
sb.setConfig("htTemplatePath", "htroot/env/templates");
sb.setConfig("parseableExt", "html,htm,txt,php,shtml,asp");
// if we are running an SVN version, we try to detect the used svn revision now ...
Properties buildProp = new Properties();
File buildPropFile = null;
try {
buildPropFile = new File(homePath,"build.properties");
buildProp.load(new FileInputStream(buildPropFile));
} catch (Exception e) {
System.err.println("ERROR: " + buildPropFile.toString() + " not found in settings path");
}
try {
if (buildProp.containsKey("releaseNr")) {
// this normally looks like this: $Revision: 181 $
String svnReleaseNrStr = buildProp.getProperty("releaseNr");
Pattern pattern = Pattern.compile("\\$Revision:\\s(.*)\\s\\$",Pattern.DOTALL+Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(svnReleaseNrStr);
if (matcher.find()) {
String svrReleaseNr = matcher.group(1);
try {
try {version = Float.parseFloat(vString);} catch (NumberFormatException e) {version = (float) 0.1;}
version = versvn2combinedVersion(version, Integer.parseInt(svrReleaseNr));
} catch (NumberFormatException e) {}
sb.setConfig("svnRevision", svrReleaseNr);
}
}
} catch (Exception e) {
System.err.println("Unable to determine the currently used SVN revision number.");
}
sb.setConfig("version", Float.toString(version));
sb.setConfig("vdate", vDATE);
sb.setConfig("applicationRoot", homePath);
sb.setConfig("startupTime", Long.toString(startup));
serverLog.logSystem("STARTUP", "YACY Version: " + version + ", Built " + vDATE);
yacyCore.latestVersion = (float) version;
// read environment
//new
int port = Integer.parseInt(sb.getConfig("port", "8080"));
int timeout = Integer.parseInt(sb.getConfig("httpdTimeout", "60000"));
if (timeout < 60000) timeout = 60000;
// create some directories
File htRootPath = new File(sb.getRootPath(), sb.getConfig("htRootPath", "htroot"));
File htDocsPath = new File(sb.getRootPath(), sb.getConfig("htDocsPath", "DATA/HTDOCS"));
File htTemplatePath = new File(sb.getRootPath(), sb.getConfig("htTemplatePath","htdocs"));
// create default notifier picture
if (!((new File(htRootPath, "env/pictures/notifier.gif")).exists())) try {
serverFileUtils.copy(new File(htRootPath, "env/pictures/empty.gif"),
new File(htRootPath, "env/pictures/notifier.gif"));
} catch (IOException e) {}
if (!(htDocsPath.exists())) htDocsPath.mkdir();
File htdocsDefaultReadme = new File(htDocsPath, "readme.txt");
if (!(htdocsDefaultReadme.exists())) try {serverFileUtils.write((
"This is your root directory for individual Web Content\r\n" +
"\r\n" +
"Please place your html files into the www subdirectory.\r\n" +
"The URL of that path is either\r\n" +
"http://www.<your-peer-name>.yacy or\r\n" +
"http://<your-ip>:<your-port>/www\r\n" +
"\r\n" +
"Other subdirectories may be created; they map to corresponding sub-domains.\r\n" +
"This directory shares it's content with the applications htroot path, so you\r\n" +
"may access your yacy search page with\r\n" +
"http://<your-peer-name>.yacy/\r\n" +
"\r\n").getBytes(), htdocsDefaultReadme);} catch (IOException e) {
System.out.println("Error creating htdocs readme: " + e.getMessage());
}
File wwwDefaultPath = new File(htDocsPath, "www");
if (!(wwwDefaultPath.exists())) wwwDefaultPath.mkdir();
File wwwDefaultClass = new File(wwwDefaultPath, "welcome.class");
//if ((!(wwwDefaultClass.exists())) || (wwwDefaultClass.length() != (new File(htRootPath, "htdocsdefault/welcome.class")).length())) try {
if((new File(htRootPath, "htdocsdefault/welcome.java")).exists())
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/welcome.java"), new File(wwwDefaultPath, "welcome.java"));
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/welcome.class"), wwwDefaultClass);
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/welcome.html"), new File(wwwDefaultPath, "welcome.html"));
//} catch (IOException e) {}
File shareDefaultPath = new File(htDocsPath, "share");
if (!(shareDefaultPath.exists())) shareDefaultPath.mkdir();
File shareDefaultClass = new File(shareDefaultPath, "dir.class");
//if ((!(shareDefaultClass.exists())) || (shareDefaultClass.length() != (new File(htRootPath, "htdocsdefault/dir.class")).length())) try {
if((new File(htRootPath, "htdocsdefault/dir.java")).exists())
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/dir.java"), new File(shareDefaultPath, "dir.java"));
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/dir.class"), shareDefaultClass);
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/dir.html"), new File(shareDefaultPath, "dir.html"));
//} catch (IOException e) {}
// set preset accounts/passwords
String acc;
if ((acc = sb.getConfig("proxyAccount", "")).length() > 0) {
sb.setConfig("proxyAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(serverCodings.standardCoder.encodeBase64String(acc)));
sb.setConfig("proxyAccount", "");
}
if ((acc = sb.getConfig("serverAccount", "")).length() > 0) {
sb.setConfig("serverAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(serverCodings.standardCoder.encodeBase64String(acc)));
sb.setConfig("serverAccount", "");
}
if ((acc = sb.getConfig("adminAccount", "")).length() > 0) {
sb.setConfig("adminAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(serverCodings.standardCoder.encodeBase64String(acc)));
sb.setConfig("adminAccount", "");
}
// fix unsafe old passwords
if ((acc = sb.getConfig("proxyAccountBase64", "")).length() > 0) {
sb.setConfig("proxyAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("proxyAccountBase64", "");
}
if ((acc = sb.getConfig("serverAccountBase64", "")).length() > 0) {
sb.setConfig("serverAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("serverAccountBase64", "");
}
if ((acc = sb.getConfig("adminAccountBase64", "")).length() > 0) {
sb.setConfig("adminAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("adminAccountBase64", "");
}
if ((acc = sb.getConfig("uploadAccountBase64", "")).length() > 0) {
sb.setConfig("uploadAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("uploadAccountBase64", "");
}
if ((acc = sb.getConfig("downloadAccountBase64", "")).length() > 0) {
sb.setConfig("downloadAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("downloadAccountBase64", "");
}
// start main threads
try {
httpd protocolHandler = new httpd(sb, new httpdFileHandler(sb), new httpdProxyHandler(sb));
serverCore server = new serverCore(port,
timeout /*control socket timeout in milliseconds*/,
true /* block attacks (wrong protocol) */,
protocolHandler /*command class*/,
sb,
30000 /*command max length incl. GET args*/);
server.setName("httpd:"+port);
server.setPriority(Thread.MAX_PRIORITY);
if (server == null) {
serverLog.logFailure("STARTUP", "Failed to start server. Probably port " + port + " already in use.");
} else {
// first start the server
sb.deployThread("10_httpd", "HTTPD Server/Proxy", "the HTTPD, used as web server and proxy", null, server, 0, 0, 0, 0);
//server.start();
// open the browser window
boolean browserPopUpTrigger = sb.getConfig("browserPopUpTrigger", "true").equals("true");
if (browserPopUpTrigger) {
String browserPopUpPage = sb.getConfig("browserPopUpPage", "Status.html");
String browserPopUpApplication = sb.getConfig("browserPopUpApplication", "netscape");
serverSystem.openBrowser("http://localhost:" + port + "/" + browserPopUpPage, browserPopUpApplication);
}
//Copy the shipped locales into DATA
File localesPath = new File(sb.getRootPath(), sb.getConfig("localesPath", "DATA/LOCALE"));
File defaultLocalesPath = new File(sb.getRootPath(), "locales");
try{
File[] defaultLocales = defaultLocalesPath.listFiles();
localesPath.mkdirs();
for(int i=0;i < defaultLocales.length; i++){
if(defaultLocales[i].getName().endsWith(".lng"))
serverFileUtils.copy(defaultLocales[i], new File(localesPath, defaultLocales[i].getName()));
}
serverLog.logInfo("STARTUP", "Copied the default lokales to DATA/LOCALE");
}catch(NullPointerException e){
serverLog.logError("STARTUP", "Nullpointer Exception while copying the default Locales");
}
//regenerate Locales from Translationlist, if needed
String lang = sb.getConfig("htLocaleSelection", "");
if(! lang.equals("") && ! lang.equals("default") ){ //locale is used
String currentRev = "";
try{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File( sb.getConfig("htRootPath", "htroot"), "locale/"+lang+"/version" ))));
currentRev = br.readLine();
br.close();
}catch(IOException e){
//Error
}
try{ //seperate try, because we want this, even when the File "version2 does not exist.
if(! currentRev.equals(sb.getConfig("svnRevision", "")) ){ //is this another version?!
File sourceDir = new File(sb.getConfig("htRootPath", "htroot"));
File destDir = new File(sourceDir, "locale/"+lang);
if(translator.translateFiles(sourceDir, destDir, new File("DATA/LOCALE/"+lang+".lng"), "html")){ //translate it
//write the new Versionnumber
BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(new File(destDir, "version"))));
bw.write(sb.getConfig("svnRevision", "Error getting Version"));
bw.close();
}
}
}catch(IOException e){
//Error
}
}
// registering shutdown hook
serverLog.logSystem("STARTUP", "Registering Shutdown Hook");
Runtime run = Runtime.getRuntime();
run.addShutdownHook(new shutdownHookThread(Thread.currentThread(), sb));
// wait for server shutdown
try {
sb.waitForShutdown();
} catch (Exception e) {
serverLog.logError("MAIN CONTROL LOOP", "PANIK: " + e.getMessage(),e);
}
// shut down
serverLog.logSystem("SHUTDOWN", "caught termination signal");
server.terminate(false);
server.interrupt();
if (server.isAlive()) try {
httpc.wget(new URL("http://localhost:" + port), 1000, null, null, null, 0); // kick server
serverLog.logSystem("SHUTDOWN", "sent termination signal to server socket");
} catch (IOException ee) {
serverLog.logSystem("SHUTDOWN", "termination signal to server socket missed (server shutdown, ok)");
}
// idle until the processes are down
while (server.isAlive()) {
Thread.currentThread().sleep(2000); // wait a while
}
serverLog.logSystem("SHUTDOWN", "server has terminated");
sb.close();
}
} catch (Exception e) {
serverLog.logError("STARTUP", "Unexpected Error: " + e.getClass().getName(),e);
//System.exit(1);
}
} catch (Exception ee) {
serverLog.logFailure("STARTUP", "FATAL ERROR: " + ee.getMessage(),ee);
ee.printStackTrace();
}
serverLog.logSystem("SHUTDOWN", "goodbye. (this is the last line)");
try {
System.exit(0);
} catch (Exception e) {} // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790)
}
| private static void startup(String homePath) {
long startup = yacyCore.universalTime();
try {
// start up
System.out.println(copyright);
System.out.println(hline);
// check java version
try {
String[] check = "a,b".split(","); // split needs java 1.4
} catch (NoSuchMethodError e) {
System.err.println("STARTUP: Java Version too low. You need at least Java 1.4.2 to run YACY");
Thread.currentThread().sleep(3000);
System.exit(-1);
}
// setting up logging
try {
serverLog.configureLogging(new File(homePath, "yacy.logging"));
} catch (IOException e) {
System.out.println("could not find logging properties in homePath=" + homePath);
e.printStackTrace();
}
serverLog.logSystem("STARTUP", copyright);
serverLog.logSystem("STARTUP", hline);
serverLog.logSystem("STARTUP", "java version " + System.getProperty("java.version", "no-java-version"));
serverLog.logSystem("STARTUP", "Application Root Path: " + homePath.toString());
// create data folder
File dataFolder = new File(homePath, "DATA");
if (!(dataFolder.exists())) dataFolder.mkdir();
plasmaSwitchboard sb = new plasmaSwitchboard(homePath, "yacy.init", "DATA/SETTINGS/httpProxy.conf");
// hardcoded, forced, temporary value-migration
sb.setConfig("htTemplatePath", "htroot/env/templates");
sb.setConfig("parseableExt", "html,htm,txt,php,shtml,asp");
// if we are running an SVN version, we try to detect the used svn revision now ...
Properties buildProp = new Properties();
File buildPropFile = null;
try {
buildPropFile = new File(homePath,"build.properties");
buildProp.load(new FileInputStream(buildPropFile));
} catch (Exception e) {
System.err.println("ERROR: " + buildPropFile.toString() + " not found in settings path");
}
try {
if (buildProp.containsKey("releaseNr")) {
// this normally looks like this: $Revision: 181 $
String svnReleaseNrStr = buildProp.getProperty("releaseNr");
Pattern pattern = Pattern.compile("\\$Revision:\\s(.*)\\s\\$",Pattern.DOTALL+Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(svnReleaseNrStr);
if (matcher.find()) {
String svrReleaseNr = matcher.group(1);
try {
try {version = Float.parseFloat(vString);} catch (NumberFormatException e) {version = (float) 0.1;}
version = versvn2combinedVersion(version, Integer.parseInt(svrReleaseNr));
} catch (NumberFormatException e) {}
sb.setConfig("svnRevision", svrReleaseNr);
}
}
} catch (Exception e) {
System.err.println("Unable to determine the currently used SVN revision number.");
}
sb.setConfig("version", Float.toString(version));
sb.setConfig("vdate", vDATE);
sb.setConfig("applicationRoot", homePath);
sb.setConfig("startupTime", Long.toString(startup));
serverLog.logSystem("STARTUP", "YACY Version: " + version + ", Built " + vDATE);
yacyCore.latestVersion = (float) version;
// read environment
//new
int port = Integer.parseInt(sb.getConfig("port", "8080"));
int timeout = Integer.parseInt(sb.getConfig("httpdTimeout", "60000"));
if (timeout < 60000) timeout = 60000;
// create some directories
File htRootPath = new File(sb.getRootPath(), sb.getConfig("htRootPath", "htroot"));
File htDocsPath = new File(sb.getRootPath(), sb.getConfig("htDocsPath", "DATA/HTDOCS"));
File htTemplatePath = new File(sb.getRootPath(), sb.getConfig("htTemplatePath","htdocs"));
// create default notifier picture
if (!((new File(htRootPath, "env/grafics/notifier.gif")).exists())) try {
serverFileUtils.copy(new File(htRootPath, "env/grafics/empty.gif"),
new File(htRootPath, "env/grafics/notifier.gif"));
} catch (IOException e) {}
if (!(htDocsPath.exists())) htDocsPath.mkdir();
File htdocsDefaultReadme = new File(htDocsPath, "readme.txt");
if (!(htdocsDefaultReadme.exists())) try {serverFileUtils.write((
"This is your root directory for individual Web Content\r\n" +
"\r\n" +
"Please place your html files into the www subdirectory.\r\n" +
"The URL of that path is either\r\n" +
"http://www.<your-peer-name>.yacy or\r\n" +
"http://<your-ip>:<your-port>/www\r\n" +
"\r\n" +
"Other subdirectories may be created; they map to corresponding sub-domains.\r\n" +
"This directory shares it's content with the applications htroot path, so you\r\n" +
"may access your yacy search page with\r\n" +
"http://<your-peer-name>.yacy/\r\n" +
"\r\n").getBytes(), htdocsDefaultReadme);} catch (IOException e) {
System.out.println("Error creating htdocs readme: " + e.getMessage());
}
File wwwDefaultPath = new File(htDocsPath, "www");
if (!(wwwDefaultPath.exists())) wwwDefaultPath.mkdir();
File wwwDefaultClass = new File(wwwDefaultPath, "welcome.class");
//if ((!(wwwDefaultClass.exists())) || (wwwDefaultClass.length() != (new File(htRootPath, "htdocsdefault/welcome.class")).length())) try {
if((new File(htRootPath, "htdocsdefault/welcome.java")).exists())
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/welcome.java"), new File(wwwDefaultPath, "welcome.java"));
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/welcome.class"), wwwDefaultClass);
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/welcome.html"), new File(wwwDefaultPath, "welcome.html"));
//} catch (IOException e) {}
File shareDefaultPath = new File(htDocsPath, "share");
if (!(shareDefaultPath.exists())) shareDefaultPath.mkdir();
File shareDefaultClass = new File(shareDefaultPath, "dir.class");
//if ((!(shareDefaultClass.exists())) || (shareDefaultClass.length() != (new File(htRootPath, "htdocsdefault/dir.class")).length())) try {
if((new File(htRootPath, "htdocsdefault/dir.java")).exists())
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/dir.java"), new File(shareDefaultPath, "dir.java"));
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/dir.class"), shareDefaultClass);
serverFileUtils.copy(new File(htRootPath, "htdocsdefault/dir.html"), new File(shareDefaultPath, "dir.html"));
//} catch (IOException e) {}
// set preset accounts/passwords
String acc;
if ((acc = sb.getConfig("proxyAccount", "")).length() > 0) {
sb.setConfig("proxyAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(serverCodings.standardCoder.encodeBase64String(acc)));
sb.setConfig("proxyAccount", "");
}
if ((acc = sb.getConfig("serverAccount", "")).length() > 0) {
sb.setConfig("serverAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(serverCodings.standardCoder.encodeBase64String(acc)));
sb.setConfig("serverAccount", "");
}
if ((acc = sb.getConfig("adminAccount", "")).length() > 0) {
sb.setConfig("adminAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(serverCodings.standardCoder.encodeBase64String(acc)));
sb.setConfig("adminAccount", "");
}
// fix unsafe old passwords
if ((acc = sb.getConfig("proxyAccountBase64", "")).length() > 0) {
sb.setConfig("proxyAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("proxyAccountBase64", "");
}
if ((acc = sb.getConfig("serverAccountBase64", "")).length() > 0) {
sb.setConfig("serverAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("serverAccountBase64", "");
}
if ((acc = sb.getConfig("adminAccountBase64", "")).length() > 0) {
sb.setConfig("adminAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("adminAccountBase64", "");
}
if ((acc = sb.getConfig("uploadAccountBase64", "")).length() > 0) {
sb.setConfig("uploadAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("uploadAccountBase64", "");
}
if ((acc = sb.getConfig("downloadAccountBase64", "")).length() > 0) {
sb.setConfig("downloadAccountBase64MD5", serverCodings.standardCoder.encodeMD5Hex(acc));
sb.setConfig("downloadAccountBase64", "");
}
// start main threads
try {
httpd protocolHandler = new httpd(sb, new httpdFileHandler(sb), new httpdProxyHandler(sb));
serverCore server = new serverCore(port,
timeout /*control socket timeout in milliseconds*/,
true /* block attacks (wrong protocol) */,
protocolHandler /*command class*/,
sb,
30000 /*command max length incl. GET args*/);
server.setName("httpd:"+port);
server.setPriority(Thread.MAX_PRIORITY);
if (server == null) {
serverLog.logFailure("STARTUP", "Failed to start server. Probably port " + port + " already in use.");
} else {
// first start the server
sb.deployThread("10_httpd", "HTTPD Server/Proxy", "the HTTPD, used as web server and proxy", null, server, 0, 0, 0, 0);
//server.start();
// open the browser window
boolean browserPopUpTrigger = sb.getConfig("browserPopUpTrigger", "true").equals("true");
if (browserPopUpTrigger) {
String browserPopUpPage = sb.getConfig("browserPopUpPage", "Status.html");
String browserPopUpApplication = sb.getConfig("browserPopUpApplication", "netscape");
serverSystem.openBrowser("http://localhost:" + port + "/" + browserPopUpPage, browserPopUpApplication);
}
//Copy the shipped locales into DATA
File localesPath = new File(sb.getRootPath(), sb.getConfig("localesPath", "DATA/LOCALE"));
File defaultLocalesPath = new File(sb.getRootPath(), "locales");
try{
File[] defaultLocales = defaultLocalesPath.listFiles();
localesPath.mkdirs();
for(int i=0;i < defaultLocales.length; i++){
if(defaultLocales[i].getName().endsWith(".lng"))
serverFileUtils.copy(defaultLocales[i], new File(localesPath, defaultLocales[i].getName()));
}
serverLog.logInfo("STARTUP", "Copied the default lokales to DATA/LOCALE");
}catch(NullPointerException e){
serverLog.logError("STARTUP", "Nullpointer Exception while copying the default Locales");
}
//regenerate Locales from Translationlist, if needed
String lang = sb.getConfig("htLocaleSelection", "");
if(! lang.equals("") && ! lang.equals("default") ){ //locale is used
String currentRev = "";
try{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File( sb.getConfig("htRootPath", "htroot"), "locale/"+lang+"/version" ))));
currentRev = br.readLine();
br.close();
}catch(IOException e){
//Error
}
try{ //seperate try, because we want this, even when the File "version2 does not exist.
if(! currentRev.equals(sb.getConfig("svnRevision", "")) ){ //is this another version?!
File sourceDir = new File(sb.getConfig("htRootPath", "htroot"));
File destDir = new File(sourceDir, "locale/"+lang);
if(translator.translateFiles(sourceDir, destDir, new File("DATA/LOCALE/"+lang+".lng"), "html")){ //translate it
//write the new Versionnumber
BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(new File(destDir, "version"))));
bw.write(sb.getConfig("svnRevision", "Error getting Version"));
bw.close();
}
}
}catch(IOException e){
//Error
}
}
// registering shutdown hook
serverLog.logSystem("STARTUP", "Registering Shutdown Hook");
Runtime run = Runtime.getRuntime();
run.addShutdownHook(new shutdownHookThread(Thread.currentThread(), sb));
// wait for server shutdown
try {
sb.waitForShutdown();
} catch (Exception e) {
serverLog.logError("MAIN CONTROL LOOP", "PANIK: " + e.getMessage(),e);
}
// shut down
serverLog.logSystem("SHUTDOWN", "caught termination signal");
server.terminate(false);
server.interrupt();
if (server.isAlive()) try {
httpc.wget(new URL("http://localhost:" + port), 1000, null, null, null, 0); // kick server
serverLog.logSystem("SHUTDOWN", "sent termination signal to server socket");
} catch (IOException ee) {
serverLog.logSystem("SHUTDOWN", "termination signal to server socket missed (server shutdown, ok)");
}
// idle until the processes are down
while (server.isAlive()) {
Thread.currentThread().sleep(2000); // wait a while
}
serverLog.logSystem("SHUTDOWN", "server has terminated");
sb.close();
}
} catch (Exception e) {
serverLog.logError("STARTUP", "Unexpected Error: " + e.getClass().getName(),e);
//System.exit(1);
}
} catch (Exception ee) {
serverLog.logFailure("STARTUP", "FATAL ERROR: " + ee.getMessage(),ee);
ee.printStackTrace();
}
serverLog.logSystem("SHUTDOWN", "goodbye. (this is the last line)");
try {
System.exit(0);
} catch (Exception e) {} // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790)
}
|
diff --git a/PacDefence/src/towers/AbstractTower.java b/PacDefence/src/towers/AbstractTower.java
index a222daf..b63648f 100644
--- a/PacDefence/src/towers/AbstractTower.java
+++ b/PacDefence/src/towers/AbstractTower.java
@@ -1,703 +1,703 @@
/*
* This file is part of Pac Defence.
*
* Pac Defence 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.
*
* Pac Defence 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 Pac Defence. If not, see <http://www.gnu.org/licenses/>.
*
* (C) Liam Byrne, 2008.
*/
package towers;
import images.ImageHelper;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import logic.Circle;
import logic.Formulae;
import logic.Game;
import logic.Helper;
import sprites.LooseFloat;
import sprites.Sprite;
public abstract class AbstractTower implements Tower {
public static final float shadowAmount = 0.75F;
protected static final float upgradeIncreaseFactor = 1.05F;
// Keep track of the loaded images so they are only loaded once
private static final Map<String, BufferedImage> towerImages =
new HashMap<String, BufferedImage>();
private static final Map<String, BufferedImage> rotatingImages =
new HashMap<String, BufferedImage>();
private static final Map<String, BufferedImage> towerButtonImages =
new HashMap<String, BufferedImage>();
private static final Map<Class<? extends AbstractTower>, Map<LooseFloat, BufferedImage>>
rotatedImages = new HashMap<Class<? extends AbstractTower>, Map<LooseFloat,
BufferedImage>>();
public static final int turretThickness = 4;
// Maps the ID of an aid tower to the aid factor it gives for each attribute
private final Map<Integer, Map<Attribute, Double>> aidFactors =
new HashMap<Integer, Map<Attribute, Double>>();
private final Map<Attribute, Double> currentFactors = createCurrentFactors();
private Map<Attribute, Integer> attributeLevels = createAttributeLevels();
// The top left point of this tower
private final Point topLeft;
// The centre of this tower
private final Point centre;
private final Circle bounds;
private final Rectangle boundingRectangle = new Rectangle();
private final String name;
// The number of clock ticks between each shot
private double fireRate;
// The number of clock ticks until this tower's next shot
private double timeToNextShot = 0;
private double range;
private final double rangeUpgrade;
private int twiceRange;
private double bulletSpeed;
private final double bulletSpeedUpgrade;
private double damage;
// The width/height of the image (as it's square)
private final int width;
private final int halfWidth;
// The width of the turret from the centre of the tower
private final int turretWidth;
private final BufferedImage baseImage;
private final BufferedImage rotatingImage;
private final boolean imageRotates;
private BufferedImage currentImage;
private final BufferedImage buttonImage;
private final Rectangle2D pathBounds;
private boolean isSelected = false;
private List<DamageNotifier> damageNotifiers = new ArrayList<DamageNotifier>();
private long damageDealt = 0;
private double fractionalDamageDealt = 0;
private int kills = 0;
private int killsLevel = 1;
private int damageDealtLevel = 1;
private long nextUpgradeDamage = Formulae.nextUpgradeDamage(killsLevel);
private int nextUpgradeKills = Formulae.nextUpgradeKills(damageDealtLevel);
private Comparator<Sprite> spriteComparator = new Sprite.FirstComparator();
private List<Bullet> bulletsToAdd = new ArrayList<Bullet>();
protected AbstractTower(Point p, Rectangle2D pathBounds, String name, int fireRate,
double range, double bulletSpeed, double damage, int width, int turretWidth,
boolean hasOverlay) {
// TODO make images all dependant on the name of the tower
centre = new Point(p);
this.pathBounds = pathBounds;
// Only temporary, it gets actually set later
topLeft = new Point(0, 0);
this.name = name;
this.fireRate = fireRate;
this.range = range;
rangeUpgrade = range * (upgradeIncreaseFactor - 1);
twiceRange = (int)(range * 2);
this.bulletSpeed = bulletSpeed;
bulletSpeedUpgrade = bulletSpeed * (upgradeIncreaseFactor - 1);
this.damage = damage;
this.width = width;
halfWidth = width / 2;
this.turretWidth = turretWidth;
bounds = new Circle(centre, halfWidth);
setTopLeft();
setBounds();
// Use the class name as the actual name could be anything (spaces, etc.)
String className = getClass().getSimpleName();
// Need to remove the 'Tower' off the end
className = className.substring(0, className.length() - 5);
String nameLowerCase = makeFirstCharacterLowerCase(className);
- baseImage = loadImage(towerButtonImages, width, "towers", nameLowerCase + ".png");
+ baseImage = loadImage(towerImages, width, "towers", nameLowerCase + ".png");
imageRotates = (hasOverlay && turretWidth != 0);
if(hasOverlay) {
rotatingImage = loadImage(rotatingImages, width, "towers", "overlays",
className + "Overlay.png");
} else {
rotatingImage = null;
}
currentImage = drawCurrentImage(rotatingImage);
buttonImage = loadImage(towerButtonImages, 0, "buttons", "towers",
className + "Tower.png");
}
private String makeFirstCharacterLowerCase(String s) {
StringBuilder sb = new StringBuilder(s);
sb.insert(0, Character.toLowerCase(sb.charAt(0)));
sb.deleteCharAt(1);
return sb.toString();
}
@Override
public List<Bullet> tick(List<Sprite> sprites) {
sprites = new ArrayList<Sprite>(sprites);
Collections.sort(sprites, spriteComparator);
// Decrements here so it's on every tick, not just when it is able to shoot
timeToNextShot--;
List<Bullet> fired = Collections.emptyList();
if(imageRotates || timeToNextShot <= 0) {
// If the image rotates, this needs to be done to find out the direction
// to rotate to
fired = fireBullets(sprites);
}
if (timeToNextShot <= 0 && fired.size() > 0) {
timeToNextShot = fireRate;
bulletsToAdd.addAll(fired);
}
List<Bullet> bullets = bulletsToAdd;
bulletsToAdd = new ArrayList<Bullet>(bulletsToAdd.size());
return bullets;
}
@Override
public void draw(Graphics g) {
if (isSelected) {
drawRange(g);
}
g.drawImage(currentImage, (int) topLeft.getX(), (int) topLeft.getY(), null);
}
@Override
public void drawShadowAt(Graphics g, Point p) {
Graphics2D g2D = (Graphics2D) g;
drawRange(g2D, p);
// Save the current composite to reset back to later
Composite c = g2D.getComposite();
// Makes it so what is drawn is partly transparent
g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, shadowAmount));
g2D.drawImage(currentImage, (int) p.getX() - halfWidth, (int) p.getY() - halfWidth, width,
width, null);
g2D.setComposite(c);
}
@Override
public boolean doesTowerClashWith(Tower t) {
Shape s = t.getBounds();
if (s instanceof Circle) {
Circle c = (Circle) s;
double distance = Point.distance(centre.getX(), centre.getY(), t.getCentre().getX(), t
.getCentre().getY());
return distance < bounds.getRadius() + c.getRadius();
} else {
return bounds.intersects(s.getBounds2D());
}
}
@Override
public boolean canTowerBeBuilt(List<Polygon> path) {
for(Polygon p : path) {
if(bounds.intersects(p)) {
return false;
}
}
return true;
}
@Override
public boolean contains(Point p) {
if (boundingRectangle.contains(p)) {
int x = (int) (p.getX() - centre.getX() + halfWidth);
int y = (int) (p.getY() - centre.getY() + halfWidth);
// RGB of zero means a completely alpha i.e. transparent pixel
return currentImage.getRGB(x, y) != 0;
}
return false;
}
@Override
public Shape getBounds() {
return bounds;
}
@Override
public String getName() {
return name + " Tower";
}
@Override
public Point getCentre() {
return centre;
}
@Override
public int getAttributeLevel(Attribute a) {
return attributeLevels.get(a);
}
@Override
public void raiseAttributeLevel(Attribute a, boolean boughtUpgrade) {
if(boughtUpgrade) {
attributeLevels.put(a, attributeLevels.get(a) + 1);
}
switch(a) {
case Damage:
upgradeDamage();
break;
case Range:
upgradeRange();
break;
case Rate:
upgradeFireRate();
break;
case Speed:
upgradeBulletSpeed();
break;
case Special:
upgradeSpecial();
break;
default:
throw new RuntimeException("New Attribute has been added or something.");
}
}
@Override
public void aidAttribute(Attribute a, double factor, int towerID) {
assert a != Attribute.Special : "Special cannot be aided";
double currentFactor = currentFactors.get(a);
if(factor == 1) { // This signals that this aid tower has been sold
aidFactors.remove(towerID);
// Find the best factor from the remaining factors
for(Map<Attribute, Double> m : aidFactors.values()) {
double d = m.get(a);
if(d > factor) {
factor = d;
}
}
// and if it isn't the current factor, make it so, as the current factor
// would've been removed.
if(factor != currentFactor) {
multiplyAttribute(a, factor / currentFactor);
currentFactors.put(a, factor);
}
} else {
if(!aidFactors.containsKey(towerID)) {
aidFactors.put(towerID, new EnumMap<Attribute, Double>(Attribute.class));
}
aidFactors.get(towerID).put(a, factor);
// This limits it to one aid tower's upgrade (the best one)
if(factor > currentFactor) {
// This applies the new upgrade and cancels out the last one
multiplyAttribute(a, factor / currentFactor);
currentFactors.put(a, factor);
}
}
}
@Override
public String getStat(Attribute a) {
switch(a) {
case Damage:
return Helper.format(damage, 2);
case Range:
return Helper.format(range, 0);
case Rate:
return Helper.format(fireRate / Game.CLOCK_TICKS_PER_SECOND, 2) + "s";
case Speed:
return Helper.format(bulletSpeed, 2);
case Special:
return getSpecial();
}
throw new RuntimeException("Invalid attribute: " + a + " given.");
}
@Override
public String getStatName(Attribute a) {
switch(a) {
case Special:
return getSpecialName();
case Rate:
return "Shoots Every";
default:
return a.toString();
}
}
@Override
public void select(boolean select) {
isSelected = select;
}
@Override
public Tower constructNew(Point p, Rectangle2D pathBounds) {
try {
Constructor<? extends Tower> c = this.getClass().getConstructor(Point.class,
Rectangle2D.class);
return c.newInstance(p, pathBounds);
} catch(Exception e) {
// No exception should be thrown if the superclass is reasonably behaved
throw new RuntimeException("\nSuperclass of AbstractTower is not well behaved.\n" + e +
" was thrown.\n Either fix this, or override constructNew()");
}
}
@Override
public void addDamageNotifier(DamageNotifier d) {
damageNotifiers.add(d);
}
@Override
public synchronized void increaseDamageDealt(double damage) {
assert damage > 0 : "Damage given was negative or zero.";
for(DamageNotifier d : damageNotifiers) {
d.notifyOfDamage(damage);
}
long longDamage = (long)damage;
damageDealt += longDamage;
// Handling of fractional amounts
fractionalDamageDealt += damage - longDamage;
if(fractionalDamageDealt > 1) {
longDamage = (long)fractionalDamageDealt;
damageDealt += longDamage;
fractionalDamageDealt -= longDamage;
}
if(damageDealt >= nextUpgradeDamage) {
damageDealtLevel++;
nextUpgradeDamage = Formulae.nextUpgradeDamage(damageDealtLevel);
upgradeAllStats();
}
}
@Override
public synchronized void increaseKills(int kills) {
assert kills > 0 : "Kills given was less than or equal to zero";
for(DamageNotifier d : damageNotifiers) {
d.notifyOfKills(kills);
}
this.kills += kills;
if (this.kills >= nextUpgradeKills) {
killsLevel++;
nextUpgradeKills = Formulae.nextUpgradeKills(killsLevel);
upgradeAllStats();
}
}
@Override
public long getDamageDealt() {
return damageDealt;
}
@Override
public long getDamageDealtForUpgrade() {
return nextUpgradeDamage;
}
@Override
public int getKills() {
return kills;
}
@Override
public int getKillsForUpgrade() {
return nextUpgradeKills;
}
@Override
public BufferedImage getButtonImage() {
return buttonImage;
}
@Override
public int getExperienceLevel() {
// -1 so it starts at level 1
return killsLevel + damageDealtLevel - 1;
}
@Override
public void setSpriteComparator(Comparator<Sprite> c) {
spriteComparator = c;
}
@Override
public Comparator<Sprite> getSpriteComparator() {
return spriteComparator;
}
protected double getFireRate() {
return fireRate;
}
protected double getRange() {
return range;
}
protected double getBulletSpeed() {
return bulletSpeed;
}
protected double getDamage() {
return damage;
}
protected double getTimeToNextShot() {
return timeToNextShot;
}
protected abstract String getSpecial();
protected abstract String getSpecialName();
protected abstract Bullet makeBullet(double dx, double dy, int turretWidth, int range,
double speed, double damage, Point p, Sprite s, Rectangle2D pathBounds);
protected List<Bullet> makeBullets(double dx, double dy, int turretWidth, int range,
double speed, double damage, Point p, Sprite s, Rectangle2D pathBounds) {
return Helper.makeListContaining(makeBullet(dx, dy, turretWidth, range, speed,
damage, p, s, pathBounds));
}
protected List<Bullet> fireBullets(List<Sprite> sprites) {
for (Sprite s : sprites) {
// Checking that the pathBounds contains the sprites position means a tower won't
// shoot so that it's bullet almost immediately goes off screen and is wasted
if (pathBounds.contains(s.getPosition()) && checkDistance(s)) {
return fireBulletsAt(s, true);
}
}
return Collections.emptyList();
}
protected boolean checkDistance(Sprite s) {
return checkDistance(s, centre, range);
}
/**
* Checks if the distance from the sprite to a point is less than the range.
* @param s
* @param p
* @param range
* @return
*/
protected boolean checkDistance(Sprite s, Point p, double range) {
if (!s.isAlive()) {
return false;
}
double distance = p.distance(s.getPosition());
return distance < range + s.getHalfWidth();
}
protected List<Bullet> fireBulletsAt(Sprite s, boolean rotateTurret) {
return fireBulletsAt(s, centre, rotateTurret, turretWidth, range, bulletSpeed, damage);
}
protected List<Bullet> fireBulletsAt(Sprite s, Point p, boolean rotateTurret,
int turretWidth, double range, double bulletSpeed, double damage) {
double dx = s.getPosition().getX() - p.getX();
double dy = s.getPosition().getY() - p.getY();
if(imageRotates && rotateTurret) {
currentImage = drawCurrentImage(rotateImage(ImageHelper.vectorAngle(dx, -dy)));
}
return makeBullets(dx, dy, turretWidth, (int)range, bulletSpeed, damage, p, s, pathBounds);
}
protected void upgradeDamage() {
damage *= upgradeIncreaseFactor;
}
protected void upgradeRange() {
range += currentFactors.get(Attribute.Range) * rangeUpgrade;
twiceRange = (int)(range * 2);
}
protected void upgradeFireRate() {
fireRate /= upgradeIncreaseFactor;
}
protected void upgradeBulletSpeed() {
bulletSpeed += currentFactors.get(Attribute.Speed) * bulletSpeedUpgrade;
}
protected abstract void upgradeSpecial();
protected void addExtraBullets(Bullet... bullets) {
bulletsToAdd.addAll(Arrays.asList(bullets));
}
private BufferedImage loadImage(Map<String, BufferedImage> map, int width,
String... imagePath) {
String imageName = imagePath[imagePath.length - 1];
if(!map.containsKey(imageName)) {
if(width == 0) {
map.put(imageName, ImageHelper.makeImage(imagePath));
} else {
map.put(imageName, ImageHelper.makeImage(width, width, imagePath));
}
}
return map.get(imageName);
}
private BufferedImage drawCurrentImage(BufferedImage rotatingOverlay) {
BufferedImage image = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D g = image.createGraphics();
g.drawImage(baseImage, 0, 0, null);
g.drawImage(rotatingOverlay, 0, 0, null);
return image;
}
private void upgradeAllStats() {
upgradeDamage();
upgradeRange();
upgradeFireRate();
upgradeBulletSpeed();
upgradeSpecial();
}
private void drawRange(Graphics g) {
drawRange(g, centre);
}
private void drawRange(Graphics g, Point p) {
int topLeftRangeX = (int)(p.getX() - range);
int topLeftRangeY = (int)(p.getY() - range);
Graphics2D g2D = (Graphics2D) g;
Composite c = g2D.getComposite();
g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5F));
g2D.setColor(Color.WHITE);
g2D.fillOval(topLeftRangeX, topLeftRangeY, twiceRange, twiceRange);
g2D.setComposite(c);
g2D.setColor(Color.BLACK);
g2D.drawOval(topLeftRangeX, topLeftRangeY, twiceRange, twiceRange);
}
private void setTopLeft() {
topLeft.setLocation((int) centre.getX() - halfWidth, (int) centre.getY() - halfWidth);
}
private void setBounds() {
boundingRectangle.setBounds((int) topLeft.getX(), (int) topLeft.getY(), width, width);
bounds.setCentre(centre);
}
private void multiplyAttribute(Attribute a, double factor) {
assert a != Attribute.Special : "Special cannot be simply multiplied";
switch(a) {
case Damage:
damage *= factor;
return;
case Range:
range *= factor;
twiceRange = (int)(range * 2);
return;
case Rate:
fireRate /= factor;
return;
case Speed:
bulletSpeed *= factor;
return;
}
}
private Map<Attribute, Double> createCurrentFactors() {
Map<Attribute, Double> map = new EnumMap<Attribute, Double>(Attribute.class);
for(Attribute a : Attribute.values()) {
if(a != Attribute.Special) {
map.put(a, 1.0);
}
}
return map;
}
private BufferedImage rotateImage(double angle) {
if(!rotatedImages.containsKey(getClass())) {
// I use a TreeMap as otherwise I'd need to implement hashCode in LooseFloat
rotatedImages.put(getClass(), new TreeMap<LooseFloat, BufferedImage>());
}
Map<LooseFloat, BufferedImage> m = rotatedImages.get(getClass());
// Use LooseFloat to reduce precision so rotated images are less likely
// to be duplicated
LooseFloat f = new AbstractTowerLooseFloat(angle);
if(!m.containsKey(f)) {
m.put(f, ImageHelper.rotateImage(rotatingImage, angle));
}
return m.get(f);
}
private Map<Attribute, Integer> createAttributeLevels() {
Map<Attribute, Integer> map = new EnumMap<Attribute, Integer>(Attribute.class);
for(Attribute a : Attribute.values()) {
// All levels start at 1
map.put(a, 1);
}
return map;
}
private class AbstractTowerLooseFloat extends LooseFloat {
public AbstractTowerLooseFloat(float f) {
super(f);
}
public AbstractTowerLooseFloat(double d) {
super(d);
}
@Override
protected float getPrecision() {
return 0.012F;
}
}
private static BufferedImage createRotatingImage(int width, int turretWidth) {
assert turretWidth > 0 : "turretWidth must be > 0";
BufferedImage turretCentre = ImageHelper.makeImage("towers", "overlays", "turrets",
"turretCentre.png");
BufferedImage image = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D g = image.createGraphics();
g.drawImage(turretCentre, width/2 - turretThickness/2, width/2 - turretThickness/2, null);
g.setColor(Color.BLACK);
g.fillRect(width/2 - turretThickness/2, width/2 - turretWidth, turretThickness, turretWidth);
// TODO perhaps make the end of the turret a little prettier
return image;
}
public static void main(String... args) {
for(int i = 1; i <= 25; i++) {
ImageHelper.writePNG(createRotatingImage(50, i), "towers", "rotatingOverlays", "turrets",
"turret" + i + ".png");
}
}
}
| true | true | protected AbstractTower(Point p, Rectangle2D pathBounds, String name, int fireRate,
double range, double bulletSpeed, double damage, int width, int turretWidth,
boolean hasOverlay) {
// TODO make images all dependant on the name of the tower
centre = new Point(p);
this.pathBounds = pathBounds;
// Only temporary, it gets actually set later
topLeft = new Point(0, 0);
this.name = name;
this.fireRate = fireRate;
this.range = range;
rangeUpgrade = range * (upgradeIncreaseFactor - 1);
twiceRange = (int)(range * 2);
this.bulletSpeed = bulletSpeed;
bulletSpeedUpgrade = bulletSpeed * (upgradeIncreaseFactor - 1);
this.damage = damage;
this.width = width;
halfWidth = width / 2;
this.turretWidth = turretWidth;
bounds = new Circle(centre, halfWidth);
setTopLeft();
setBounds();
// Use the class name as the actual name could be anything (spaces, etc.)
String className = getClass().getSimpleName();
// Need to remove the 'Tower' off the end
className = className.substring(0, className.length() - 5);
String nameLowerCase = makeFirstCharacterLowerCase(className);
baseImage = loadImage(towerButtonImages, width, "towers", nameLowerCase + ".png");
imageRotates = (hasOverlay && turretWidth != 0);
if(hasOverlay) {
rotatingImage = loadImage(rotatingImages, width, "towers", "overlays",
className + "Overlay.png");
} else {
rotatingImage = null;
}
currentImage = drawCurrentImage(rotatingImage);
buttonImage = loadImage(towerButtonImages, 0, "buttons", "towers",
className + "Tower.png");
}
| protected AbstractTower(Point p, Rectangle2D pathBounds, String name, int fireRate,
double range, double bulletSpeed, double damage, int width, int turretWidth,
boolean hasOverlay) {
// TODO make images all dependant on the name of the tower
centre = new Point(p);
this.pathBounds = pathBounds;
// Only temporary, it gets actually set later
topLeft = new Point(0, 0);
this.name = name;
this.fireRate = fireRate;
this.range = range;
rangeUpgrade = range * (upgradeIncreaseFactor - 1);
twiceRange = (int)(range * 2);
this.bulletSpeed = bulletSpeed;
bulletSpeedUpgrade = bulletSpeed * (upgradeIncreaseFactor - 1);
this.damage = damage;
this.width = width;
halfWidth = width / 2;
this.turretWidth = turretWidth;
bounds = new Circle(centre, halfWidth);
setTopLeft();
setBounds();
// Use the class name as the actual name could be anything (spaces, etc.)
String className = getClass().getSimpleName();
// Need to remove the 'Tower' off the end
className = className.substring(0, className.length() - 5);
String nameLowerCase = makeFirstCharacterLowerCase(className);
baseImage = loadImage(towerImages, width, "towers", nameLowerCase + ".png");
imageRotates = (hasOverlay && turretWidth != 0);
if(hasOverlay) {
rotatingImage = loadImage(rotatingImages, width, "towers", "overlays",
className + "Overlay.png");
} else {
rotatingImage = null;
}
currentImage = drawCurrentImage(rotatingImage);
buttonImage = loadImage(towerButtonImages, 0, "buttons", "towers",
className + "Tower.png");
}
|
diff --git a/clients/opennaas-gui-vcpe/src/main/java/org/opennaas/gui/vcpe/controllers/SingleProviderController.java b/clients/opennaas-gui-vcpe/src/main/java/org/opennaas/gui/vcpe/controllers/SingleProviderController.java
index 2be607c9b..ac66b3bd5 100644
--- a/clients/opennaas-gui-vcpe/src/main/java/org/opennaas/gui/vcpe/controllers/SingleProviderController.java
+++ b/clients/opennaas-gui-vcpe/src/main/java/org/opennaas/gui/vcpe/controllers/SingleProviderController.java
@@ -1,250 +1,251 @@
package org.opennaas.gui.vcpe.controllers;
import java.util.Locale;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.opennaas.gui.vcpe.entities.SingleProviderLogical;
import org.opennaas.gui.vcpe.entities.SingleProviderPhysical;
import org.opennaas.gui.vcpe.services.rest.RestServiceException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author Jordi
*/
@Controller
public class SingleProviderController extends VCPENetworkController {
private static final Logger LOGGER = Logger.getLogger(SingleProviderController.class);
/**
* Redirect to the single provider physical view
*
* @param templateType
* @param model
* @param locale
* @return
*/
@Override
@RequestMapping(method = RequestMethod.GET, value = "/secure/noc/vcpeNetwork/singleProvider/physical")
public String getPhysicalForm(@RequestParam("templateType") String templateType, Model model, Locale locale) {
return super.getPhysicalForm(templateType, model, locale);
}
/**
* Redirect to the form to create a single provider VCPENetwork
*
* @param model
* @return
*/
@RequestMapping(method = RequestMethod.POST, value = "/secure/noc/vcpeNetwork/singleProvider/logical")
public String getLogicalForm(@ModelAttribute("physicalInfrastructure") SingleProviderPhysical physical, Model model, Locale locale) {
return super.getLogicalForm(physical, model, locale);
}
/**
* Create a single provider VCPE Network
*
* @param logical
* @param result
* @return
* @throws RestServiceException
*/
@RequestMapping(method = RequestMethod.POST, value = "/secure/noc/vcpeNetwork/singleProvider/create")
public String create(@Valid @ModelAttribute("logicalInfrastructure") SingleProviderLogical logical,
BindingResult result, Model model, Locale locale) throws RestServiceException {
return super.create(logical, result, model, locale);
}
/**
* Edit a single provider VCPE Network
*
* @param vcpeNetwork
* @param result
* @return
*/
@Override
@RequestMapping(method = RequestMethod.GET, value = "/secure/noc/vcpeNetwork/singleProvider/edit")
public String edit(String vcpeNetworkId, Model model, Locale locale) {
return super.edit(vcpeNetworkId, model, locale);
}
/**
* Update a single provider VCPE Network
*
* @param logical
* @param result
* @param model
* @param locale
* @return
* @throws RestServiceException
*/
@RequestMapping(method = RequestMethod.POST, value = "/secure/noc/vcpeNetwork/singleProvider/update")
public String update(@Valid @ModelAttribute("logicalInfrastructure") SingleProviderLogical logical,
BindingResult result, Model model, Locale locale) throws RestServiceException {
return super.update(logical, result, model, locale);
}
/**
* Delete a single provider VCPE Network
*
* @param vcpeNetworkId
* @param model
* @param locale
* @return
* @throws RestServiceException
*/
@Override
@RequestMapping(method = RequestMethod.GET, value = "/secure/noc/vcpeNetwork/singleProvider/delete")
public String delete(String vcpeNetworkId, Model model, Locale locale) throws RestServiceException {
return super.delete(vcpeNetworkId, model, locale);
}
/**
* Redirect to the form to modify the ip's. Client entry method
*
* @param vcpeNetworkId
* @param model
* @param locale
* @return
* @throws RestServiceException
*/
@RequestMapping(method = RequestMethod.GET, value = "/secure/vcpeNetwork/singleProvider/updateIpsForm")
public String updateIpsForm(String vcpeNetworkId, Model model, Locale locale) {
return updateIpsFormSecure(vcpeNetworkId, model, locale);
}
/**
* Redirect to the form to modify the ip's. Noc entry method
*
* @param vcpeNetworkId
* @param model
* @param locale
* @return
* @throws RestServiceException
*/
@RequestMapping(method = RequestMethod.GET, value = "/secure/noc/vcpeNetwork/singleProvider/updateIpsForm")
public String updateIpsFormSecure(String vcpeNetworkId, Model model, Locale locale) {
LOGGER.debug("updateIpsForm entity with id: " + vcpeNetworkId);
try {
model.addAttribute("vcpeNetworkList", vcpeNetworkBO.getAllVCPENetworks());
model.addAttribute("logicalInfrastructure", vcpeNetworkBO.getById(vcpeNetworkId));
} catch (RestServiceException e) {
model.addAttribute("errorMsg", messageSource
.getMessage("vcpenetwork.edit.message.error", null, locale));
}
return "updateIpsVCPENetwork";
}
/**
* Redirect to the form to modify the ip's
*
* @param logical
* @param model
* @param locale
* @return
* @throws RestServiceException
*/
@RequestMapping(method = RequestMethod.POST, value = "/secure/vcpeNetwork/singleProvider/updateIps")
public String updateIps(@ModelAttribute("logicalInfrastructure") SingleProviderLogical logical, Model model, Locale locale) {
return updateIpsSecure(logical, model, locale);
}
/**
* Redirect to the form to modify the ip's
*
* @param logical
* @param model
* @param locale
* @return
*/
@RequestMapping(method = RequestMethod.POST, value = "/secure/noc/vcpeNetwork/singleProvider/updateIps")
public String updateIpsSecure(@ModelAttribute("logicalInfrastructure") SingleProviderLogical logical, Model model, Locale locale) {
LOGGER.debug("update Ips of VCPENetwork: " + logical);
try {
model.addAttribute("vcpeNetworkList", vcpeNetworkBO.getAllVCPENetworks());
vcpeNetworkBO.updateIps(logical);
model.addAttribute("logicalInfrastructure", vcpeNetworkBO.getById(logical.getId()));
model.addAttribute("infoMsg", messageSource
.getMessage("vcpenetwork.updateIps.message.info", null, locale));
} catch (RestServiceException e) {
model.addAttribute("errorMsg", messageSource
.getMessage("vcpenetwork.updateIps.message.error", null, locale));
}
return "updateIpsVCPENetwork";
}
/**
* Method for the client user to update the VRRP Ip
*
* @param singleProviderLogical
* @param model
* @param locale
* @return
* @throws RestServiceException
*/
@RequestMapping(method = RequestMethod.POST, value = "/secure/vcpeNetwork/singleProvider/updateVRRPIp")
public String updateVRRPIpClient(@ModelAttribute("logicalInfrastructure") SingleProviderLogical logical,
Model model, Locale locale) {
return updateVRRPIp(logical, model, locale);
}
/**
* Modifiy the VRRP Ip
*
* @param singleProviderLogical
* @param model
* @param locale
* @return
* @throws RestServiceException
*/
@RequestMapping(method = RequestMethod.POST, value = "/secure/noc/vcpeNetwork/singleProvider/updateVRRPIp")
public String updateVRRPIp(@ModelAttribute("logicalInfrastructure") SingleProviderLogical logical,
Model model, Locale locale) {
LOGGER.debug("update VRRP ip of VCPENetwork: " + logical);
try {
+ model.addAttribute("action", "update");
model.addAttribute("vcpeNetworkList", vcpeNetworkBO.getAllVCPENetworks());
vcpeNetworkBO.updateVRRPIp(logical);
model.addAttribute("logicalInfrastructure", vcpeNetworkBO.getById(logical.getId()));
model.addAttribute("infoMsg", messageSource
.getMessage("vcpenetwork.updateVRRPIp.message.info", null, locale));
} catch (RestServiceException e) {
model.addAttribute("errorMsg", messageSource
.getMessage("vcpenetwork.updateVRRPIp.message.error", null, locale));
}
return "logicalForm";
}
/**
* Change the priority in VRRP
*
* @param singleProviderLogical
* @param model
* @param locale
* @return
*/
@RequestMapping(method = RequestMethod.POST, value = "/secure/noc/vcpeNetwork/singleProvider/changeVRRPPriority")
public String changeVRRPPriority(@ModelAttribute("logicalInfrastructure") SingleProviderLogical logical,
Model model, Locale locale) {
LOGGER.debug("change priority VRRP of VCPENetwork: " + logical);
try {
model.addAttribute("action", "update");
model.addAttribute("vcpeNetworkList", vcpeNetworkBO.getAllVCPENetworks());
model.addAttribute("logicalInfrastructure", vcpeNetworkBO.changeVRRPPriority(logical));
model.addAttribute("infoMsg", messageSource
.getMessage("vcpenetwork.changeVRRPPriority.message.info", null, locale));
} catch (RestServiceException e) {
model.addAttribute("errorMsg", messageSource
.getMessage("vcpenetwork.changeVRRPPriority.message.error", null, locale));
}
return "logicalForm";
}
}
| true | true | public String updateVRRPIp(@ModelAttribute("logicalInfrastructure") SingleProviderLogical logical,
Model model, Locale locale) {
LOGGER.debug("update VRRP ip of VCPENetwork: " + logical);
try {
model.addAttribute("vcpeNetworkList", vcpeNetworkBO.getAllVCPENetworks());
vcpeNetworkBO.updateVRRPIp(logical);
model.addAttribute("logicalInfrastructure", vcpeNetworkBO.getById(logical.getId()));
model.addAttribute("infoMsg", messageSource
.getMessage("vcpenetwork.updateVRRPIp.message.info", null, locale));
} catch (RestServiceException e) {
model.addAttribute("errorMsg", messageSource
.getMessage("vcpenetwork.updateVRRPIp.message.error", null, locale));
}
return "logicalForm";
}
| public String updateVRRPIp(@ModelAttribute("logicalInfrastructure") SingleProviderLogical logical,
Model model, Locale locale) {
LOGGER.debug("update VRRP ip of VCPENetwork: " + logical);
try {
model.addAttribute("action", "update");
model.addAttribute("vcpeNetworkList", vcpeNetworkBO.getAllVCPENetworks());
vcpeNetworkBO.updateVRRPIp(logical);
model.addAttribute("logicalInfrastructure", vcpeNetworkBO.getById(logical.getId()));
model.addAttribute("infoMsg", messageSource
.getMessage("vcpenetwork.updateVRRPIp.message.info", null, locale));
} catch (RestServiceException e) {
model.addAttribute("errorMsg", messageSource
.getMessage("vcpenetwork.updateVRRPIp.message.error", null, locale));
}
return "logicalForm";
}
|
diff --git a/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/control/login/LoginManager.java b/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/control/login/LoginManager.java
index 42498baf..f8c4ef01 100644
--- a/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/control/login/LoginManager.java
+++ b/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/control/login/LoginManager.java
@@ -1,187 +1,186 @@
package org.vpac.grisu.frontend.control.login;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.ssl.HttpSecureProtocol;
import org.apache.commons.ssl.TrustMaterial;
import org.globus.gsi.GlobusCredential;
import org.vpac.grisu.control.ServiceInterface;
import org.vpac.grisu.control.exceptions.ServiceInterfaceException;
import org.vpac.grisu.settings.Environment;
import org.vpac.grisu.utils.GrisuPluginFilenameFilter;
import org.vpac.security.light.control.CertificateFiles;
import au.org.arcs.jcommons.dependencies.ClasspathHacker;
import au.org.arcs.jcommons.dependencies.DependencyManager;
public class LoginManager {
/**
* One-for-all method to login to a Grisu backend.
*
* Specify nothing except the loginParams (without the myproxy username &
* password) in order to use a local proxy. If you specify the password in
* addition to that the local x509 cert will be used to create a local proxy
* which in turn will be used to login to the Grisu backend.
*
* If you specify the myproxy username & password in the login params those
* will be used for a simple myproxy login to the backend.
*
* In order to use shibboleth login, you need to specify the password, the
* idp-username and the name of the idp.
*
* @param password
* the password or null
* @param username
* the shib-username or null
* @param idp
* the name of the idp or null
* @param loginParams
* the login parameters
* @return the serviceinterface
* @throws LoginException
* if the login doesn't succeed
* @throws IOException
* if necessary plugins couldn't be downloaded/stored in the
* .grisu/plugins folder
*/
public static ServiceInterface login(GlobusCredential cred, char[] password, String username,
- String idp, LoginParams loginParams) throws LoginException,
- IOException {
+ String idp, LoginParams loginParams) throws LoginException {
try {
addPluginsToClasspath();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
throw new RuntimeException(e2);
}
try {
CertificateFiles.copyCACerts();
} catch (Exception e1) {
e1.printStackTrace();
}
// do the cacert thingy
try {
URL cacertURL = LoginManager.class.getResource("/ipsca.pem");
HttpSecureProtocol protocolSocketFactory = new HttpSecureProtocol();
TrustMaterial trustMaterial = null;
trustMaterial = new TrustMaterial(cacertURL);
// We can use setTrustMaterial() instead of addTrustMaterial()
// if we want to remove
// HttpSecureProtocol's default trust of TrustMaterial.CACERTS.
protocolSocketFactory.addTrustMaterial(trustMaterial);
// Maybe we want to turn off CN validation (not recommended!):
protocolSocketFactory.setCheckHostname(false);
Protocol protocol = new Protocol("https",
(ProtocolSocketFactory) protocolSocketFactory, 443);
Protocol.registerProtocol("https", protocol);
} catch (Exception e) {
e.printStackTrace();
}
DependencyManager.checkForDependency(
"org.bouncycastle.jce.provider.BouncyCastleProvider",
"http://www.bouncycastle.org/download/bcprov-jdk15-143.jar",
new File(Environment.getGrisuPluginDirectory(),
"bcprov-jdk15-143.jar"));
String serviceInterfaceUrl = loginParams.getServiceInterfaceUrl();
if ("Local".equals(serviceInterfaceUrl)
|| "Dummy".equals(serviceInterfaceUrl)) {
DependencyManager
.checkForDependency(
"org.vpac.grisu.control.serviceInterfaces.LocalServiceInterface",
"https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/backend/grisu-core/target/local-backend.jar",
new File(Environment.getGrisuPluginDirectory(),
"local-backend.jar"));
} else if (serviceInterfaceUrl.startsWith("http")) {
// assume xfire -- that needs to get smarter later on
DependencyManager
.checkForDependency(
"org.vpac.grisu.client.control.XFireServiceInterfaceCreator",
"https://code.arcs.org.au/hudson/job/Grisu-connectors-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend-modules/xfire-frontend/target/xfire-frontend.jar",
new File(Environment.getGrisuPluginDirectory(),
"xfire-frontend.jar"));
// also try to use client side mds
DependencyManager
.checkForDependency(
"org.vpac.grisu.frontend.info.clientsidemds.ClientSideGrisuRegistry",
"https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend/client-side-mds/target/client-side-mds.jar",
new File(Environment.getGrisuPluginDirectory(),
"client-side-mds.jar"));
}
if (StringUtils.isBlank(username)) {
if (StringUtils.isBlank(loginParams.getMyProxyUsername())) {
if ( cred != null ) {
try {
return LoginHelpers.globusCredentialLogin(loginParams, cred);
} catch (Exception e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
} else if (password == null || password.length == 0) {
// means certificate auth
try {
// means try to load local proxy
if ( loginParams == null ) {
return LoginHelpers.defaultLocalProxyLogin();
} else {
return LoginHelpers.defaultLocalProxyLogin(loginParams);
}
} catch (Exception e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
} else {
// means to create local proxy
try {
return LoginHelpers.localProxyLogin(password,
loginParams);
} catch (ServiceInterfaceException e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
}
} else {
// means myproxy login
try {
return LoginHelpers.myProxyLogin(loginParams);
} catch (ServiceInterfaceException e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
}
} else {
// means shib login
throw new RuntimeException("Shib login not supported yet...");
}
}
public static void addPluginsToClasspath() throws IOException {
ClasspathHacker.initFolder(new File(Environment
.getGrisuPluginDirectory()), new GrisuPluginFilenameFilter());
}
}
| true | true | public static ServiceInterface login(GlobusCredential cred, char[] password, String username,
String idp, LoginParams loginParams) throws LoginException,
IOException {
try {
addPluginsToClasspath();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
throw new RuntimeException(e2);
}
try {
CertificateFiles.copyCACerts();
} catch (Exception e1) {
e1.printStackTrace();
}
// do the cacert thingy
try {
URL cacertURL = LoginManager.class.getResource("/ipsca.pem");
HttpSecureProtocol protocolSocketFactory = new HttpSecureProtocol();
TrustMaterial trustMaterial = null;
trustMaterial = new TrustMaterial(cacertURL);
// We can use setTrustMaterial() instead of addTrustMaterial()
// if we want to remove
// HttpSecureProtocol's default trust of TrustMaterial.CACERTS.
protocolSocketFactory.addTrustMaterial(trustMaterial);
// Maybe we want to turn off CN validation (not recommended!):
protocolSocketFactory.setCheckHostname(false);
Protocol protocol = new Protocol("https",
(ProtocolSocketFactory) protocolSocketFactory, 443);
Protocol.registerProtocol("https", protocol);
} catch (Exception e) {
e.printStackTrace();
}
DependencyManager.checkForDependency(
"org.bouncycastle.jce.provider.BouncyCastleProvider",
"http://www.bouncycastle.org/download/bcprov-jdk15-143.jar",
new File(Environment.getGrisuPluginDirectory(),
"bcprov-jdk15-143.jar"));
String serviceInterfaceUrl = loginParams.getServiceInterfaceUrl();
if ("Local".equals(serviceInterfaceUrl)
|| "Dummy".equals(serviceInterfaceUrl)) {
DependencyManager
.checkForDependency(
"org.vpac.grisu.control.serviceInterfaces.LocalServiceInterface",
"https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/backend/grisu-core/target/local-backend.jar",
new File(Environment.getGrisuPluginDirectory(),
"local-backend.jar"));
} else if (serviceInterfaceUrl.startsWith("http")) {
// assume xfire -- that needs to get smarter later on
DependencyManager
.checkForDependency(
"org.vpac.grisu.client.control.XFireServiceInterfaceCreator",
"https://code.arcs.org.au/hudson/job/Grisu-connectors-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend-modules/xfire-frontend/target/xfire-frontend.jar",
new File(Environment.getGrisuPluginDirectory(),
"xfire-frontend.jar"));
// also try to use client side mds
DependencyManager
.checkForDependency(
"org.vpac.grisu.frontend.info.clientsidemds.ClientSideGrisuRegistry",
"https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend/client-side-mds/target/client-side-mds.jar",
new File(Environment.getGrisuPluginDirectory(),
"client-side-mds.jar"));
}
if (StringUtils.isBlank(username)) {
if (StringUtils.isBlank(loginParams.getMyProxyUsername())) {
if ( cred != null ) {
try {
return LoginHelpers.globusCredentialLogin(loginParams, cred);
} catch (Exception e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
} else if (password == null || password.length == 0) {
// means certificate auth
try {
// means try to load local proxy
if ( loginParams == null ) {
return LoginHelpers.defaultLocalProxyLogin();
} else {
return LoginHelpers.defaultLocalProxyLogin(loginParams);
}
} catch (Exception e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
} else {
// means to create local proxy
try {
return LoginHelpers.localProxyLogin(password,
loginParams);
} catch (ServiceInterfaceException e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
}
} else {
// means myproxy login
try {
return LoginHelpers.myProxyLogin(loginParams);
} catch (ServiceInterfaceException e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
}
} else {
// means shib login
throw new RuntimeException("Shib login not supported yet...");
}
}
| public static ServiceInterface login(GlobusCredential cred, char[] password, String username,
String idp, LoginParams loginParams) throws LoginException {
try {
addPluginsToClasspath();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
throw new RuntimeException(e2);
}
try {
CertificateFiles.copyCACerts();
} catch (Exception e1) {
e1.printStackTrace();
}
// do the cacert thingy
try {
URL cacertURL = LoginManager.class.getResource("/ipsca.pem");
HttpSecureProtocol protocolSocketFactory = new HttpSecureProtocol();
TrustMaterial trustMaterial = null;
trustMaterial = new TrustMaterial(cacertURL);
// We can use setTrustMaterial() instead of addTrustMaterial()
// if we want to remove
// HttpSecureProtocol's default trust of TrustMaterial.CACERTS.
protocolSocketFactory.addTrustMaterial(trustMaterial);
// Maybe we want to turn off CN validation (not recommended!):
protocolSocketFactory.setCheckHostname(false);
Protocol protocol = new Protocol("https",
(ProtocolSocketFactory) protocolSocketFactory, 443);
Protocol.registerProtocol("https", protocol);
} catch (Exception e) {
e.printStackTrace();
}
DependencyManager.checkForDependency(
"org.bouncycastle.jce.provider.BouncyCastleProvider",
"http://www.bouncycastle.org/download/bcprov-jdk15-143.jar",
new File(Environment.getGrisuPluginDirectory(),
"bcprov-jdk15-143.jar"));
String serviceInterfaceUrl = loginParams.getServiceInterfaceUrl();
if ("Local".equals(serviceInterfaceUrl)
|| "Dummy".equals(serviceInterfaceUrl)) {
DependencyManager
.checkForDependency(
"org.vpac.grisu.control.serviceInterfaces.LocalServiceInterface",
"https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/backend/grisu-core/target/local-backend.jar",
new File(Environment.getGrisuPluginDirectory(),
"local-backend.jar"));
} else if (serviceInterfaceUrl.startsWith("http")) {
// assume xfire -- that needs to get smarter later on
DependencyManager
.checkForDependency(
"org.vpac.grisu.client.control.XFireServiceInterfaceCreator",
"https://code.arcs.org.au/hudson/job/Grisu-connectors-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend-modules/xfire-frontend/target/xfire-frontend.jar",
new File(Environment.getGrisuPluginDirectory(),
"xfire-frontend.jar"));
// also try to use client side mds
DependencyManager
.checkForDependency(
"org.vpac.grisu.frontend.info.clientsidemds.ClientSideGrisuRegistry",
"https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend/client-side-mds/target/client-side-mds.jar",
new File(Environment.getGrisuPluginDirectory(),
"client-side-mds.jar"));
}
if (StringUtils.isBlank(username)) {
if (StringUtils.isBlank(loginParams.getMyProxyUsername())) {
if ( cred != null ) {
try {
return LoginHelpers.globusCredentialLogin(loginParams, cred);
} catch (Exception e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
} else if (password == null || password.length == 0) {
// means certificate auth
try {
// means try to load local proxy
if ( loginParams == null ) {
return LoginHelpers.defaultLocalProxyLogin();
} else {
return LoginHelpers.defaultLocalProxyLogin(loginParams);
}
} catch (Exception e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
} else {
// means to create local proxy
try {
return LoginHelpers.localProxyLogin(password,
loginParams);
} catch (ServiceInterfaceException e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
}
} else {
// means myproxy login
try {
return LoginHelpers.myProxyLogin(loginParams);
} catch (ServiceInterfaceException e) {
throw new LoginException("Could not login: "
+ e.getLocalizedMessage(), e);
}
}
} else {
// means shib login
throw new RuntimeException("Shib login not supported yet...");
}
}
|
diff --git a/src/com/m0pt0pmatt/bettereconomy/EconomyListener.java b/src/com/m0pt0pmatt/bettereconomy/EconomyListener.java
index 9a44132..76cc5d6 100644
--- a/src/com/m0pt0pmatt/bettereconomy/EconomyListener.java
+++ b/src/com/m0pt0pmatt/bettereconomy/EconomyListener.java
@@ -1,95 +1,95 @@
package com.m0pt0pmatt.bettereconomy;
import java.util.Random;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerLoginEvent;
/**
* Listener for economy related events
* @author Matthew
*
*/
public class EconomyListener implements Listener{
/**
* hook to grab the economy
*/
private EconomyManager economy;
/**
* Default constructor
*/
public EconomyListener(BetterEconomy plugin){
//try to grab the EconomyManager
this.economy = BetterEconomy.economy;
}
/**
* Creates accounts for users when they log in, if they don't already have an account
* @param event PlayerLoginEvent
*/
@EventHandler(priority = EventPriority.LOWEST)
public void createAccount(PlayerLoginEvent event) {
//try to grab the economy. I know
while (economy == null){
economy = BetterEconomy.economy;
return;
}
//If player does not have an account, create one
if (!(economy.hasAccount(event.getPlayer().getName()))){
economy.addAccount(new InventoryAccount(event.getPlayer().getName(), EconomyManager.startingBalance));
event.getPlayer().sendMessage("Your new account has been made");
System.out.println("[HomeWorldPlugin-Economy] made new account for " + event.getPlayer().getName());
}
}
/*
* Removes a percentage (40-70) of currency from a player's enderchest upon death in the wilderness
* @param event PlayerDeathEvent
*/
@EventHandler(priority = EventPriority.NORMAL)
public void wildernessDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if(player.getLocation().getWorld().getName().equals("Wilderness")) {
Random random = new Random();
int percentLost = random.nextInt(30) + 40;
int inventoryAmount = 0;
int valueLost = 0;
// Iterates through arraylists depositing items
for(Currency currency: economy.getCurrencies()){
inventoryAmount = economy.countInventory(player.getEnderChest(), currency);
economy.removeCurrency(player.getEnderChest(), currency, (int)Math.ceil(inventoryAmount * percentLost / 100.));
valueLost += economy.getCurrencyValue(currency.getName()) * (int)Math.ceil(inventoryAmount * percentLost / 100.);
}
for(Currency currency: economy.getOres()){
- inventoryAmount = economy.countInventory(player.getEnderChest(), currency);
+ inventoryAmount = economy.countOreInventory(player.getEnderChest(), currency);
economy.removeCurrency(player.getEnderChest(), currency, (int)Math.ceil(inventoryAmount * percentLost / 100.));
valueLost += economy.getOreValue(currency.getName()) * (int)Math.ceil(inventoryAmount * percentLost / 100.);
}
player.sendMessage("You died in the wilderness");
player.sendMessage("$" + valueLost + " was lost from your EnderChest (" + percentLost + "% of currencies)");
if(player.getKiller() != null){
economy.depositPlayer(player.getKiller().getName(), valueLost);
player.getKiller().sendMessage("You have been rewarded " + valueLost + "for killing " + player.getName());
}
else{
if (!economy.hasAccount("__Server")){
economy.createPlayerAccount("__Server");
}
economy.depositPlayer("__Server", valueLost);
}
}
}
}
| true | true | public void wildernessDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if(player.getLocation().getWorld().getName().equals("Wilderness")) {
Random random = new Random();
int percentLost = random.nextInt(30) + 40;
int inventoryAmount = 0;
int valueLost = 0;
// Iterates through arraylists depositing items
for(Currency currency: economy.getCurrencies()){
inventoryAmount = economy.countInventory(player.getEnderChest(), currency);
economy.removeCurrency(player.getEnderChest(), currency, (int)Math.ceil(inventoryAmount * percentLost / 100.));
valueLost += economy.getCurrencyValue(currency.getName()) * (int)Math.ceil(inventoryAmount * percentLost / 100.);
}
for(Currency currency: economy.getOres()){
inventoryAmount = economy.countInventory(player.getEnderChest(), currency);
economy.removeCurrency(player.getEnderChest(), currency, (int)Math.ceil(inventoryAmount * percentLost / 100.));
valueLost += economy.getOreValue(currency.getName()) * (int)Math.ceil(inventoryAmount * percentLost / 100.);
}
player.sendMessage("You died in the wilderness");
player.sendMessage("$" + valueLost + " was lost from your EnderChest (" + percentLost + "% of currencies)");
if(player.getKiller() != null){
economy.depositPlayer(player.getKiller().getName(), valueLost);
player.getKiller().sendMessage("You have been rewarded " + valueLost + "for killing " + player.getName());
}
else{
if (!economy.hasAccount("__Server")){
economy.createPlayerAccount("__Server");
}
economy.depositPlayer("__Server", valueLost);
}
}
}
| public void wildernessDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if(player.getLocation().getWorld().getName().equals("Wilderness")) {
Random random = new Random();
int percentLost = random.nextInt(30) + 40;
int inventoryAmount = 0;
int valueLost = 0;
// Iterates through arraylists depositing items
for(Currency currency: economy.getCurrencies()){
inventoryAmount = economy.countInventory(player.getEnderChest(), currency);
economy.removeCurrency(player.getEnderChest(), currency, (int)Math.ceil(inventoryAmount * percentLost / 100.));
valueLost += economy.getCurrencyValue(currency.getName()) * (int)Math.ceil(inventoryAmount * percentLost / 100.);
}
for(Currency currency: economy.getOres()){
inventoryAmount = economy.countOreInventory(player.getEnderChest(), currency);
economy.removeCurrency(player.getEnderChest(), currency, (int)Math.ceil(inventoryAmount * percentLost / 100.));
valueLost += economy.getOreValue(currency.getName()) * (int)Math.ceil(inventoryAmount * percentLost / 100.);
}
player.sendMessage("You died in the wilderness");
player.sendMessage("$" + valueLost + " was lost from your EnderChest (" + percentLost + "% of currencies)");
if(player.getKiller() != null){
economy.depositPlayer(player.getKiller().getName(), valueLost);
player.getKiller().sendMessage("You have been rewarded " + valueLost + "for killing " + player.getName());
}
else{
if (!economy.hasAccount("__Server")){
economy.createPlayerAccount("__Server");
}
economy.depositPlayer("__Server", valueLost);
}
}
}
|
diff --git a/src/plugins/KeyUtils/KeyExplorerUtils.java b/src/plugins/KeyUtils/KeyExplorerUtils.java
index c706c20..9f93447 100644
--- a/src/plugins/KeyUtils/KeyExplorerUtils.java
+++ b/src/plugins/KeyUtils/KeyExplorerUtils.java
@@ -1,488 +1,488 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.KeyUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;
import com.db4o.ObjectContainer;
import freenet.client.ArchiveContext;
import freenet.client.ClientMetadata;
import freenet.client.FetchContext;
import freenet.client.FetchException;
import freenet.client.FetchResult;
import freenet.client.FetchWaiter;
import freenet.client.HighLevelSimpleClient;
import freenet.client.Metadata;
import freenet.client.MetadataParseException;
import freenet.client.InsertContext.CompatibilityMode;
import freenet.client.async.ClientContext;
import freenet.client.async.ClientGetState;
import freenet.client.async.ClientGetWorkerThread;
import freenet.client.async.ClientGetter;
import freenet.client.async.ManifestElement;
import freenet.client.async.GetCompletionCallback;
import freenet.client.async.KeyListenerConstructionException;
import freenet.client.async.SnoopBucket;
import freenet.client.async.SplitFileFetcher;
import freenet.client.async.StreamGenerator;
import freenet.client.filter.UnsafeContentTypeException;
import freenet.crypt.HashResult;
import freenet.keys.FreenetURI;
import freenet.node.RequestClient;
import freenet.node.RequestStarter;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.Logger;
import freenet.support.OOMHandler;
import freenet.support.api.Bucket;
import freenet.support.api.BucketFactory;
import freenet.support.compress.CompressionOutputSizeException;
import freenet.support.compress.Compressor;
import freenet.support.compress.DecompressorThreadManager;
import freenet.support.compress.Compressor.COMPRESSOR_TYPE;
import freenet.support.io.BucketTools;
import freenet.support.io.Closer;
public class KeyExplorerUtils {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(KeyExplorerUtils.class);
}
private static class SnoopGetter implements SnoopBucket {
private GetResult result;
private final BucketFactory _bf;
SnoopGetter (BucketFactory bf) {
_bf = bf;
}
public boolean snoopBucket(Bucket data, boolean isMetadata,
ObjectContainer container, ClientContext context) {
Bucket temp;
try {
temp = _bf.makeBucket(data.size());
BucketTools.copy(data, temp);
} catch (IOException e) {
Logger.error(this, "Bucket error, disk full?", e);
return true;
}
result = new GetResult(temp, isMetadata);
return true;
}
}
public static Metadata simpleManifestGet(PluginRespirator pr, FreenetURI uri) throws MetadataParseException, FetchException, IOException {
GetResult res = simpleGet(pr, uri);
if (!res.isMetaData()) {
throw new MetadataParseException("uri did not point to metadata " + uri);
}
return Metadata.construct(res.getData());
}
public static GetResult simpleGet(PluginRespirator pr, FreenetURI uri) throws FetchException {
SnoopGetter snooper = new SnoopGetter(pr.getNode().clientCore.tempBucketFactory);
FetchContext context = pr.getHLSimpleClient().getFetchContext();
FetchWaiter fw = new FetchWaiter();
ClientGetter get = new ClientGetter(fw, uri, context, RequestStarter.INTERACTIVE_PRIORITY_CLASS, (RequestClient)pr.getHLSimpleClient(), null, null);
get.setBucketSnoop(snooper);
try {
get.start(null, pr.getNode().clientCore.clientContext);
fw.waitForCompletion();
} catch (FetchException e) {
if (snooper.result == null) {
// really an error
Logger.error(KeyExplorerUtils.class, "pfehler", e);
throw e;
}
}
return snooper.result;
}
public static FetchResult splitGet(PluginRespirator pr, Metadata metadata) throws FetchException, MetadataParseException,
KeyListenerConstructionException {
if (!metadata.isSplitfile()) {
throw new MetadataParseException("uri did not point to splitfile");
}
final FetchWaiter fw = new FetchWaiter();
final FetchContext ctx = pr.getHLSimpleClient().getFetchContext();
GetCompletionCallback cb = new GetCompletionCallback() {
public void onBlockSetFinished(ClientGetState state, ObjectContainer container, ClientContext context) {
}
public void onExpectedMIME(String mime, ObjectContainer container, ClientContext context) {
}
public void onExpectedSize(long size, ObjectContainer container, ClientContext context) {
}
public void onFailure(FetchException e, ClientGetState state, ObjectContainer container, ClientContext context) {
fw.onFailure(e, null, container);
}
public void onFinalizedMetadata(ObjectContainer container) {
}
public void onTransition(ClientGetState oldState, ClientGetState newState, ObjectContainer container) {
}
public void onExpectedTopSize(long size, long compressed,
int blocksReq, int blocksTotal, ObjectContainer container,
ClientContext context) {
}
public void onHashes(HashResult[] hashes,
ObjectContainer container, ClientContext context) {
}
public void onSplitfileCompatibilityMode(CompatibilityMode min,
CompatibilityMode max, byte[] customSplitfileKey,
boolean compressed, boolean bottomLayer,
boolean definitiveAnyway, ObjectContainer container,
ClientContext context) {
}
public void onSuccess(StreamGenerator streamGenerator,
ClientMetadata clientMetadata,
List<? extends Compressor> decompressors,
ClientGetState state, ObjectContainer container,
ClientContext context) {
PipedOutputStream dataOutput = new PipedOutputStream();
PipedInputStream dataInput = new PipedInputStream();
OutputStream output = null;
DecompressorThreadManager decompressorManager = null;
ClientGetWorkerThread worker = null;
Bucket finalResult = null;
FetchResult result = null;
// FIXME use the two max lengths separately.
long maxLen = Math.max(ctx.maxTempLength, ctx.maxOutputLength);
try {
finalResult = context.getBucketFactory(false).makeBucket(maxLen);
dataOutput .connect(dataInput);
result = new FetchResult(clientMetadata, finalResult);
// Decompress
if(decompressors != null) {
if(logMINOR) Logger.minor(this, "Decompressing...");
decompressorManager = new DecompressorThreadManager(dataInput, decompressors, maxLen);
dataInput = decompressorManager.execute();
}
output = finalResult.getOutputStream();
worker = new ClientGetWorkerThread(dataInput, output, null, null, null, false, ctx.charset, ctx.prefetchHook, ctx.tagReplacer);
worker.start();
try {
streamGenerator.writeTo(dataOutput, container, context);
} catch(IOException e) {
//Check if the worker thread caught an exception
worker.getError();
//If not, throw the original error
throw e;
}
if(logMINOR) Logger.minor(this, "Size of written data: "+result.asBucket().size());
if(decompressorManager != null) {
if(logMINOR) Logger.minor(this, "Waiting for decompression to finalize");
decompressorManager.waitFinished();
}
if(logMINOR) Logger.minor(this, "Waiting for hashing, filtration, and writing to finish");
worker.waitFinished();
if(worker.getClientMetadata() != null) {
clientMetadata = worker.getClientMetadata();
result = new FetchResult(clientMetadata, finalResult);
}
dataOutput.close();
dataInput.close();
output.close();
} catch (OutOfMemoryError e) {
OOMHandler.handleOOM(e);
System.err.println("Failing above attempted fetch...");
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(UnsafeContentTypeException e) {
Logger.error(this, "Impossible, this piece of code does not filter", e);
onFailure(new FetchException(e.getFetchErrorCode(), e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(URISyntaxException e) {
//Impossible
Logger.error(this, "URISyntaxException converting a FreenetURI to a URI!: "+e, e);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state/*Not really the state's fault*/, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(CompressionOutputSizeException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.TOO_BIG, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(IOException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.BUCKET_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(FetchException e) {
Logger.error(this, "Caught "+e, e);
onFailure(e, state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(Throwable t) {
Logger.error(this, "Caught "+t, t);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, t), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} finally {
Closer.close(dataInput);
Closer.close(dataOutput);
Closer.close(output);
}
fw.onSuccess(result, null, container);
}
};
List<COMPRESSOR_TYPE> decompressors = new LinkedList<COMPRESSOR_TYPE>();
boolean deleteFetchContext = false;
ClientMetadata clientMetadata = null;
ArchiveContext actx = null;
int recursionLevel = 0;
Bucket returnBucket = null;
long token = 0;
if (metadata.isCompressed()) {
COMPRESSOR_TYPE codec = metadata.getCompressionCodec();
decompressors.add(codec);
}
VerySimpleGetter vsg = new VerySimpleGetter((short) 1, null, (RequestClient) pr.getHLSimpleClient());
- SplitFileFetcher sf = new SplitFileFetcher(metadata, cb, vsg, ctx, deleteFetchContext, decompressors, clientMetadata, actx, recursionLevel, token,
+ SplitFileFetcher sf = new SplitFileFetcher(metadata, cb, vsg, ctx, deleteFetchContext, true, decompressors, clientMetadata, actx, recursionLevel, token,
false, (short) 0, null, pr.getNode().clientCore.clientContext);
// VerySimpleGetter vsg = new VerySimpleGetter((short) 1, uri,
// (RequestClient) pr.getHLSimpleClient());
// VerySimpleGet vs = new VerySimpleGet(ck, 0,
// pr.getHLSimpleClient().getFetchContext(), vsg);
sf.schedule(null, pr.getNode().clientCore.clientContext);
// fw.waitForCompletion();
return fw.waitForCompletion();
}
public static Metadata splitManifestGet(PluginRespirator pr, Metadata metadata) throws MetadataParseException, IOException, FetchException, KeyListenerConstructionException {
FetchResult res = splitGet(pr, metadata);
return Metadata.construct(res.asBucket());
}
public static Metadata zipManifestGet(PluginRespirator pr, FreenetURI uri) throws FetchException, MetadataParseException, IOException {
HighLevelSimpleClient hlsc = pr.getHLSimpleClient();
FetchContext fctx = hlsc.getFetchContext();
fctx.returnZIPManifests = true;
FetchWaiter fw = new FetchWaiter();
hlsc.fetch(uri, -1, (RequestClient) hlsc, fw, fctx);
FetchResult fr = fw.waitForCompletion();
ZipInputStream zis = new ZipInputStream(fr.asBucket().getInputStream());
ZipEntry entry;
ByteArrayOutputStream bos;
while (true) {
entry = zis.getNextEntry();
if (entry == null)
break;
if (entry.isDirectory())
continue;
String name = entry.getName();
if (".metadata".equals(name)) {
byte[] buf = new byte[32768];
bos = new ByteArrayOutputStream();
// Read the element
int readBytes;
while ((readBytes = zis.read(buf)) > 0) {
bos.write(buf, 0, readBytes);
}
bos.close();
return Metadata.construct(bos.toByteArray());
}
}
throw new FetchException(200, "impossible? no metadata in archive " + uri);
}
public static Metadata tarManifestGet(PluginRespirator pr, Metadata md, String metaName) throws FetchException, MetadataParseException, IOException {
FetchResult fr;
try {
fr = splitGet(pr, md);
} catch (KeyListenerConstructionException e) {
throw new FetchException(FetchException.INTERNAL_ERROR, e);
}
return internalTarManifestGet(fr.asBucket(), metaName);
}
public static Metadata tarManifestGet(PluginRespirator pr, FreenetURI uri, String metaName) throws FetchException, MetadataParseException, IOException {
HighLevelSimpleClient hlsc = pr.getHLSimpleClient();
FetchContext fctx = hlsc.getFetchContext();
fctx.returnZIPManifests = true;
FetchWaiter fw = new FetchWaiter();
hlsc.fetch(uri, -1, (RequestClient) hlsc, fw, fctx);
FetchResult fr = fw.waitForCompletion();
return internalTarManifestGet(fr.asBucket(), metaName);
}
public static Metadata internalTarManifestGet(Bucket data, String metaName) throws IOException, MetadataParseException, FetchException {
TarInputStream zis = new TarInputStream(data.getInputStream());
TarEntry entry;
ByteArrayOutputStream bos;
while (true) {
entry = zis.getNextEntry();
if (entry == null)
break;
if (entry.isDirectory())
continue;
String name = entry.getName();
if (metaName.equals(name)) {
byte[] buf = new byte[32768];
bos = new ByteArrayOutputStream();
// Read the element
int readBytes;
while ((readBytes = zis.read(buf)) > 0) {
bos.write(buf, 0, readBytes);
}
bos.close();
return Metadata.construct(bos.toByteArray());
}
}
throw new FetchException(200, "impossible? no metadata in archive ");
}
public static HashMap<String, Object> parseMetadata(Metadata oldMetadata, FreenetURI oldUri) throws MalformedURLException {
return parseMetadata(oldMetadata.getDocuments(), oldUri, "");
}
private static HashMap<String, Object> parseMetadata(HashMap<String, Metadata> oldMetadata, FreenetURI oldUri, String prefix) throws MalformedURLException {
HashMap<String, Object> newMetadata = new HashMap<String, Object>();
for(Entry<String, Metadata> entry:oldMetadata.entrySet()) {
Metadata md = entry.getValue();
String name = entry.getKey();
if (md.isArchiveInternalRedirect()) {
String fname = prefix + name;
FreenetURI newUri = new FreenetURI(oldUri.toString(false, false) + "/"+ fname);
//System.err.println("NewURI: "+newUri.toString(false, false));
newMetadata.put(name, new ManifestElement(name, newUri, null));
} else if (md.isSingleFileRedirect()) {
newMetadata.put(name, new ManifestElement(name, md.getSingleTarget(), null));
} else if (md.isSplitfile()) {
newMetadata.put(name, new ManifestElement(name, md.getSingleTarget(), null));
} else {
newMetadata.put(name, parseMetadata(md.getDocuments(), oldUri, prefix + name + "/"));
}
}
return newMetadata;
}
private byte[] doDownload(PluginRespirator pluginRespirator, List<String> errors, String key) {
if (errors.size() > 0) {
return null;
}
if (key == null || (key.trim().length() == 0)) {
errors.add("Are you jokingly? Empty URI");
return null;
}
try {
//FreenetURI furi = sanitizeURI(errors, key);
FreenetURI furi = new FreenetURI(key);
GetResult getresult = simpleGet(pluginRespirator, furi);
if (getresult.isMetaData()) {
return unrollMetadata(pluginRespirator, errors, Metadata.construct(getresult.getData()));
} else {
return BucketTools.toByteArray(getresult.getData());
}
} catch (MalformedURLException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (MetadataParseException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (FetchException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (KeyListenerConstructionException e) {
errors.add(e.getMessage());
e.printStackTrace();
}
return null;
}
public static byte[] unrollMetadata(PluginRespirator pluginRespirator, List<String> errors, Metadata md) throws MalformedURLException, IOException, FetchException, MetadataParseException, KeyListenerConstructionException {
if (!md.isSplitfile()) {
errors.add("Unsupported Metadata: Not a Splitfile");
return null;
}
byte[] result = null;
result = BucketTools.toByteArray(splitGet(pluginRespirator, md).asBucket());
return result;
}
}
| true | true | public static FetchResult splitGet(PluginRespirator pr, Metadata metadata) throws FetchException, MetadataParseException,
KeyListenerConstructionException {
if (!metadata.isSplitfile()) {
throw new MetadataParseException("uri did not point to splitfile");
}
final FetchWaiter fw = new FetchWaiter();
final FetchContext ctx = pr.getHLSimpleClient().getFetchContext();
GetCompletionCallback cb = new GetCompletionCallback() {
public void onBlockSetFinished(ClientGetState state, ObjectContainer container, ClientContext context) {
}
public void onExpectedMIME(String mime, ObjectContainer container, ClientContext context) {
}
public void onExpectedSize(long size, ObjectContainer container, ClientContext context) {
}
public void onFailure(FetchException e, ClientGetState state, ObjectContainer container, ClientContext context) {
fw.onFailure(e, null, container);
}
public void onFinalizedMetadata(ObjectContainer container) {
}
public void onTransition(ClientGetState oldState, ClientGetState newState, ObjectContainer container) {
}
public void onExpectedTopSize(long size, long compressed,
int blocksReq, int blocksTotal, ObjectContainer container,
ClientContext context) {
}
public void onHashes(HashResult[] hashes,
ObjectContainer container, ClientContext context) {
}
public void onSplitfileCompatibilityMode(CompatibilityMode min,
CompatibilityMode max, byte[] customSplitfileKey,
boolean compressed, boolean bottomLayer,
boolean definitiveAnyway, ObjectContainer container,
ClientContext context) {
}
public void onSuccess(StreamGenerator streamGenerator,
ClientMetadata clientMetadata,
List<? extends Compressor> decompressors,
ClientGetState state, ObjectContainer container,
ClientContext context) {
PipedOutputStream dataOutput = new PipedOutputStream();
PipedInputStream dataInput = new PipedInputStream();
OutputStream output = null;
DecompressorThreadManager decompressorManager = null;
ClientGetWorkerThread worker = null;
Bucket finalResult = null;
FetchResult result = null;
// FIXME use the two max lengths separately.
long maxLen = Math.max(ctx.maxTempLength, ctx.maxOutputLength);
try {
finalResult = context.getBucketFactory(false).makeBucket(maxLen);
dataOutput .connect(dataInput);
result = new FetchResult(clientMetadata, finalResult);
// Decompress
if(decompressors != null) {
if(logMINOR) Logger.minor(this, "Decompressing...");
decompressorManager = new DecompressorThreadManager(dataInput, decompressors, maxLen);
dataInput = decompressorManager.execute();
}
output = finalResult.getOutputStream();
worker = new ClientGetWorkerThread(dataInput, output, null, null, null, false, ctx.charset, ctx.prefetchHook, ctx.tagReplacer);
worker.start();
try {
streamGenerator.writeTo(dataOutput, container, context);
} catch(IOException e) {
//Check if the worker thread caught an exception
worker.getError();
//If not, throw the original error
throw e;
}
if(logMINOR) Logger.minor(this, "Size of written data: "+result.asBucket().size());
if(decompressorManager != null) {
if(logMINOR) Logger.minor(this, "Waiting for decompression to finalize");
decompressorManager.waitFinished();
}
if(logMINOR) Logger.minor(this, "Waiting for hashing, filtration, and writing to finish");
worker.waitFinished();
if(worker.getClientMetadata() != null) {
clientMetadata = worker.getClientMetadata();
result = new FetchResult(clientMetadata, finalResult);
}
dataOutput.close();
dataInput.close();
output.close();
} catch (OutOfMemoryError e) {
OOMHandler.handleOOM(e);
System.err.println("Failing above attempted fetch...");
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(UnsafeContentTypeException e) {
Logger.error(this, "Impossible, this piece of code does not filter", e);
onFailure(new FetchException(e.getFetchErrorCode(), e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(URISyntaxException e) {
//Impossible
Logger.error(this, "URISyntaxException converting a FreenetURI to a URI!: "+e, e);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state/*Not really the state's fault*/, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(CompressionOutputSizeException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.TOO_BIG, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(IOException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.BUCKET_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(FetchException e) {
Logger.error(this, "Caught "+e, e);
onFailure(e, state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(Throwable t) {
Logger.error(this, "Caught "+t, t);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, t), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} finally {
Closer.close(dataInput);
Closer.close(dataOutput);
Closer.close(output);
}
fw.onSuccess(result, null, container);
}
};
List<COMPRESSOR_TYPE> decompressors = new LinkedList<COMPRESSOR_TYPE>();
boolean deleteFetchContext = false;
ClientMetadata clientMetadata = null;
ArchiveContext actx = null;
int recursionLevel = 0;
Bucket returnBucket = null;
long token = 0;
if (metadata.isCompressed()) {
COMPRESSOR_TYPE codec = metadata.getCompressionCodec();
decompressors.add(codec);
}
VerySimpleGetter vsg = new VerySimpleGetter((short) 1, null, (RequestClient) pr.getHLSimpleClient());
SplitFileFetcher sf = new SplitFileFetcher(metadata, cb, vsg, ctx, deleteFetchContext, decompressors, clientMetadata, actx, recursionLevel, token,
false, (short) 0, null, pr.getNode().clientCore.clientContext);
// VerySimpleGetter vsg = new VerySimpleGetter((short) 1, uri,
// (RequestClient) pr.getHLSimpleClient());
// VerySimpleGet vs = new VerySimpleGet(ck, 0,
// pr.getHLSimpleClient().getFetchContext(), vsg);
sf.schedule(null, pr.getNode().clientCore.clientContext);
// fw.waitForCompletion();
return fw.waitForCompletion();
}
| public static FetchResult splitGet(PluginRespirator pr, Metadata metadata) throws FetchException, MetadataParseException,
KeyListenerConstructionException {
if (!metadata.isSplitfile()) {
throw new MetadataParseException("uri did not point to splitfile");
}
final FetchWaiter fw = new FetchWaiter();
final FetchContext ctx = pr.getHLSimpleClient().getFetchContext();
GetCompletionCallback cb = new GetCompletionCallback() {
public void onBlockSetFinished(ClientGetState state, ObjectContainer container, ClientContext context) {
}
public void onExpectedMIME(String mime, ObjectContainer container, ClientContext context) {
}
public void onExpectedSize(long size, ObjectContainer container, ClientContext context) {
}
public void onFailure(FetchException e, ClientGetState state, ObjectContainer container, ClientContext context) {
fw.onFailure(e, null, container);
}
public void onFinalizedMetadata(ObjectContainer container) {
}
public void onTransition(ClientGetState oldState, ClientGetState newState, ObjectContainer container) {
}
public void onExpectedTopSize(long size, long compressed,
int blocksReq, int blocksTotal, ObjectContainer container,
ClientContext context) {
}
public void onHashes(HashResult[] hashes,
ObjectContainer container, ClientContext context) {
}
public void onSplitfileCompatibilityMode(CompatibilityMode min,
CompatibilityMode max, byte[] customSplitfileKey,
boolean compressed, boolean bottomLayer,
boolean definitiveAnyway, ObjectContainer container,
ClientContext context) {
}
public void onSuccess(StreamGenerator streamGenerator,
ClientMetadata clientMetadata,
List<? extends Compressor> decompressors,
ClientGetState state, ObjectContainer container,
ClientContext context) {
PipedOutputStream dataOutput = new PipedOutputStream();
PipedInputStream dataInput = new PipedInputStream();
OutputStream output = null;
DecompressorThreadManager decompressorManager = null;
ClientGetWorkerThread worker = null;
Bucket finalResult = null;
FetchResult result = null;
// FIXME use the two max lengths separately.
long maxLen = Math.max(ctx.maxTempLength, ctx.maxOutputLength);
try {
finalResult = context.getBucketFactory(false).makeBucket(maxLen);
dataOutput .connect(dataInput);
result = new FetchResult(clientMetadata, finalResult);
// Decompress
if(decompressors != null) {
if(logMINOR) Logger.minor(this, "Decompressing...");
decompressorManager = new DecompressorThreadManager(dataInput, decompressors, maxLen);
dataInput = decompressorManager.execute();
}
output = finalResult.getOutputStream();
worker = new ClientGetWorkerThread(dataInput, output, null, null, null, false, ctx.charset, ctx.prefetchHook, ctx.tagReplacer);
worker.start();
try {
streamGenerator.writeTo(dataOutput, container, context);
} catch(IOException e) {
//Check if the worker thread caught an exception
worker.getError();
//If not, throw the original error
throw e;
}
if(logMINOR) Logger.minor(this, "Size of written data: "+result.asBucket().size());
if(decompressorManager != null) {
if(logMINOR) Logger.minor(this, "Waiting for decompression to finalize");
decompressorManager.waitFinished();
}
if(logMINOR) Logger.minor(this, "Waiting for hashing, filtration, and writing to finish");
worker.waitFinished();
if(worker.getClientMetadata() != null) {
clientMetadata = worker.getClientMetadata();
result = new FetchResult(clientMetadata, finalResult);
}
dataOutput.close();
dataInput.close();
output.close();
} catch (OutOfMemoryError e) {
OOMHandler.handleOOM(e);
System.err.println("Failing above attempted fetch...");
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(UnsafeContentTypeException e) {
Logger.error(this, "Impossible, this piece of code does not filter", e);
onFailure(new FetchException(e.getFetchErrorCode(), e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(URISyntaxException e) {
//Impossible
Logger.error(this, "URISyntaxException converting a FreenetURI to a URI!: "+e, e);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state/*Not really the state's fault*/, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(CompressionOutputSizeException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.TOO_BIG, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(IOException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.BUCKET_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(FetchException e) {
Logger.error(this, "Caught "+e, e);
onFailure(e, state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(Throwable t) {
Logger.error(this, "Caught "+t, t);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, t), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} finally {
Closer.close(dataInput);
Closer.close(dataOutput);
Closer.close(output);
}
fw.onSuccess(result, null, container);
}
};
List<COMPRESSOR_TYPE> decompressors = new LinkedList<COMPRESSOR_TYPE>();
boolean deleteFetchContext = false;
ClientMetadata clientMetadata = null;
ArchiveContext actx = null;
int recursionLevel = 0;
Bucket returnBucket = null;
long token = 0;
if (metadata.isCompressed()) {
COMPRESSOR_TYPE codec = metadata.getCompressionCodec();
decompressors.add(codec);
}
VerySimpleGetter vsg = new VerySimpleGetter((short) 1, null, (RequestClient) pr.getHLSimpleClient());
SplitFileFetcher sf = new SplitFileFetcher(metadata, cb, vsg, ctx, deleteFetchContext, true, decompressors, clientMetadata, actx, recursionLevel, token,
false, (short) 0, null, pr.getNode().clientCore.clientContext);
// VerySimpleGetter vsg = new VerySimpleGetter((short) 1, uri,
// (RequestClient) pr.getHLSimpleClient());
// VerySimpleGet vs = new VerySimpleGet(ck, 0,
// pr.getHLSimpleClient().getFetchContext(), vsg);
sf.schedule(null, pr.getNode().clientCore.clientContext);
// fw.waitForCompletion();
return fw.waitForCompletion();
}
|
diff --git a/scm-webapp/src/main/java/sonia/scm/security/SecurityFilter.java b/scm-webapp/src/main/java/sonia/scm/security/SecurityFilter.java
index 75b418dae..15a1341cf 100644
--- a/scm-webapp/src/main/java/sonia/scm/security/SecurityFilter.java
+++ b/scm-webapp/src/main/java/sonia/scm/security/SecurityFilter.java
@@ -1,194 +1,194 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sonia.scm.security;
//~--- non-JDK imports --------------------------------------------------------
import sonia.scm.User;
//~--- JDK imports ------------------------------------------------------------
import java.io.IOException;
import java.security.Principal;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Sebastian Sdorra
*/
@WebFilter(urlPatterns = "/api/rest/*")
public class SecurityFilter implements Filter
{
/** Field description */
public static final String URL_AUTHENTICATION = "/api/rest/authentication";
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*/
@Override
public void destroy()
{
// do nothing
}
/**
* Method description
*
*
* @param req
* @param res
* @param chain
*
* @throws IOException
* @throws ServletException
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)
throws IOException, ServletException
{
if ((req instanceof HttpServletRequest)
&& (res instanceof HttpServletResponse))
{
HttpServletRequest request = (HttpServletRequest) req;
String uri =
request.getRequestURI().substring(request.getContextPath().length());
if (!uri.startsWith(URL_AUTHENTICATION))
{
User user = authenticator.getUser(request);
if (user != null)
{
- ((HttpServletResponse) res).sendError(
- HttpServletResponse.SC_UNAUTHORIZED);
+ chain.doFilter(new ScmHttpServletRequest(request, user), res);
}
else
{
- chain.doFilter(new ScmHttpServletRequest(request, user), res);
+ ((HttpServletResponse) res).sendError(
+ HttpServletResponse.SC_UNAUTHORIZED);
}
}
else
{
chain.doFilter(req, res);
}
}
else
{
throw new ServletException("request is not an HttpServletRequest");
}
}
/**
* Method description
*
*
* @param filterConfig
*
* @throws ServletException
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
// do nothing
}
//~--- inner classes --------------------------------------------------------
/**
* Class description
*
*
* @version Enter version here..., 10/09/08
* @author Enter your name here...
*/
private static class ScmHttpServletRequest extends HttpServletRequestWrapper
{
/**
* Constructs ...
*
*
* @param request
* @param user
*/
public ScmHttpServletRequest(HttpServletRequest request, User user)
{
super(request);
this.user = user;
}
//~--- get methods --------------------------------------------------------
/**
* Method description
*
*
* @return
*/
@Override
public String getRemoteUser()
{
return user.getName();
}
/**
* Method description
*
*
* @return
*/
public User getUser()
{
return user;
}
/**
* Method description
*
*
* @return
*/
@Override
public Principal getUserPrincipal()
{
return user;
}
//~--- fields -------------------------------------------------------------
/** Field description */
private User user;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
@Inject
private Authenticator authenticator;
}
| false | true | public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)
throws IOException, ServletException
{
if ((req instanceof HttpServletRequest)
&& (res instanceof HttpServletResponse))
{
HttpServletRequest request = (HttpServletRequest) req;
String uri =
request.getRequestURI().substring(request.getContextPath().length());
if (!uri.startsWith(URL_AUTHENTICATION))
{
User user = authenticator.getUser(request);
if (user != null)
{
((HttpServletResponse) res).sendError(
HttpServletResponse.SC_UNAUTHORIZED);
}
else
{
chain.doFilter(new ScmHttpServletRequest(request, user), res);
}
}
else
{
chain.doFilter(req, res);
}
}
else
{
throw new ServletException("request is not an HttpServletRequest");
}
}
| public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)
throws IOException, ServletException
{
if ((req instanceof HttpServletRequest)
&& (res instanceof HttpServletResponse))
{
HttpServletRequest request = (HttpServletRequest) req;
String uri =
request.getRequestURI().substring(request.getContextPath().length());
if (!uri.startsWith(URL_AUTHENTICATION))
{
User user = authenticator.getUser(request);
if (user != null)
{
chain.doFilter(new ScmHttpServletRequest(request, user), res);
}
else
{
((HttpServletResponse) res).sendError(
HttpServletResponse.SC_UNAUTHORIZED);
}
}
else
{
chain.doFilter(req, res);
}
}
else
{
throw new ServletException("request is not an HttpServletRequest");
}
}
|
diff --git a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUserDetail.java b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUserDetail.java
index d1168ba..39cef66 100644
--- a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUserDetail.java
+++ b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUserDetail.java
@@ -1,13 +1,15 @@
package hudson.plugins.active_directory;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.User;
/**
* @author Kohsuke Kawaguchi
*/
public class ActiveDirectoryUserDetail extends User {
public ActiveDirectoryUserDetail(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities) throws IllegalArgumentException {
- super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
+ // Acegi doesn't like null password, but during remember-me processing we don't know the password.
+ // so we need to set some dummy. See #1229
+ super(username, password!=null?password:"PASSWORD", enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
}
| true | true | public ActiveDirectoryUserDetail(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities) throws IllegalArgumentException {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
| public ActiveDirectoryUserDetail(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities) throws IllegalArgumentException {
// Acegi doesn't like null password, but during remember-me processing we don't know the password.
// so we need to set some dummy. See #1229
super(username, password!=null?password:"PASSWORD", enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
|
diff --git a/src/com/android/inputmethod/latin/LatinIME.java b/src/com/android/inputmethod/latin/LatinIME.java
index 4c81b33b..18b277c5 100644
--- a/src/com/android/inputmethod/latin/LatinIME.java
+++ b/src/com/android/inputmethod/latin/LatinIME.java
@@ -1,1952 +1,1953 @@
/*
* Copyright (C) 2008-2009 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.android.inputmethod.latin;
import com.android.inputmethod.voice.EditingUtil;
import com.android.inputmethod.voice.FieldContext;
import com.android.inputmethod.voice.SettingsUtil;
import com.android.inputmethod.voice.VoiceInput;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.media.AudioManager;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.speech.RecognitionManager;
import android.text.AutoText;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
public class LatinIME extends InputMethodService
implements KeyboardView.OnKeyboardActionListener,
VoiceInput.UiListener,
SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "LatinIME";
static final boolean DEBUG = false;
static final boolean TRACE = false;
static final boolean VOICE_INSTALLED = true;
static final boolean ENABLE_VOICE_BUTTON = true;
private static final String PREF_VIBRATE_ON = "vibrate_on";
private static final String PREF_SOUND_ON = "sound_on";
private static final String PREF_AUTO_CAP = "auto_cap";
private static final String PREF_QUICK_FIXES = "quick_fixes";
private static final String PREF_SHOW_SUGGESTIONS = "show_suggestions";
private static final String PREF_AUTO_COMPLETE = "auto_complete";
private static final String PREF_VOICE_MODE = "voice_mode";
// Whether or not the user has used voice input before (and thus, whether to show the
// first-run warning dialog or not).
private static final String PREF_HAS_USED_VOICE_INPUT = "has_used_voice_input";
// Whether or not the user has used voice input from an unsupported locale UI before.
// For example, the user has a Chinese UI but activates voice input.
private static final String PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE =
"has_used_voice_input_unsupported_locale";
// A list of locales which are supported by default for voice input, unless we get a
// different list from Gservices.
public static final String DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES =
"en " +
"en_US " +
"en_GB " +
"en_AU " +
"en_CA " +
"en_IE " +
"en_IN " +
"en_NZ " +
"en_SG " +
"en_ZA ";
// The private IME option used to indicate that no microphone should be shown for a
// given text field. For instance this is specified by the search dialog when the
// dialog is already showing a voice search button.
private static final String IME_OPTION_NO_MICROPHONE = "nm";
public static final String PREF_SELECTED_LANGUAGES = "selected_languages";
public static final String PREF_INPUT_LANGUAGE = "input_language";
private static final int MSG_UPDATE_SUGGESTIONS = 0;
private static final int MSG_START_TUTORIAL = 1;
private static final int MSG_UPDATE_SHIFT_STATE = 2;
private static final int MSG_VOICE_RESULTS = 3;
private static final int MSG_START_LISTENING_AFTER_SWIPE = 4;
// If we detect a swipe gesture within N ms of typing, then swipe is
// ignored, since it may in fact be two key presses in quick succession.
private static final long MIN_MILLIS_AFTER_TYPING_BEFORE_SWIPE = 1000;
// How many continuous deletes at which to start deleting at a higher speed.
private static final int DELETE_ACCELERATE_AT = 20;
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
static final int KEYCODE_ENTER = '\n';
static final int KEYCODE_SPACE = ' ';
static final int KEYCODE_PERIOD = '.';
// Contextual menu positions
private static final int POS_SETTINGS = 0;
private static final int POS_METHOD = 1;
private LatinKeyboardView mInputView;
private CandidateViewContainer mCandidateViewContainer;
private CandidateView mCandidateView;
private Suggest mSuggest;
private CompletionInfo[] mCompletions;
private AlertDialog mOptionsDialog;
private AlertDialog mVoiceWarningDialog;
KeyboardSwitcher mKeyboardSwitcher;
private UserDictionary mUserDictionary;
private ContactsDictionary mContactsDictionary;
private ExpandableDictionary mAutoDictionary;
private Hints mHints;
Resources mResources;
private String mLocale;
private LanguageSwitcher mLanguageSwitcher;
private StringBuilder mComposing = new StringBuilder();
private WordComposer mWord = new WordComposer();
private int mCommittedLength;
private boolean mPredicting;
private boolean mRecognizing;
private boolean mAfterVoiceInput;
private boolean mImmediatelyAfterVoiceInput;
private boolean mShowingVoiceSuggestions;
private boolean mImmediatelyAfterVoiceSuggestions;
private boolean mVoiceInputHighlighted;
private boolean mEnableVoiceButton;
private CharSequence mBestWord;
private boolean mPredictionOn;
private boolean mCompletionOn;
private boolean mHasDictionary;
private boolean mAutoSpace;
private boolean mJustAddedAutoSpace;
private boolean mAutoCorrectEnabled;
private boolean mAutoCorrectOn;
private boolean mCapsLock;
private boolean mPasswordText;
private boolean mEmailText;
private boolean mVibrateOn;
private boolean mSoundOn;
private boolean mAutoCap;
private boolean mQuickFixes;
private boolean mHasUsedVoiceInput;
private boolean mHasUsedVoiceInputUnsupportedLocale;
private boolean mLocaleSupportedForVoiceInput;
private boolean mShowSuggestions;
private boolean mSuggestionShouldReplaceCurrentWord;
private boolean mIsShowingHint;
private int mCorrectionMode;
private boolean mEnableVoice = true;
private boolean mVoiceOnPrimary;
private int mOrientation;
private List<CharSequence> mSuggestPuncList;
// Indicates whether the suggestion strip is to be on in landscape
private boolean mJustAccepted;
private CharSequence mJustRevertedSeparator;
private int mDeleteCount;
private long mLastKeyTime;
private Tutorial mTutorial;
private AudioManager mAudioManager;
// Align sound effect volume on music volume
private final float FX_VOLUME = -1.0f;
private boolean mSilentMode;
private String mWordSeparators;
private String mSentenceSeparators;
private VoiceInput mVoiceInput;
private VoiceResults mVoiceResults = new VoiceResults();
private long mSwipeTriggerTimeMillis;
// For each word, a list of potential replacements, usually from voice.
private Map<String, List<CharSequence>> mWordToSuggestions =
new HashMap<String, List<CharSequence>>();
private class VoiceResults {
List<String> candidates;
Map<String, List<CharSequence>> alternatives;
}
private boolean mRefreshKeyboardRequired;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_SUGGESTIONS:
updateSuggestions();
break;
case MSG_START_TUTORIAL:
if (mTutorial == null) {
if (mInputView.isShown()) {
mTutorial = new Tutorial(LatinIME.this, mInputView);
mTutorial.start();
} else {
// Try again soon if the view is not yet showing
sendMessageDelayed(obtainMessage(MSG_START_TUTORIAL), 100);
}
}
break;
case MSG_UPDATE_SHIFT_STATE:
updateShiftKeyState(getCurrentInputEditorInfo());
break;
case MSG_VOICE_RESULTS:
handleVoiceResults();
break;
case MSG_START_LISTENING_AFTER_SWIPE:
if (mLastKeyTime < mSwipeTriggerTimeMillis) {
startListening(true);
}
}
}
};
@Override public void onCreate() {
super.onCreate();
//setStatusIcon(R.drawable.ime_qwerty);
mResources = getResources();
final Configuration conf = mResources.getConfiguration();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mLanguageSwitcher = new LanguageSwitcher(this);
mLanguageSwitcher.loadLocales(prefs);
mKeyboardSwitcher = new KeyboardSwitcher(this, this);
mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher);
boolean enableMultipleLanguages = mLanguageSwitcher.getLocaleCount() > 0;
String inputLanguage = mLanguageSwitcher.getInputLanguage();
if (inputLanguage == null) {
inputLanguage = conf.locale.toString();
}
initSuggest(inputLanguage);
mOrientation = conf.orientation;
initSuggestPuncList();
// register to receive ringer mode changes for silent mode
IntentFilter filter = new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
if (VOICE_INSTALLED) {
mVoiceInput = new VoiceInput(this, this);
mHints = new Hints(this, new Hints.Display() {
public void showHint(int viewResource) {
LayoutInflater inflater = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(viewResource, null);
setCandidatesView(view);
setCandidatesViewShown(true);
mIsShowingHint = true;
}
});
}
prefs.registerOnSharedPreferenceChangeListener(this);
}
private void initSuggest(String locale) {
mLocale = locale;
Resources orig = getResources();
Configuration conf = orig.getConfiguration();
Locale saveLocale = conf.locale;
conf.locale = new Locale(locale);
orig.updateConfiguration(conf, orig.getDisplayMetrics());
if (mSuggest != null) {
mSuggest.close();
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true);
mSuggest = new Suggest(this, R.raw.main);
updateAutoTextEnabled(saveLocale);
if (mUserDictionary != null) mUserDictionary.close();
mUserDictionary = new UserDictionary(this, mLocale);
if (mContactsDictionary == null) {
mContactsDictionary = new ContactsDictionary(this);
}
if (mAutoDictionary != null) {
mAutoDictionary.close();
}
mAutoDictionary = new AutoDictionary(this, this, mLocale);
mSuggest.setUserDictionary(mUserDictionary);
mSuggest.setContactsDictionary(mContactsDictionary);
mSuggest.setAutoDictionary(mAutoDictionary);
updateCorrectionMode();
mWordSeparators = mResources.getString(R.string.word_separators);
mSentenceSeparators = mResources.getString(R.string.sentence_separators);
conf.locale = saveLocale;
orig.updateConfiguration(conf, orig.getDisplayMetrics());
}
@Override
public void onDestroy() {
mUserDictionary.close();
mContactsDictionary.close();
unregisterReceiver(mReceiver);
if (VOICE_INSTALLED) {
mVoiceInput.destroy();
}
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration conf) {
// If the system locale changes and is different from the saved
// locale (mLocale), then reload the input locale list from the
// latin ime settings (shared prefs) and reset the input locale
// to the first one.
if (!TextUtils.equals(conf.locale.toString(), mLocale)) {
if (mLanguageSwitcher != null) {
mLanguageSwitcher.loadLocales(
PreferenceManager.getDefaultSharedPreferences(this));
toggleLanguage(true, true);
} else {
reloadKeyboards();
}
}
// If orientation changed while predicting, commit the change
if (conf.orientation != mOrientation) {
InputConnection ic = getCurrentInputConnection();
commitTyped(ic);
if (ic != null) ic.finishComposingText(); // For voice input
mOrientation = conf.orientation;
reloadKeyboards();
}
super.onConfigurationChanged(conf);
}
@Override
public View onCreateInputView() {
mInputView = (LatinKeyboardView) getLayoutInflater().inflate(
R.layout.input, null);
mKeyboardSwitcher.setInputView(mInputView);
mKeyboardSwitcher.makeKeyboards(true);
mInputView.setOnKeyboardActionListener(this);
mKeyboardSwitcher.setKeyboardMode(
KeyboardSwitcher.MODE_TEXT, 0,
shouldShowVoiceButton(makeFieldContext(), getCurrentInputEditorInfo()));
return mInputView;
}
@Override
public void onInitializeInterface() {
// Create a new view associated with voice input if the old
// view is stuck in another layout (e.g. if switching from
// portrait to landscape while speaking)
// NOTE: This must be done here because for some reason
// onCreateInputView isn't called after an orientation change while
// speech rec is in progress.
if (mVoiceInput != null && mVoiceInput.getView().getParent() != null) {
mVoiceInput.newView();
}
super.onInitializeInterface();
}
@Override
public View onCreateCandidatesView() {
mKeyboardSwitcher.makeKeyboards(true);
mCandidateViewContainer = (CandidateViewContainer) getLayoutInflater().inflate(
R.layout.candidates, null);
mCandidateViewContainer.initViews();
mCandidateView = (CandidateView) mCandidateViewContainer.findViewById(R.id.candidates);
mCandidateView.setService(this);
setCandidatesViewShown(true);
return mCandidateViewContainer;
}
@Override
public void onStartInputView(EditorInfo attribute, boolean restarting) {
// In landscape mode, this method gets called without the input view being created.
if (mInputView == null) {
return;
}
if (mRefreshKeyboardRequired) {
mRefreshKeyboardRequired = false;
toggleLanguage(true, true);
}
mKeyboardSwitcher.makeKeyboards(false);
TextEntryState.newSession(this);
// Most such things we decide below in the switch statement, but we need to know
// now whether this is a password text field, because we need to know now (before
// the switch statement) whether we want to enable the voice button.
mPasswordText = false;
int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION;
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
mPasswordText = true;
}
mEnableVoiceButton = shouldShowVoiceButton(makeFieldContext(), attribute);
final boolean enableVoiceButton = mEnableVoiceButton && mEnableVoice;
mAfterVoiceInput = false;
mImmediatelyAfterVoiceInput = false;
mShowingVoiceSuggestions = false;
mImmediatelyAfterVoiceSuggestions = false;
mVoiceInputHighlighted = false;
mWordToSuggestions.clear();
mInputTypeNoAutoCorrect = false;
mPredictionOn = false;
mCompletionOn = false;
mCompletions = null;
mCapsLock = false;
mEmailText = false;
switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) {
case EditorInfo.TYPE_CLASS_NUMBER:
case EditorInfo.TYPE_CLASS_DATETIME:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_SYMBOLS,
attribute.imeOptions, enableVoiceButton);
break;
case EditorInfo.TYPE_CLASS_PHONE:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE,
attribute.imeOptions, enableVoiceButton);
break;
case EditorInfo.TYPE_CLASS_TEXT:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
//startPrediction();
mPredictionOn = true;
// Make sure that passwords are not displayed in candidate view
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ) {
mPredictionOn = false;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mEmailText = true;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
|| variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME) {
mAutoSpace = false;
} else {
mAutoSpace = true;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) {
mPredictionOn = false;
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_WEB,
attribute.imeOptions, enableVoiceButton);
// If it's a browser edit field and auto correct is not ON explicitly, then
// disable auto correction, but keep suggestions on.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) {
mInputTypeNoAutoCorrect = true;
}
}
// If NO_SUGGESTIONS is set, don't do prediction.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) {
mPredictionOn = false;
mInputTypeNoAutoCorrect = true;
}
// If it's not multiline and the autoCorrect flag is not set, then don't correct
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0 &&
(attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) == 0) {
mInputTypeNoAutoCorrect = true;
}
if ((attribute.inputType&EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) {
mPredictionOn = false;
mCompletionOn = true && isFullscreenMode();
}
updateShiftKeyState(attribute);
break;
default:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
updateShiftKeyState(attribute);
}
mInputView.closing();
mComposing.setLength(0);
mPredicting = false;
mDeleteCount = 0;
mJustAddedAutoSpace = false;
loadSettings();
+ updateShiftKeyState(attribute);
setCandidatesViewShown(false);
setSuggestions(null, false, false, false);
// If the dictionary is not big enough, don't auto correct
mHasDictionary = mSuggest.hasMainDictionary();
updateCorrectionMode();
mInputView.setProximityCorrectionEnabled(true);
mPredictionOn = mPredictionOn && (mCorrectionMode > 0 || mShowSuggestions);
checkTutorial(attribute.privateImeOptions);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
@Override
public void onFinishInput() {
super.onFinishInput();
if (VOICE_INSTALLED && mAfterVoiceInput) {
mVoiceInput.logInputEnded();
}
if (VOICE_INSTALLED) {
mVoiceInput.flushLogs();
}
if (mInputView != null) {
mInputView.closing();
}
if (VOICE_INSTALLED && mRecognizing) {
mVoiceInput.cancel();
}
}
@Override
public void onUpdateExtractedText(int token, ExtractedText text) {
super.onUpdateExtractedText(token, text);
InputConnection ic = getCurrentInputConnection();
if (!mImmediatelyAfterVoiceInput && mAfterVoiceInput && ic != null) {
mVoiceInput.logTextModified();
if (mHints.showPunctuationHintIfNecessary(ic)) {
mVoiceInput.logPunctuationHintDisplayed();
}
}
mImmediatelyAfterVoiceInput = false;
}
@Override
public void onUpdateSelection(int oldSelStart, int oldSelEnd,
int newSelStart, int newSelEnd,
int candidatesStart, int candidatesEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
candidatesStart, candidatesEnd);
if (DEBUG) {
Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart
+ ", ose=" + oldSelEnd
+ ", nss=" + newSelStart
+ ", nse=" + newSelEnd
+ ", cs=" + candidatesStart
+ ", ce=" + candidatesEnd);
}
mSuggestionShouldReplaceCurrentWord = false;
// If the current selection in the text view changes, we should
// clear whatever candidate text we have.
if ((((mComposing.length() > 0 && mPredicting) || mVoiceInputHighlighted)
&& (newSelStart != candidatesEnd
|| newSelEnd != candidatesEnd))) {
mComposing.setLength(0);
mPredicting = false;
updateSuggestions();
TextEntryState.reset();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.finishComposingText();
}
mVoiceInputHighlighted = false;
} else if (!mPredicting && !mJustAccepted) {
switch (TextEntryState.getState()) {
case TextEntryState.STATE_ACCEPTED_DEFAULT:
TextEntryState.reset();
// fall through
case TextEntryState.STATE_SPACE_AFTER_PICKED:
mJustAddedAutoSpace = false; // The user moved the cursor.
break;
}
}
mJustAccepted = false;
postUpdateShiftKeyState();
if (VOICE_INSTALLED) {
if (mShowingVoiceSuggestions) {
if (mImmediatelyAfterVoiceSuggestions) {
mImmediatelyAfterVoiceSuggestions = false;
} else {
updateSuggestions();
mShowingVoiceSuggestions = false;
}
}
if (VoiceInput.ENABLE_WORD_CORRECTIONS) {
// If we have alternatives for the current word, then show them.
String word = EditingUtil.getWordAtCursor(
getCurrentInputConnection(), getWordSeparators());
if (word != null && mWordToSuggestions.containsKey(word.trim())) {
mSuggestionShouldReplaceCurrentWord = true;
final List<CharSequence> suggestions = mWordToSuggestions.get(word.trim());
setSuggestions(suggestions, false, true, true);
setCandidatesViewShown(true);
}
}
}
}
@Override
public void hideWindow() {
if (mAfterVoiceInput) mVoiceInput.logInputEnded();
if (TRACE) Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
if (mVoiceWarningDialog != null && mVoiceWarningDialog.isShowing()) {
mVoiceInput.logKeyboardWarningDialogDismissed();
mVoiceWarningDialog.dismiss();
mVoiceWarningDialog = null;
}
if (mTutorial != null) {
mTutorial.close();
mTutorial = null;
}
if (VOICE_INSTALLED & mRecognizing) {
mVoiceInput.cancel();
}
super.hideWindow();
TextEntryState.endSession();
}
@Override
public void onDisplayCompletions(CompletionInfo[] completions) {
if (false) {
Log.i("foo", "Received completions:");
for (int i=0; i<(completions != null ? completions.length : 0); i++) {
Log.i("foo", " #" + i + ": " + completions[i]);
}
}
if (mCompletionOn) {
mCompletions = completions;
if (completions == null) {
setSuggestions(null, false, false, false);
return;
}
List<CharSequence> stringList = new ArrayList<CharSequence>();
for (int i=0; i<(completions != null ? completions.length : 0); i++) {
CompletionInfo ci = completions[i];
if (ci != null) stringList.add(ci.getText());
}
//CharSequence typedWord = mWord.getTypedWord();
setSuggestions(stringList, true, true, true);
mBestWord = null;
setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn);
}
}
@Override
public void setCandidatesViewShown(boolean shown) {
// TODO: Remove this if we support candidates with hard keyboard
if (onEvaluateInputViewShown()) {
super.setCandidatesViewShown(shown);
}
}
@Override
public void onComputeInsets(InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
if (!isFullscreenMode()) {
outInsets.contentTopInsets = outInsets.visibleTopInsets;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.getRepeatCount() == 0 && mInputView != null) {
if (mInputView.handleBack()) {
return true;
} else if (mTutorial != null) {
mTutorial.close();
mTutorial = null;
}
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// If tutorial is visible, don't allow dpad to work
if (mTutorial != null) {
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// If tutorial is visible, don't allow dpad to work
if (mTutorial != null) {
return true;
}
// Enable shift key and DPAD to do selections
if (mInputView != null && mInputView.isShown() && mInputView.isShifted()) {
event = new KeyEvent(event.getDownTime(), event.getEventTime(),
event.getAction(), event.getKeyCode(), event.getRepeatCount(),
event.getDeviceId(), event.getScanCode(),
KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON);
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.sendKeyEvent(event);
return true;
}
break;
}
return super.onKeyUp(keyCode, event);
}
private void revertVoiceInput() {
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.commitText("", 1);
updateSuggestions();
mVoiceInputHighlighted = false;
}
private void commitVoiceInput() {
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.finishComposingText();
updateSuggestions();
mVoiceInputHighlighted = false;
}
private void reloadKeyboards() {
if (mKeyboardSwitcher == null) {
mKeyboardSwitcher = new KeyboardSwitcher(this, this);
}
mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher);
if (mInputView != null) {
mKeyboardSwitcher.setVoiceMode(mEnableVoice && mEnableVoiceButton, mVoiceOnPrimary);
}
mKeyboardSwitcher.makeKeyboards(true);
}
private void commitTyped(InputConnection inputConnection) {
if (mPredicting) {
mPredicting = false;
if (mComposing.length() > 0) {
if (inputConnection != null) {
inputConnection.commitText(mComposing, 1);
}
mCommittedLength = mComposing.length();
TextEntryState.acceptedTyped(mComposing);
checkAddToDictionary(mComposing, AutoDictionary.FREQUENCY_FOR_TYPED);
}
updateSuggestions();
}
}
private void postUpdateShiftKeyState() {
mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SHIFT_STATE), 300);
}
public void updateShiftKeyState(EditorInfo attr) {
InputConnection ic = getCurrentInputConnection();
if (attr != null && mInputView != null && mKeyboardSwitcher.isAlphabetMode()
&& ic != null) {
mInputView.setShifted(mCapsLock || getCursorCapsMode(ic, attr) != 0);
}
}
private int getCursorCapsMode(InputConnection ic, EditorInfo attr) {
int caps = 0;
EditorInfo ei = getCurrentInputEditorInfo();
if (mAutoCap && ei != null && ei.inputType != EditorInfo.TYPE_NULL) {
caps = ic.getCursorCapsMode(attr.inputType);
}
return caps;
}
private void swapPunctuationAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastTwo = ic.getTextBeforeCursor(2, 0);
if (lastTwo != null && lastTwo.length() == 2
&& lastTwo.charAt(0) == KEYCODE_SPACE && isSentenceSeparator(lastTwo.charAt(1))) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(lastTwo.charAt(1) + " ", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustAddedAutoSpace = true;
}
}
private void reswapPeriodAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& lastThree.charAt(0) == KEYCODE_PERIOD
&& lastThree.charAt(1) == KEYCODE_SPACE
&& lastThree.charAt(2) == KEYCODE_PERIOD) {
ic.beginBatchEdit();
ic.deleteSurroundingText(3, 0);
ic.commitText(" ..", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
}
}
private void doubleSpace() {
//if (!mAutoPunctuate) return;
if (mCorrectionMode == Suggest.CORRECTION_NONE) return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& Character.isLetterOrDigit(lastThree.charAt(0))
&& lastThree.charAt(1) == KEYCODE_SPACE && lastThree.charAt(2) == KEYCODE_SPACE) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(". ", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustAddedAutoSpace = true;
}
}
private void maybeRemovePreviousPeriod(CharSequence text) {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
// When the text's first character is '.', remove the previous period
// if there is one.
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == KEYCODE_PERIOD
&& text.charAt(0) == KEYCODE_PERIOD) {
ic.deleteSurroundingText(1, 0);
}
}
private void removeTrailingSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == KEYCODE_SPACE) {
ic.deleteSurroundingText(1, 0);
}
}
public boolean addWordToDictionary(String word) {
mUserDictionary.addWord(word, 128);
return true;
}
private boolean isAlphabet(int code) {
if (Character.isLetter(code)) {
return true;
} else {
return false;
}
}
// Implementation of KeyboardViewListener
public void onKey(int primaryCode, int[] keyCodes) {
long when = SystemClock.uptimeMillis();
if (primaryCode != Keyboard.KEYCODE_DELETE ||
when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
handleBackspace();
mDeleteCount++;
break;
case Keyboard.KEYCODE_SHIFT:
handleShift();
break;
case Keyboard.KEYCODE_CANCEL:
if (mOptionsDialog == null || !mOptionsDialog.isShowing()) {
handleClose();
}
break;
case LatinKeyboardView.KEYCODE_OPTIONS:
showOptionsMenu();
break;
case LatinKeyboardView.KEYCODE_NEXT_LANGUAGE:
toggleLanguage(false, true);
break;
case LatinKeyboardView.KEYCODE_PREV_LANGUAGE:
toggleLanguage(false, false);
break;
case LatinKeyboardView.KEYCODE_SHIFT_LONGPRESS:
if (mCapsLock) {
handleShift();
} else {
toggleCapsLock();
}
break;
case Keyboard.KEYCODE_MODE_CHANGE:
changeKeyboardMode();
break;
case LatinKeyboardView.KEYCODE_VOICE:
if (VOICE_INSTALLED) {
startListening(false /* was a button press, was not a swipe */);
}
break;
case 9 /*Tab*/:
sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB);
break;
default:
if (primaryCode != KEYCODE_ENTER) {
mJustAddedAutoSpace = false;
}
if (isWordSeparator(primaryCode)) {
handleSeparator(primaryCode);
} else {
handleCharacter(primaryCode, keyCodes);
}
// Cancel the just reverted state
mJustRevertedSeparator = null;
}
if (mKeyboardSwitcher.onKey(primaryCode)) {
changeKeyboardMode();
}
}
public void onText(CharSequence text) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ic.beginBatchEdit();
if (mPredicting) {
commitTyped(ic);
}
maybeRemovePreviousPeriod(text);
ic.commitText(text, 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustRevertedSeparator = null;
mJustAddedAutoSpace = false;
}
private void handleBackspace() {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
revertVoiceInput();
return;
}
boolean deleteChar = false;
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
if (mPredicting) {
final int length = mComposing.length();
if (length > 0) {
mComposing.delete(length - 1, length);
mWord.deleteLast();
ic.setComposingText(mComposing, 1);
if (mComposing.length() == 0) {
mPredicting = false;
}
postUpdateSuggestions();
} else {
ic.deleteSurroundingText(1, 0);
}
} else {
deleteChar = true;
}
postUpdateShiftKeyState();
TextEntryState.backspace();
if (TextEntryState.getState() == TextEntryState.STATE_UNDO_COMMIT) {
revertLastWord(deleteChar);
return;
} else if (deleteChar) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
if (mDeleteCount > DELETE_ACCELERATE_AT) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
}
}
mJustRevertedSeparator = null;
}
private void handleShift() {
mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE);
if (mKeyboardSwitcher.isAlphabetMode()) {
// Alphabet keyboard
checkToggleCapsLock();
mInputView.setShifted(mCapsLock || !mInputView.isShifted());
} else {
mKeyboardSwitcher.toggleShift();
}
}
private void handleCharacter(int primaryCode, int[] keyCodes) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
if (isAlphabet(primaryCode) && isPredictionOn() && !isCursorTouchingWord()) {
if (!mPredicting) {
mPredicting = true;
mComposing.setLength(0);
mWord.reset();
}
}
if (mInputView.isShifted()) {
// TODO: This doesn't work with ß, need to fix it in the next release.
if (keyCodes == null || keyCodes[0] < Character.MIN_CODE_POINT
|| keyCodes[0] > Character.MAX_CODE_POINT) {
return;
}
primaryCode = new String(keyCodes, 0, 1).toUpperCase().charAt(0);
}
if (mPredicting) {
if (mInputView.isShifted() && mComposing.length() == 0) {
mWord.setCapitalized(true);
}
mComposing.append((char) primaryCode);
mWord.add(primaryCode, keyCodes);
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
// If it's the first letter, make note of auto-caps state
if (mWord.size() == 1) {
mWord.setAutoCapitalized(
getCursorCapsMode(ic, getCurrentInputEditorInfo()) != 0);
}
ic.setComposingText(mComposing, 1);
}
postUpdateSuggestions();
} else {
sendKeyChar((char)primaryCode);
}
updateShiftKeyState(getCurrentInputEditorInfo());
measureCps();
TextEntryState.typedCharacter((char) primaryCode, isWordSeparator(primaryCode));
}
private void handleSeparator(int primaryCode) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
boolean pickedDefault = false;
// Handle separator
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mPredicting) {
// In certain languages where single quote is a separator, it's better
// not to auto correct, but accept the typed word. For instance,
// in Italian dov' should not be expanded to dove' because the elision
// requires the last vowel to be removed.
if (mAutoCorrectOn && primaryCode != '\'' &&
(mJustRevertedSeparator == null
|| mJustRevertedSeparator.length() == 0
|| mJustRevertedSeparator.charAt(0) != primaryCode)) {
pickDefaultSuggestion();
pickedDefault = true;
// Picked the suggestion by the space key. We consider this
// as "added an auto space".
if (primaryCode == KEYCODE_SPACE) {
mJustAddedAutoSpace = true;
}
} else {
commitTyped(ic);
}
}
if (mJustAddedAutoSpace && primaryCode == KEYCODE_ENTER) {
removeTrailingSpace();
mJustAddedAutoSpace = false;
}
sendKeyChar((char)primaryCode);
// Handle the case of ". ." -> " .." with auto-space if necessary
// before changing the TextEntryState.
if (TextEntryState.getState() == TextEntryState.STATE_PUNCTUATION_AFTER_ACCEPTED
&& primaryCode == KEYCODE_PERIOD) {
reswapPeriodAndSpace();
}
TextEntryState.typedCharacter((char) primaryCode, true);
if (TextEntryState.getState() == TextEntryState.STATE_PUNCTUATION_AFTER_ACCEPTED
&& primaryCode != KEYCODE_ENTER) {
swapPunctuationAndSpace();
} else if (isPredictionOn() && primaryCode == KEYCODE_SPACE) {
//else if (TextEntryState.STATE_SPACE_AFTER_ACCEPTED) {
doubleSpace();
}
if (pickedDefault && mBestWord != null) {
TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord);
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (ic != null) {
ic.endBatchEdit();
}
}
private void handleClose() {
commitTyped(getCurrentInputConnection());
if (VOICE_INSTALLED & mRecognizing) {
mVoiceInput.cancel();
}
requestHideSelf(0);
mInputView.closing();
TextEntryState.endSession();
}
private void checkToggleCapsLock() {
if (mInputView.getKeyboard().isShifted()) {
toggleCapsLock();
}
}
private void toggleCapsLock() {
mCapsLock = !mCapsLock;
if (mKeyboardSwitcher.isAlphabetMode()) {
((LatinKeyboard) mInputView.getKeyboard()).setShiftLocked(mCapsLock);
}
}
private void postUpdateSuggestions() {
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SUGGESTIONS), 100);
}
private boolean isPredictionOn() {
boolean predictionOn = mPredictionOn;
return predictionOn;
}
private boolean isCandidateStripVisible() {
return isPredictionOn() && mShowSuggestions;
}
public void onCancelVoice() {
if (mRecognizing) {
switchToKeyboardView();
}
}
private void switchToKeyboardView() {
mHandler.post(new Runnable() {
public void run() {
mRecognizing = false;
if (mInputView != null) {
setInputView(mInputView);
}
updateInputViewShown();
}});
}
private void switchToRecognitionStatusView() {
mHandler.post(new Runnable() {
public void run() {
mRecognizing = true;
setInputView(mVoiceInput.getView());
updateInputViewShown();
}});
}
private void startListening(boolean swipe) {
if (!mHasUsedVoiceInput ||
(!mLocaleSupportedForVoiceInput && !mHasUsedVoiceInputUnsupportedLocale)) {
// Calls reallyStartListening if user clicks OK, does nothing if user clicks Cancel.
showVoiceWarningDialog(swipe);
} else {
reallyStartListening(swipe);
}
}
private void reallyStartListening(boolean swipe) {
if (!mHasUsedVoiceInput) {
// The user has started a voice input, so remember that in the
// future (so we don't show the warning dialog after the first run).
SharedPreferences.Editor editor =
PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(PREF_HAS_USED_VOICE_INPUT, true);
editor.commit();
mHasUsedVoiceInput = true;
}
if (!mLocaleSupportedForVoiceInput && !mHasUsedVoiceInputUnsupportedLocale) {
// The user has started a voice input from an unsupported locale, so remember that
// in the future (so we don't show the warning dialog the next time they do this).
SharedPreferences.Editor editor =
PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE, true);
editor.commit();
mHasUsedVoiceInputUnsupportedLocale = true;
}
// Clear N-best suggestions
setSuggestions(null, false, false, true);
FieldContext context = new FieldContext(
getCurrentInputConnection(),
getCurrentInputEditorInfo(),
mLanguageSwitcher.getInputLanguage(),
mLanguageSwitcher.getEnabledLanguages());
mVoiceInput.startListening(context, swipe);
switchToRecognitionStatusView();
}
private void showVoiceWarningDialog(final boolean swipe) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_mic_dialog);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mVoiceInput.logKeyboardWarningDialogOk();
reallyStartListening(swipe);
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mVoiceInput.logKeyboardWarningDialogCancel();
}
});
if (mLocaleSupportedForVoiceInput) {
String message = getString(R.string.voice_warning_may_not_understand) + "\n\n" +
getString(R.string.voice_warning_how_to_turn_off);
builder.setMessage(message);
} else {
String message = getString(R.string.voice_warning_locale_not_supported) + "\n\n" +
getString(R.string.voice_warning_may_not_understand) + "\n\n" +
getString(R.string.voice_warning_how_to_turn_off);
builder.setMessage(message);
}
builder.setTitle(R.string.voice_warning_title);
mVoiceWarningDialog = builder.create();
Window window = mVoiceWarningDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mInputView.getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mVoiceInput.logKeyboardWarningDialogShown();
mVoiceWarningDialog.show();
}
public void onVoiceResults(List<String> candidates,
Map<String, List<CharSequence>> alternatives) {
if (!mRecognizing) {
return;
}
mVoiceResults.candidates = candidates;
mVoiceResults.alternatives = alternatives;
mHandler.sendMessage(mHandler.obtainMessage(MSG_VOICE_RESULTS));
}
private void handleVoiceResults() {
mAfterVoiceInput = true;
mImmediatelyAfterVoiceInput = true;
InputConnection ic = getCurrentInputConnection();
if (!isFullscreenMode()) {
// Start listening for updates to the text from typing, etc.
if (ic != null) {
ExtractedTextRequest req = new ExtractedTextRequest();
ic.getExtractedText(req, InputConnection.GET_EXTRACTED_TEXT_MONITOR);
}
}
vibrate();
switchToKeyboardView();
final List<CharSequence> nBest = new ArrayList<CharSequence>();
boolean capitalizeFirstWord = preferCapitalization()
|| (mKeyboardSwitcher.isAlphabetMode() && mInputView.isShifted());
for (String c : mVoiceResults.candidates) {
if (capitalizeFirstWord) {
c = Character.toUpperCase(c.charAt(0)) + c.substring(1, c.length());
}
nBest.add(c);
}
if (nBest.size() == 0) {
return;
}
String bestResult = nBest.get(0).toString();
mVoiceInput.logVoiceInputDelivered();
mHints.registerVoiceResult(bestResult);
if (ic != null) ic.beginBatchEdit(); // To avoid extra updates on committing older text
commitTyped(ic);
EditingUtil.appendText(ic, bestResult);
if (ic != null) ic.endBatchEdit();
// Show N-Best alternates, if there is more than one choice.
if (nBest.size() > 1) {
mImmediatelyAfterVoiceSuggestions = true;
mShowingVoiceSuggestions = true;
setSuggestions(nBest.subList(1, nBest.size()), false, true, true);
setCandidatesViewShown(true);
}
mVoiceInputHighlighted = true;
mWordToSuggestions.putAll(mVoiceResults.alternatives);
}
private void setSuggestions(
List<CharSequence> suggestions,
boolean completions,
boolean typedWordValid,
boolean haveMinimalSuggestion) {
if (mIsShowingHint) {
setCandidatesView(mCandidateViewContainer);
mIsShowingHint = false;
}
if (mCandidateView != null) {
mCandidateView.setSuggestions(
suggestions, completions, typedWordValid, haveMinimalSuggestion);
}
}
private void updateSuggestions() {
mSuggestionShouldReplaceCurrentWord = false;
((LatinKeyboard) mInputView.getKeyboard()).setPreferredLetters(null);
// Check if we have a suggestion engine attached.
if ((mSuggest == null || !isPredictionOn()) && !mVoiceInputHighlighted) {
return;
}
if (!mPredicting) {
setNextSuggestions();
return;
}
List<CharSequence> stringList = mSuggest.getSuggestions(mInputView, mWord, false);
int[] nextLettersFrequencies = mSuggest.getNextLettersFrequencies();
((LatinKeyboard) mInputView.getKeyboard()).setPreferredLetters(nextLettersFrequencies);
boolean correctionAvailable = mSuggest.hasMinimalCorrection();
//|| mCorrectionMode == mSuggest.CORRECTION_FULL;
CharSequence typedWord = mWord.getTypedWord();
// If we're in basic correct
boolean typedWordValid = mSuggest.isValidWord(typedWord) ||
(preferCapitalization() && mSuggest.isValidWord(typedWord.toString().toLowerCase()));
if (mCorrectionMode == Suggest.CORRECTION_FULL) {
correctionAvailable |= typedWordValid;
}
// Don't auto-correct words with multiple capital letter
correctionAvailable &= !mWord.isMostlyCaps();
setSuggestions(stringList, false, typedWordValid, correctionAvailable);
if (stringList.size() > 0) {
if (correctionAvailable && !typedWordValid && stringList.size() > 1) {
mBestWord = stringList.get(1);
} else {
mBestWord = typedWord;
}
} else {
mBestWord = null;
}
setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn);
}
private void pickDefaultSuggestion() {
// Complete any pending candidate query first
if (mHandler.hasMessages(MSG_UPDATE_SUGGESTIONS)) {
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
updateSuggestions();
}
if (mBestWord != null) {
TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord);
mJustAccepted = true;
pickSuggestion(mBestWord);
// Add the word to the auto dictionary if it's not a known word
checkAddToDictionary(mBestWord, AutoDictionary.FREQUENCY_FOR_TYPED);
}
}
public void pickSuggestionManually(int index, CharSequence suggestion) {
if (mAfterVoiceInput && mShowingVoiceSuggestions) mVoiceInput.logNBestChoose(index);
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mCompletionOn && mCompletions != null && index >= 0
&& index < mCompletions.length) {
CompletionInfo ci = mCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1 && isWordSeparator(suggestion.charAt(0))) {
onKey(suggestion.charAt(0), null);
if (ic != null) {
ic.endBatchEdit();
}
return;
}
mJustAccepted = true;
pickSuggestion(suggestion);
// Add the word to the auto dictionary if it's not a known word
checkAddToDictionary(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mAutoSpace) {
sendSpace();
mJustAddedAutoSpace = true;
}
// Fool the state watcher so that a subsequent backspace will not do a revert
TextEntryState.typedCharacter((char) KEYCODE_SPACE, true);
if (index == 0 && mCorrectionMode > 0 && !mSuggest.isValidWord(suggestion)) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
private void pickSuggestion(CharSequence suggestion) {
if (mCapsLock) {
suggestion = suggestion.toString().toUpperCase();
} else if (preferCapitalization()
|| (mKeyboardSwitcher.isAlphabetMode() && mInputView.isShifted())) {
suggestion = suggestion.toString().toUpperCase().charAt(0)
+ suggestion.subSequence(1, suggestion.length()).toString();
}
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
if (mSuggestionShouldReplaceCurrentWord) {
EditingUtil.deleteWordAtCursor(ic, getWordSeparators());
}
if (!VoiceInput.DELETE_SYMBOL.equals(suggestion)) {
ic.commitText(suggestion, 1);
}
}
mPredicting = false;
mCommittedLength = suggestion.length();
((LatinKeyboard) mInputView.getKeyboard()).setPreferredLetters(null);
setNextSuggestions();
updateShiftKeyState(getCurrentInputEditorInfo());
}
private void setNextSuggestions() {
setSuggestions(mSuggestPuncList, false, false, false);
}
private void checkAddToDictionary(CharSequence suggestion, int frequencyDelta) {
if (mAutoDictionary.isValidWord(suggestion)
|| !mSuggest.isValidWord(suggestion.toString().toLowerCase())) {
mAutoDictionary.addWord(suggestion.toString(), frequencyDelta);
}
}
private boolean isCursorTouchingWord() {
InputConnection ic = getCurrentInputConnection();
if (ic == null) return false;
CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
CharSequence toRight = ic.getTextAfterCursor(1, 0);
if (!TextUtils.isEmpty(toLeft)
&& !isWordSeparator(toLeft.charAt(0))) {
return true;
}
if (!TextUtils.isEmpty(toRight)
&& !isWordSeparator(toRight.charAt(0))) {
return true;
}
return false;
}
public void revertLastWord(boolean deleteChar) {
final int length = mComposing.length();
if (!mPredicting && length > 0) {
final InputConnection ic = getCurrentInputConnection();
mPredicting = true;
ic.beginBatchEdit();
mJustRevertedSeparator = ic.getTextBeforeCursor(1, 0);
if (deleteChar) ic.deleteSurroundingText(1, 0);
int toDelete = mCommittedLength;
CharSequence toTheLeft = ic.getTextBeforeCursor(mCommittedLength, 0);
if (toTheLeft != null && toTheLeft.length() > 0
&& isWordSeparator(toTheLeft.charAt(0))) {
toDelete--;
}
ic.deleteSurroundingText(toDelete, 0);
ic.setComposingText(mComposing, 1);
TextEntryState.backspace();
ic.endBatchEdit();
postUpdateSuggestions();
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
mJustRevertedSeparator = null;
}
}
protected String getWordSeparators() {
return mWordSeparators;
}
public boolean isWordSeparator(int code) {
String separators = getWordSeparators();
return separators.contains(String.valueOf((char)code));
}
public boolean isSentenceSeparator(int code) {
return mSentenceSeparators.contains(String.valueOf((char)code));
}
private void sendSpace() {
sendKeyChar((char)KEYCODE_SPACE);
updateShiftKeyState(getCurrentInputEditorInfo());
//onKey(KEY_SPACE[0], KEY_SPACE);
}
public boolean preferCapitalization() {
return mWord.isCapitalized();
}
public void swipeRight() {
if (userHasNotTypedRecently() && VOICE_INSTALLED && mEnableVoice &&
fieldCanDoVoice(makeFieldContext())) {
startListening(true /* was a swipe */);
}
if (LatinKeyboardView.DEBUG_AUTO_PLAY) {
ClipboardManager cm = ((ClipboardManager)getSystemService(CLIPBOARD_SERVICE));
CharSequence text = cm.getText();
if (!TextUtils.isEmpty(text)) {
mInputView.startPlaying(text.toString());
}
}
}
private void toggleLanguage(boolean reset, boolean next) {
if (reset) {
mLanguageSwitcher.reset();
} else {
if (next) {
mLanguageSwitcher.next();
} else {
mLanguageSwitcher.prev();
}
}
int currentKeyboardMode = mKeyboardSwitcher.getKeyboardMode();
reloadKeyboards();
mKeyboardSwitcher.makeKeyboards(true);
mKeyboardSwitcher.setKeyboardMode(currentKeyboardMode, 0,
mEnableVoiceButton && mEnableVoice);
initSuggest(mLanguageSwitcher.getInputLanguage());
mLanguageSwitcher.persist();
updateShiftKeyState(getCurrentInputEditorInfo());
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PREF_SELECTED_LANGUAGES.equals(key)) {
mLanguageSwitcher.loadLocales(sharedPreferences);
mRefreshKeyboardRequired = true;
}
}
public void swipeLeft() {
}
public void swipeDown() {
handleClose();
}
public void swipeUp() {
//launchSettings();
}
public void onPress(int primaryCode) {
vibrate();
playKeyClick(primaryCode);
}
public void onRelease(int primaryCode) {
// Reset any drag flags in the keyboard
((LatinKeyboard) mInputView.getKeyboard()).keyReleased();
//vibrate();
}
private FieldContext makeFieldContext() {
return new FieldContext(
getCurrentInputConnection(),
getCurrentInputEditorInfo(),
mLanguageSwitcher.getInputLanguage(),
mLanguageSwitcher.getEnabledLanguages());
}
private boolean fieldCanDoVoice(FieldContext fieldContext) {
return !mPasswordText
&& mVoiceInput != null
&& !mVoiceInput.isBlacklistedField(fieldContext);
}
private boolean shouldShowVoiceButton(FieldContext fieldContext, EditorInfo attribute) {
return ENABLE_VOICE_BUTTON && fieldCanDoVoice(fieldContext)
&& !(attribute != null && attribute.privateImeOptions != null
&& attribute.privateImeOptions.equals(IME_OPTION_NO_MICROPHONE))
&& RecognitionManager.isRecognitionAvailable(this);
}
// receive ringer mode changes to detect silent mode
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateRingerMode();
}
};
// update flags for silent mode
private void updateRingerMode() {
if (mAudioManager == null) {
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
if (mAudioManager != null) {
mSilentMode = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
}
}
private boolean userHasNotTypedRecently() {
return (SystemClock.uptimeMillis() - mLastKeyTime)
> MIN_MILLIS_AFTER_TYPING_BEFORE_SWIPE;
}
private void playKeyClick(int primaryCode) {
// if mAudioManager is null, we don't have the ringer state yet
// mAudioManager will be set by updateRingerMode
if (mAudioManager == null) {
if (mInputView != null) {
updateRingerMode();
}
}
if (mSoundOn && !mSilentMode) {
// FIXME: Volume and enable should come from UI settings
// FIXME: These should be triggered after auto-repeat logic
int sound = AudioManager.FX_KEYPRESS_STANDARD;
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
sound = AudioManager.FX_KEYPRESS_DELETE;
break;
case KEYCODE_ENTER:
sound = AudioManager.FX_KEYPRESS_RETURN;
break;
case KEYCODE_SPACE:
sound = AudioManager.FX_KEYPRESS_SPACEBAR;
break;
}
mAudioManager.playSoundEffect(sound, FX_VOLUME);
}
}
private void vibrate() {
if (!mVibrateOn) {
return;
}
if (mInputView != null) {
mInputView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
}
private void checkTutorial(String privateImeOptions) {
if (privateImeOptions == null) return;
if (privateImeOptions.equals("com.android.setupwizard:ShowTutorial")) {
if (mTutorial == null) startTutorial();
} else if (privateImeOptions.equals("com.android.setupwizard:HideTutorial")) {
if (mTutorial != null) {
if (mTutorial.close()) {
mTutorial = null;
}
}
}
}
private void startTutorial() {
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_START_TUTORIAL), 500);
}
void tutorialDone() {
mTutorial = null;
}
void promoteToUserDictionary(String word, int frequency) {
if (mUserDictionary.isValidWord(word)) return;
mUserDictionary.addWord(word, frequency);
}
WordComposer getCurrentWord() {
return mWord;
}
private void updateCorrectionMode() {
mHasDictionary = mSuggest != null ? mSuggest.hasMainDictionary() : false;
mAutoCorrectOn = (mAutoCorrectEnabled || mQuickFixes)
&& !mInputTypeNoAutoCorrect && mHasDictionary;
mCorrectionMode = (mAutoCorrectOn && mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL
: (mAutoCorrectOn ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE);
if (mSuggest != null) {
mSuggest.setCorrectionMode(mCorrectionMode);
}
}
private void updateAutoTextEnabled(Locale systemLocale) {
if (mSuggest == null) return;
boolean different = !systemLocale.getLanguage().equalsIgnoreCase(mLocale.substring(0, 2));
mSuggest.setAutoTextEnabled(!different && mQuickFixes);
}
protected void launchSettings() {
launchSettings(LatinIMESettings.class);
}
protected void launchSettings(Class settingsClass) {
handleClose();
Intent intent = new Intent();
intent.setClass(LatinIME.this, settingsClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void loadSettings() {
// Get the settings preferences
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
mVibrateOn = sp.getBoolean(PREF_VIBRATE_ON, false);
mSoundOn = sp.getBoolean(PREF_SOUND_ON, false);
mAutoCap = sp.getBoolean(PREF_AUTO_CAP, true);
mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true);
mHasUsedVoiceInput = sp.getBoolean(PREF_HAS_USED_VOICE_INPUT, false);
mHasUsedVoiceInputUnsupportedLocale =
sp.getBoolean(PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE, false);
// Get the current list of supported locales and check the current locale against that
// list. We cache this value so as not to check it every time the user starts a voice
// input. Because this method is called by onStartInputView, this should mean that as
// long as the locale doesn't change while the user is keeping the IME open, the
// value should never be stale.
String supportedLocalesString = SettingsUtil.getSettingsString(
getContentResolver(),
SettingsUtil.LATIN_IME_VOICE_INPUT_SUPPORTED_LOCALES,
DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES);
ArrayList<String> voiceInputSupportedLocales =
newArrayList(supportedLocalesString.split("\\s+"));
mLocaleSupportedForVoiceInput = voiceInputSupportedLocales.contains(mLocale);
mShowSuggestions = sp.getBoolean(PREF_SHOW_SUGGESTIONS, true);
if (VOICE_INSTALLED) {
final String voiceMode = sp.getString(PREF_VOICE_MODE,
getString(R.string.voice_mode_main));
boolean enableVoice = !voiceMode.equals(getString(R.string.voice_mode_off))
&& mEnableVoiceButton;
boolean voiceOnPrimary = voiceMode.equals(getString(R.string.voice_mode_main));
if (mKeyboardSwitcher != null &&
(enableVoice != mEnableVoice || voiceOnPrimary != mVoiceOnPrimary)) {
mKeyboardSwitcher.setVoiceMode(enableVoice, voiceOnPrimary);
}
mEnableVoice = enableVoice;
mVoiceOnPrimary = voiceOnPrimary;
}
mAutoCorrectEnabled = sp.getBoolean(PREF_AUTO_COMPLETE,
mResources.getBoolean(R.bool.enable_autocorrect)) & mShowSuggestions;
updateCorrectionMode();
updateAutoTextEnabled(mResources.getConfiguration().locale);
mLanguageSwitcher.loadLocales(sp);
}
private void initSuggestPuncList() {
mSuggestPuncList = new ArrayList<CharSequence>();
String suggestPuncs = mResources.getString(R.string.suggested_punctuations);
if (suggestPuncs != null) {
for (int i = 0; i < suggestPuncs.length(); i++) {
mSuggestPuncList.add(suggestPuncs.subSequence(i, i + 1));
}
}
}
private void showOptionsMenu() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_dialog_keyboard);
builder.setNegativeButton(android.R.string.cancel, null);
CharSequence itemSettings = getString(R.string.english_ime_settings);
CharSequence itemInputMethod = getString(R.string.inputMethod);
builder.setItems(new CharSequence[] {
itemSettings, itemInputMethod},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case POS_SETTINGS:
launchSettings();
break;
case POS_METHOD:
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.showInputMethodPicker();
break;
}
}
});
builder.setTitle(mResources.getString(R.string.english_ime_name));
mOptionsDialog = builder.create();
Window window = mOptionsDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mInputView.getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog.show();
}
private void changeKeyboardMode() {
mKeyboardSwitcher.toggleSymbols();
if (mCapsLock && mKeyboardSwitcher.isAlphabetMode()) {
((LatinKeyboard) mInputView.getKeyboard()).setShiftLocked(mCapsLock);
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
@Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
super.dump(fd, fout, args);
final Printer p = new PrintWriterPrinter(fout);
p.println("LatinIME state :");
p.println(" Keyboard mode = " + mKeyboardSwitcher.getKeyboardMode());
p.println(" mCapsLock=" + mCapsLock);
p.println(" mComposing=" + mComposing.toString());
p.println(" mPredictionOn=" + mPredictionOn);
p.println(" mCorrectionMode=" + mCorrectionMode);
p.println(" mPredicting=" + mPredicting);
p.println(" mAutoCorrectOn=" + mAutoCorrectOn);
p.println(" mAutoSpace=" + mAutoSpace);
p.println(" mCompletionOn=" + mCompletionOn);
p.println(" TextEntryState.state=" + TextEntryState.getState());
p.println(" mSoundOn=" + mSoundOn);
p.println(" mVibrateOn=" + mVibrateOn);
}
// Characters per second measurement
private static final boolean PERF_DEBUG = false;
private long mLastCpsTime;
private static final int CPS_BUFFER_SIZE = 16;
private long[] mCpsIntervals = new long[CPS_BUFFER_SIZE];
private int mCpsIndex;
private boolean mInputTypeNoAutoCorrect;
private void measureCps() {
if (!LatinIME.PERF_DEBUG) return;
long now = System.currentTimeMillis();
if (mLastCpsTime == 0) mLastCpsTime = now - 100; // Initial
mCpsIntervals[mCpsIndex] = now - mLastCpsTime;
mLastCpsTime = now;
mCpsIndex = (mCpsIndex + 1) % CPS_BUFFER_SIZE;
long total = 0;
for (int i = 0; i < CPS_BUFFER_SIZE; i++) total += mCpsIntervals[i];
System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total));
}
}
| true | true | public void onStartInputView(EditorInfo attribute, boolean restarting) {
// In landscape mode, this method gets called without the input view being created.
if (mInputView == null) {
return;
}
if (mRefreshKeyboardRequired) {
mRefreshKeyboardRequired = false;
toggleLanguage(true, true);
}
mKeyboardSwitcher.makeKeyboards(false);
TextEntryState.newSession(this);
// Most such things we decide below in the switch statement, but we need to know
// now whether this is a password text field, because we need to know now (before
// the switch statement) whether we want to enable the voice button.
mPasswordText = false;
int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION;
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
mPasswordText = true;
}
mEnableVoiceButton = shouldShowVoiceButton(makeFieldContext(), attribute);
final boolean enableVoiceButton = mEnableVoiceButton && mEnableVoice;
mAfterVoiceInput = false;
mImmediatelyAfterVoiceInput = false;
mShowingVoiceSuggestions = false;
mImmediatelyAfterVoiceSuggestions = false;
mVoiceInputHighlighted = false;
mWordToSuggestions.clear();
mInputTypeNoAutoCorrect = false;
mPredictionOn = false;
mCompletionOn = false;
mCompletions = null;
mCapsLock = false;
mEmailText = false;
switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) {
case EditorInfo.TYPE_CLASS_NUMBER:
case EditorInfo.TYPE_CLASS_DATETIME:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_SYMBOLS,
attribute.imeOptions, enableVoiceButton);
break;
case EditorInfo.TYPE_CLASS_PHONE:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE,
attribute.imeOptions, enableVoiceButton);
break;
case EditorInfo.TYPE_CLASS_TEXT:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
//startPrediction();
mPredictionOn = true;
// Make sure that passwords are not displayed in candidate view
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ) {
mPredictionOn = false;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mEmailText = true;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
|| variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME) {
mAutoSpace = false;
} else {
mAutoSpace = true;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) {
mPredictionOn = false;
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_WEB,
attribute.imeOptions, enableVoiceButton);
// If it's a browser edit field and auto correct is not ON explicitly, then
// disable auto correction, but keep suggestions on.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) {
mInputTypeNoAutoCorrect = true;
}
}
// If NO_SUGGESTIONS is set, don't do prediction.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) {
mPredictionOn = false;
mInputTypeNoAutoCorrect = true;
}
// If it's not multiline and the autoCorrect flag is not set, then don't correct
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0 &&
(attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) == 0) {
mInputTypeNoAutoCorrect = true;
}
if ((attribute.inputType&EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) {
mPredictionOn = false;
mCompletionOn = true && isFullscreenMode();
}
updateShiftKeyState(attribute);
break;
default:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
updateShiftKeyState(attribute);
}
mInputView.closing();
mComposing.setLength(0);
mPredicting = false;
mDeleteCount = 0;
mJustAddedAutoSpace = false;
loadSettings();
setCandidatesViewShown(false);
setSuggestions(null, false, false, false);
// If the dictionary is not big enough, don't auto correct
mHasDictionary = mSuggest.hasMainDictionary();
updateCorrectionMode();
mInputView.setProximityCorrectionEnabled(true);
mPredictionOn = mPredictionOn && (mCorrectionMode > 0 || mShowSuggestions);
checkTutorial(attribute.privateImeOptions);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
| public void onStartInputView(EditorInfo attribute, boolean restarting) {
// In landscape mode, this method gets called without the input view being created.
if (mInputView == null) {
return;
}
if (mRefreshKeyboardRequired) {
mRefreshKeyboardRequired = false;
toggleLanguage(true, true);
}
mKeyboardSwitcher.makeKeyboards(false);
TextEntryState.newSession(this);
// Most such things we decide below in the switch statement, but we need to know
// now whether this is a password text field, because we need to know now (before
// the switch statement) whether we want to enable the voice button.
mPasswordText = false;
int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION;
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
mPasswordText = true;
}
mEnableVoiceButton = shouldShowVoiceButton(makeFieldContext(), attribute);
final boolean enableVoiceButton = mEnableVoiceButton && mEnableVoice;
mAfterVoiceInput = false;
mImmediatelyAfterVoiceInput = false;
mShowingVoiceSuggestions = false;
mImmediatelyAfterVoiceSuggestions = false;
mVoiceInputHighlighted = false;
mWordToSuggestions.clear();
mInputTypeNoAutoCorrect = false;
mPredictionOn = false;
mCompletionOn = false;
mCompletions = null;
mCapsLock = false;
mEmailText = false;
switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) {
case EditorInfo.TYPE_CLASS_NUMBER:
case EditorInfo.TYPE_CLASS_DATETIME:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_SYMBOLS,
attribute.imeOptions, enableVoiceButton);
break;
case EditorInfo.TYPE_CLASS_PHONE:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE,
attribute.imeOptions, enableVoiceButton);
break;
case EditorInfo.TYPE_CLASS_TEXT:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
//startPrediction();
mPredictionOn = true;
// Make sure that passwords are not displayed in candidate view
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ) {
mPredictionOn = false;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mEmailText = true;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
|| variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME) {
mAutoSpace = false;
} else {
mAutoSpace = true;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) {
mPredictionOn = false;
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_WEB,
attribute.imeOptions, enableVoiceButton);
// If it's a browser edit field and auto correct is not ON explicitly, then
// disable auto correction, but keep suggestions on.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) {
mInputTypeNoAutoCorrect = true;
}
}
// If NO_SUGGESTIONS is set, don't do prediction.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) {
mPredictionOn = false;
mInputTypeNoAutoCorrect = true;
}
// If it's not multiline and the autoCorrect flag is not set, then don't correct
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0 &&
(attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) == 0) {
mInputTypeNoAutoCorrect = true;
}
if ((attribute.inputType&EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) {
mPredictionOn = false;
mCompletionOn = true && isFullscreenMode();
}
updateShiftKeyState(attribute);
break;
default:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
updateShiftKeyState(attribute);
}
mInputView.closing();
mComposing.setLength(0);
mPredicting = false;
mDeleteCount = 0;
mJustAddedAutoSpace = false;
loadSettings();
updateShiftKeyState(attribute);
setCandidatesViewShown(false);
setSuggestions(null, false, false, false);
// If the dictionary is not big enough, don't auto correct
mHasDictionary = mSuggest.hasMainDictionary();
updateCorrectionMode();
mInputView.setProximityCorrectionEnabled(true);
mPredictionOn = mPredictionOn && (mCorrectionMode > 0 || mShowSuggestions);
checkTutorial(attribute.privateImeOptions);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
|
diff --git a/src/be/ibridge/kettle/trans/step/addsequence/AddSequence.java b/src/be/ibridge/kettle/trans/step/addsequence/AddSequence.java
index 48d1c9e8..8f4253cf 100644
--- a/src/be/ibridge/kettle/trans/step/addsequence/AddSequence.java
+++ b/src/be/ibridge/kettle/trans/step/addsequence/AddSequence.java
@@ -1,219 +1,218 @@
/**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.trans.step.addsequence;
import java.util.Hashtable;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Adds a sequential number to a stream of rows.
*
* @author Matt
* @since 13-mei-2003
*/
public class AddSequence extends BaseStep implements StepInterface
{
private AddSequenceMeta meta;
private AddSequenceData data;
public AddSequence(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
- public synchronized boolean addSequence(Row row)
- throws KettleException
+ public boolean addSequence(Row row) throws KettleException
{
Value next = null;
if (meta.isDatabaseUsed())
{
try
{
next = data.getDb().getNextSequenceValue(meta.getSequenceName(), meta.getValuename());
}
catch(KettleDatabaseException dbe)
{
throw new KettleStepException(Messages.getString("AddSequence.Exception.ErrorReadingSequence",meta.getSequenceName()), dbe); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else
if (meta.isCounterUsed())
{
Long prev = (Long)getTransMeta().getCounters().get(data.getLookup());
//System.out.println("Found prev value: "+prev.longValue()+", increment_by = "+info.increment_by+", max_value = "+info.max_value);
long nval = prev.longValue() + meta.getIncrementBy();
if (meta.getIncrementBy()>0 && nval>meta.getMaxValue()) nval=meta.getStartAt();
if (meta.getIncrementBy()<0 && nval<meta.getMaxValue()) nval=meta.getStartAt();
getTransMeta().getCounters().put(data.getLookup(), new Long(nval));
next = new Value(meta.getValuename(), prev.longValue());
//System.out.println("Next value: "+next);
}
else
{
// This should never happen, but if it does, don't continue!!!
throw new KettleStepException(Messages.getString("AddSequence.Exception.NoSpecifiedMethod")); //$NON-NLS-1$
}
if (next!=null)
{
row.addValue(next);
}
else
{
throw new KettleStepException(Messages.getString("AddSequence.Exception.CouldNotFindNextValueForSequence")+meta.getValuename()); //$NON-NLS-1$
}
return true;
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(AddSequenceMeta)smi;
data=(AddSequenceData)sdi;
Row r=null;
r=getRow(); // Get row from input rowset & set row busy!
if (r==null) // no more input to be expected...
{
setOutputDone();
return false;
}
if (log.isRowLevel()) log.logRowlevel(toString(), Messages.getString("AddSequence.Log.ReadRow")+linesRead+" : "+r); //$NON-NLS-1$ //$NON-NLS-2$
try
{
addSequence(r); // add new values to the row in rowset[0].
putRow(r); // copy row to output rowset(s);
if (log.isRowLevel()) log.logRowlevel(toString(), Messages.getString("AddSequence.Log.WriteRow")+linesWritten+" : "+r); //$NON-NLS-1$ //$NON-NLS-2$
if ((linesRead>0) && (linesRead>0) && (linesRead%Const.ROWS_UPDATE)==0) logBasic(Messages.getString("AddSequence.Log.LineNumber")+linesRead); //$NON-NLS-1$
}
catch(KettleException e)
{
logError(Messages.getString("AddSequence.Log.ErrorInStep")+e.getMessage()); //$NON-NLS-1$
setErrors(1);
stopAll();
setOutputDone(); // signal end to receiver(s)
return false;
}
return true;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(AddSequenceMeta)smi;
data=(AddSequenceData)sdi;
if (super.init(smi, sdi))
{
if (meta.isDatabaseUsed())
{
data.setDb( new Database(meta.getDatabase()) );
try
{
data.getDb().connect();
logBasic(Messages.getString("AddSequence.Log.ConnectedDB")); //$NON-NLS-1$
return true;
}
catch(KettleDatabaseException dbe)
{
logError(Messages.getString("AddSequence.Log.CouldNotConnectToDB")+dbe.getMessage()); //$NON-NLS-1$
}
}
else
if (meta.isCounterUsed())
{
data.setLookup( "@@sequence:"+meta.getValuename() ); //$NON-NLS-1$
if (getTransMeta().getCounters()!=null)
{
Hashtable counters = getTransMeta().getCounters();
counters.put(data.getLookup(), new Long(meta.getStartAt()));
return true;
}
else
{
logError(Messages.getString("AddSequence.Log.TransformationCountersHashtableNotAllocated")); //$NON-NLS-1$
}
}
else
{
logError(Messages.getString("AddSequence.Log.NeedToSelectSequence")); //$NON-NLS-1$
}
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta = (AddSequenceMeta)smi;
data = (AddSequenceData)sdi;
if (meta.isDatabaseUsed())
{
data.getDb().disconnect();
}
super.dispose(smi, sdi);
}
//
// Run is were the action happens!
//
public void run()
{
try
{
logBasic(Messages.getString("AddSequence.Log.StartingToRun")); //$NON-NLS-1$
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError(Messages.getString("AddSequence.Log.UnexpectedError")+" : "+e.toString()); //$NON-NLS-1$ //$NON-NLS-2$
logError(Const.getStackTracker(e));
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
markStop();
logSummary();
}
}
}
| true | true | public synchronized boolean addSequence(Row row)
throws KettleException
{
Value next = null;
if (meta.isDatabaseUsed())
{
try
{
next = data.getDb().getNextSequenceValue(meta.getSequenceName(), meta.getValuename());
}
catch(KettleDatabaseException dbe)
{
throw new KettleStepException(Messages.getString("AddSequence.Exception.ErrorReadingSequence",meta.getSequenceName()), dbe); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else
if (meta.isCounterUsed())
{
Long prev = (Long)getTransMeta().getCounters().get(data.getLookup());
//System.out.println("Found prev value: "+prev.longValue()+", increment_by = "+info.increment_by+", max_value = "+info.max_value);
long nval = prev.longValue() + meta.getIncrementBy();
if (meta.getIncrementBy()>0 && nval>meta.getMaxValue()) nval=meta.getStartAt();
if (meta.getIncrementBy()<0 && nval<meta.getMaxValue()) nval=meta.getStartAt();
getTransMeta().getCounters().put(data.getLookup(), new Long(nval));
next = new Value(meta.getValuename(), prev.longValue());
//System.out.println("Next value: "+next);
}
else
{
// This should never happen, but if it does, don't continue!!!
throw new KettleStepException(Messages.getString("AddSequence.Exception.NoSpecifiedMethod")); //$NON-NLS-1$
}
if (next!=null)
{
row.addValue(next);
}
else
{
throw new KettleStepException(Messages.getString("AddSequence.Exception.CouldNotFindNextValueForSequence")+meta.getValuename()); //$NON-NLS-1$
}
return true;
}
| public boolean addSequence(Row row) throws KettleException
{
Value next = null;
if (meta.isDatabaseUsed())
{
try
{
next = data.getDb().getNextSequenceValue(meta.getSequenceName(), meta.getValuename());
}
catch(KettleDatabaseException dbe)
{
throw new KettleStepException(Messages.getString("AddSequence.Exception.ErrorReadingSequence",meta.getSequenceName()), dbe); //$NON-NLS-1$ //$NON-NLS-2$
}
}
else
if (meta.isCounterUsed())
{
Long prev = (Long)getTransMeta().getCounters().get(data.getLookup());
//System.out.println("Found prev value: "+prev.longValue()+", increment_by = "+info.increment_by+", max_value = "+info.max_value);
long nval = prev.longValue() + meta.getIncrementBy();
if (meta.getIncrementBy()>0 && nval>meta.getMaxValue()) nval=meta.getStartAt();
if (meta.getIncrementBy()<0 && nval<meta.getMaxValue()) nval=meta.getStartAt();
getTransMeta().getCounters().put(data.getLookup(), new Long(nval));
next = new Value(meta.getValuename(), prev.longValue());
//System.out.println("Next value: "+next);
}
else
{
// This should never happen, but if it does, don't continue!!!
throw new KettleStepException(Messages.getString("AddSequence.Exception.NoSpecifiedMethod")); //$NON-NLS-1$
}
if (next!=null)
{
row.addValue(next);
}
else
{
throw new KettleStepException(Messages.getString("AddSequence.Exception.CouldNotFindNextValueForSequence")+meta.getValuename()); //$NON-NLS-1$
}
return true;
}
|
diff --git a/Swirc/src/swirc/SwircController.java b/Swirc/src/swirc/SwircController.java
index 3078fd7..5c7645a 100644
--- a/Swirc/src/swirc/SwircController.java
+++ b/Swirc/src/swirc/SwircController.java
@@ -1,132 +1,134 @@
package swirc;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
/**
* Controller class for Swirc MVC-model. Implements ActionListener and Observer
* interfaces.
* @author Janne Kallunki, Ville Hämäläinen, Jaakko Ritvanen
*/
public class SwircController implements ActionListener, Observer {
private SwircModel model;
private SwircView view;
/**
* Constructer.
* @param model Model object of Swircs MVC-model
* @param view View object of Swircs MVC-model
*/
public SwircController(SwircModel model, SwircView view) {
this.model = model;
this.view = view;
}
/**
* Invoked when an action occurs.
* @param e ActionEvent
*/
@Override
public void actionPerformed(ActionEvent e) {
String code = e.getActionCommand();
if(code.equals("connectServer")) {
HashMap<String,String> con = view.connectPrompt();
- if(con != null && !con.get("serverAddress").equals("") && !con.get("nick").equals("")) {
- this.view.addServerView(con.get("serverAddress"));
- this.model.connect(con.get("serverAddress"), con.get("nick"), con.get("port"), con.get("pasword"));
- }
- else {
- view.showWarning("Your server address or nick was empty!");
+ if(con != null) {
+ if(!con.get("serverAddress").equals("") && !con.get("nick").equals("")) {
+ this.view.addServerView(con.get("serverAddress"));
+ this.model.connect(con.get("serverAddress"), con.get("nick"), con.get("port"), con.get("pasword"));
+ }
+ else {
+ view.showWarning("Your server address or nick was empty!");
+ }
}
}
else if(code.equals("disconnect")) {
this.model.disconnect();
}
else if(code.equals("reconnect")) {
this.model.reconnect();
}
else if(code.equals("join")) {
HashMap<String, String> join = view.joinPrompt();
if(join != null) {
model.joinChannel(join.get("channel"), Integer.parseInt(join.get("server")));
}
}
else if(code.equals("leave")) {
String channel = view.getActiveChannel();
if(channel.startsWith("#")) {
model.leaveChannel(channel);
}
}
else if(code.equals("quit")) {
System.exit(0);
}
else if(code.equals("userData")) {
HashMap<String, String> saveUser = view.userPrompt();
if(saveUser != null) {
this.model.setUserData(saveUser);
this.model.saveUserData();
}
}
else if(code.equals("send")) {
String msg = view.getInput();
String channel = view.getActiveChannel();
if(!msg.isEmpty() && channel.startsWith("#")) {
model.sendMsg(msg, channel);
}
view.resetInput();
}
}
/**
* This method is called whenever the observed object is changed.
* @param o The observable object.
* @param arg An argument passed to the notifyObservers method.
*/
@Override
public void update(Observable o, Object arg) {
String code = arg.toString();
//System.out.println(code);
if(code.startsWith("ConnectedServer")) {
this.view.setJoinEnabled();
this.view.setReconnectEnabled();
this.view.setDisconnectEnabled();
}
else if(code.equals("disconnect")) {
this.view.closeAllTabs();
this.view.setJoinUnenabled();
this.view.setLeaveUnenabled();
this.view.setDisconnectUnenabled();
}
else if(code.equals("reconnect")) {
String[] servers = this.model.getConnectedServers();
if(servers != null) {
for(int i = 0; i < servers.length; i++) {
this.view.addServerView(servers[i]);
}
}
}
else if(code.equals("join")) {
this.view.setLeaveEnabled();
}
else if(code.equals("leave")) {
this.view.closeTab();
if(this.view.getTabCount() < 2) {
this.view.setLeaveUnenabled();
}
}
else if(code.equals("cant connect")) {
this.view.showWarning("Can't connect server!");
}
else if(code.equals("cant join")) {
this.view.showWarning("Can't join channel!");
}
else if(code.equals("userDataError")) {
this.view.showWarning("There were empty fields in userdata!");
}
else if(code.equals("userDataDublicate")) {
this.view.showWarning("Some of your userdata was wrong!");
}
}
}
| true | true | public void actionPerformed(ActionEvent e) {
String code = e.getActionCommand();
if(code.equals("connectServer")) {
HashMap<String,String> con = view.connectPrompt();
if(con != null && !con.get("serverAddress").equals("") && !con.get("nick").equals("")) {
this.view.addServerView(con.get("serverAddress"));
this.model.connect(con.get("serverAddress"), con.get("nick"), con.get("port"), con.get("pasword"));
}
else {
view.showWarning("Your server address or nick was empty!");
}
}
else if(code.equals("disconnect")) {
this.model.disconnect();
}
else if(code.equals("reconnect")) {
this.model.reconnect();
}
else if(code.equals("join")) {
HashMap<String, String> join = view.joinPrompt();
if(join != null) {
model.joinChannel(join.get("channel"), Integer.parseInt(join.get("server")));
}
}
else if(code.equals("leave")) {
String channel = view.getActiveChannel();
if(channel.startsWith("#")) {
model.leaveChannel(channel);
}
}
else if(code.equals("quit")) {
System.exit(0);
}
else if(code.equals("userData")) {
HashMap<String, String> saveUser = view.userPrompt();
if(saveUser != null) {
this.model.setUserData(saveUser);
this.model.saveUserData();
}
}
else if(code.equals("send")) {
String msg = view.getInput();
String channel = view.getActiveChannel();
if(!msg.isEmpty() && channel.startsWith("#")) {
model.sendMsg(msg, channel);
}
view.resetInput();
}
}
| public void actionPerformed(ActionEvent e) {
String code = e.getActionCommand();
if(code.equals("connectServer")) {
HashMap<String,String> con = view.connectPrompt();
if(con != null) {
if(!con.get("serverAddress").equals("") && !con.get("nick").equals("")) {
this.view.addServerView(con.get("serverAddress"));
this.model.connect(con.get("serverAddress"), con.get("nick"), con.get("port"), con.get("pasword"));
}
else {
view.showWarning("Your server address or nick was empty!");
}
}
}
else if(code.equals("disconnect")) {
this.model.disconnect();
}
else if(code.equals("reconnect")) {
this.model.reconnect();
}
else if(code.equals("join")) {
HashMap<String, String> join = view.joinPrompt();
if(join != null) {
model.joinChannel(join.get("channel"), Integer.parseInt(join.get("server")));
}
}
else if(code.equals("leave")) {
String channel = view.getActiveChannel();
if(channel.startsWith("#")) {
model.leaveChannel(channel);
}
}
else if(code.equals("quit")) {
System.exit(0);
}
else if(code.equals("userData")) {
HashMap<String, String> saveUser = view.userPrompt();
if(saveUser != null) {
this.model.setUserData(saveUser);
this.model.saveUserData();
}
}
else if(code.equals("send")) {
String msg = view.getInput();
String channel = view.getActiveChannel();
if(!msg.isEmpty() && channel.startsWith("#")) {
model.sendMsg(msg, channel);
}
view.resetInput();
}
}
|
diff --git a/src/com/itmill/toolkit/ui/ExpandLayout.java b/src/com/itmill/toolkit/ui/ExpandLayout.java
index 7530d7c24..439f6cbba 100644
--- a/src/com/itmill/toolkit/ui/ExpandLayout.java
+++ b/src/com/itmill/toolkit/ui/ExpandLayout.java
@@ -1,50 +1,54 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.ui;
/**
* A layout that will give one of it's components as much space as possible,
* while still showing the other components in the layout. The other components
* will in effect be given a fixed sized space, while the space given to the
* expanded component will grow/shrink to fill the rest of the space available -
* for instance when re-sizing the window.
*
* Note that this layout is 100% in both directions by default ({link
* {@link #setSizeFull()}). Remember to set the units if you want to specify a
* fixed size. If the layout fails to show up, check that the parent layout is
* actually giving some space.
*
* @deprecated Deprecated in favor of new OrderedLayout
*/
@Deprecated
public class ExpandLayout extends OrderedLayout {
private Component expanded = null;
public ExpandLayout() {
this(ORIENTATION_VERTICAL);
}
public ExpandLayout(int orientation) {
super(orientation);
setSizeFull();
}
/**
* @param c
* Component which container will be maximized
*/
public void expand(Component c) {
if (expanded != null) {
- setExpandRatio(expanded, 0.0f);
+ try {
+ setExpandRatio(expanded, 0.0f);
+ } catch (IllegalArgumentException e) {
+ // Ignore error if component has been removed
+ }
}
expanded = c;
setExpandRatio(expanded, 1.0f);
requestRepaint();
}
}
| true | true | public void expand(Component c) {
if (expanded != null) {
setExpandRatio(expanded, 0.0f);
}
expanded = c;
setExpandRatio(expanded, 1.0f);
requestRepaint();
}
| public void expand(Component c) {
if (expanded != null) {
try {
setExpandRatio(expanded, 0.0f);
} catch (IllegalArgumentException e) {
// Ignore error if component has been removed
}
}
expanded = c;
setExpandRatio(expanded, 1.0f);
requestRepaint();
}
|
diff --git a/jgnash-core/src/main/java/jgnash/engine/jpa/JpaTrashDAO.java b/jgnash-core/src/main/java/jgnash/engine/jpa/JpaTrashDAO.java
index 3fdb87f3..5b0e6379 100644
--- a/jgnash-core/src/main/java/jgnash/engine/jpa/JpaTrashDAO.java
+++ b/jgnash-core/src/main/java/jgnash/engine/jpa/JpaTrashDAO.java
@@ -1,101 +1,101 @@
/*
* jGnash, a personal finance application
* Copyright (C) 2001-2013 Craig Cavanaugh
*
* 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 jgnash.engine.jpa;
import jgnash.engine.StoredObject;
import jgnash.engine.TrashObject;
import jgnash.engine.dao.TrashDAO;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
/**
* Trash DAO
*
* @author Craig Cavanaugh
*/
class JpaTrashDAO extends AbstractJpaDAO implements TrashDAO {
private static final Logger logger = Logger.getLogger(JpaTrashDAO.class.getName());
JpaTrashDAO(final EntityManager entityManager, final boolean isRemote) {
super(entityManager, isRemote);
}
@Override
public List<TrashObject> getTrashObjects() {
try {
emLock.lock();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<TrashObject> cq = cb.createQuery(TrashObject.class);
Root<TrashObject> root = cq.from(TrashObject.class);
cq.select(root);
TypedQuery<TrashObject> q = em.createQuery(cq);
return new ArrayList<>(q.getResultList());
} finally {
emLock.unlock();
}
}
@Override
public void add(final TrashObject trashObject) {
try {
emLock.lock();
em.getTransaction().begin();
em.persist(trashObject.getObject());
em.persist(trashObject);
em.getTransaction().commit();
} finally {
emLock.unlock();
}
}
@Override
public void remove(final TrashObject trashObject) {
try {
emLock.lock();
em.getTransaction().begin();
- StoredObject object = getObjectByUuid(trashObject.getUuid());
+ StoredObject object = trashObject.getObject();
em.remove(object);
em.remove(trashObject);
em.getTransaction().commit();
logger.info("Removed TrashObject");
} finally {
emLock.unlock();
}
}
}
| true | true | public void remove(final TrashObject trashObject) {
try {
emLock.lock();
em.getTransaction().begin();
StoredObject object = getObjectByUuid(trashObject.getUuid());
em.remove(object);
em.remove(trashObject);
em.getTransaction().commit();
logger.info("Removed TrashObject");
} finally {
emLock.unlock();
}
}
| public void remove(final TrashObject trashObject) {
try {
emLock.lock();
em.getTransaction().begin();
StoredObject object = trashObject.getObject();
em.remove(object);
em.remove(trashObject);
em.getTransaction().commit();
logger.info("Removed TrashObject");
} finally {
emLock.unlock();
}
}
|
diff --git a/src/frontend/org/voltdb/SnapshotSaveAPI.java b/src/frontend/org/voltdb/SnapshotSaveAPI.java
index 5fe265949..daf04ddcd 100644
--- a/src/frontend/org/voltdb/SnapshotSaveAPI.java
+++ b/src/frontend/org/voltdb/SnapshotSaveAPI.java
@@ -1,813 +1,813 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* VoltDB 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.
*
* VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.KeeperException.NodeExistsException;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.apache.zookeeper_voltpatches.data.Stat;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.json_voltpatches.JSONStringer;
import org.voltcore.logging.VoltLogger;
import org.voltcore.utils.CoreUtils;
import org.voltcore.zk.ZKUtil;
import org.voltdb.catalog.Table;
import org.voltdb.dtxn.SiteTracker;
import org.voltdb.iv2.TxnEgo;
import org.voltdb.rejoin.StreamSnapshotDataTarget;
import org.voltdb.sysprocs.SnapshotRegistry;
import org.voltdb.sysprocs.SnapshotSave;
import org.voltdb.sysprocs.saverestore.SnapshotUtil;
import org.voltdb.utils.CatalogUtil;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
/**
* SnapshotSaveAPI extracts reusuable snapshot production code
* that can be called from the SnapshotSave stored procedure or
* directly from an ExecutionSite thread, perhaps has a message
* or failure action.
*/
public class SnapshotSaveAPI
{
private static final VoltLogger TRACE_LOG = new VoltLogger(SnapshotSaveAPI.class.getName());
private static final VoltLogger HOST_LOG = new VoltLogger("HOST");
// ugh, ick, ugh
public static final AtomicInteger recoveringSiteCount = new AtomicInteger(0);
/**
* The only public method: do all the work to start a snapshot.
* Assumes that a snapshot is feasible, that the caller has validated it can
* be accomplished, that the caller knows this is a consistent or useful
* transaction point at which to snapshot.
*
* @param file_path
* @param file_nonce
* @param format
* @param block
* @param txnId
* @param data
* @param context
* @param hostname
* @return VoltTable describing the results of the snapshot attempt
*/
public VoltTable startSnapshotting(
String file_path, String file_nonce, SnapshotFormat format, byte block,
long multiPartTxnId, long partitionTxnId, long legacyPerPartitionTxnIds[],
String data, SystemProcedureExecutionContext context, String hostname)
{
TRACE_LOG.trace("Creating snapshot target and handing to EEs");
final VoltTable result = SnapshotSave.constructNodeResultsTable();
final int numLocalSites = (context.getSiteTrackerForSnapshot().getLocalSites().length -
recoveringSiteCount.get());
// One site wins the race to create the snapshot targets, populating
// m_taskListsForSites for the other sites and creating an appropriate
// number of snapshot permits.
synchronized (SnapshotSiteProcessor.m_snapshotCreateLock) {
// First time use lazy initialization (need to calculate numLocalSites.
if (SnapshotSiteProcessor.m_snapshotCreateSetupPermit == null) {
SnapshotSiteProcessor.m_snapshotCreateSetupPermit = new Semaphore(numLocalSites);
}
try {
//From within this EE, record the sequence numbers as of the start of the snapshot (now)
//so that the info can be put in the digest.
SnapshotSiteProcessor.populateExportSequenceNumbersForExecutionSite(context);
SnapshotSiteProcessor.m_snapshotCreateSetupPermit.acquire();
if (VoltDB.instance().isIV2Enabled()) {
SnapshotSiteProcessor.m_partitionLastSeenTransactionIds.add(partitionTxnId);
}
} catch (InterruptedException e) {
result.addRow(
context.getHostId(),
hostname,
"",
"FAILURE",
e.toString());
return result;
}
if (SnapshotSiteProcessor.m_snapshotCreateSetupPermit.availablePermits() == 0) {
List<Long> partitionTransactionIds = new ArrayList<Long>();
if (VoltDB.instance().isIV2Enabled()) {
partitionTransactionIds = SnapshotSiteProcessor.m_partitionLastSeenTransactionIds;
SnapshotSiteProcessor.m_partitionLastSeenTransactionIds = new ArrayList<Long>();
partitionTransactionIds.add(multiPartTxnId);
/*
* Do a quick sanity check that the provided IDs
* don't conflict with currently active partitions. If they do
* it isn't fatal we can just skip it.
*/
for (long txnId : legacyPerPartitionTxnIds) {
final int legacyPartition = (int)TxnEgo.getPartitionId(txnId);
boolean isDup = false;
for (long existingId : partitionTransactionIds) {
final int existingPartition = (int)TxnEgo.getPartitionId(existingId);
if (existingPartition == legacyPartition) {
HOST_LOG.warn("While saving a snapshot and propagating legacy " +
"transaction ids found an id that matches currently active partition" +
existingPartition);
isDup = true;
}
}
if (!isDup) {
partitionTransactionIds.add(txnId);
}
}
}
createSetup(
file_path,
file_nonce,
format,
multiPartTxnId,
partitionTransactionIds,
data,
context,
hostname,
result);
// release permits for the next setup, now that is one is complete
SnapshotSiteProcessor.m_snapshotCreateSetupPermit.release(numLocalSites);
}
}
// All sites wait for a permit to start their individual snapshot tasks
VoltTable error = acquireSnapshotPermit(context, hostname, result);
if (error != null) {
return error;
}
synchronized (SnapshotSiteProcessor.m_taskListsForSites) {
final Deque<SnapshotTableTask> m_taskList = SnapshotSiteProcessor.m_taskListsForSites.poll();
if (m_taskList == null) {
return result;
} else {
assert(SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.get() > 0);
context.getSiteSnapshotConnection().initiateSnapshots(
m_taskList,
multiPartTxnId,
context.getSiteTrackerForSnapshot().getAllHosts().size());
}
}
if (block != 0) {
HashSet<Exception> failures = null;
String status = "SUCCESS";
String err = "";
try {
failures = context.getSiteSnapshotConnection().completeSnapshotWork();
} catch (InterruptedException e) {
status = "FAILURE";
err = e.toString();
failures = new HashSet<Exception>();
failures.add(e);
}
final VoltTable blockingResult = SnapshotSave.constructPartitionResultsTable();
if (failures.isEmpty()) {
blockingResult.addRow(
context.getHostId(),
hostname,
CoreUtils.getSiteIdFromHSId(context.getSiteId()),
status,
err);
} else {
status = "FAILURE";
for (Exception e : failures) {
err = e.toString();
}
blockingResult.addRow(
context.getHostId(),
hostname,
CoreUtils.getSiteIdFromHSId(context.getSiteId()),
status,
err);
}
return blockingResult;
}
return result;
}
private void logSnapshotStartToZK(long txnId,
SystemProcedureExecutionContext context, String nonce, String truncReqId) {
/*
* Going to send out the requests async to make snapshot init move faster
*/
ZKUtil.StringCallback cb1 = new ZKUtil.StringCallback();
/*
* Log that we are currently snapshotting this snapshot
*/
try {
//This node shouldn't already exist... should have been erased when the last snapshot finished
assert(VoltDB.instance().getHostMessenger().getZK().exists(
VoltZK.nodes_currently_snapshotting + "/" + VoltDB.instance().getHostMessenger().getHostId(), false)
== null);
ByteBuffer snapshotTxnId = ByteBuffer.allocate(8);
snapshotTxnId.putLong(txnId);
VoltDB.instance().getHostMessenger().getZK().create(
VoltZK.nodes_currently_snapshotting + "/" + VoltDB.instance().getHostMessenger().getHostId(),
snapshotTxnId.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, cb1, null);
} catch (NodeExistsException e) {
HOST_LOG.warn("Didn't expect the snapshot node to already exist", e);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
String nextTruncationNonce = null;
boolean isTruncation = false;
try {
final byte payloadBytes[] =
VoltDB.instance().getHostMessenger().getZK().getData(VoltZK.request_truncation_snapshot, false, null);
//request_truncation_snapshot data may be null when initially created. If that is the case
//then this snapshot is definitely not a truncation snapshot because
//the snapshot daemon hasn't gotten around to asking for a truncation snapshot
if (payloadBytes != null) {
ByteBuffer payload = ByteBuffer.wrap(payloadBytes);
nextTruncationNonce = Long.toString(payload.getLong());
}
} catch (KeeperException.NoNodeException e) {}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Getting the nonce should never fail with anything other than no node", true, e);
}
if (nextTruncationNonce == null) {
isTruncation = false;
} else {
if (nextTruncationNonce.equals(nonce)) {
isTruncation = true;
} else {
isTruncation = false;
}
}
/*
* Race with the others to create the place where will count down to completing the snapshot
*/
if (!createSnapshotCompletionNode(nonce, txnId, context.getHostId(), isTruncation, truncReqId)) {
// the node already exists, add local host ID to the list
increaseParticipateHostCount(txnId, context.getHostId());
}
try {
cb1.get();
} catch (NodeExistsException e) {
HOST_LOG.warn("Didn't expect the snapshot node to already exist", e);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
}
/**
* Add the host to the list of hosts participating in this snapshot.
*
* @param txnId The snapshot txnId
* @param hostId The host ID of the host that's calling this
*/
public static void increaseParticipateHostCount(long txnId, int hostId) {
ZooKeeper zk = VoltDB.instance().getHostMessenger().getZK();
final String snapshotPath = VoltZK.completed_snapshots + "/" + txnId;
boolean success = false;
while (!success) {
Stat stat = new Stat();
byte data[] = null;
try {
data = zk.getData(snapshotPath, false, stat);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("This ZK get should never fail", true, e);
}
if (data == null) {
VoltDB.crashLocalVoltDB("Data should not be null if the node exists", false, null);
}
try {
JSONObject jsonObj = new JSONObject(new String(data, "UTF-8"));
if (jsonObj.getLong("txnId") != txnId) {
VoltDB.crashLocalVoltDB("TxnId should match", false, null);
}
boolean hasLocalhost = false;
JSONArray hosts = jsonObj.getJSONArray("hosts");
for (int i = 0; i < hosts.length(); i++) {
if (hosts.getInt(i) == hostId) {
hasLocalhost = true;
break;
}
}
if (!hasLocalhost) {
hosts.put(hostId);
}
zk.setData(snapshotPath, jsonObj.toString(4).getBytes("UTF-8"), stat.getVersion());
} catch (KeeperException.BadVersionException e) {
continue;
} catch (Exception e) {
VoltDB.crashLocalVoltDB("This ZK call should never fail", true, e);
}
success = true;
}
}
/**
* Create the completion node for the snapshot identified by the txnId. It
* assumes that all hosts will race to call this, so it doesn't fail if the
* node already exists.
*
* @param nonce Nonce of the snapshot
* @param txnId
* @param hostId The local host ID
* @param isTruncation Whether or not this is a truncation snapshot
* @param truncReqId Optional unique ID fed back to the monitor for identification
* @return true if the node is created successfully, false if the node already exists.
*/
public static boolean createSnapshotCompletionNode(String nonce,
long txnId,
int hostId,
boolean isTruncation,
String truncReqId) {
if (!(txnId > 0)) {
VoltDB.crashGlobalVoltDB("Txnid must be greather than 0", true, null);
}
byte nodeBytes[] = null;
try {
JSONStringer stringer = new JSONStringer();
stringer.object();
stringer.key("txnId").value(txnId);
stringer.key("hosts").array().value(hostId).endArray();
stringer.key("isTruncation").value(isTruncation);
stringer.key("finishedHosts").value(0);
stringer.key("nonce").value(nonce);
stringer.key("truncReqId").value(truncReqId);
stringer.endObject();
JSONObject jsonObj = new JSONObject(stringer.toString());
nodeBytes = jsonObj.toString(4).getBytes("UTF-8");
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error serializing snapshot completion node JSON", true, e);
}
ZKUtil.StringCallback cb = new ZKUtil.StringCallback();
final String snapshotPath = VoltZK.completed_snapshots + "/" + txnId;
VoltDB.instance().getHostMessenger().getZK().create(
snapshotPath, nodeBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT,
cb, null);
try {
cb.get();
return true;
} catch (KeeperException.NodeExistsException e) {
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unexpected exception logging snapshot completion to ZK", true, e);
}
return false;
}
private void createSetup(
String file_path, String file_nonce, SnapshotFormat format,
long txnId, List<Long> partitionTransactionIds,
String data, SystemProcedureExecutionContext context,
String hostname, final VoltTable result) {
{
SiteTracker tracker = context.getSiteTrackerForSnapshot();
final int numLocalSites =
(tracker.getLocalSites().length - recoveringSiteCount.get());
// non-null if targeting only one site (used for rejoin)
// set later from the "data" JSON string
Long targetHSid = null;
JSONObject jsData = null;
- if (data != null) {
+ if (data != null && !data.isEmpty()) {
try {
jsData = new JSONObject(data);
}
catch (JSONException e) {
HOST_LOG.error(String.format("JSON exception on snapshot data \"%s\".", data),
e);
}
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
/*
* List of partitions to include if this snapshot is
* going to be deduped. Attempts to break up the work
* by seeding an RNG selecting
* a random replica to do the work. Will not work in failure
* cases, but we don't use dedupe when we want durability.
*
* Originally used the partition id as the seed, but it turns out
* that nextInt(2) returns a 1 for seeds 0-4095. Now use SHA-1
* on the txnid + partition id.
*/
List<Integer> partitionsToInclude = new ArrayList<Integer>();
List<Long> sitesToInclude = new ArrayList<Long>();
for (long localSite : tracker.getLocalSites()) {
final int partitionId = tracker.getPartitionForSite(localSite);
List<Long> sites =
new ArrayList<Long>(tracker.getSitesForPartition(tracker.getPartitionForSite(localSite)));
Collections.sort(sites);
digest.update(Longs.toByteArray(txnId));
final long seed = Longs.fromByteArray(Arrays.copyOf( digest.digest(Ints.toByteArray(partitionId)), 8));
int siteIndex = new java.util.Random(seed).nextInt(sites.size());
if (localSite == sites.get(siteIndex)) {
partitionsToInclude.add(partitionId);
sitesToInclude.add(localSite);
}
}
assert(partitionsToInclude.size() == sitesToInclude.size());
/*
* Used to close targets on failure
*/
final ArrayList<SnapshotDataTarget> targets = new ArrayList<SnapshotDataTarget>();
try {
final ArrayDeque<SnapshotTableTask> partitionedSnapshotTasks =
new ArrayDeque<SnapshotTableTask>();
final ArrayList<SnapshotTableTask> replicatedSnapshotTasks =
new ArrayList<SnapshotTableTask>();
assert(SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.get() == -1);
final List<Table> tables = SnapshotUtil.getTablesToSave(context.getDatabase());
if (format.isFileBased()) {
Runnable completionTask = SnapshotUtil.writeSnapshotDigest(
txnId,
context.getCatalogCRC(),
file_path,
file_nonce,
tables,
context.getHostId(),
SnapshotSiteProcessor.getExportSequenceNumbers(),
partitionTransactionIds,
VoltDB.instance().getHostMessenger().getInstanceId());
if (completionTask != null) {
SnapshotSiteProcessor.m_tasksOnSnapshotCompletion.offer(completionTask);
}
completionTask = SnapshotUtil.writeSnapshotCatalog(file_path, file_nonce);
if (completionTask != null) {
SnapshotSiteProcessor.m_tasksOnSnapshotCompletion.offer(completionTask);
}
}
final AtomicInteger numTables = new AtomicInteger(tables.size());
final SnapshotRegistry.Snapshot snapshotRecord =
SnapshotRegistry.startSnapshot(
txnId,
context.getHostId(),
file_path,
file_nonce,
format,
tables.toArray(new Table[0]));
SnapshotDataTarget sdt = null;
if (!format.isTableBased()) {
// table schemas for all the tables we'll snapshot on this partition
Map<Integer, byte[]> schemas = new HashMap<Integer, byte[]>();
for (final Table table : SnapshotUtil.getTablesToSave(context.getDatabase())) {
VoltTable schemaTable = CatalogUtil.getVoltTable(table);
schemas.put(table.getRelativeIndex(), schemaTable.getSchemaBytes());
}
if (format == SnapshotFormat.STREAM && jsData != null) {
long hsId = jsData.getLong("hsId");
// if a target_hsid exists, set it for filtering a snapshot for a specific site
try {
targetHSid = jsData.getLong("target_hsid");
}
catch (JSONException e) {} // leave value as null on exception
// if this snapshot targets a specific site...
if (targetHSid != null) {
// get the list of sites on this node
List<Long> localHSids = tracker.getSitesForHost(context.getHostId());
// if the target site is local to this node...
if (localHSids.contains(targetHSid)) {
sdt = new StreamSnapshotDataTarget(hsId, schemas);
}
else {
sdt = new DevNullSnapshotTarget();
}
}
}
}
for (final Table table : SnapshotUtil.getTablesToSave(context.getDatabase()))
{
/*
* For a deduped csv snapshot, only produce the replicated tables on the "leader"
* host.
*/
if (format == SnapshotFormat.CSV && table.getIsreplicated() && !tracker.isFirstHost()) {
snapshotRecord.removeTable(table.getTypeName());
continue;
}
String canSnapshot = "SUCCESS";
String err_msg = "";
File saveFilePath = null;
if (format.isFileBased()) {
saveFilePath = SnapshotUtil.constructFileForTable(
table,
file_path,
file_nonce,
format,
context.getHostId());
}
try {
if (format == SnapshotFormat.CSV) {
sdt = new SimpleFileSnapshotDataTarget(saveFilePath);
} else if (format == SnapshotFormat.NATIVE) {
sdt =
constructSnapshotDataTargetForTable(
context,
saveFilePath,
table,
context.getHostId(),
tracker.m_numberOfPartitions,
txnId);
}
if (sdt == null) {
throw new IOException("Unable to create snapshot target");
}
targets.add(sdt);
final SnapshotDataTarget sdtFinal = sdt;
final Runnable onClose = new Runnable() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
snapshotRecord.updateTable(table.getTypeName(),
new SnapshotRegistry.Snapshot.TableUpdater() {
@Override
public SnapshotRegistry.Snapshot.Table update(
SnapshotRegistry.Snapshot.Table registryTable) {
return snapshotRecord.new Table(
registryTable,
sdtFinal.getBytesWritten(),
sdtFinal.getLastWriteException());
}
});
int tablesLeft = numTables.decrementAndGet();
if (tablesLeft == 0) {
final SnapshotRegistry.Snapshot completed =
SnapshotRegistry.finishSnapshot(snapshotRecord);
final double duration =
(completed.timeFinished - org.voltdb.TransactionIdManager.getTimestampFromTransactionId(completed.txnId)) / 1000.0;
HOST_LOG.info(
"Snapshot " + snapshotRecord.nonce + " finished at " +
completed.timeFinished + " and took " + duration
+ " seconds ");
}
}
};
sdt.setOnCloseHandler(onClose);
List<SnapshotDataFilter> filters = new ArrayList<SnapshotDataFilter>();
if (format == SnapshotFormat.CSV) {
/*
* Don't need to do filtering on a replicated table.
*/
if (!table.getIsreplicated()) {
filters.add(
new PartitionProjectionSnapshotFilter(
Ints.toArray(partitionsToInclude),
0));
}
filters.add(new CSVSnapshotFilter(CatalogUtil.getVoltTable(table), ',', null));
}
// if this snapshot targets a specific site...
if (targetHSid != null) {
// get the list of sites on this node
List<Long> localHSids = tracker.getSitesForHost(context.getHostId());
// if the target site is local to this node...
if (localHSids.contains(targetHSid)) {
// ...get its partition id...
int partitionId = tracker.getPartitionForSite(targetHSid);
// ...and build a filter to only get that partition
filters.add(new PartitionProjectionSnapshotFilter(
new int[] { partitionId }, sdt.getHeaderSize()));
}
else {
// filter EVERYTHING because the site we want isn't local
filters.add(new PartitionProjectionSnapshotFilter(
new int[0], sdt.getHeaderSize()));
}
}
final SnapshotTableTask task =
new SnapshotTableTask(
table.getRelativeIndex(),
sdt,
filters.toArray(new SnapshotDataFilter[filters.size()]),
table.getIsreplicated(),
table.getTypeName());
if (table.getIsreplicated()) {
replicatedSnapshotTasks.add(task);
} else {
partitionedSnapshotTasks.offer(task);
}
} catch (IOException ex) {
/*
* Creation of this specific target failed. Close it if it was created.
* Continue attempting the snapshot anyways so that at least some of the data
* can be retrieved.
*/
try {
if (sdt != null) {
targets.remove(sdt);
sdt.close();
}
} catch (Exception e) {
HOST_LOG.error(e);
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
canSnapshot = "FAILURE";
err_msg = "SNAPSHOT INITIATION OF " + file_nonce +
"RESULTED IN IOException: \n" + sw.toString();
}
result.addRow(context.getHostId(),
hostname,
table.getTypeName(),
canSnapshot,
err_msg);
}
synchronized (SnapshotSiteProcessor.m_taskListsForSites) {
boolean aborted = false;
if (!partitionedSnapshotTasks.isEmpty() || !replicatedSnapshotTasks.isEmpty()) {
SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.set(numLocalSites);
for (int ii = 0; ii < numLocalSites; ii++) {
SnapshotSiteProcessor.m_taskListsForSites.add(new ArrayDeque<SnapshotTableTask>());
}
} else {
SnapshotRegistry.discardSnapshot(snapshotRecord);
aborted = true;
}
/**
* Distribute the writing of replicated tables to exactly one partition.
*/
for (int ii = 0; ii < numLocalSites && !partitionedSnapshotTasks.isEmpty(); ii++) {
SnapshotSiteProcessor.m_taskListsForSites.get(ii).addAll(partitionedSnapshotTasks);
if (!format.isTableBased()) {
SnapshotSiteProcessor.m_taskListsForSites.get(ii).addAll(replicatedSnapshotTasks);
}
}
if (format.isTableBased()) {
int siteIndex = 0;
for (SnapshotTableTask t : replicatedSnapshotTasks) {
SnapshotSiteProcessor.m_taskListsForSites.get(siteIndex++ % numLocalSites).offer(t);
}
}
if (!aborted) {
/*
* Inform the SnapshotCompletionMonitor of what the partition specific txnids for
* this snapshot were so it can forward that to completion interests.
*/
VoltDB.instance().getSnapshotCompletionMonitor().registerPartitionTxnIdsForSnapshot(
txnId, partitionTransactionIds);
// Provide the truncation request ID so the monitor can recognize a specific snapshot.
String truncReqId = "";
if (jsData != null && jsData.has("truncReqId")) {
truncReqId = jsData.getString("truncReqId");
}
logSnapshotStartToZK( txnId, context, file_nonce, truncReqId);
}
}
} catch (Exception ex) {
/*
* Close all the targets to release the threads. Don't let sites get any tasks.
*/
SnapshotSiteProcessor.m_taskListsForSites.clear();
for (SnapshotDataTarget sdt : targets) {
try {
sdt.close();
} catch (Exception e) {
HOST_LOG.error(ex);
}
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
result.addRow(
context.getHostId(),
hostname,
"",
"FAILURE",
"SNAPSHOT INITIATION OF " + file_path + file_nonce +
"RESULTED IN Exception: \n" + sw.toString());
HOST_LOG.error(ex);
} finally {
SnapshotSiteProcessor.m_snapshotPermits.release(numLocalSites);
}
}
}
private VoltTable acquireSnapshotPermit(SystemProcedureExecutionContext context,
String hostname, final VoltTable result) {
try {
SnapshotSiteProcessor.m_snapshotPermits.acquire();
} catch (Exception e) {
result.addRow(context.getHostId(),
hostname,
"",
"FAILURE",
e.toString());
return result;
}
return null;
}
private final SnapshotDataTarget constructSnapshotDataTargetForTable(
SystemProcedureExecutionContext context,
File f,
Table table,
int hostId,
int numPartitions,
long txnId)
throws IOException
{
return new DefaultSnapshotDataTarget(f,
hostId,
context.getCluster().getTypeName(),
context.getDatabase().getTypeName(),
table.getTypeName(),
numPartitions,
table.getIsreplicated(),
context.getSiteTrackerForSnapshot().getPartitionsForHost(hostId),
CatalogUtil.getVoltTable(table),
txnId);
}
}
| true | true | private void createSetup(
String file_path, String file_nonce, SnapshotFormat format,
long txnId, List<Long> partitionTransactionIds,
String data, SystemProcedureExecutionContext context,
String hostname, final VoltTable result) {
{
SiteTracker tracker = context.getSiteTrackerForSnapshot();
final int numLocalSites =
(tracker.getLocalSites().length - recoveringSiteCount.get());
// non-null if targeting only one site (used for rejoin)
// set later from the "data" JSON string
Long targetHSid = null;
JSONObject jsData = null;
if (data != null) {
try {
jsData = new JSONObject(data);
}
catch (JSONException e) {
HOST_LOG.error(String.format("JSON exception on snapshot data \"%s\".", data),
e);
}
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
/*
* List of partitions to include if this snapshot is
* going to be deduped. Attempts to break up the work
* by seeding an RNG selecting
* a random replica to do the work. Will not work in failure
* cases, but we don't use dedupe when we want durability.
*
* Originally used the partition id as the seed, but it turns out
* that nextInt(2) returns a 1 for seeds 0-4095. Now use SHA-1
* on the txnid + partition id.
*/
List<Integer> partitionsToInclude = new ArrayList<Integer>();
List<Long> sitesToInclude = new ArrayList<Long>();
for (long localSite : tracker.getLocalSites()) {
final int partitionId = tracker.getPartitionForSite(localSite);
List<Long> sites =
new ArrayList<Long>(tracker.getSitesForPartition(tracker.getPartitionForSite(localSite)));
Collections.sort(sites);
digest.update(Longs.toByteArray(txnId));
final long seed = Longs.fromByteArray(Arrays.copyOf( digest.digest(Ints.toByteArray(partitionId)), 8));
int siteIndex = new java.util.Random(seed).nextInt(sites.size());
if (localSite == sites.get(siteIndex)) {
partitionsToInclude.add(partitionId);
sitesToInclude.add(localSite);
}
}
assert(partitionsToInclude.size() == sitesToInclude.size());
/*
* Used to close targets on failure
*/
final ArrayList<SnapshotDataTarget> targets = new ArrayList<SnapshotDataTarget>();
try {
final ArrayDeque<SnapshotTableTask> partitionedSnapshotTasks =
new ArrayDeque<SnapshotTableTask>();
final ArrayList<SnapshotTableTask> replicatedSnapshotTasks =
new ArrayList<SnapshotTableTask>();
assert(SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.get() == -1);
final List<Table> tables = SnapshotUtil.getTablesToSave(context.getDatabase());
if (format.isFileBased()) {
Runnable completionTask = SnapshotUtil.writeSnapshotDigest(
txnId,
context.getCatalogCRC(),
file_path,
file_nonce,
tables,
context.getHostId(),
SnapshotSiteProcessor.getExportSequenceNumbers(),
partitionTransactionIds,
VoltDB.instance().getHostMessenger().getInstanceId());
if (completionTask != null) {
SnapshotSiteProcessor.m_tasksOnSnapshotCompletion.offer(completionTask);
}
completionTask = SnapshotUtil.writeSnapshotCatalog(file_path, file_nonce);
if (completionTask != null) {
SnapshotSiteProcessor.m_tasksOnSnapshotCompletion.offer(completionTask);
}
}
final AtomicInteger numTables = new AtomicInteger(tables.size());
final SnapshotRegistry.Snapshot snapshotRecord =
SnapshotRegistry.startSnapshot(
txnId,
context.getHostId(),
file_path,
file_nonce,
format,
tables.toArray(new Table[0]));
SnapshotDataTarget sdt = null;
if (!format.isTableBased()) {
// table schemas for all the tables we'll snapshot on this partition
Map<Integer, byte[]> schemas = new HashMap<Integer, byte[]>();
for (final Table table : SnapshotUtil.getTablesToSave(context.getDatabase())) {
VoltTable schemaTable = CatalogUtil.getVoltTable(table);
schemas.put(table.getRelativeIndex(), schemaTable.getSchemaBytes());
}
if (format == SnapshotFormat.STREAM && jsData != null) {
long hsId = jsData.getLong("hsId");
// if a target_hsid exists, set it for filtering a snapshot for a specific site
try {
targetHSid = jsData.getLong("target_hsid");
}
catch (JSONException e) {} // leave value as null on exception
// if this snapshot targets a specific site...
if (targetHSid != null) {
// get the list of sites on this node
List<Long> localHSids = tracker.getSitesForHost(context.getHostId());
// if the target site is local to this node...
if (localHSids.contains(targetHSid)) {
sdt = new StreamSnapshotDataTarget(hsId, schemas);
}
else {
sdt = new DevNullSnapshotTarget();
}
}
}
}
for (final Table table : SnapshotUtil.getTablesToSave(context.getDatabase()))
{
/*
* For a deduped csv snapshot, only produce the replicated tables on the "leader"
* host.
*/
if (format == SnapshotFormat.CSV && table.getIsreplicated() && !tracker.isFirstHost()) {
snapshotRecord.removeTable(table.getTypeName());
continue;
}
String canSnapshot = "SUCCESS";
String err_msg = "";
File saveFilePath = null;
if (format.isFileBased()) {
saveFilePath = SnapshotUtil.constructFileForTable(
table,
file_path,
file_nonce,
format,
context.getHostId());
}
try {
if (format == SnapshotFormat.CSV) {
sdt = new SimpleFileSnapshotDataTarget(saveFilePath);
} else if (format == SnapshotFormat.NATIVE) {
sdt =
constructSnapshotDataTargetForTable(
context,
saveFilePath,
table,
context.getHostId(),
tracker.m_numberOfPartitions,
txnId);
}
if (sdt == null) {
throw new IOException("Unable to create snapshot target");
}
targets.add(sdt);
final SnapshotDataTarget sdtFinal = sdt;
final Runnable onClose = new Runnable() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
snapshotRecord.updateTable(table.getTypeName(),
new SnapshotRegistry.Snapshot.TableUpdater() {
@Override
public SnapshotRegistry.Snapshot.Table update(
SnapshotRegistry.Snapshot.Table registryTable) {
return snapshotRecord.new Table(
registryTable,
sdtFinal.getBytesWritten(),
sdtFinal.getLastWriteException());
}
});
int tablesLeft = numTables.decrementAndGet();
if (tablesLeft == 0) {
final SnapshotRegistry.Snapshot completed =
SnapshotRegistry.finishSnapshot(snapshotRecord);
final double duration =
(completed.timeFinished - org.voltdb.TransactionIdManager.getTimestampFromTransactionId(completed.txnId)) / 1000.0;
HOST_LOG.info(
"Snapshot " + snapshotRecord.nonce + " finished at " +
completed.timeFinished + " and took " + duration
+ " seconds ");
}
}
};
sdt.setOnCloseHandler(onClose);
List<SnapshotDataFilter> filters = new ArrayList<SnapshotDataFilter>();
if (format == SnapshotFormat.CSV) {
/*
* Don't need to do filtering on a replicated table.
*/
if (!table.getIsreplicated()) {
filters.add(
new PartitionProjectionSnapshotFilter(
Ints.toArray(partitionsToInclude),
0));
}
filters.add(new CSVSnapshotFilter(CatalogUtil.getVoltTable(table), ',', null));
}
// if this snapshot targets a specific site...
if (targetHSid != null) {
// get the list of sites on this node
List<Long> localHSids = tracker.getSitesForHost(context.getHostId());
// if the target site is local to this node...
if (localHSids.contains(targetHSid)) {
// ...get its partition id...
int partitionId = tracker.getPartitionForSite(targetHSid);
// ...and build a filter to only get that partition
filters.add(new PartitionProjectionSnapshotFilter(
new int[] { partitionId }, sdt.getHeaderSize()));
}
else {
// filter EVERYTHING because the site we want isn't local
filters.add(new PartitionProjectionSnapshotFilter(
new int[0], sdt.getHeaderSize()));
}
}
final SnapshotTableTask task =
new SnapshotTableTask(
table.getRelativeIndex(),
sdt,
filters.toArray(new SnapshotDataFilter[filters.size()]),
table.getIsreplicated(),
table.getTypeName());
if (table.getIsreplicated()) {
replicatedSnapshotTasks.add(task);
} else {
partitionedSnapshotTasks.offer(task);
}
} catch (IOException ex) {
/*
* Creation of this specific target failed. Close it if it was created.
* Continue attempting the snapshot anyways so that at least some of the data
* can be retrieved.
*/
try {
if (sdt != null) {
targets.remove(sdt);
sdt.close();
}
} catch (Exception e) {
HOST_LOG.error(e);
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
canSnapshot = "FAILURE";
err_msg = "SNAPSHOT INITIATION OF " + file_nonce +
"RESULTED IN IOException: \n" + sw.toString();
}
result.addRow(context.getHostId(),
hostname,
table.getTypeName(),
canSnapshot,
err_msg);
}
synchronized (SnapshotSiteProcessor.m_taskListsForSites) {
boolean aborted = false;
if (!partitionedSnapshotTasks.isEmpty() || !replicatedSnapshotTasks.isEmpty()) {
SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.set(numLocalSites);
for (int ii = 0; ii < numLocalSites; ii++) {
SnapshotSiteProcessor.m_taskListsForSites.add(new ArrayDeque<SnapshotTableTask>());
}
} else {
SnapshotRegistry.discardSnapshot(snapshotRecord);
aborted = true;
}
/**
* Distribute the writing of replicated tables to exactly one partition.
*/
for (int ii = 0; ii < numLocalSites && !partitionedSnapshotTasks.isEmpty(); ii++) {
SnapshotSiteProcessor.m_taskListsForSites.get(ii).addAll(partitionedSnapshotTasks);
if (!format.isTableBased()) {
SnapshotSiteProcessor.m_taskListsForSites.get(ii).addAll(replicatedSnapshotTasks);
}
}
if (format.isTableBased()) {
int siteIndex = 0;
for (SnapshotTableTask t : replicatedSnapshotTasks) {
SnapshotSiteProcessor.m_taskListsForSites.get(siteIndex++ % numLocalSites).offer(t);
}
}
if (!aborted) {
/*
* Inform the SnapshotCompletionMonitor of what the partition specific txnids for
* this snapshot were so it can forward that to completion interests.
*/
VoltDB.instance().getSnapshotCompletionMonitor().registerPartitionTxnIdsForSnapshot(
txnId, partitionTransactionIds);
// Provide the truncation request ID so the monitor can recognize a specific snapshot.
String truncReqId = "";
if (jsData != null && jsData.has("truncReqId")) {
truncReqId = jsData.getString("truncReqId");
}
logSnapshotStartToZK( txnId, context, file_nonce, truncReqId);
}
}
} catch (Exception ex) {
/*
* Close all the targets to release the threads. Don't let sites get any tasks.
*/
SnapshotSiteProcessor.m_taskListsForSites.clear();
for (SnapshotDataTarget sdt : targets) {
try {
sdt.close();
} catch (Exception e) {
HOST_LOG.error(ex);
}
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
result.addRow(
context.getHostId(),
hostname,
"",
"FAILURE",
"SNAPSHOT INITIATION OF " + file_path + file_nonce +
"RESULTED IN Exception: \n" + sw.toString());
HOST_LOG.error(ex);
} finally {
SnapshotSiteProcessor.m_snapshotPermits.release(numLocalSites);
}
}
}
| private void createSetup(
String file_path, String file_nonce, SnapshotFormat format,
long txnId, List<Long> partitionTransactionIds,
String data, SystemProcedureExecutionContext context,
String hostname, final VoltTable result) {
{
SiteTracker tracker = context.getSiteTrackerForSnapshot();
final int numLocalSites =
(tracker.getLocalSites().length - recoveringSiteCount.get());
// non-null if targeting only one site (used for rejoin)
// set later from the "data" JSON string
Long targetHSid = null;
JSONObject jsData = null;
if (data != null && !data.isEmpty()) {
try {
jsData = new JSONObject(data);
}
catch (JSONException e) {
HOST_LOG.error(String.format("JSON exception on snapshot data \"%s\".", data),
e);
}
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
/*
* List of partitions to include if this snapshot is
* going to be deduped. Attempts to break up the work
* by seeding an RNG selecting
* a random replica to do the work. Will not work in failure
* cases, but we don't use dedupe when we want durability.
*
* Originally used the partition id as the seed, but it turns out
* that nextInt(2) returns a 1 for seeds 0-4095. Now use SHA-1
* on the txnid + partition id.
*/
List<Integer> partitionsToInclude = new ArrayList<Integer>();
List<Long> sitesToInclude = new ArrayList<Long>();
for (long localSite : tracker.getLocalSites()) {
final int partitionId = tracker.getPartitionForSite(localSite);
List<Long> sites =
new ArrayList<Long>(tracker.getSitesForPartition(tracker.getPartitionForSite(localSite)));
Collections.sort(sites);
digest.update(Longs.toByteArray(txnId));
final long seed = Longs.fromByteArray(Arrays.copyOf( digest.digest(Ints.toByteArray(partitionId)), 8));
int siteIndex = new java.util.Random(seed).nextInt(sites.size());
if (localSite == sites.get(siteIndex)) {
partitionsToInclude.add(partitionId);
sitesToInclude.add(localSite);
}
}
assert(partitionsToInclude.size() == sitesToInclude.size());
/*
* Used to close targets on failure
*/
final ArrayList<SnapshotDataTarget> targets = new ArrayList<SnapshotDataTarget>();
try {
final ArrayDeque<SnapshotTableTask> partitionedSnapshotTasks =
new ArrayDeque<SnapshotTableTask>();
final ArrayList<SnapshotTableTask> replicatedSnapshotTasks =
new ArrayList<SnapshotTableTask>();
assert(SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.get() == -1);
final List<Table> tables = SnapshotUtil.getTablesToSave(context.getDatabase());
if (format.isFileBased()) {
Runnable completionTask = SnapshotUtil.writeSnapshotDigest(
txnId,
context.getCatalogCRC(),
file_path,
file_nonce,
tables,
context.getHostId(),
SnapshotSiteProcessor.getExportSequenceNumbers(),
partitionTransactionIds,
VoltDB.instance().getHostMessenger().getInstanceId());
if (completionTask != null) {
SnapshotSiteProcessor.m_tasksOnSnapshotCompletion.offer(completionTask);
}
completionTask = SnapshotUtil.writeSnapshotCatalog(file_path, file_nonce);
if (completionTask != null) {
SnapshotSiteProcessor.m_tasksOnSnapshotCompletion.offer(completionTask);
}
}
final AtomicInteger numTables = new AtomicInteger(tables.size());
final SnapshotRegistry.Snapshot snapshotRecord =
SnapshotRegistry.startSnapshot(
txnId,
context.getHostId(),
file_path,
file_nonce,
format,
tables.toArray(new Table[0]));
SnapshotDataTarget sdt = null;
if (!format.isTableBased()) {
// table schemas for all the tables we'll snapshot on this partition
Map<Integer, byte[]> schemas = new HashMap<Integer, byte[]>();
for (final Table table : SnapshotUtil.getTablesToSave(context.getDatabase())) {
VoltTable schemaTable = CatalogUtil.getVoltTable(table);
schemas.put(table.getRelativeIndex(), schemaTable.getSchemaBytes());
}
if (format == SnapshotFormat.STREAM && jsData != null) {
long hsId = jsData.getLong("hsId");
// if a target_hsid exists, set it for filtering a snapshot for a specific site
try {
targetHSid = jsData.getLong("target_hsid");
}
catch (JSONException e) {} // leave value as null on exception
// if this snapshot targets a specific site...
if (targetHSid != null) {
// get the list of sites on this node
List<Long> localHSids = tracker.getSitesForHost(context.getHostId());
// if the target site is local to this node...
if (localHSids.contains(targetHSid)) {
sdt = new StreamSnapshotDataTarget(hsId, schemas);
}
else {
sdt = new DevNullSnapshotTarget();
}
}
}
}
for (final Table table : SnapshotUtil.getTablesToSave(context.getDatabase()))
{
/*
* For a deduped csv snapshot, only produce the replicated tables on the "leader"
* host.
*/
if (format == SnapshotFormat.CSV && table.getIsreplicated() && !tracker.isFirstHost()) {
snapshotRecord.removeTable(table.getTypeName());
continue;
}
String canSnapshot = "SUCCESS";
String err_msg = "";
File saveFilePath = null;
if (format.isFileBased()) {
saveFilePath = SnapshotUtil.constructFileForTable(
table,
file_path,
file_nonce,
format,
context.getHostId());
}
try {
if (format == SnapshotFormat.CSV) {
sdt = new SimpleFileSnapshotDataTarget(saveFilePath);
} else if (format == SnapshotFormat.NATIVE) {
sdt =
constructSnapshotDataTargetForTable(
context,
saveFilePath,
table,
context.getHostId(),
tracker.m_numberOfPartitions,
txnId);
}
if (sdt == null) {
throw new IOException("Unable to create snapshot target");
}
targets.add(sdt);
final SnapshotDataTarget sdtFinal = sdt;
final Runnable onClose = new Runnable() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
snapshotRecord.updateTable(table.getTypeName(),
new SnapshotRegistry.Snapshot.TableUpdater() {
@Override
public SnapshotRegistry.Snapshot.Table update(
SnapshotRegistry.Snapshot.Table registryTable) {
return snapshotRecord.new Table(
registryTable,
sdtFinal.getBytesWritten(),
sdtFinal.getLastWriteException());
}
});
int tablesLeft = numTables.decrementAndGet();
if (tablesLeft == 0) {
final SnapshotRegistry.Snapshot completed =
SnapshotRegistry.finishSnapshot(snapshotRecord);
final double duration =
(completed.timeFinished - org.voltdb.TransactionIdManager.getTimestampFromTransactionId(completed.txnId)) / 1000.0;
HOST_LOG.info(
"Snapshot " + snapshotRecord.nonce + " finished at " +
completed.timeFinished + " and took " + duration
+ " seconds ");
}
}
};
sdt.setOnCloseHandler(onClose);
List<SnapshotDataFilter> filters = new ArrayList<SnapshotDataFilter>();
if (format == SnapshotFormat.CSV) {
/*
* Don't need to do filtering on a replicated table.
*/
if (!table.getIsreplicated()) {
filters.add(
new PartitionProjectionSnapshotFilter(
Ints.toArray(partitionsToInclude),
0));
}
filters.add(new CSVSnapshotFilter(CatalogUtil.getVoltTable(table), ',', null));
}
// if this snapshot targets a specific site...
if (targetHSid != null) {
// get the list of sites on this node
List<Long> localHSids = tracker.getSitesForHost(context.getHostId());
// if the target site is local to this node...
if (localHSids.contains(targetHSid)) {
// ...get its partition id...
int partitionId = tracker.getPartitionForSite(targetHSid);
// ...and build a filter to only get that partition
filters.add(new PartitionProjectionSnapshotFilter(
new int[] { partitionId }, sdt.getHeaderSize()));
}
else {
// filter EVERYTHING because the site we want isn't local
filters.add(new PartitionProjectionSnapshotFilter(
new int[0], sdt.getHeaderSize()));
}
}
final SnapshotTableTask task =
new SnapshotTableTask(
table.getRelativeIndex(),
sdt,
filters.toArray(new SnapshotDataFilter[filters.size()]),
table.getIsreplicated(),
table.getTypeName());
if (table.getIsreplicated()) {
replicatedSnapshotTasks.add(task);
} else {
partitionedSnapshotTasks.offer(task);
}
} catch (IOException ex) {
/*
* Creation of this specific target failed. Close it if it was created.
* Continue attempting the snapshot anyways so that at least some of the data
* can be retrieved.
*/
try {
if (sdt != null) {
targets.remove(sdt);
sdt.close();
}
} catch (Exception e) {
HOST_LOG.error(e);
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
canSnapshot = "FAILURE";
err_msg = "SNAPSHOT INITIATION OF " + file_nonce +
"RESULTED IN IOException: \n" + sw.toString();
}
result.addRow(context.getHostId(),
hostname,
table.getTypeName(),
canSnapshot,
err_msg);
}
synchronized (SnapshotSiteProcessor.m_taskListsForSites) {
boolean aborted = false;
if (!partitionedSnapshotTasks.isEmpty() || !replicatedSnapshotTasks.isEmpty()) {
SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.set(numLocalSites);
for (int ii = 0; ii < numLocalSites; ii++) {
SnapshotSiteProcessor.m_taskListsForSites.add(new ArrayDeque<SnapshotTableTask>());
}
} else {
SnapshotRegistry.discardSnapshot(snapshotRecord);
aborted = true;
}
/**
* Distribute the writing of replicated tables to exactly one partition.
*/
for (int ii = 0; ii < numLocalSites && !partitionedSnapshotTasks.isEmpty(); ii++) {
SnapshotSiteProcessor.m_taskListsForSites.get(ii).addAll(partitionedSnapshotTasks);
if (!format.isTableBased()) {
SnapshotSiteProcessor.m_taskListsForSites.get(ii).addAll(replicatedSnapshotTasks);
}
}
if (format.isTableBased()) {
int siteIndex = 0;
for (SnapshotTableTask t : replicatedSnapshotTasks) {
SnapshotSiteProcessor.m_taskListsForSites.get(siteIndex++ % numLocalSites).offer(t);
}
}
if (!aborted) {
/*
* Inform the SnapshotCompletionMonitor of what the partition specific txnids for
* this snapshot were so it can forward that to completion interests.
*/
VoltDB.instance().getSnapshotCompletionMonitor().registerPartitionTxnIdsForSnapshot(
txnId, partitionTransactionIds);
// Provide the truncation request ID so the monitor can recognize a specific snapshot.
String truncReqId = "";
if (jsData != null && jsData.has("truncReqId")) {
truncReqId = jsData.getString("truncReqId");
}
logSnapshotStartToZK( txnId, context, file_nonce, truncReqId);
}
}
} catch (Exception ex) {
/*
* Close all the targets to release the threads. Don't let sites get any tasks.
*/
SnapshotSiteProcessor.m_taskListsForSites.clear();
for (SnapshotDataTarget sdt : targets) {
try {
sdt.close();
} catch (Exception e) {
HOST_LOG.error(ex);
}
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
result.addRow(
context.getHostId(),
hostname,
"",
"FAILURE",
"SNAPSHOT INITIATION OF " + file_path + file_nonce +
"RESULTED IN Exception: \n" + sw.toString());
HOST_LOG.error(ex);
} finally {
SnapshotSiteProcessor.m_snapshotPermits.release(numLocalSites);
}
}
}
|
diff --git a/src/com/undi/javascheme/SchemeObject.java b/src/com/undi/javascheme/SchemeObject.java
index 5838707..a3bbdff 100644
--- a/src/com/undi/javascheme/SchemeObject.java
+++ b/src/com/undi/javascheme/SchemeObject.java
@@ -1,595 +1,602 @@
package com.undi.javascheme;
import java.util.HashMap;
import java.util.Vector;
import com.undi.util.HashCodeUtil;
//This class works almost like a union
public class SchemeObject {
public static enum type {
NUMBER, BOOLEAN, CHARACTER, STRING, SYMBOL, PAIR, EMPTY_LIST, NATIVE_PROC,
COMPOUND_PROC, VECTOR, HASH_MAP, NUM_TYPES
};
public type getType() {
return this.mType;
}
public static final SchemeObject True = SchemeObject.createBoolean(true);
public static final SchemeObject False = SchemeObject.createBoolean(false);
public static final SchemeObject EmptyList = SchemeObject.createEmptyList();
public static SchemeObject SymbolTable = SchemeObject.EmptyList;
public static final SchemeObject QuoteSymbol = SchemeObject
.makeSymbol("quote");
public static final SchemeObject DefineSymbol = SchemeObject
.makeSymbol("define");
public static final SchemeObject SetSymbol = SchemeObject.makeSymbol("set!");
public static final SchemeObject OkSymbol = SchemeObject.makeSymbol("ok");
public static final SchemeObject IfSymbol = SchemeObject.makeSymbol("if");
public static final SchemeObject LambdaSymbol = SchemeObject
.makeSymbol("lambda");
public static final SchemeObject BeginSymbol = SchemeObject
.makeSymbol("begin");
public static final SchemeObject CondSymbol = SchemeObject.makeSymbol("cond");
public static final SchemeObject ElseSymbol = SchemeObject.makeSymbol("else");
public static final SchemeObject LetSymbol = SchemeObject.makeSymbol("let");
public static final SchemeObject LoadSymbol = SchemeObject.makeSymbol("load");
public static final SchemeObject OrSymbol = SchemeObject.makeSymbol("or");
public static final SchemeObject AndSymbol = SchemeObject.makeSymbol("and");
public static final SchemeObject ApplySymbol = SchemeObject
.makeSymbol("apply");
// TODO: This doesn't work
public boolean valueEqual(SchemeObject other) {
if (other.mType != this.mType) {
return false;
}
switch (this.mType) {
case NUMBER:
return this.getNumber() == other.getNumber();
case STRING:
return (new String(this.getString()))
.equals(new String(other.getString()));
case CHARACTER:
return this.getCharacter() == other.getCharacter();
default:
return this.mData == other.mData;
}
}
// Compound Proc
public static SchemeObject makeCompoundProc(SchemeObject params,
SchemeObject body, SchemeObject env) {
SchemeObject obj = new SchemeObject();
obj.mType = type.COMPOUND_PROC;
SchemeObject[] newData = new SchemeObject[3];
newData[0] = params;
newData[1] = body;
newData[2] = env;
obj.mData = newData;
return obj;
}
public SchemeObject getCompoundProcParams() {
if (this.mType != type.COMPOUND_PROC) {
System.err.println("Object Isn't a Compound Proc!");
System.exit(1);
}
SchemeObject[] data = (SchemeObject[]) this.mData;
return data[0];
}
public SchemeObject getCompoundProcBody() {
if (this.mType != type.COMPOUND_PROC) {
System.err.println("Object Isn't a Compound Proc!");
System.exit(1);
}
SchemeObject[] data = (SchemeObject[]) this.mData;
return data[1];
}
public SchemeObject getCompoundProcEnv() {
if (this.mType != type.COMPOUND_PROC) {
System.err.println("Object Isn't a Compound Proc!");
System.exit(1);
}
SchemeObject[] data = (SchemeObject[]) this.mData;
return data[2];
}
public boolean isCompoundProc() {
return this.mType == type.COMPOUND_PROC;
}
// Native Proc
public static SchemeObject makeNativeProc(SchemeNatives.nativeProc proc) {
SchemeObject obj = new SchemeObject();
obj.mType = type.NATIVE_PROC;
obj.mData = proc;
return obj;
}
public boolean isNativeProc() {
return this.mType == type.NATIVE_PROC;
}
public SchemeNatives.nativeProc getNativeProc() {
if (this.mType != type.NATIVE_PROC) {
System.err.println("Object Isn't a Native Proc!");
System.exit(1);
}
return (SchemeNatives.nativeProc) this.mData;
}
// Pairs
public static SchemeObject makePair(SchemeObject car, SchemeObject cdr) {
if (car == null && cdr == null) {
return EmptyList;
}
SchemeObject obj = new SchemeObject();
obj.mType = type.PAIR;
obj.mData = new SchemeObject[2];
obj.setCar(car);
obj.setCdr(cdr);
return obj;
}
public boolean isPair() {
return this.mType == type.PAIR;
}
public void setCar(SchemeObject car) {
SchemeObject[] data = (SchemeObject[]) this.mData;
data[0] = car;
}
public void setCdr(SchemeObject cdr) {
SchemeObject[] data = (SchemeObject[]) this.mData;
data[1] = cdr;
}
public SchemeObject getCar() {
if (this.mType == type.PAIR) {
return ((SchemeObject[]) this.mData)[0];
} else {
return this;
}
}
public SchemeObject getCdr() {
if (this.mType == type.PAIR) {
return ((SchemeObject[]) this.mData)[1];
} else {
return EmptyList;
}
}
public static SchemeObject car(SchemeObject obj) {
return obj.getCar();
}
public static SchemeObject cdr(SchemeObject obj) {
return obj.getCdr();
}
public static SchemeObject caar(SchemeObject obj) {
return car(car(obj));
}
public static SchemeObject cadr(SchemeObject obj) {
return car(cdr(obj));
}
public static SchemeObject cdar(SchemeObject obj) {
return cdr(car(obj));
}
public static SchemeObject cddr(SchemeObject obj) {
return cdr(cdr(obj));
}
public static SchemeObject caddr(SchemeObject obj) {
return car(cdr(cdr(obj)));
}
public static SchemeObject cdadr(SchemeObject obj) {
return cdr(car(cdr(obj)));
}
public static SchemeObject caadr(SchemeObject obj) {
return car(car(cdr(obj)));
}
public static SchemeObject cadddr(SchemeObject obj) {
return car(cdr(cdr(cdr(obj))));
}
public static SchemeObject caaddr(SchemeObject obj) {
return car(car(cdr(cdr(obj))));
}
public SchemeObject[] getPair() {
if (this.mType != type.PAIR) {
System.err.println("Object Isn't a Pair!");
System.exit(1);
}
return (SchemeObject[]) this.mData;
}
public static SchemeObject cons(SchemeObject car, SchemeObject cdr) {
return SchemeObject.makePair(car, cdr);
}
public static SchemeObject concatList(SchemeObject list, SchemeObject item) {
if (list.isEmptyList()) {
return item;
} else {
return cons(list.getCar(), concatList(list.getCdr(), item));
}
}
public static boolean isFalse(SchemeObject obj) {
return obj == False;
}
public static boolean isTrue(SchemeObject obj) {
return !isFalse(obj);
}
/**
* Prints a list, modifies input tempString
*
* @param tempString
*/
private void writePair(StringBuilder tempString) {
SchemeObject[] pair = getPair();
SchemeObject carObj = pair[0];
SchemeObject cdrObj = pair[1];
tempString.append(carObj);
if (cdrObj.mType == type.PAIR) {
tempString.append(' ');
cdrObj.writePair(tempString);
} else if (cdrObj.isEmptyList()) {
return;
} else {
tempString.append(" . ");
tempString.append(cdrObj);
}
}
// Numbers
public static SchemeObject makeNumber(double value) {
SchemeObject obj = new SchemeObject();
obj.setNumber(value);
return obj;
}
public boolean isNumber() {
return this.mType == type.NUMBER;
}
public double getNumber() {
if (this.mType != type.NUMBER) {
System.err.println("Object Isn't a Number!");
System.exit(1);
}
return (Double) this.mData;
}
public void setNumber(double value) {
this.mType = type.NUMBER;
this.mData = value;
}
// Booleans
private static SchemeObject createBoolean(boolean value) {
SchemeObject obj = new SchemeObject();
obj.setBoolean(value);
return obj;
}
public boolean isBoolean() {
return this.mType == type.BOOLEAN;
}
public static SchemeObject makeBoolean(boolean value) {
return (value) ? SchemeObject.True : SchemeObject.False;
}
private void setBoolean(boolean value) {
this.mType = type.BOOLEAN;
this.mData = value;
}
public boolean getBoolean() {
if (this.mType != type.BOOLEAN) {
System.err.println("Object Isn't a Boolean!");
System.exit(1);
}
return (Boolean) this.mData;
}
// Characters
public static SchemeObject makeCharacter(short value) {
SchemeObject obj = new SchemeObject();
obj.setCharacter(value);
return obj;
}
public boolean isCharacter() {
return this.mType == type.CHARACTER;
}
public short getCharacter() {
if (this.mType != type.CHARACTER) {
System.err.println("Object Isn't a Character!");
System.exit(1);
}
return (Short) this.mData;
}
public void setCharacter(short value) {
this.mType = type.CHARACTER;
this.mData = value;
}
// Strings
public static SchemeObject makeString(String value) {
SchemeObject obj = new SchemeObject();
obj.setString(value);
return obj;
}
public boolean isString() {
return this.mType == type.STRING;
}
public char[] getString() {
if (this.mType != type.STRING) {
System.err.println("Object Isn't a String!");
System.exit(1);
}
return (char[]) this.mData;
}
public void setString(String value) {
this.mType = type.STRING;
this.mData = value.toCharArray();
}
// Empty list
private static SchemeObject createEmptyList() {
SchemeObject obj = new SchemeObject();
obj.mData = null;
obj.mType = type.EMPTY_LIST;
return obj;
}
public static SchemeObject makeEmptyList() {
return SchemeObject.EmptyList;
}
public boolean isEmptyList() {
return this.mType == type.EMPTY_LIST;
}
// Symbols
public static SchemeObject makeSymbol(String value) {
// See if this symbol is in the symbol table
SchemeObject elt = SymbolTable;
while (!elt.isEmptyList()) {
if (car(elt).getSymbol().equals(value)) {
return car(elt);
}
elt = cdr(elt);
}
SchemeObject obj = new SchemeObject();
obj.setSymbol(value);
SymbolTable = cons(obj, SymbolTable);
return obj;
}
public boolean isSymbol() {
return this.mType == type.SYMBOL;
}
public String getSymbol() {
if (this.mType != type.SYMBOL) {
System.err.println("Object Isn't a Symbol!");
System.exit(1);
}
return (String) this.mData;
}
public void setSymbol(String value) {
this.mType = type.SYMBOL;
this.mData = value;
}
// Vectors
public static SchemeObject makeVector(SchemeObject contents) {
SchemeObject obj = new SchemeObject();
obj.mType = type.VECTOR;
obj.mData = new Vector<SchemeObject>();
while (!contents.isEmptyList()) {
obj.addToVector(contents.getCar());
contents = contents.getCdr();
}
return obj;
}
@SuppressWarnings("unchecked")
public Vector<SchemeObject> getVector() {
if (!this.isVector()) {
System.err.println("Object Isn't a Vector!");
System.exit(1);
}
return (Vector<SchemeObject>) this.mData;
}
public SchemeObject addToVector(SchemeObject obj) {
// If it's a vector, we know it has a vector as data
Vector<SchemeObject> myVec = this.getVector();
myVec.add(obj);
return OkSymbol;
}
public boolean isVector() {
return this.mType == type.VECTOR;
}
// Hash Tables
public boolean isHashMap() {
return this.mType == type.HASH_MAP;
}
public static SchemeObject makeHashMap(SchemeObject elts) {
SchemeObject obj = new SchemeObject();
obj.mType = type.HASH_MAP;
obj.mData = new HashMap<SchemeObject, SchemeObject>();
// elts is a list of key value pairs, so (1 "one" 2 "two") -> {1 => "one", 2
// => "two"}
SchemeObject newKey;
SchemeObject newVal;
while (!elts.isEmptyList()) {
newKey = SchemeObject.car(elts);
newVal = SchemeObject.cadr(elts);
obj.setHashMap(newKey, newVal);
// skip to the next pair
elts = SchemeObject.cddr(elts);
}
return obj;
}
public SchemeObject setHashMap(SchemeObject key, SchemeObject val) {
this.getHashMap().put(key, val);
return OkSymbol;
}
@SuppressWarnings("unchecked")
public HashMap<SchemeObject, SchemeObject> getHashMap() {
if (!this.isHashMap()) {
System.err.println("Object Isn't a HashMap!");
System.exit(1);
}
return (HashMap<SchemeObject, SchemeObject>) this.mData;
}
/**
* Returns the object as a string **Writer in repl**
*/
@Override
public String toString() {
StringBuilder tempString = new StringBuilder();
// tempString.append("Type: " + this.mType.name());
// tempString.append(" Value: ");
switch (this.mType) {
case NUMBER:
tempString.append(getNumber());
break;
case STRING:
tempString.append('"');
tempString.append(getString());
tempString.append('"');
break;
case CHARACTER:
tempString.append((char) getCharacter());
break;
case BOOLEAN:
tempString.append(getBoolean() ? "true" : "false");
break;
case SYMBOL:
tempString.append(getSymbol());
break;
case PAIR:
tempString.append('(');
this.writePair(tempString);
tempString.append(')');
break;
case EMPTY_LIST:
tempString.append("()");
break;
case COMPOUND_PROC:
tempString.append("#<interpreted procedure>");
break;
case NATIVE_PROC:
tempString.append("#<native procedure>");
break;
case VECTOR:
tempString.append("#(");
Vector<SchemeObject> data = this.getVector();
int elts = data.size();
for (int i = 0; i < elts; i++) {
tempString.append(data.get(i));
if (elts - i > 1) {
tempString.append(' ');
}
}
tempString.append(")");
break;
case HASH_MAP:
tempString.append("{");
- for (SchemeObject key : this.getHashMap().keySet()) {
- tempString.append(key + " => " + this.getHashMap().get(key) + ", ");
+ SchemeObject nextEntry;
+ HashMap<SchemeObject, SchemeObject> myMap = this.getHashMap();
+ for (SchemeObject key : myMap.keySet()) {
+ nextEntry = myMap.get(key);
+ if(nextEntry.isHashMap() || nextEntry.isPair()){
+ tempString.append(key + " => *Hash Map or List*, ");
+ }else{
+ tempString.append(key + " => " + nextEntry + ", ");
+ }
}
// Clear out the last ", "
tempString.delete(tempString.lastIndexOf(", "), tempString.length());
tempString.append("}");
break;
}
// tempString.append(">");
return tempString.toString();
}
@Override
public boolean equals(Object obj) {
if (obj.getClass() != SchemeObject.class) {
return super.equals(obj);
}
SchemeObject sObj = (SchemeObject) obj;
if (this.mType != sObj.mType) {
return false;
}
switch (this.mType) {
case NUMBER:
return this.getNumber() == sObj.getNumber();
case CHARACTER:
return this.getCharacter() == sObj.getCharacter();
case STRING:
return new String(this.getString()).equals(new String(sObj.getString()));
case SYMBOL:
return this.getSymbol().equals(sObj.getSymbol());
}
return false;
}
@Override
public int hashCode() {
switch (this.mType) {
case NUMBER:
return HashCodeUtil.hash(HashCodeUtil.SEED, (long) this.getNumber());
case CHARACTER:
return HashCodeUtil.hash(HashCodeUtil.SEED, this.getCharacter());
case STRING:
return HashCodeUtil.hash(HashCodeUtil.SEED, new String(this.getString()));
case SYMBOL:
HashCodeUtil.hash(HashCodeUtil.SEED, this.getSymbol());
}
return HashCodeUtil.hash(HashCodeUtil.SEED, this.mData);
}
private type mType;
private Object mData;
}
| true | true | public String toString() {
StringBuilder tempString = new StringBuilder();
// tempString.append("Type: " + this.mType.name());
// tempString.append(" Value: ");
switch (this.mType) {
case NUMBER:
tempString.append(getNumber());
break;
case STRING:
tempString.append('"');
tempString.append(getString());
tempString.append('"');
break;
case CHARACTER:
tempString.append((char) getCharacter());
break;
case BOOLEAN:
tempString.append(getBoolean() ? "true" : "false");
break;
case SYMBOL:
tempString.append(getSymbol());
break;
case PAIR:
tempString.append('(');
this.writePair(tempString);
tempString.append(')');
break;
case EMPTY_LIST:
tempString.append("()");
break;
case COMPOUND_PROC:
tempString.append("#<interpreted procedure>");
break;
case NATIVE_PROC:
tempString.append("#<native procedure>");
break;
case VECTOR:
tempString.append("#(");
Vector<SchemeObject> data = this.getVector();
int elts = data.size();
for (int i = 0; i < elts; i++) {
tempString.append(data.get(i));
if (elts - i > 1) {
tempString.append(' ');
}
}
tempString.append(")");
break;
case HASH_MAP:
tempString.append("{");
for (SchemeObject key : this.getHashMap().keySet()) {
tempString.append(key + " => " + this.getHashMap().get(key) + ", ");
}
// Clear out the last ", "
tempString.delete(tempString.lastIndexOf(", "), tempString.length());
tempString.append("}");
break;
}
// tempString.append(">");
return tempString.toString();
}
| public String toString() {
StringBuilder tempString = new StringBuilder();
// tempString.append("Type: " + this.mType.name());
// tempString.append(" Value: ");
switch (this.mType) {
case NUMBER:
tempString.append(getNumber());
break;
case STRING:
tempString.append('"');
tempString.append(getString());
tempString.append('"');
break;
case CHARACTER:
tempString.append((char) getCharacter());
break;
case BOOLEAN:
tempString.append(getBoolean() ? "true" : "false");
break;
case SYMBOL:
tempString.append(getSymbol());
break;
case PAIR:
tempString.append('(');
this.writePair(tempString);
tempString.append(')');
break;
case EMPTY_LIST:
tempString.append("()");
break;
case COMPOUND_PROC:
tempString.append("#<interpreted procedure>");
break;
case NATIVE_PROC:
tempString.append("#<native procedure>");
break;
case VECTOR:
tempString.append("#(");
Vector<SchemeObject> data = this.getVector();
int elts = data.size();
for (int i = 0; i < elts; i++) {
tempString.append(data.get(i));
if (elts - i > 1) {
tempString.append(' ');
}
}
tempString.append(")");
break;
case HASH_MAP:
tempString.append("{");
SchemeObject nextEntry;
HashMap<SchemeObject, SchemeObject> myMap = this.getHashMap();
for (SchemeObject key : myMap.keySet()) {
nextEntry = myMap.get(key);
if(nextEntry.isHashMap() || nextEntry.isPair()){
tempString.append(key + " => *Hash Map or List*, ");
}else{
tempString.append(key + " => " + nextEntry + ", ");
}
}
// Clear out the last ", "
tempString.delete(tempString.lastIndexOf(", "), tempString.length());
tempString.append("}");
break;
}
// tempString.append(">");
return tempString.toString();
}
|
diff --git a/org.nelfin.othello/test/iago/SmartPlayerTestAbstract.java b/org.nelfin.othello/test/iago/SmartPlayerTestAbstract.java
index ead7fe3..7e1690a 100644
--- a/org.nelfin.othello/test/iago/SmartPlayerTestAbstract.java
+++ b/org.nelfin.othello/test/iago/SmartPlayerTestAbstract.java
@@ -1,33 +1,39 @@
package iago;
import iago.players.Player;
import iago.players.Player.PlayerType;
import org.junit.Test;
public abstract class SmartPlayerTestAbstract extends PlayerTestAbstract {
protected Player smartWhitePlayer, smartBlackPlayer;
//This is a solved game, white (2nd player) wins by 8
@Test
public void testPerfectPlay() {
Board small4x4Board = new Board(DebugFunctions.make4x4OthelloString());
Boolean blacksTurn = true;
Move nextMove = new Move(0,0);
- while(!nextMove.equals(new Move(-1,-1)))
+ int consecutivePasses = 0;
+ while(consecutivePasses < 2)
{
if(blacksTurn)
{
nextMove = smartBlackPlayer.chooseMove(small4x4Board);
}else{
nextMove = smartWhitePlayer.chooseMove(small4x4Board);
}
- //apply the move
- small4x4Board.apply(nextMove, blacksTurn?PlayerType.BLACK:PlayerType.WHITE, true);
+ if (nextMove.equals(Move.NO_MOVE)) {
+ consecutivePasses++;
+ } else {
+ //apply the move
+ small4x4Board.apply(nextMove, blacksTurn?PlayerType.BLACK:PlayerType.WHITE, true);
+ consecutivePasses = 0;
+ }
blacksTurn = !blacksTurn;
}
- assertEquals(small4x4Board.scoreBoard(PlayerType.WHITE),8);
+ assertEquals(8, small4x4Board.scoreBoard(PlayerType.WHITE));
}
}
| false | true | public void testPerfectPlay() {
Board small4x4Board = new Board(DebugFunctions.make4x4OthelloString());
Boolean blacksTurn = true;
Move nextMove = new Move(0,0);
while(!nextMove.equals(new Move(-1,-1)))
{
if(blacksTurn)
{
nextMove = smartBlackPlayer.chooseMove(small4x4Board);
}else{
nextMove = smartWhitePlayer.chooseMove(small4x4Board);
}
//apply the move
small4x4Board.apply(nextMove, blacksTurn?PlayerType.BLACK:PlayerType.WHITE, true);
blacksTurn = !blacksTurn;
}
assertEquals(small4x4Board.scoreBoard(PlayerType.WHITE),8);
}
| public void testPerfectPlay() {
Board small4x4Board = new Board(DebugFunctions.make4x4OthelloString());
Boolean blacksTurn = true;
Move nextMove = new Move(0,0);
int consecutivePasses = 0;
while(consecutivePasses < 2)
{
if(blacksTurn)
{
nextMove = smartBlackPlayer.chooseMove(small4x4Board);
}else{
nextMove = smartWhitePlayer.chooseMove(small4x4Board);
}
if (nextMove.equals(Move.NO_MOVE)) {
consecutivePasses++;
} else {
//apply the move
small4x4Board.apply(nextMove, blacksTurn?PlayerType.BLACK:PlayerType.WHITE, true);
consecutivePasses = 0;
}
blacksTurn = !blacksTurn;
}
assertEquals(8, small4x4Board.scoreBoard(PlayerType.WHITE));
}
|
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/app/routing/QoSTestApp.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/app/routing/QoSTestApp.java
index f5bacab2..3e1a0d8c 100644
--- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/app/routing/QoSTestApp.java
+++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/app/routing/QoSTestApp.java
@@ -1,739 +1,743 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management
* Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* 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.
******************************************************************************/
package de.tuilmenau.ics.fog.app.routing;
import java.rmi.RemoteException;
import java.util.LinkedList;
import java.util.Random;
import java.util.HashMap;
import de.tuilmenau.ics.fog.application.ThreadApplication;
import de.tuilmenau.ics.fog.application.util.Session;
import de.tuilmenau.ics.fog.facade.Connection;
import de.tuilmenau.ics.fog.facade.Name;
import de.tuilmenau.ics.fog.facade.NetworkException;
import de.tuilmenau.ics.fog.packets.InvisibleMarker;
import de.tuilmenau.ics.fog.routing.hierarchical.HRMConfig;
import de.tuilmenau.ics.fog.routing.hierarchical.HRMController;
import de.tuilmenau.ics.fog.routing.hierarchical.IHRMApi;
import de.tuilmenau.ics.fog.routing.hierarchical.properties.HRMRoutingProperty;
import de.tuilmenau.ics.fog.routing.naming.HierarchicalNameMappingService;
import de.tuilmenau.ics.fog.routing.naming.NameMappingEntry;
import de.tuilmenau.ics.fog.routing.naming.NameMappingService;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID;
import de.tuilmenau.ics.fog.topology.Node;
import de.tuilmenau.ics.fog.ui.Logging;
import de.tuilmenau.ics.fog.ui.Marker;
import de.tuilmenau.ics.fog.ui.MarkerContainer;
import de.tuilmenau.ics.fog.ui.eclipse.commands.hierarchical.ProbeRouting;
import de.tuilmenau.ics.fog.util.SimpleName;
/**
* This class is responsible for creating QoS-probe connections and also for their destruction.
*/
public class QoSTestApp extends ThreadApplication
{
/**
* Stores a reference to the NMS instance.
*/
private NameMappingService mNMS = null;
/**
* Stores the current node where the probe routing should start
*/
private Node mNode = null;
/**
* Stores the name of the destination node
*/
private Name mDestinationNodeName = null;
/**
* Stores the last destination HRMID
*/
private HRMID mDestinationHRMID = null;
/**
* Stores the established connections
*/
private LinkedList<Connection> mConnections = new LinkedList<Connection>();
private HashMap<Connection, QoSTestAppSession> mConnectionSessions = new HashMap<Connection, QoSTestAppSession>();
/**
* Stores the established connections with fulfilled QoS requirements
*/
private LinkedList<Connection> mConnectionsWithFulfilledQoS = new LinkedList<Connection>();
/**
* Stores the established connections with feedback
*/
private LinkedList<Connection> mConnectionsWithFeedback = new LinkedList<Connection>();
/**
* Stores the marker per connection
*/
private HashMap<Connection, Marker> mMarkers = new HashMap<Connection, Marker>();
/**
* Stores the default max. desired delay in [ms]
*/
private int mDefaultDelay = 53; // some random number above 0
/**
* Stores the default min. desired data rate in [kbit/s]
*/
private int mDefaultDataRate = 1000;
/**
* Stores if the QoSTestApp is still needed or is already exit
*/
private boolean mQoSTestAppNeeded = true;
/**
* Stores if the QoSTestApp is running
*/
private boolean mQoSTestAppRunning = false;
/**
* The possible operations: increase/decrease connection amount
*/
private enum Operation{INC_CONN, DEC_CONN};
/**
* The pending operations
*/
private LinkedList<Operation> mOperations = new LinkedList<Operation>();
// debugging?
private boolean DEBUG = false;
/**
* Constructor
*
* @param pLocalNode the local node where this app. instance is running
*/
public QoSTestApp(Node pLocalNode)
{
super(pLocalNode, null);
mNode = pLocalNode;
/**
* Get a reference to the naming-service
*/
try {
mNMS = HierarchicalNameMappingService.getGlobalNameMappingService(mNode.getAS().getSimulation());
} catch (RuntimeException tExc) {
mNMS = HierarchicalNameMappingService.createGlobalNameMappingService(mNode.getAS().getSimulation());
}
}
/**
* Returns a reference to the local HRMApi
*
* @return the HRMApi
*/
public IHRMApi getHRMApi()
{
IHRMApi tResult = HRMController.getHRMApi(mNode);
return tResult;
}
/**
* Constructor
*
* @param pLocalNode the local node where this app. instance is running
* @param pDestinationNodeNameStr the name of the destination node as string
*/
public QoSTestApp(Node pLocalNode, String pDestinationNodeNameStr)
{
this(pLocalNode);
setDestination(pDestinationNodeNameStr);
}
/**
* Sets a new destination node name
*
* @param pDestinationNodeNamestr the new destination node name
*/
public void setDestination(String pDestinationNodeNameStr)
{
mDestinationNodeName = new SimpleName(Node.NAMESPACE_HOST, pDestinationNodeNameStr);
}
/**
* Determines the HRMIDs of the destination node
*
* @return the list of HRMIDs
*/
private LinkedList<HRMID> getDestinationHRMIDsFromDNS()
{
LinkedList<HRMID> tResult = new LinkedList<HRMID>();
/**
* Get the HRMID of the destination node
*/
// send a HRM probe-packet to each registered address for the given target name
try {
for(NameMappingEntry<?> tNMSEntryForTarget : mNMS.getAddresses(mDestinationNodeName)) {
if(tNMSEntryForTarget.getAddress() instanceof HRMID) {
// get the HRMID of the target node
HRMID tTargetNodeHRMID = (HRMID)tNMSEntryForTarget.getAddress();
if(DEBUG){
Logging.log(this, "Found in the NMS the HRMID " + tTargetNodeHRMID.toString() + " for node " + mDestinationNodeName);
}
}
}
for(NameMappingEntry<?> tNMSEntryForTarget : mNMS.getAddresses(mDestinationNodeName)) {
if(tNMSEntryForTarget.getAddress() instanceof HRMID) {
// get the HRMID of the target node
HRMID tDestinationNodeHRMID = (HRMID)tNMSEntryForTarget.getAddress();
// an entry in the result list
tResult.add(tDestinationNodeHRMID);
}
}
} catch (RemoteException tExc) {
Logging.err(this, "Unable to determine addresses for node " + mDestinationNodeName, tExc);
}
return tResult;
}
/**
* Returns the best HRMID of the destination node
*
* @return the best HRMID of the destination node
*/
private HRMID getBestDestinationHRMIDFromDNS()
{
HRMID tResult = null;
LinkedList<HRMID> tDestinationHRMIDs = getDestinationHRMIDsFromDNS();
if((tDestinationHRMIDs != null) && (!tDestinationHRMIDs.isEmpty())){
// use first HRMID as default value
tResult = tDestinationHRMIDs.getFirst();
// search for a better choice
for(HRMID tHRMID : tDestinationHRMIDs){
IHRMApi tHRMApi = HRMController.getHRMApi(mNode);
if(tHRMApi != null){
if(!tHRMApi.isLocalCluster(tHRMID.getClusterAddress(0))){
tResult = tHRMID;
break;
}
}
}
}
return tResult;
}
/**
* EVENT: increase connections
*/
public synchronized void eventIncreaseConnections()
{
if(DEBUG){
Logging.log(this, "EVENT: increase connections (currently: " + countConnections() + ")");
}
synchronized (mOperations) {
mOperations.add(Operation.INC_CONN);
}
notify();
}
/**
* EVENT: decrease connections
*/
public synchronized void eventDecreaseConnections()
{
if(DEBUG){
Logging.log(this, "EVENT: decrease connections (currently: " + countConnections() + ")");
}
synchronized (mOperations) {
mOperations.add(Operation.DEC_CONN);
}
notify();
}
/**
* Returns the default delay
*
* @return the default delay
*/
public int getDefaultDelay()
{
return mDefaultDelay;
}
/**
* Sets a new default delay for future connections
*
* @param pDefaultDelay the new default delay
*/
public void setDefaultDelay(int pDefaultDelay)
{
mDefaultDelay = pDefaultDelay;
}
/**
* Returns the default data rate
*
* @return the default data rate
*/
public int getDefaultDataRate()
{
return mDefaultDataRate;
}
/**
* Sets a new default data rate for future connections
*
* @param pDefaultDataRate the new default data rate
*/
public void setDefaultDataRate(int pDefaultDataRate)
{
mDefaultDataRate = pDefaultDataRate;
}
/**
* Sends a marker along an established connection
*
* @param pConnection the connection, whose route should be marked
*/
private void sendMarker(Connection pConnection)
{
Random tRandom = new Random();
int tRed = (int)(tRandom.nextFloat() * 128) + 127;
int tGreen = (int)(tRandom.nextFloat() * 128) + 127;
int tBlue = (int)(tRandom.nextFloat() * 128) + 127;
if(DEBUG){
Logging.log("Creating marker with coloring (" + tRed + ", " + tGreen + ", " + tBlue + ")");
}
java.awt.Color tMarkerColor = new java.awt.Color(tRed, tGreen, tBlue);
String tMarkerText = "Marker " +new Random().nextInt();
InvisibleMarker.Operation tMarkerOperation = InvisibleMarker.Operation.ADD;
Marker tMarker = new Marker(tMarkerText, tMarkerColor);
InvisibleMarker tMarkerPacketPayload = new InvisibleMarker(tMarker, tMarkerOperation);
// store the marker for this connection in order to be able to remove the marker later
mMarkers.put(pConnection, tMarker);
if(DEBUG){
//Logging.log(this, "Sending: " + tMarkerPacketPayload);
}
try {
pConnection.write(tMarkerPacketPayload);
} catch (NetworkException tExc) {
Logging.err(this, "sendMarker() wasn't able to send marker", tExc);
}
}
/**
* Returns the last destination HRMID
*
* @return the last destination HRMID
*/
public HRMID getLastDestinationHRMID()
{
return mDestinationHRMID;
}
/**
* Adds another connection
*/
private void incConnections()
{
if(DEBUG){
Logging.log(this, "Increasing connections (currently: " + countConnections() + ")");
}
HRMID tDestinationHRMID = getBestDestinationHRMIDFromDNS();
if(tDestinationHRMID != null){
mDestinationHRMID = tDestinationHRMID;
/**
* Connect to the destination node
*/
boolean tRetryConnection = false;
boolean tRetriedConnection = false;
int tAttemptNr = 1;
Connection tConnection = null;
do{
tRetryConnection = false;
tConnection = ProbeRouting.createProbeRoutingConnection(this, mNode, tDestinationHRMID, mDefaultDelay /* ms */, mDefaultDataRate /* kbit/s */, false);
- if((tConnection == null) && (tAttemptNr < HRMConfig.Hierarchy.CONNECTION_MAX_RETRIES)){
- tAttemptNr++;
- tRetryConnection = true;
- tRetriedConnection = true;
- Logging.warn(this, "Cannot connect to: " + tDestinationHRMID + ", connect attempt nr. " + tAttemptNr);
+ if(tConnection == null){
+ if(tAttemptNr < HRMConfig.Hierarchy.CONNECTION_MAX_RETRIES){
+ tAttemptNr++;
+ tRetryConnection = true;
+ tRetriedConnection = true;
+ Logging.warn(this, "Cannot connect to: " + tDestinationHRMID + ", connect attempt nr. " + tAttemptNr);
+ }else{
+ Logging.err(this, "Give up, no connection possible to: " + tDestinationHRMID + " with QoS: " + mDefaultDelay + "ms, " + mDefaultDataRate + "kbit/s");
+ }
}
}while((tRetryConnection) && (mQoSTestAppNeeded));
/**
* Check if connect request was successful
*/
if(tConnection != null){
if(tRetriedConnection){
Logging.warn(this, "Successfully recovered from connection problems towards: " + tDestinationHRMID + ", connect attempts: " + tAttemptNr);
}
if(DEBUG){
Logging.log(this, " ..found valid connection to " + tDestinationHRMID);
}
synchronized (mConnections) {
mConnections.add(tConnection);
}
/**
* Create the connection session
*/
QoSTestAppSession tConnectionSession = new QoSTestAppSession(this);
tConnectionSession.start(tConnection);
synchronized (mConnectionSessions) {
mConnectionSessions.put(tConnection, tConnectionSession);
}
/**
* Send some test data
*/
// for(int i = 0; i < 3; i++){
// try {
// //Logging.log(this, " ..sending test data " + i);
// tConnection.write("TEST DATA " + Integer.toString(i));
// } catch (NetworkException tExc) {
// Logging.err(this, "Couldn't send test data", tExc);
// }
// }
/**
* Send connection marker
*/
sendMarker(tConnection);
}
}else{
Logging.err(this, "No destination HRMID found for: " + mDestinationNodeName);
}
}
/**
* Removes the last connection
*/
private void decConnections()
{
if(DEBUG){
Logging.log(this, "Decreasing connections (currently: " + countConnections() + ")");
}
/**
* get the last connection
*/
Connection tConnection = null;
synchronized (mConnections) {
if(countConnections() > 0){
tConnection = mConnections.removeLast();
if(DEBUG){
Logging.log(this, " ..seleted for renoving the connection: " + tConnection);
}
}
}
if(tConnection != null){
/**
* Remove the marker
*/
synchronized(mMarkers){
Marker tMarker = mMarkers.get(tConnection);
if(tMarker != null){
mMarkers.remove(tConnection);
MarkerContainer.getInstance().removeMarker(tMarker);
}
}
/**
* Stop the connection session
*/
QoSTestAppSession tConnectionSession = null;
synchronized (mConnectionSessions) {
tConnectionSession = mConnectionSessions.remove(tConnection);
}
if(tConnectionSession != null){
tConnectionSession.stop();
}
/**
* Disconnect by closing the connection
*/
tConnection.close();
/**
* Remove as QoS connection
*/
synchronized (mConnectionsWithFulfilledQoS) {
if(mConnectionsWithFulfilledQoS.contains(tConnection)){
mConnectionsWithFulfilledQoS.remove(tConnection);
}
}
synchronized (mConnectionsWithFeedback) {
if(mConnectionsWithFeedback.contains(tConnection)){
mConnectionsWithFeedback.remove(tConnection);
}
}
}
}
/**
* Counts the already established connections which fulfill the desired QoS requirements
*
* @return the number of connections
*/
public int countConnectionsWithFulfilledQoS()
{
int tResult = 0;
synchronized (mConnectionsWithFulfilledQoS) {
tResult = mConnectionsWithFulfilledQoS.size();
}
return tResult;
}
/**
* Counts the already established connections which have already a feedback from the server to the client (this app)
*
* @return the number of connections
*/
public int countConnectionsWithFeedback()
{
int tResult = 0;
synchronized (mConnectionsWithFeedback) {
tResult = mConnectionsWithFeedback.size();
}
return tResult;
}
/**
* Counts the already established connections
*
* @return the number of connections
*/
public int countConnections()
{
int tResult = 0;
synchronized (mConnections) {
if(mConnections != null){
tResult = mConnections.size();
}
}
if(DEBUG){
//Logging.log(this, "Connections: " + tResult);
}
return tResult;
}
/**
* Waits for the next wake-up signal (a new event was triggered)
*/
private synchronized void waitForNextEvent()
{
// suspend until next trigger
try {
wait();
//Logging.log(this, "WakeUp");
} catch (InterruptedException tExc) {
Logging.warn(this, "waitForNextEvent() got an interrupt", tExc);
}
}
/**
* The main loop
*/
/* (non-Javadoc)
* @see de.tuilmenau.ics.fog.application.ThreadApplication#execute()
*/
@Override
protected void execute()
{
Thread.currentThread().setName(getClass().getSimpleName() + "@" + mNode);
/**
* START
*/
Logging.log(this, "Main loop started");
mQoSTestAppRunning = true;
/**
* MAIN LOOP
*/
while(mQoSTestAppNeeded){
Operation tNextOperation = null;
do{
/**
* Get the next operation
*/
tNextOperation = null;
synchronized (mOperations) {
if(mOperations.size() > 0){
tNextOperation = mOperations.removeFirst();
}
}
/**
* Process the next operation
*/
if(tNextOperation != null){
if(DEBUG){
Logging.log(this, "Processing operation: " + tNextOperation);
}
switch(tNextOperation)
{
case INC_CONN:
incConnections();
break;
case DEC_CONN:
decConnections();
break;
default:
break;
}
}
}while(tNextOperation != null);
waitForNextEvent();
}
/**
* Close all existing connections
*/
while(countConnections() > 0){
decConnections();
}
/**
* END
*/
Logging.log(this, "Main loop finished");
mQoSTestAppRunning = false;
}
/**
* Exit the QoS test app. right now
*/
/* (non-Javadoc)
* @see de.tuilmenau.ics.fog.application.Application#exit()
*/
@Override
public synchronized void exit()
{
Logging.log(this, "exit() starting... (running: " + isRunning() + ")");
mQoSTestAppNeeded = false;
// wakeup
if(isRunning()){
notifyAll();
}
Logging.log(this, "..exit() finished");
}
/**
* Returns if the QoS test app. is still running
*
* @return true or false
*/
/* (non-Javadoc)
* @see de.tuilmenau.ics.fog.application.Application#isRunning()
*/
@Override
public boolean isRunning()
{
return mQoSTestAppRunning;
}
/**
* Returns a descriptive string about this app.
*
* @return the descriptive string
*/
@Override
public String toString()
{
return getClass().getSimpleName() +"@" + mNode;
}
private class QoSTestAppSession extends Session
{
private QoSTestApp mQoSTestApp = null;
public QoSTestAppSession(QoSTestApp pQoSTestApp)
{
super(false, mHost.getLogger(), null);
mQoSTestApp = pQoSTestApp;
}
@Override
public boolean receiveData(Object pData) {
boolean tResult = false;
// incoming UDP encapsulation data
if (pData instanceof HRMRoutingProperty){
HRMRoutingProperty tProbeRoutingProperty = (HRMRoutingProperty)pData;
//if(DEBUG){
Logging.log(mQoSTestApp, "Received ProbeRoutingProperty: ");
tProbeRoutingProperty.logAll(this);
//}
//tProbeRoutingProperty.logAll(mQoSTestApp);
/**
* Count the number of connections with fulfilled QoS requirements
*/
boolean tQoSFulfilled = true;
if((tProbeRoutingProperty.getDesiredDelay() > 0) && (tProbeRoutingProperty.getDesiredDelay() < tProbeRoutingProperty.getRecordedDelay())){
tQoSFulfilled = false;
}
if((tProbeRoutingProperty.getDesiredDataRate() > 0) && (tProbeRoutingProperty.getDesiredDataRate() > tProbeRoutingProperty.getRecordedDataRate())){
tQoSFulfilled = false;
}
if(tQoSFulfilled){
synchronized (mConnectionsWithFulfilledQoS) {
mConnectionsWithFulfilledQoS.add(getConnection());
}
}
/**
* Count the number of connections with a valid feedback
*/
synchronized (mConnectionsWithFeedback) {
mConnectionsWithFeedback.add(getConnection());
}
tResult = true;
}else{
getLogger().warn(this, "Malformed received data from HRMController: " + pData);
}
return tResult;
}
}
}
| true | true | private void incConnections()
{
if(DEBUG){
Logging.log(this, "Increasing connections (currently: " + countConnections() + ")");
}
HRMID tDestinationHRMID = getBestDestinationHRMIDFromDNS();
if(tDestinationHRMID != null){
mDestinationHRMID = tDestinationHRMID;
/**
* Connect to the destination node
*/
boolean tRetryConnection = false;
boolean tRetriedConnection = false;
int tAttemptNr = 1;
Connection tConnection = null;
do{
tRetryConnection = false;
tConnection = ProbeRouting.createProbeRoutingConnection(this, mNode, tDestinationHRMID, mDefaultDelay /* ms */, mDefaultDataRate /* kbit/s */, false);
if((tConnection == null) && (tAttemptNr < HRMConfig.Hierarchy.CONNECTION_MAX_RETRIES)){
tAttemptNr++;
tRetryConnection = true;
tRetriedConnection = true;
Logging.warn(this, "Cannot connect to: " + tDestinationHRMID + ", connect attempt nr. " + tAttemptNr);
}
}while((tRetryConnection) && (mQoSTestAppNeeded));
/**
* Check if connect request was successful
*/
if(tConnection != null){
if(tRetriedConnection){
Logging.warn(this, "Successfully recovered from connection problems towards: " + tDestinationHRMID + ", connect attempts: " + tAttemptNr);
}
if(DEBUG){
Logging.log(this, " ..found valid connection to " + tDestinationHRMID);
}
synchronized (mConnections) {
mConnections.add(tConnection);
}
/**
* Create the connection session
*/
QoSTestAppSession tConnectionSession = new QoSTestAppSession(this);
tConnectionSession.start(tConnection);
synchronized (mConnectionSessions) {
mConnectionSessions.put(tConnection, tConnectionSession);
}
/**
* Send some test data
*/
// for(int i = 0; i < 3; i++){
// try {
// //Logging.log(this, " ..sending test data " + i);
// tConnection.write("TEST DATA " + Integer.toString(i));
// } catch (NetworkException tExc) {
// Logging.err(this, "Couldn't send test data", tExc);
// }
// }
/**
* Send connection marker
*/
sendMarker(tConnection);
}
}else{
Logging.err(this, "No destination HRMID found for: " + mDestinationNodeName);
}
}
| private void incConnections()
{
if(DEBUG){
Logging.log(this, "Increasing connections (currently: " + countConnections() + ")");
}
HRMID tDestinationHRMID = getBestDestinationHRMIDFromDNS();
if(tDestinationHRMID != null){
mDestinationHRMID = tDestinationHRMID;
/**
* Connect to the destination node
*/
boolean tRetryConnection = false;
boolean tRetriedConnection = false;
int tAttemptNr = 1;
Connection tConnection = null;
do{
tRetryConnection = false;
tConnection = ProbeRouting.createProbeRoutingConnection(this, mNode, tDestinationHRMID, mDefaultDelay /* ms */, mDefaultDataRate /* kbit/s */, false);
if(tConnection == null){
if(tAttemptNr < HRMConfig.Hierarchy.CONNECTION_MAX_RETRIES){
tAttemptNr++;
tRetryConnection = true;
tRetriedConnection = true;
Logging.warn(this, "Cannot connect to: " + tDestinationHRMID + ", connect attempt nr. " + tAttemptNr);
}else{
Logging.err(this, "Give up, no connection possible to: " + tDestinationHRMID + " with QoS: " + mDefaultDelay + "ms, " + mDefaultDataRate + "kbit/s");
}
}
}while((tRetryConnection) && (mQoSTestAppNeeded));
/**
* Check if connect request was successful
*/
if(tConnection != null){
if(tRetriedConnection){
Logging.warn(this, "Successfully recovered from connection problems towards: " + tDestinationHRMID + ", connect attempts: " + tAttemptNr);
}
if(DEBUG){
Logging.log(this, " ..found valid connection to " + tDestinationHRMID);
}
synchronized (mConnections) {
mConnections.add(tConnection);
}
/**
* Create the connection session
*/
QoSTestAppSession tConnectionSession = new QoSTestAppSession(this);
tConnectionSession.start(tConnection);
synchronized (mConnectionSessions) {
mConnectionSessions.put(tConnection, tConnectionSession);
}
/**
* Send some test data
*/
// for(int i = 0; i < 3; i++){
// try {
// //Logging.log(this, " ..sending test data " + i);
// tConnection.write("TEST DATA " + Integer.toString(i));
// } catch (NetworkException tExc) {
// Logging.err(this, "Couldn't send test data", tExc);
// }
// }
/**
* Send connection marker
*/
sendMarker(tConnection);
}
}else{
Logging.err(this, "No destination HRMID found for: " + mDestinationNodeName);
}
}
|
diff --git a/src/main/java/br/org/indt/ndg/mobile/SortsKeys.java b/src/main/java/br/org/indt/ndg/mobile/SortsKeys.java
index 5a3fa07..ff9b16a 100644
--- a/src/main/java/br/org/indt/ndg/mobile/SortsKeys.java
+++ b/src/main/java/br/org/indt/ndg/mobile/SortsKeys.java
@@ -1,61 +1,61 @@
/*
* Sorts.java
*
* Created on November 6, 2007, 2:18 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package br.org.indt.ndg.mobile;
import java.util.Vector;
/**
*
* @author tdickes
*/
public class SortsKeys {
/** Creates a new instance of Sorts */
public SortsKeys() {
}
//Vector of Strings version
public void qsort(Vector list) {
quicksort(list, 0, list.size()-1);
}
//Vector of Strings version
private void quicksort(Vector list, int p, int r) {
if (p < r) {
int q = qpartition(list, p, r);
if (q == r) {
q--;
}
quicksort(list, p, q);
quicksort(list, q+1, r);
}
}
//Vector of Strings version
private int qpartition(Vector list, int p, int r) {
- String pivot = (String)list.elementAt(p);
+ int pivot = Integer.parseInt((String)list.elementAt(p));
int lo = p;
int hi = r;
while (true) {
- while ( ((String)list.elementAt(hi)).compareTo(pivot) >= 0 && lo < hi) {
+ while ( Integer.parseInt((String)list.elementAt(hi)) >= pivot && lo < hi) {
hi--;
}
- while ( ((String) list.elementAt(lo)).compareTo(pivot) < 0 && lo < hi) {
+ while ( Integer.parseInt((String) list.elementAt(lo)) < pivot && lo < hi) {
lo++;
}
if (lo < hi) {
String T = (String) list.elementAt(lo);
list.setElementAt(list.elementAt(hi), lo);
list.setElementAt(T, hi);
}
else return hi;
}
}
}
| false | true | private int qpartition(Vector list, int p, int r) {
String pivot = (String)list.elementAt(p);
int lo = p;
int hi = r;
while (true) {
while ( ((String)list.elementAt(hi)).compareTo(pivot) >= 0 && lo < hi) {
hi--;
}
while ( ((String) list.elementAt(lo)).compareTo(pivot) < 0 && lo < hi) {
lo++;
}
if (lo < hi) {
String T = (String) list.elementAt(lo);
list.setElementAt(list.elementAt(hi), lo);
list.setElementAt(T, hi);
}
else return hi;
}
}
| private int qpartition(Vector list, int p, int r) {
int pivot = Integer.parseInt((String)list.elementAt(p));
int lo = p;
int hi = r;
while (true) {
while ( Integer.parseInt((String)list.elementAt(hi)) >= pivot && lo < hi) {
hi--;
}
while ( Integer.parseInt((String) list.elementAt(lo)) < pivot && lo < hi) {
lo++;
}
if (lo < hi) {
String T = (String) list.elementAt(lo);
list.setElementAt(list.elementAt(hi), lo);
list.setElementAt(T, hi);
}
else return hi;
}
}
|
diff --git a/src/servers/src/org/xtreemfs/common/util/Nettest.java b/src/servers/src/org/xtreemfs/common/util/Nettest.java
index 3edb2c4b..936a1605 100644
--- a/src/servers/src/org/xtreemfs/common/util/Nettest.java
+++ b/src/servers/src/org/xtreemfs/common/util/Nettest.java
@@ -1,81 +1,82 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.xtreemfs.common.util;
import org.xtreemfs.common.buffer.BufferPool;
import org.xtreemfs.common.buffer.ReusableBuffer;
import org.xtreemfs.foundation.ErrNo;
import org.xtreemfs.foundation.oncrpc.server.ONCRPCRequest;
import org.xtreemfs.foundation.oncrpc.utils.XDRUnmarshaller;
import org.xtreemfs.interfaces.DIRInterface.ProtocolException;
import org.xtreemfs.interfaces.NettestInterface.nopRequest;
import org.xtreemfs.interfaces.NettestInterface.nopResponse;
import org.xtreemfs.interfaces.NettestInterface.recv_bufferRequest;
import org.xtreemfs.interfaces.NettestInterface.recv_bufferResponse;
import org.xtreemfs.interfaces.NettestInterface.send_bufferRequest;
import org.xtreemfs.interfaces.NettestInterface.send_bufferResponse;
import org.xtreemfs.interfaces.utils.ONCRPCRequestHeader;
import org.xtreemfs.interfaces.utils.ONCRPCResponseHeader;
import org.xtreemfs.interfaces.utils.XDRUtils;
/**
*
* @author bjko
*/
public class Nettest {
public static void handleNettest(ONCRPCRequestHeader header, ONCRPCRequest rq) {
try {
if (header.getMessageType() != XDRUtils.TYPE_CALL) {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_GARBAGE_ARGS,
ErrNo.EINVAL, "message type must be CALL"));
return;
}
switch (header.getProcedure()) {
case send_bufferRequest.TAG: {
send_bufferRequest pRq = new send_bufferRequest();
pRq.unmarshal(new XDRUnmarshaller(rq.getRequestFragment()));
send_bufferResponse pResp = new send_bufferResponse();
+ BufferPool.free(pRq.getData());
rq.sendResponse(pResp);
break;
}
case recv_bufferRequest.TAG: {
recv_bufferRequest pRq = new recv_bufferRequest();
pRq.unmarshal(new XDRUnmarshaller(rq.getRequestFragment()));
if (pRq.getSize() > 1024*1024*2) {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_GARBAGE_ARGS,
ErrNo.EINVAL, "max buffer size is 2MB"));
return;
}
ReusableBuffer data = BufferPool.allocate(pRq.getSize());
data.position(0);
data.limit(data.capacity());
recv_bufferResponse pResp = new recv_bufferResponse(data);
rq.sendResponse(pResp);
break;
}
case nopRequest.TAG: {
nopResponse response = new nopResponse();
rq.sendResponse(response);
break;
}
default: {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_PROC_UNAVAIL,
ErrNo.EINVAL, "requested operation is not available on this DIR"));
return;
}
}
} catch (Exception ex) {
try {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_SYSTEM_ERR,
ErrNo.EINVAL, "internal server error:"+ex));
} catch (Throwable th) {
//ignore
}
}
}
}
| true | true | public static void handleNettest(ONCRPCRequestHeader header, ONCRPCRequest rq) {
try {
if (header.getMessageType() != XDRUtils.TYPE_CALL) {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_GARBAGE_ARGS,
ErrNo.EINVAL, "message type must be CALL"));
return;
}
switch (header.getProcedure()) {
case send_bufferRequest.TAG: {
send_bufferRequest pRq = new send_bufferRequest();
pRq.unmarshal(new XDRUnmarshaller(rq.getRequestFragment()));
send_bufferResponse pResp = new send_bufferResponse();
rq.sendResponse(pResp);
break;
}
case recv_bufferRequest.TAG: {
recv_bufferRequest pRq = new recv_bufferRequest();
pRq.unmarshal(new XDRUnmarshaller(rq.getRequestFragment()));
if (pRq.getSize() > 1024*1024*2) {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_GARBAGE_ARGS,
ErrNo.EINVAL, "max buffer size is 2MB"));
return;
}
ReusableBuffer data = BufferPool.allocate(pRq.getSize());
data.position(0);
data.limit(data.capacity());
recv_bufferResponse pResp = new recv_bufferResponse(data);
rq.sendResponse(pResp);
break;
}
case nopRequest.TAG: {
nopResponse response = new nopResponse();
rq.sendResponse(response);
break;
}
default: {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_PROC_UNAVAIL,
ErrNo.EINVAL, "requested operation is not available on this DIR"));
return;
}
}
} catch (Exception ex) {
try {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_SYSTEM_ERR,
ErrNo.EINVAL, "internal server error:"+ex));
} catch (Throwable th) {
//ignore
}
}
}
| public static void handleNettest(ONCRPCRequestHeader header, ONCRPCRequest rq) {
try {
if (header.getMessageType() != XDRUtils.TYPE_CALL) {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_GARBAGE_ARGS,
ErrNo.EINVAL, "message type must be CALL"));
return;
}
switch (header.getProcedure()) {
case send_bufferRequest.TAG: {
send_bufferRequest pRq = new send_bufferRequest();
pRq.unmarshal(new XDRUnmarshaller(rq.getRequestFragment()));
send_bufferResponse pResp = new send_bufferResponse();
BufferPool.free(pRq.getData());
rq.sendResponse(pResp);
break;
}
case recv_bufferRequest.TAG: {
recv_bufferRequest pRq = new recv_bufferRequest();
pRq.unmarshal(new XDRUnmarshaller(rq.getRequestFragment()));
if (pRq.getSize() > 1024*1024*2) {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_GARBAGE_ARGS,
ErrNo.EINVAL, "max buffer size is 2MB"));
return;
}
ReusableBuffer data = BufferPool.allocate(pRq.getSize());
data.position(0);
data.limit(data.capacity());
recv_bufferResponse pResp = new recv_bufferResponse(data);
rq.sendResponse(pResp);
break;
}
case nopRequest.TAG: {
nopResponse response = new nopResponse();
rq.sendResponse(response);
break;
}
default: {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_PROC_UNAVAIL,
ErrNo.EINVAL, "requested operation is not available on this DIR"));
return;
}
}
} catch (Exception ex) {
try {
rq.sendException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_SYSTEM_ERR,
ErrNo.EINVAL, "internal server error:"+ex));
} catch (Throwable th) {
//ignore
}
}
}
|
diff --git a/api/src/main/java/org/openmrs/api/handler/PersonSaveHandler.java b/api/src/main/java/org/openmrs/api/handler/PersonSaveHandler.java
index e0dacb40..75a05647 100644
--- a/api/src/main/java/org/openmrs/api/handler/PersonSaveHandler.java
+++ b/api/src/main/java/org/openmrs/api/handler/PersonSaveHandler.java
@@ -1,113 +1,113 @@
/**
* 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.api.handler;
import java.util.Date;
import org.openmrs.Person;
import org.openmrs.PersonAddress;
import org.openmrs.PersonAttribute;
import org.openmrs.PersonName;
import org.openmrs.User;
import org.openmrs.annotation.Handler;
import org.openmrs.aop.RequiredDataAdvice;
import org.openmrs.api.APIException;
import org.springframework.util.StringUtils;
/**
* This class deals with {@link Person} objects when they are saved via a save* method in an Openmrs
* Service. This handler is automatically called by the {@link RequiredDataAdvice} AOP class. <br/>
*
* @see RequiredDataHandler
* @see SaveHandler
* @see Person
* @since 1.5
*/
@Handler(supports = Person.class)
public class PersonSaveHandler implements SaveHandler<Person> {
/**
* @see org.openmrs.api.handler.SaveHandler#handle(org.openmrs.OpenmrsObject, org.openmrs.User,
* java.util.Date, java.lang.String)
*/
public void handle(Person person, User creator, Date dateCreated, String other) {
// only set the creator and date created if they weren't set by the developer already
if (person.getPersonCreator() == null) {
person.setPersonCreator(creator);
}
if (person.getPersonDateCreated() == null) {
person.setPersonDateCreated(dateCreated);
}
// if there is an id already, we assume its been saved before and so set personChanged*
boolean hasId;
try {
hasId = person.getId() != null;
}
catch (UnsupportedOperationException e) {
hasId = true; // if no "id" to check, just go ahead and set them
}
if (hasId) {
person.setPersonChangedBy(creator);
person.setPersonDateChanged(dateCreated);
}
// address collection
if (person.getAddresses() != null && person.getAddresses().size() > 0) {
for (PersonAddress pAddress : person.getAddresses()) {
pAddress.setPerson(person);
}
}
// name collection
if (person.getNames() != null && person.getNames().size() > 0) {
for (PersonName pName : person.getNames()) {
pName.setPerson(person);
}
}
// attribute collection
if (person.getAttributes() != null && person.getAttributes().size() > 0) {
for (PersonAttribute pAttr : person.getAttributes()) {
pAttr.setPerson(person);
}
}
//if the patient was marked as dead and reversed, drop the cause of death
if (!person.isDead() && person.getCauseOfDeath() != null)
person.setCauseOfDeath(null);
// do the checks for voided attributes (also in PersonVoidHandler)
if (person.isPersonVoided()) {
- if (!StringUtils.hasLength(person.getVoidReason()))
+ if (!StringUtils.hasLength(person.getPersonVoidReason()))
throw new APIException(
"The voided bit was set to true, so a void reason is required at save time for person: " + person);
if (person.getPersonVoidedBy() == null) {
person.setPersonVoidedBy(creator);
}
if (person.getPersonDateVoided() == null) {
person.setPersonDateVoided(dateCreated);
}
} else {
// voided is set to false
person.setPersonVoidedBy(null);
person.setPersonDateVoided(null);
person.setPersonVoidReason(null);
}
}
}
| true | true | public void handle(Person person, User creator, Date dateCreated, String other) {
// only set the creator and date created if they weren't set by the developer already
if (person.getPersonCreator() == null) {
person.setPersonCreator(creator);
}
if (person.getPersonDateCreated() == null) {
person.setPersonDateCreated(dateCreated);
}
// if there is an id already, we assume its been saved before and so set personChanged*
boolean hasId;
try {
hasId = person.getId() != null;
}
catch (UnsupportedOperationException e) {
hasId = true; // if no "id" to check, just go ahead and set them
}
if (hasId) {
person.setPersonChangedBy(creator);
person.setPersonDateChanged(dateCreated);
}
// address collection
if (person.getAddresses() != null && person.getAddresses().size() > 0) {
for (PersonAddress pAddress : person.getAddresses()) {
pAddress.setPerson(person);
}
}
// name collection
if (person.getNames() != null && person.getNames().size() > 0) {
for (PersonName pName : person.getNames()) {
pName.setPerson(person);
}
}
// attribute collection
if (person.getAttributes() != null && person.getAttributes().size() > 0) {
for (PersonAttribute pAttr : person.getAttributes()) {
pAttr.setPerson(person);
}
}
//if the patient was marked as dead and reversed, drop the cause of death
if (!person.isDead() && person.getCauseOfDeath() != null)
person.setCauseOfDeath(null);
// do the checks for voided attributes (also in PersonVoidHandler)
if (person.isPersonVoided()) {
if (!StringUtils.hasLength(person.getVoidReason()))
throw new APIException(
"The voided bit was set to true, so a void reason is required at save time for person: " + person);
if (person.getPersonVoidedBy() == null) {
person.setPersonVoidedBy(creator);
}
if (person.getPersonDateVoided() == null) {
person.setPersonDateVoided(dateCreated);
}
} else {
// voided is set to false
person.setPersonVoidedBy(null);
person.setPersonDateVoided(null);
person.setPersonVoidReason(null);
}
}
| public void handle(Person person, User creator, Date dateCreated, String other) {
// only set the creator and date created if they weren't set by the developer already
if (person.getPersonCreator() == null) {
person.setPersonCreator(creator);
}
if (person.getPersonDateCreated() == null) {
person.setPersonDateCreated(dateCreated);
}
// if there is an id already, we assume its been saved before and so set personChanged*
boolean hasId;
try {
hasId = person.getId() != null;
}
catch (UnsupportedOperationException e) {
hasId = true; // if no "id" to check, just go ahead and set them
}
if (hasId) {
person.setPersonChangedBy(creator);
person.setPersonDateChanged(dateCreated);
}
// address collection
if (person.getAddresses() != null && person.getAddresses().size() > 0) {
for (PersonAddress pAddress : person.getAddresses()) {
pAddress.setPerson(person);
}
}
// name collection
if (person.getNames() != null && person.getNames().size() > 0) {
for (PersonName pName : person.getNames()) {
pName.setPerson(person);
}
}
// attribute collection
if (person.getAttributes() != null && person.getAttributes().size() > 0) {
for (PersonAttribute pAttr : person.getAttributes()) {
pAttr.setPerson(person);
}
}
//if the patient was marked as dead and reversed, drop the cause of death
if (!person.isDead() && person.getCauseOfDeath() != null)
person.setCauseOfDeath(null);
// do the checks for voided attributes (also in PersonVoidHandler)
if (person.isPersonVoided()) {
if (!StringUtils.hasLength(person.getPersonVoidReason()))
throw new APIException(
"The voided bit was set to true, so a void reason is required at save time for person: " + person);
if (person.getPersonVoidedBy() == null) {
person.setPersonVoidedBy(creator);
}
if (person.getPersonDateVoided() == null) {
person.setPersonDateVoided(dateCreated);
}
} else {
// voided is set to false
person.setPersonVoidedBy(null);
person.setPersonDateVoided(null);
person.setPersonVoidReason(null);
}
}
|
diff --git a/app/models/Shopper.java b/app/models/Shopper.java
index fe05b12..fc79f6c 100644
--- a/app/models/Shopper.java
+++ b/app/models/Shopper.java
@@ -1,125 +1,125 @@
package models;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import play.db.ebean.Model;
import play.libs.Json;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: epanahi
* Date: 12/6/12
* Time: 3:38 PM
* To change this template use File | Settings | File Templates.
*/
public class Shopper
{
/**
* Process the customer's request; evaluate their needs against the inventory and return to them
* a list of the optimal purchases.
* @param items The items that the customer wants, as JsonNodes containing priority, quantity etc.
* @param budget How much the customer wants to spend
* @return An object node with fields 'spent', 'budget', 'totalcost', 'bought', and 'notbought' (and 'status' to find out how it went)
*/
public static ObjectNode goShopping(ArrayNode items, double budget)
{
//Get the inventory
Map<String, InventoryItem> inventory = new Model.Finder(String.class, InventoryItem.class)
.setMapKey("name").findMap();
//Create a list of 'useful' objects so that it's easy to sort
List<ObjectNode> cart = new ArrayList<ObjectNode>();
Iterator<JsonNode> iter = items.getElements();
while (iter.hasNext())
{
JsonNode node = iter.next();
ObjectNode itemInfo = InventoryItem.asJsonNode(inventory.get(node.get("name").asText()));
itemInfo.put("buying", node.get("buying"));
itemInfo.put("priority", node.get("priority"));
cart.add(itemInfo);
}
Collections.sort(cart, new Comparator<ObjectNode>() {
@Override
public int compare(ObjectNode itemOne, ObjectNode itemTwo) {
Integer intOne = itemOne.get("priority").asInt();
Integer intTwo = itemTwo.get("priority").asInt();
int comparison = intOne.compareTo(intTwo) * -1; // reverse order, higher numbers should come first
if (comparison == 0) {
Double priceOne = itemOne.get("price").asDouble();
Double priceTwo = itemTwo.get("price").asDouble();
comparison = priceOne.compareTo(priceTwo);
}
return comparison;
}
});
ObjectNode result = Json.newObject();
ArrayNode bought = JsonNodeFactory.instance.arrayNode();
ArrayNode notbought = JsonNodeFactory.instance.arrayNode();
double totalcost = 0.0;
double spent = 0.0;
int currentIndex = 0;
Iterator<ObjectNode> buyer = cart.iterator();
while (buyer.hasNext())
{
ObjectNode node = buyer.next();
double price = node.get("price").asDouble();
int startingQuantity = node.get("buying").asInt();
int numLeftToBuy = startingQuantity;
totalcost += startingQuantity * price;
- while ((spent + price) < budget && numLeftToBuy > 0)
+ while ((spent + price) <= budget && numLeftToBuy > 0)
{
System.out.println(node.get("name").asText() + " " + startingQuantity + " " + numLeftToBuy + " " + currentIndex);
//Object hasn't been added to the array
if (numLeftToBuy == startingQuantity)
{
//Add the item and set quantity bought to 1
bought.add(node);
( (ObjectNode) bought.get(currentIndex)).put("buying", 1);
//Subtract 1 from the node and numLeftToBuy
numLeftToBuy--;
spent += price;
}
else //Increment the item that's already in the array
{
//We'll reverse these operations because we can use the decremented numLeft to evaluate
//how much has now been bought
numLeftToBuy--;
( (ObjectNode) bought.get(currentIndex)).put("buying", startingQuantity - numLeftToBuy);
spent += price;
}
}
if (numLeftToBuy > 0)
{
ObjectNode didntBuy = JsonNodeFactory.instance.objectNode();
didntBuy.putAll(node);
didntBuy.put("buying", numLeftToBuy);
notbought.add(didntBuy);
};
buyer.remove();
currentIndex++;
}
result.put("status", "OK");
result.put("spent", spent);
result.put("budget", budget);
result.put("totalcost", totalcost);
result.put("bought", bought);
result.put("notbought", notbought);
return result;
}
}
| true | true | public static ObjectNode goShopping(ArrayNode items, double budget)
{
//Get the inventory
Map<String, InventoryItem> inventory = new Model.Finder(String.class, InventoryItem.class)
.setMapKey("name").findMap();
//Create a list of 'useful' objects so that it's easy to sort
List<ObjectNode> cart = new ArrayList<ObjectNode>();
Iterator<JsonNode> iter = items.getElements();
while (iter.hasNext())
{
JsonNode node = iter.next();
ObjectNode itemInfo = InventoryItem.asJsonNode(inventory.get(node.get("name").asText()));
itemInfo.put("buying", node.get("buying"));
itemInfo.put("priority", node.get("priority"));
cart.add(itemInfo);
}
Collections.sort(cart, new Comparator<ObjectNode>() {
@Override
public int compare(ObjectNode itemOne, ObjectNode itemTwo) {
Integer intOne = itemOne.get("priority").asInt();
Integer intTwo = itemTwo.get("priority").asInt();
int comparison = intOne.compareTo(intTwo) * -1; // reverse order, higher numbers should come first
if (comparison == 0) {
Double priceOne = itemOne.get("price").asDouble();
Double priceTwo = itemTwo.get("price").asDouble();
comparison = priceOne.compareTo(priceTwo);
}
return comparison;
}
});
ObjectNode result = Json.newObject();
ArrayNode bought = JsonNodeFactory.instance.arrayNode();
ArrayNode notbought = JsonNodeFactory.instance.arrayNode();
double totalcost = 0.0;
double spent = 0.0;
int currentIndex = 0;
Iterator<ObjectNode> buyer = cart.iterator();
while (buyer.hasNext())
{
ObjectNode node = buyer.next();
double price = node.get("price").asDouble();
int startingQuantity = node.get("buying").asInt();
int numLeftToBuy = startingQuantity;
totalcost += startingQuantity * price;
while ((spent + price) < budget && numLeftToBuy > 0)
{
System.out.println(node.get("name").asText() + " " + startingQuantity + " " + numLeftToBuy + " " + currentIndex);
//Object hasn't been added to the array
if (numLeftToBuy == startingQuantity)
{
//Add the item and set quantity bought to 1
bought.add(node);
( (ObjectNode) bought.get(currentIndex)).put("buying", 1);
//Subtract 1 from the node and numLeftToBuy
numLeftToBuy--;
spent += price;
}
else //Increment the item that's already in the array
{
//We'll reverse these operations because we can use the decremented numLeft to evaluate
//how much has now been bought
numLeftToBuy--;
( (ObjectNode) bought.get(currentIndex)).put("buying", startingQuantity - numLeftToBuy);
spent += price;
}
}
if (numLeftToBuy > 0)
{
ObjectNode didntBuy = JsonNodeFactory.instance.objectNode();
didntBuy.putAll(node);
didntBuy.put("buying", numLeftToBuy);
notbought.add(didntBuy);
};
buyer.remove();
currentIndex++;
}
result.put("status", "OK");
result.put("spent", spent);
result.put("budget", budget);
result.put("totalcost", totalcost);
result.put("bought", bought);
result.put("notbought", notbought);
return result;
}
| public static ObjectNode goShopping(ArrayNode items, double budget)
{
//Get the inventory
Map<String, InventoryItem> inventory = new Model.Finder(String.class, InventoryItem.class)
.setMapKey("name").findMap();
//Create a list of 'useful' objects so that it's easy to sort
List<ObjectNode> cart = new ArrayList<ObjectNode>();
Iterator<JsonNode> iter = items.getElements();
while (iter.hasNext())
{
JsonNode node = iter.next();
ObjectNode itemInfo = InventoryItem.asJsonNode(inventory.get(node.get("name").asText()));
itemInfo.put("buying", node.get("buying"));
itemInfo.put("priority", node.get("priority"));
cart.add(itemInfo);
}
Collections.sort(cart, new Comparator<ObjectNode>() {
@Override
public int compare(ObjectNode itemOne, ObjectNode itemTwo) {
Integer intOne = itemOne.get("priority").asInt();
Integer intTwo = itemTwo.get("priority").asInt();
int comparison = intOne.compareTo(intTwo) * -1; // reverse order, higher numbers should come first
if (comparison == 0) {
Double priceOne = itemOne.get("price").asDouble();
Double priceTwo = itemTwo.get("price").asDouble();
comparison = priceOne.compareTo(priceTwo);
}
return comparison;
}
});
ObjectNode result = Json.newObject();
ArrayNode bought = JsonNodeFactory.instance.arrayNode();
ArrayNode notbought = JsonNodeFactory.instance.arrayNode();
double totalcost = 0.0;
double spent = 0.0;
int currentIndex = 0;
Iterator<ObjectNode> buyer = cart.iterator();
while (buyer.hasNext())
{
ObjectNode node = buyer.next();
double price = node.get("price").asDouble();
int startingQuantity = node.get("buying").asInt();
int numLeftToBuy = startingQuantity;
totalcost += startingQuantity * price;
while ((spent + price) <= budget && numLeftToBuy > 0)
{
System.out.println(node.get("name").asText() + " " + startingQuantity + " " + numLeftToBuy + " " + currentIndex);
//Object hasn't been added to the array
if (numLeftToBuy == startingQuantity)
{
//Add the item and set quantity bought to 1
bought.add(node);
( (ObjectNode) bought.get(currentIndex)).put("buying", 1);
//Subtract 1 from the node and numLeftToBuy
numLeftToBuy--;
spent += price;
}
else //Increment the item that's already in the array
{
//We'll reverse these operations because we can use the decremented numLeft to evaluate
//how much has now been bought
numLeftToBuy--;
( (ObjectNode) bought.get(currentIndex)).put("buying", startingQuantity - numLeftToBuy);
spent += price;
}
}
if (numLeftToBuy > 0)
{
ObjectNode didntBuy = JsonNodeFactory.instance.objectNode();
didntBuy.putAll(node);
didntBuy.put("buying", numLeftToBuy);
notbought.add(didntBuy);
};
buyer.remove();
currentIndex++;
}
result.put("status", "OK");
result.put("spent", spent);
result.put("budget", budget);
result.put("totalcost", totalcost);
result.put("bought", bought);
result.put("notbought", notbought);
return result;
}
|
diff --git a/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSBundle.java b/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSBundle.java
index a6017da4..b48a43d6 100644
--- a/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSBundle.java
+++ b/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSBundle.java
@@ -1,171 +1,172 @@
/* Copyright (c) 2002-2011 by XMLVM.org
*
* Project Info: http://www.xmlvm.org
*
* 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package org.xmlvm.iphone;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import org.xmlvm.XMLVMSkeletonOnly;
@XMLVMSkeletonOnly
public class NSBundle extends NSObject {
private static final String SYSRES = "/sys_resources";
private static final String CLASS_RESOURCE_LIST = "/META-INF/list.resources";
private static final String XCODE_RESOURCE_LIST = System.getProperty("user.dir")
+ File.separator + "xmlvm.properties";
private static NSBundle mainBundle = new NSBundle();
private static Set<String> runtime_res;
private NSBundle() {
}
public static NSBundle mainBundle() {
return mainBundle;
}
public String pathForResource(String resource, String type, String directory) {
/* Calculate file name */
String filename = type == null ? resource : resource + "." + type;
if (directory != null && !directory.equals("")) {
filename = directory + "/" + filename;
}
/* Check if the resource file has an absolute pathname */
- if (filename.startsWith(File.separator) && new File(filename).exists()) {
+ File file = new File(filename);
+ if (file.isAbsolute() && file.exists()) {
return filename;
}
/* Check it as a local resource file */
for (String dname : getDeclaredResources()) {
File dfile = new File(dname);
try {
if (dfile.isFile()) { // Resource is a file
if (dfile.getName().equals(filename))
return dfile.getAbsolutePath();
} else { // Resource is a directory
File req = null;
if (dname.endsWith("/")) // Search inside directory
req = new File(dfile, filename);
else { // Take into account resource directory
int slash = filename.indexOf('/');
String doubledir = filename.substring(0, slash);
if (doubledir.equals(dfile.getName())) // Only if both
// directories
// are the same
req = new File(dfile, filename.substring(slash + 1));
}
if (req != null && req.exists())
return req.getAbsolutePath();
}
} catch (Exception ex) {
}
}
/*
* If file was not found, search as a system resource file. This is a
* rare case and used only internally for the emulator.
*
* Please do not use it in your own projects. Use "xmlvm.resource" in
* file "xmlvm.properties" instead.
*/
String sysfilename = SYSRES + (filename.startsWith("/") ? "" : "/") + filename;
try {
String path = getClass().getResource(sysfilename).toURI().toURL().toString();
if (path != null) {
return path;
}
} catch (Exception ex) {
}
/* Not found */
return null;
}
public String pathForResource(String resource, String type) {
return pathForResource(resource, type, null);
}
public String bundlePath() {
// First we assume that we are running an Android app and we use the
// 'res' directory
// to locate the proper classpath location. We have to do this since the
// classpath
// usually consists of several directories and we use 'res' as a unique
// identifier
// to locate the correct location.
String path = pathForResource("", null, "res");
if (path == null) {
// We are not running an Android app. Just return the main directory
// in this case
File res = new File(getClass().getResource("/").getFile());
if (res.exists()) {
return res.getAbsolutePath();
}
return null;
}
return new File(path).getParent();
}
/**
* Runtime resources, given as a special file under
* ${CLASSPATH}/META-INF/xmlvm.properties or under
* ${user.dir}/xmlvm.properties
*
* This is required in order to run applications as Java from the command
* line.
*/
private static Set<String> getDeclaredResources() {
if (runtime_res == null) {
runtime_res = new HashSet<String>();
Properties pr = new Properties();
try {
// Load resources definition in the META-INF directory
pr.load(NSBundle.class.getResourceAsStream(CLASS_RESOURCE_LIST));
} catch (Exception ex1) {
try {
pr.load(new FileInputStream(XCODE_RESOURCE_LIST));
} catch (Exception ex2) {
return runtime_res;
}
}
String path = pr.getProperty("xmlvm.resource.path", System.getProperty("user.dir"));
if (!path.endsWith(File.separator))
path += File.separator;
String list = pr.getProperty("xmlvm.resource", "");
StringTokenizer tk = new StringTokenizer(list, ":");
while (tk.hasMoreTokens()) {
String item = tk.nextToken();
if (item.startsWith(File.separator))
runtime_res.add(item);
else
runtime_res.add(path + item);
}
}
return runtime_res;
}
}
| true | true | public String pathForResource(String resource, String type, String directory) {
/* Calculate file name */
String filename = type == null ? resource : resource + "." + type;
if (directory != null && !directory.equals("")) {
filename = directory + "/" + filename;
}
/* Check if the resource file has an absolute pathname */
if (filename.startsWith(File.separator) && new File(filename).exists()) {
return filename;
}
/* Check it as a local resource file */
for (String dname : getDeclaredResources()) {
File dfile = new File(dname);
try {
if (dfile.isFile()) { // Resource is a file
if (dfile.getName().equals(filename))
return dfile.getAbsolutePath();
} else { // Resource is a directory
File req = null;
if (dname.endsWith("/")) // Search inside directory
req = new File(dfile, filename);
else { // Take into account resource directory
int slash = filename.indexOf('/');
String doubledir = filename.substring(0, slash);
if (doubledir.equals(dfile.getName())) // Only if both
// directories
// are the same
req = new File(dfile, filename.substring(slash + 1));
}
if (req != null && req.exists())
return req.getAbsolutePath();
}
} catch (Exception ex) {
}
}
/*
* If file was not found, search as a system resource file. This is a
* rare case and used only internally for the emulator.
*
* Please do not use it in your own projects. Use "xmlvm.resource" in
* file "xmlvm.properties" instead.
*/
String sysfilename = SYSRES + (filename.startsWith("/") ? "" : "/") + filename;
try {
String path = getClass().getResource(sysfilename).toURI().toURL().toString();
if (path != null) {
return path;
}
} catch (Exception ex) {
}
/* Not found */
return null;
}
| public String pathForResource(String resource, String type, String directory) {
/* Calculate file name */
String filename = type == null ? resource : resource + "." + type;
if (directory != null && !directory.equals("")) {
filename = directory + "/" + filename;
}
/* Check if the resource file has an absolute pathname */
File file = new File(filename);
if (file.isAbsolute() && file.exists()) {
return filename;
}
/* Check it as a local resource file */
for (String dname : getDeclaredResources()) {
File dfile = new File(dname);
try {
if (dfile.isFile()) { // Resource is a file
if (dfile.getName().equals(filename))
return dfile.getAbsolutePath();
} else { // Resource is a directory
File req = null;
if (dname.endsWith("/")) // Search inside directory
req = new File(dfile, filename);
else { // Take into account resource directory
int slash = filename.indexOf('/');
String doubledir = filename.substring(0, slash);
if (doubledir.equals(dfile.getName())) // Only if both
// directories
// are the same
req = new File(dfile, filename.substring(slash + 1));
}
if (req != null && req.exists())
return req.getAbsolutePath();
}
} catch (Exception ex) {
}
}
/*
* If file was not found, search as a system resource file. This is a
* rare case and used only internally for the emulator.
*
* Please do not use it in your own projects. Use "xmlvm.resource" in
* file "xmlvm.properties" instead.
*/
String sysfilename = SYSRES + (filename.startsWith("/") ? "" : "/") + filename;
try {
String path = getClass().getResource(sysfilename).toURI().toURL().toString();
if (path != null) {
return path;
}
} catch (Exception ex) {
}
/* Not found */
return null;
}
|
diff --git a/core/java/android/webkit/CallbackProxy.java b/core/java/android/webkit/CallbackProxy.java
index 312af71c..fea6be67 100644
--- a/core/java/android/webkit/CallbackProxy.java
+++ b/core/java/android/webkit/CallbackProxy.java
@@ -1,1410 +1,1415 @@
/*
* Copyright (C) 2007 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 android.webkit;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Browser;
import android.util.Log;
import android.view.KeyEvent;
import com.android.internal.R;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class is a proxy class for handling WebCore -> UI thread messaging. All
* the callback functions are called from the WebCore thread and messages are
* posted to the UI thread for the actual client callback.
*/
/*
* This class is created in the UI thread so its handler and any private classes
* that extend Handler will operate in the UI thread.
*/
class CallbackProxy extends Handler {
// Logging tag
private static final String LOGTAG = "CallbackProxy";
// Instance of WebViewClient that is the client callback.
private volatile WebViewClient mWebViewClient;
// Instance of WebChromeClient for handling all chrome functions.
private volatile WebChromeClient mWebChromeClient;
// Instance of WebViewClassic for handling UI requests.
private final WebViewClassic mWebView;
// Client registered callback listener for download events
private volatile DownloadListener mDownloadListener;
// Keep track of multiple progress updates.
private boolean mProgressUpdatePending;
// Keep track of the last progress amount.
// Start with 100 to indicate it is not in load for the empty page.
private volatile int mLatestProgress = 100;
// Back/Forward list
private final WebBackForwardListClassic mBackForwardList;
// Back/Forward list client
private volatile WebBackForwardListClient mWebBackForwardListClient;
// Used to call startActivity during url override.
private final Context mContext;
// block messages flag for destroy
private boolean mBlockMessages;
// Message IDs
private static final int PAGE_STARTED = 100;
private static final int RECEIVED_ICON = 101;
private static final int RECEIVED_TITLE = 102;
private static final int OVERRIDE_URL = 103;
private static final int AUTH_REQUEST = 104;
private static final int SSL_ERROR = 105;
private static final int PROGRESS = 106;
private static final int UPDATE_VISITED = 107;
private static final int LOAD_RESOURCE = 108;
private static final int CREATE_WINDOW = 109;
private static final int CLOSE_WINDOW = 110;
private static final int SAVE_PASSWORD = 111;
private static final int JS_DIALOG = 112;
private static final int ASYNC_KEYEVENTS = 116;
private static final int DOWNLOAD_FILE = 118;
private static final int REPORT_ERROR = 119;
private static final int RESEND_POST_DATA = 120;
private static final int PAGE_FINISHED = 121;
private static final int REQUEST_FOCUS = 122;
private static final int SCALE_CHANGED = 123;
private static final int RECEIVED_CERTIFICATE = 124;
private static final int SWITCH_OUT_HISTORY = 125;
private static final int EXCEEDED_DATABASE_QUOTA = 126;
private static final int REACHED_APPCACHE_MAXSIZE = 127;
private static final int JS_TIMEOUT = 128;
private static final int ADD_MESSAGE_TO_CONSOLE = 129;
private static final int GEOLOCATION_PERMISSIONS_SHOW_PROMPT = 130;
private static final int GEOLOCATION_PERMISSIONS_HIDE_PROMPT = 131;
private static final int RECEIVED_TOUCH_ICON_URL = 132;
private static final int GET_VISITED_HISTORY = 133;
private static final int OPEN_FILE_CHOOSER = 134;
private static final int ADD_HISTORY_ITEM = 135;
private static final int HISTORY_INDEX_CHANGED = 136;
private static final int AUTH_CREDENTIALS = 137;
private static final int AUTO_LOGIN = 140;
private static final int CLIENT_CERT_REQUEST = 141;
private static final int PROCEEDED_AFTER_SSL_ERROR = 144;
// Message triggered by the client to resume execution
private static final int NOTIFY = 200;
// Result transportation object for returning results across thread
// boundaries.
private static class ResultTransport<E> {
// Private result object
private E mResult;
public ResultTransport(E defaultResult) {
mResult = defaultResult;
}
public synchronized void setResult(E result) {
mResult = result;
}
public synchronized E getResult() {
return mResult;
}
}
private class JsResultReceiver implements JsResult.ResultReceiver {
// This prevents a user from interacting with the result before WebCore is
// ready to handle it.
private boolean mReady;
// Tells us if the user tried to confirm or cancel the result before WebCore
// is ready.
private boolean mTriedToNotifyBeforeReady;
public JsPromptResult mJsResult = new JsPromptResult(this);
final void setReady() {
mReady = true;
if (mTriedToNotifyBeforeReady) {
notifyCallbackProxy();
}
}
/* Wake up the WebCore thread. */
@Override
public void onJsResultComplete(JsResult result) {
if (mReady) {
notifyCallbackProxy();
} else {
mTriedToNotifyBeforeReady = true;
}
}
private void notifyCallbackProxy() {
synchronized (CallbackProxy.this) {
CallbackProxy.this.notify();
}
}
}
/**
* Construct a new CallbackProxy.
*/
public CallbackProxy(Context context, WebViewClassic w) {
// Used to start a default activity.
mContext = context;
mWebView = w;
mBackForwardList = new WebBackForwardListClassic(this);
}
protected synchronized void blockMessages() {
mBlockMessages = true;
}
protected synchronized boolean messagesBlocked() {
return mBlockMessages;
}
protected void shutdown() {
removeCallbacksAndMessages(null);
setWebViewClient(null);
setWebChromeClient(null);
}
/**
* Set the WebViewClient.
* @param client An implementation of WebViewClient.
*/
public void setWebViewClient(WebViewClient client) {
mWebViewClient = client;
}
/**
* Get the WebViewClient.
* @return the current WebViewClient instance.
*/
public WebViewClient getWebViewClient() {
return mWebViewClient;
}
/**
* Set the WebChromeClient.
* @param client An implementation of WebChromeClient.
*/
public void setWebChromeClient(WebChromeClient client) {
mWebChromeClient = client;
}
/**
* Get the WebChromeClient.
* @return the current WebChromeClient instance.
*/
public WebChromeClient getWebChromeClient() {
return mWebChromeClient;
}
/**
* Set the client DownloadListener.
* @param client An implementation of DownloadListener.
*/
public void setDownloadListener(DownloadListener client) {
mDownloadListener = client;
}
/**
* Get the Back/Forward list to return to the user or to update the cached
* history list.
*/
public WebBackForwardListClassic getBackForwardList() {
return mBackForwardList;
}
void setWebBackForwardListClient(WebBackForwardListClient client) {
mWebBackForwardListClient = client;
}
WebBackForwardListClient getWebBackForwardListClient() {
return mWebBackForwardListClient;
}
/**
* Called by the UI side. Calling overrideUrlLoading from the WebCore
* side will post a message to call this method.
*/
public boolean uiOverrideUrlLoading(String overrideUrl) {
if (overrideUrl == null || overrideUrl.length() == 0) {
return false;
}
boolean override = false;
if (mWebViewClient != null) {
override = mWebViewClient.shouldOverrideUrlLoading(mWebView.getWebView(),
overrideUrl);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(overrideUrl));
intent.addCategory(Intent.CATEGORY_BROWSABLE);
// If another application is running a WebView and launches the
// Browser through this Intent, we want to reuse the same window if
// possible.
intent.putExtra(Browser.EXTRA_APPLICATION_ID,
mContext.getPackageName());
try {
mContext.startActivity(intent);
override = true;
} catch (ActivityNotFoundException ex) {
// If no application can handle the URL, assume that the
// browser can handle it.
}
}
return override;
}
/**
* Called by UI side.
*/
public boolean uiOverrideKeyEvent(KeyEvent event) {
if (mWebViewClient != null) {
return mWebViewClient.shouldOverrideKeyEvent(mWebView.getWebView(), event);
}
return false;
}
@Override
public void handleMessage(Message msg) {
// We don't have to do synchronization because this function operates
// in the UI thread. The WebViewClient and WebChromeClient functions
// that check for a non-null callback are ok because java ensures atomic
// 32-bit reads and writes.
- if (messagesBlocked()) return;
+ if (messagesBlocked()) {
+ synchronized (this) {
+ notify();
+ }
+ return;
+ }
switch (msg.what) {
case PAGE_STARTED:
String startedUrl = msg.getData().getString("url");
mWebView.onPageStarted(startedUrl);
if (mWebViewClient != null) {
mWebViewClient.onPageStarted(mWebView.getWebView(), startedUrl,
(Bitmap) msg.obj);
}
break;
case PAGE_FINISHED:
String finishedUrl = (String) msg.obj;
mWebView.onPageFinished(finishedUrl);
if (mWebViewClient != null) {
mWebViewClient.onPageFinished(mWebView.getWebView(), finishedUrl);
}
break;
case RECEIVED_ICON:
if (mWebChromeClient != null) {
mWebChromeClient.onReceivedIcon(mWebView.getWebView(), (Bitmap) msg.obj);
}
break;
case RECEIVED_TOUCH_ICON_URL:
if (mWebChromeClient != null) {
mWebChromeClient.onReceivedTouchIconUrl(mWebView.getWebView(),
(String) msg.obj, msg.arg1 == 1);
}
break;
case RECEIVED_TITLE:
if (mWebChromeClient != null) {
mWebChromeClient.onReceivedTitle(mWebView.getWebView(),
(String) msg.obj);
}
break;
case REPORT_ERROR:
if (mWebViewClient != null) {
int reasonCode = msg.arg1;
final String description = msg.getData().getString("description");
final String failUrl = msg.getData().getString("failingUrl");
mWebViewClient.onReceivedError(mWebView.getWebView(), reasonCode,
description, failUrl);
}
break;
case RESEND_POST_DATA:
Message resend =
(Message) msg.getData().getParcelable("resend");
Message dontResend =
(Message) msg.getData().getParcelable("dontResend");
if (mWebViewClient != null) {
mWebViewClient.onFormResubmission(mWebView.getWebView(), dontResend,
resend);
} else {
dontResend.sendToTarget();
}
break;
case OVERRIDE_URL:
String overrideUrl = msg.getData().getString("url");
boolean override = uiOverrideUrlLoading(overrideUrl);
ResultTransport<Boolean> result =
(ResultTransport<Boolean>) msg.obj;
synchronized (this) {
result.setResult(override);
notify();
}
break;
case AUTH_REQUEST:
if (mWebViewClient != null) {
HttpAuthHandler handler = (HttpAuthHandler) msg.obj;
String host = msg.getData().getString("host");
String realm = msg.getData().getString("realm");
mWebViewClient.onReceivedHttpAuthRequest(mWebView.getWebView(), handler,
host, realm);
}
break;
case SSL_ERROR:
if (mWebViewClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
mWebViewClient.onReceivedSslError(mWebView.getWebView(),
(SslErrorHandler) map.get("handler"),
(SslError) map.get("error"));
}
break;
case PROCEEDED_AFTER_SSL_ERROR:
if (mWebViewClient != null && mWebViewClient instanceof WebViewClientClassicExt) {
((WebViewClientClassicExt) mWebViewClient).onProceededAfterSslError(
mWebView.getWebView(),
(SslError) msg.obj);
}
break;
case CLIENT_CERT_REQUEST:
if (mWebViewClient != null && mWebViewClient instanceof WebViewClientClassicExt) {
HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
((WebViewClientClassicExt) mWebViewClient).onReceivedClientCertRequest(
mWebView.getWebView(),
(ClientCertRequestHandler) map.get("handler"),
(String) map.get("host_and_port"));
}
break;
case PROGRESS:
// Synchronize to ensure mLatestProgress is not modified after
// setProgress is called and before mProgressUpdatePending is
// changed.
synchronized (this) {
if (mWebChromeClient != null) {
mWebChromeClient.onProgressChanged(mWebView.getWebView(),
mLatestProgress);
}
mProgressUpdatePending = false;
}
break;
case UPDATE_VISITED:
if (mWebViewClient != null) {
mWebViewClient.doUpdateVisitedHistory(mWebView.getWebView(),
(String) msg.obj, msg.arg1 != 0);
}
break;
case LOAD_RESOURCE:
if (mWebViewClient != null) {
mWebViewClient.onLoadResource(mWebView.getWebView(), (String) msg.obj);
}
break;
case DOWNLOAD_FILE:
if (mDownloadListener != null) {
String url = msg.getData().getString("url");
String userAgent = msg.getData().getString("userAgent");
String contentDisposition =
msg.getData().getString("contentDisposition");
String mimetype = msg.getData().getString("mimetype");
String referer = msg.getData().getString("referer");
Long contentLength = msg.getData().getLong("contentLength");
if (mDownloadListener instanceof BrowserDownloadListener) {
((BrowserDownloadListener) mDownloadListener).onDownloadStart(url,
userAgent, contentDisposition, mimetype, referer, contentLength);
} else {
mDownloadListener.onDownloadStart(url, userAgent,
contentDisposition, mimetype, contentLength);
}
}
break;
case CREATE_WINDOW:
if (mWebChromeClient != null) {
if (!mWebChromeClient.onCreateWindow(mWebView.getWebView(),
msg.arg1 == 1, msg.arg2 == 1,
(Message) msg.obj)) {
synchronized (this) {
notify();
}
}
mWebView.dismissZoomControl();
}
break;
case REQUEST_FOCUS:
if (mWebChromeClient != null) {
mWebChromeClient.onRequestFocus(mWebView.getWebView());
}
break;
case CLOSE_WINDOW:
if (mWebChromeClient != null) {
mWebChromeClient.onCloseWindow(((WebViewClassic) msg.obj).getWebView());
}
break;
case SAVE_PASSWORD:
Bundle bundle = msg.getData();
String schemePlusHost = bundle.getString("host");
String username = bundle.getString("username");
String password = bundle.getString("password");
// If the client returned false it means that the notify message
// will not be sent and we should notify WebCore ourselves.
if (!mWebView.onSavePassword(schemePlusHost, username, password,
(Message) msg.obj)) {
synchronized (this) {
notify();
}
}
break;
case ASYNC_KEYEVENTS:
if (mWebViewClient != null) {
mWebViewClient.onUnhandledKeyEvent(mWebView.getWebView(),
(KeyEvent) msg.obj);
}
break;
case EXCEEDED_DATABASE_QUOTA:
if (mWebChromeClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
String databaseIdentifier =
(String) map.get("databaseIdentifier");
String url = (String) map.get("url");
long quota =
((Long) map.get("quota")).longValue();
long totalQuota =
((Long) map.get("totalQuota")).longValue();
long estimatedDatabaseSize =
((Long) map.get("estimatedDatabaseSize")).longValue();
WebStorage.QuotaUpdater quotaUpdater =
(WebStorage.QuotaUpdater) map.get("quotaUpdater");
mWebChromeClient.onExceededDatabaseQuota(url,
databaseIdentifier, quota, estimatedDatabaseSize,
totalQuota, quotaUpdater);
}
break;
case REACHED_APPCACHE_MAXSIZE:
if (mWebChromeClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
long requiredStorage =
((Long) map.get("requiredStorage")).longValue();
long quota =
((Long) map.get("quota")).longValue();
WebStorage.QuotaUpdater quotaUpdater =
(WebStorage.QuotaUpdater) map.get("quotaUpdater");
mWebChromeClient.onReachedMaxAppCacheSize(requiredStorage,
quota, quotaUpdater);
}
break;
case GEOLOCATION_PERMISSIONS_SHOW_PROMPT:
if (mWebChromeClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
String origin = (String) map.get("origin");
GeolocationPermissions.Callback callback =
(GeolocationPermissions.Callback)
map.get("callback");
mWebChromeClient.onGeolocationPermissionsShowPrompt(origin,
callback);
}
break;
case GEOLOCATION_PERMISSIONS_HIDE_PROMPT:
if (mWebChromeClient != null) {
mWebChromeClient.onGeolocationPermissionsHidePrompt();
}
break;
case JS_DIALOG:
if (mWebChromeClient != null) {
final JsResultReceiver receiver = (JsResultReceiver) msg.obj;
JsDialogHelper helper = new JsDialogHelper(receiver.mJsResult, msg);
if (!helper.invokeCallback(mWebChromeClient, mWebView.getWebView())) {
helper.showDialog(mContext);
}
receiver.setReady();
}
break;
case JS_TIMEOUT:
if(mWebChromeClient != null) {
final JsResultReceiver receiver = (JsResultReceiver) msg.obj;
final JsResult res = receiver.mJsResult;
if (mWebChromeClient.onJsTimeout()) {
res.confirm();
} else {
res.cancel();
}
receiver.setReady();
}
break;
case RECEIVED_CERTIFICATE:
mWebView.setCertificate((SslCertificate) msg.obj);
break;
case NOTIFY:
synchronized (this) {
notify();
}
break;
case SCALE_CHANGED:
if (mWebViewClient != null) {
mWebViewClient.onScaleChanged(mWebView.getWebView(), msg.getData()
.getFloat("old"), msg.getData().getFloat("new"));
}
break;
case SWITCH_OUT_HISTORY:
mWebView.switchOutDrawHistory();
break;
case ADD_MESSAGE_TO_CONSOLE:
if (mWebChromeClient == null) {
break;
}
String message = msg.getData().getString("message");
String sourceID = msg.getData().getString("sourceID");
int lineNumber = msg.getData().getInt("lineNumber");
int msgLevel = msg.getData().getInt("msgLevel");
int numberOfMessageLevels = ConsoleMessage.MessageLevel.values().length;
// Sanity bounds check as we'll index an array with msgLevel
if (msgLevel < 0 || msgLevel >= numberOfMessageLevels) {
msgLevel = 0;
}
ConsoleMessage.MessageLevel messageLevel =
ConsoleMessage.MessageLevel.values()[msgLevel];
if (!mWebChromeClient.onConsoleMessage(new ConsoleMessage(message, sourceID,
lineNumber, messageLevel))) {
// If false was returned the user did not provide their own console function so
// we should output some default messages to the system log.
String logTag = "Web Console";
String logMessage = message + " at " + sourceID + ":" + lineNumber;
switch (messageLevel) {
case TIP:
Log.v(logTag, logMessage);
break;
case LOG:
Log.i(logTag, logMessage);
break;
case WARNING:
Log.w(logTag, logMessage);
break;
case ERROR:
Log.e(logTag, logMessage);
break;
case DEBUG:
Log.d(logTag, logMessage);
break;
}
}
break;
case GET_VISITED_HISTORY:
if (mWebChromeClient != null) {
mWebChromeClient.getVisitedHistory((ValueCallback<String[]>)msg.obj);
}
break;
case OPEN_FILE_CHOOSER:
if (mWebChromeClient != null) {
UploadFileMessageData data = (UploadFileMessageData)msg.obj;
mWebChromeClient.openFileChooser(data.getUploadFile(), data.getAcceptType(),
data.getCapture());
}
break;
case ADD_HISTORY_ITEM:
if (mWebBackForwardListClient != null) {
mWebBackForwardListClient.onNewHistoryItem(
(WebHistoryItem) msg.obj);
}
break;
case HISTORY_INDEX_CHANGED:
if (mWebBackForwardListClient != null) {
mWebBackForwardListClient.onIndexChanged(
(WebHistoryItem) msg.obj, msg.arg1);
}
break;
case AUTH_CREDENTIALS: {
String host = msg.getData().getString("host");
String realm = msg.getData().getString("realm");
username = msg.getData().getString("username");
password = msg.getData().getString("password");
mWebView.setHttpAuthUsernamePassword(
host, realm, username, password);
break;
}
case AUTO_LOGIN: {
if (mWebViewClient != null) {
String realm = msg.getData().getString("realm");
String account = msg.getData().getString("account");
String args = msg.getData().getString("args");
mWebViewClient.onReceivedLoginRequest(mWebView.getWebView(), realm,
account, args);
}
break;
}
}
}
/**
* Return the latest progress.
*/
public int getProgress() {
return mLatestProgress;
}
/**
* Called by WebCore side to switch out of history Picture drawing mode
*/
void switchOutDrawHistory() {
sendMessage(obtainMessage(SWITCH_OUT_HISTORY));
}
//--------------------------------------------------------------------------
// WebViewClient functions.
// NOTE: shouldOverrideKeyEvent is never called from the WebCore thread so
// it is not necessary to include it here.
//--------------------------------------------------------------------------
// Performance probe
private static final boolean PERF_PROBE = false;
private long mWebCoreThreadTime;
private long mWebCoreIdleTime;
/*
* If PERF_PROBE is true, this block needs to be added to MessageQueue.java.
* startWait() and finishWait() should be called before and after wait().
private WaitCallback mWaitCallback = null;
public static interface WaitCallback {
void startWait();
void finishWait();
}
public final void setWaitCallback(WaitCallback callback) {
mWaitCallback = callback;
}
*/
// un-comment this block if PERF_PROBE is true
/*
private IdleCallback mIdleCallback = new IdleCallback();
private final class IdleCallback implements MessageQueue.WaitCallback {
private long mStartTime = 0;
public void finishWait() {
mWebCoreIdleTime += SystemClock.uptimeMillis() - mStartTime;
}
public void startWait() {
mStartTime = SystemClock.uptimeMillis();
}
}
*/
public void onPageStarted(String url, Bitmap favicon) {
// We need to send the message even if no WebViewClient is set, because we need to call
// WebView.onPageStarted().
// Performance probe
if (PERF_PROBE) {
mWebCoreThreadTime = SystemClock.currentThreadTimeMillis();
mWebCoreIdleTime = 0;
// un-comment this if PERF_PROBE is true
// Looper.myQueue().setWaitCallback(mIdleCallback);
}
Message msg = obtainMessage(PAGE_STARTED);
msg.obj = favicon;
msg.getData().putString("url", url);
sendMessage(msg);
}
public void onPageFinished(String url) {
// Performance probe
if (PERF_PROBE) {
// un-comment this if PERF_PROBE is true
// Looper.myQueue().setWaitCallback(null);
Log.d("WebCore", "WebCore thread used " +
(SystemClock.currentThreadTimeMillis() - mWebCoreThreadTime)
+ " ms and idled " + mWebCoreIdleTime + " ms");
}
Message msg = obtainMessage(PAGE_FINISHED, url);
sendMessage(msg);
}
// Because this method is public and because CallbackProxy is mistakenly
// party of the public classes, we cannot remove this method.
public void onTooManyRedirects(Message cancelMsg, Message continueMsg) {
// deprecated.
}
public void onReceivedError(int errorCode, String description,
String failingUrl) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebViewClient == null) {
return;
}
Message msg = obtainMessage(REPORT_ERROR);
msg.arg1 = errorCode;
msg.getData().putString("description", description);
msg.getData().putString("failingUrl", failingUrl);
sendMessage(msg);
}
public void onFormResubmission(Message dontResend,
Message resend) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebViewClient == null) {
dontResend.sendToTarget();
return;
}
Message msg = obtainMessage(RESEND_POST_DATA);
Bundle bundle = msg.getData();
bundle.putParcelable("resend", resend);
bundle.putParcelable("dontResend", dontResend);
sendMessage(msg);
}
/**
* Called by the WebCore side
*/
public boolean shouldOverrideUrlLoading(String url) {
// We have a default behavior if no client exists so always send the
// message.
ResultTransport<Boolean> res = new ResultTransport<Boolean>(false);
Message msg = obtainMessage(OVERRIDE_URL);
msg.getData().putString("url", url);
msg.obj = res;
sendMessageToUiThreadSync(msg);
return res.getResult().booleanValue();
}
public void onReceivedHttpAuthRequest(HttpAuthHandler handler,
String hostName, String realmName) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebViewClient == null) {
handler.cancel();
return;
}
Message msg = obtainMessage(AUTH_REQUEST, handler);
msg.getData().putString("host", hostName);
msg.getData().putString("realm", realmName);
sendMessage(msg);
}
public void onReceivedSslError(SslErrorHandler handler, SslError error) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebViewClient == null) {
handler.cancel();
return;
}
Message msg = obtainMessage(SSL_ERROR);
HashMap<String, Object> map = new HashMap();
map.put("handler", handler);
map.put("error", error);
msg.obj = map;
sendMessage(msg);
}
public void onProceededAfterSslError(SslError error) {
if (mWebViewClient == null || !(mWebViewClient instanceof WebViewClientClassicExt)) {
return;
}
Message msg = obtainMessage(PROCEEDED_AFTER_SSL_ERROR);
msg.obj = error;
sendMessage(msg);
}
public void onReceivedClientCertRequest(ClientCertRequestHandler handler, String host_and_port) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebViewClient == null || !(mWebViewClient instanceof WebViewClientClassicExt)) {
handler.cancel();
return;
}
Message msg = obtainMessage(CLIENT_CERT_REQUEST);
HashMap<String, Object> map = new HashMap();
map.put("handler", handler);
map.put("host_and_port", host_and_port);
msg.obj = map;
sendMessage(msg);
}
public void onReceivedCertificate(SslCertificate certificate) {
// here, certificate can be null (if the site is not secure)
sendMessage(obtainMessage(RECEIVED_CERTIFICATE, certificate));
}
public void doUpdateVisitedHistory(String url, boolean isReload) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebViewClient == null) {
return;
}
sendMessage(obtainMessage(UPDATE_VISITED, isReload ? 1 : 0, 0, url));
}
WebResourceResponse shouldInterceptRequest(String url) {
if (mWebViewClient == null) {
return null;
}
// Note: This method does _not_ send a message.
WebResourceResponse r =
mWebViewClient.shouldInterceptRequest(mWebView.getWebView(), url);
if (r == null) {
sendMessage(obtainMessage(LOAD_RESOURCE, url));
}
return r;
}
public void onUnhandledKeyEvent(KeyEvent event) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebViewClient == null) {
return;
}
sendMessage(obtainMessage(ASYNC_KEYEVENTS, event));
}
public void onScaleChanged(float oldScale, float newScale) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebViewClient == null) {
return;
}
Message msg = obtainMessage(SCALE_CHANGED);
Bundle bundle = msg.getData();
bundle.putFloat("old", oldScale);
bundle.putFloat("new", newScale);
sendMessage(msg);
}
void onReceivedLoginRequest(String realm, String account, String args) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebViewClient == null) {
return;
}
Message msg = obtainMessage(AUTO_LOGIN);
Bundle bundle = msg.getData();
bundle.putString("realm", realm);
bundle.putString("account", account);
bundle.putString("args", args);
sendMessage(msg);
}
//--------------------------------------------------------------------------
// DownloadListener functions.
//--------------------------------------------------------------------------
/**
* Starts a download if a download listener has been registered, otherwise
* return false.
*/
public boolean onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, String referer,
long contentLength) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mDownloadListener == null) {
// Cancel the download if there is no browser client.
return false;
}
Message msg = obtainMessage(DOWNLOAD_FILE);
Bundle bundle = msg.getData();
bundle.putString("url", url);
bundle.putString("userAgent", userAgent);
bundle.putString("mimetype", mimetype);
bundle.putString("referer", referer);
bundle.putLong("contentLength", contentLength);
bundle.putString("contentDisposition", contentDisposition);
sendMessage(msg);
return true;
}
//--------------------------------------------------------------------------
// WebView specific functions that do not interact with a client. These
// functions just need to operate within the UI thread.
//--------------------------------------------------------------------------
public boolean onSavePassword(String schemePlusHost, String username,
String password, Message resumeMsg) {
// resumeMsg should be null at this point because we want to create it
// within the CallbackProxy.
if (DebugFlags.CALLBACK_PROXY) {
junit.framework.Assert.assertNull(resumeMsg);
}
resumeMsg = obtainMessage(NOTIFY);
Message msg = obtainMessage(SAVE_PASSWORD, resumeMsg);
Bundle bundle = msg.getData();
bundle.putString("host", schemePlusHost);
bundle.putString("username", username);
bundle.putString("password", password);
sendMessageToUiThreadSync(msg);
// Doesn't matter here
return false;
}
public void onReceivedHttpAuthCredentials(String host, String realm,
String username, String password) {
Message msg = obtainMessage(AUTH_CREDENTIALS);
msg.getData().putString("host", host);
msg.getData().putString("realm", realm);
msg.getData().putString("username", username);
msg.getData().putString("password", password);
sendMessage(msg);
}
//--------------------------------------------------------------------------
// WebChromeClient methods
//--------------------------------------------------------------------------
public void onProgressChanged(int newProgress) {
// Synchronize so that mLatestProgress is up-to-date.
synchronized (this) {
// update mLatestProgress even mWebChromeClient is null as
// WebView.getProgress() needs it
if (mLatestProgress == newProgress) {
return;
}
mLatestProgress = newProgress;
if (mWebChromeClient == null) {
return;
}
if (!mProgressUpdatePending) {
sendEmptyMessage(PROGRESS);
mProgressUpdatePending = true;
}
}
}
public BrowserFrame createWindow(boolean dialog, boolean userGesture) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebChromeClient == null) {
return null;
}
WebView.WebViewTransport transport =
mWebView.getWebView().new WebViewTransport();
final Message msg = obtainMessage(NOTIFY);
msg.obj = transport;
sendMessageToUiThreadSync(obtainMessage(CREATE_WINDOW, dialog ? 1 : 0,
userGesture ? 1 : 0, msg));
WebViewClassic w = WebViewClassic.fromWebView(transport.getWebView());
if (w != null) {
WebViewCore core = w.getWebViewCore();
// If WebView.destroy() has been called, core may be null. Skip
// initialization in that case and return null.
if (core != null) {
core.initializeSubwindow();
return core.getBrowserFrame();
}
}
return null;
}
public void onRequestFocus() {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebChromeClient == null) {
return;
}
sendEmptyMessage(REQUEST_FOCUS);
}
public void onCloseWindow(WebViewClassic window) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebChromeClient == null) {
return;
}
sendMessage(obtainMessage(CLOSE_WINDOW, window));
}
public void onReceivedIcon(Bitmap icon) {
// The current item might be null if the icon was already stored in the
// database and this is a new WebView.
WebHistoryItemClassic i = mBackForwardList.getCurrentItem();
if (i != null) {
i.setFavicon(icon);
}
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebChromeClient == null) {
return;
}
sendMessage(obtainMessage(RECEIVED_ICON, icon));
}
/* package */ void onReceivedTouchIconUrl(String url, boolean precomposed) {
// We should have a current item but we do not want to crash so check
// for null.
WebHistoryItemClassic i = mBackForwardList.getCurrentItem();
if (i != null) {
i.setTouchIconUrl(url, precomposed);
}
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebChromeClient == null) {
return;
}
sendMessage(obtainMessage(RECEIVED_TOUCH_ICON_URL,
precomposed ? 1 : 0, 0, url));
}
public void onReceivedTitle(String title) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebChromeClient == null) {
return;
}
sendMessage(obtainMessage(RECEIVED_TITLE, title));
}
public void onJsAlert(String url, String message) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebChromeClient == null) {
return;
}
JsResultReceiver result = new JsResultReceiver();
Message alert = obtainMessage(JS_DIALOG, result);
alert.getData().putString("message", message);
alert.getData().putString("url", url);
alert.getData().putInt("type", JsDialogHelper.ALERT);
sendMessageToUiThreadSync(alert);
}
public boolean onJsConfirm(String url, String message) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebChromeClient == null) {
return false;
}
JsResultReceiver result = new JsResultReceiver();
Message confirm = obtainMessage(JS_DIALOG, result);
confirm.getData().putString("message", message);
confirm.getData().putString("url", url);
confirm.getData().putInt("type", JsDialogHelper.CONFIRM);
sendMessageToUiThreadSync(confirm);
return result.mJsResult.getResult();
}
public String onJsPrompt(String url, String message, String defaultValue) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebChromeClient == null) {
return null;
}
JsResultReceiver result = new JsResultReceiver();
Message prompt = obtainMessage(JS_DIALOG, result);
prompt.getData().putString("message", message);
prompt.getData().putString("default", defaultValue);
prompt.getData().putString("url", url);
prompt.getData().putInt("type", JsDialogHelper.PROMPT);
sendMessageToUiThreadSync(prompt);
return result.mJsResult.getStringResult();
}
public boolean onJsBeforeUnload(String url, String message) {
// Do an unsynchronized quick check to avoid posting if no callback has
// been set.
if (mWebChromeClient == null) {
return true;
}
JsResultReceiver result = new JsResultReceiver();
Message unload = obtainMessage(JS_DIALOG, result);
unload.getData().putString("message", message);
unload.getData().putString("url", url);
unload.getData().putInt("type", JsDialogHelper.UNLOAD);
sendMessageToUiThreadSync(unload);
return result.mJsResult.getResult();
}
/**
* Called by WebViewCore to inform the Java side that the current origin
* has overflowed it's database quota. Called in the WebCore thread so
* posts a message to the UI thread that will prompt the WebChromeClient
* for what to do. On return back to C++ side, the WebCore thread will
* sleep pending a new quota value.
* @param url The URL that caused the quota overflow.
* @param databaseIdentifier The identifier of the database that the
* transaction that caused the overflow was running on.
* @param quota The current quota the origin is allowed.
* @param estimatedDatabaseSize The estimated size of the database.
* @param totalQuota is the sum of all origins' quota.
* @param quotaUpdater An instance of a class encapsulating a callback
* to WebViewCore to run when the decision to allow or deny more
* quota has been made.
*/
public void onExceededDatabaseQuota(
String url, String databaseIdentifier, long quota,
long estimatedDatabaseSize, long totalQuota,
WebStorage.QuotaUpdater quotaUpdater) {
if (mWebChromeClient == null) {
// Native-side logic prevents the quota being updated to a smaller
// value.
quotaUpdater.updateQuota(quota);
return;
}
Message exceededQuota = obtainMessage(EXCEEDED_DATABASE_QUOTA);
HashMap<String, Object> map = new HashMap();
map.put("databaseIdentifier", databaseIdentifier);
map.put("url", url);
map.put("quota", quota);
map.put("estimatedDatabaseSize", estimatedDatabaseSize);
map.put("totalQuota", totalQuota);
map.put("quotaUpdater", quotaUpdater);
exceededQuota.obj = map;
sendMessage(exceededQuota);
}
/**
* Called by WebViewCore to inform the Java side that the appcache has
* exceeded its max size.
* @param requiredStorage is the amount of storage, in bytes, that would be
* needed in order for the last appcache operation to succeed.
* @param quota is the current quota (for all origins).
* @param quotaUpdater An instance of a class encapsulating a callback
* to WebViewCore to run when the decision to allow or deny a bigger
* app cache size has been made.
*/
public void onReachedMaxAppCacheSize(long requiredStorage,
long quota, WebStorage.QuotaUpdater quotaUpdater) {
if (mWebChromeClient == null) {
// Native-side logic prevents the quota being updated to a smaller
// value.
quotaUpdater.updateQuota(quota);
return;
}
Message msg = obtainMessage(REACHED_APPCACHE_MAXSIZE);
HashMap<String, Object> map = new HashMap();
map.put("requiredStorage", requiredStorage);
map.put("quota", quota);
map.put("quotaUpdater", quotaUpdater);
msg.obj = map;
sendMessage(msg);
}
/**
* Called by WebViewCore to instruct the browser to display a prompt to ask
* the user to set the Geolocation permission state for the given origin.
* @param origin The origin requesting Geolocation permsissions.
* @param callback The callback to call once a permission state has been
* obtained.
*/
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
if (mWebChromeClient == null) {
return;
}
Message showMessage =
obtainMessage(GEOLOCATION_PERMISSIONS_SHOW_PROMPT);
HashMap<String, Object> map = new HashMap();
map.put("origin", origin);
map.put("callback", callback);
showMessage.obj = map;
sendMessage(showMessage);
}
/**
* Called by WebViewCore to instruct the browser to hide the Geolocation
* permissions prompt.
*/
public void onGeolocationPermissionsHidePrompt() {
if (mWebChromeClient == null) {
return;
}
Message hideMessage = obtainMessage(GEOLOCATION_PERMISSIONS_HIDE_PROMPT);
sendMessage(hideMessage);
}
/**
* Called by WebViewCore when we have a message to be added to the JavaScript
* error console. Sends a message to the Java side with the details.
* @param message The message to add to the console.
* @param lineNumber The lineNumber of the source file on which the error
* occurred.
* @param sourceID The filename of the source file in which the error
* occurred.
* @param msgLevel The message level, corresponding to the MessageLevel enum in
* WebCore/page/Console.h
*/
public void addMessageToConsole(String message, int lineNumber, String sourceID, int msgLevel) {
if (mWebChromeClient == null) {
return;
}
Message msg = obtainMessage(ADD_MESSAGE_TO_CONSOLE);
msg.getData().putString("message", message);
msg.getData().putString("sourceID", sourceID);
msg.getData().putInt("lineNumber", lineNumber);
msg.getData().putInt("msgLevel", msgLevel);
sendMessage(msg);
}
public boolean onJsTimeout() {
//always interrupt timedout JS by default
if (mWebChromeClient == null) {
return true;
}
JsResultReceiver result = new JsResultReceiver();
Message timeout = obtainMessage(JS_TIMEOUT, result);
sendMessageToUiThreadSync(timeout);
return result.mJsResult.getResult();
}
public void getVisitedHistory(ValueCallback<String[]> callback) {
if (mWebChromeClient == null) {
return;
}
Message msg = obtainMessage(GET_VISITED_HISTORY);
msg.obj = callback;
sendMessage(msg);
}
private static class UploadFileMessageData {
private UploadFile mCallback;
private String mAcceptType;
private String mCapture;
public UploadFileMessageData(UploadFile uploadFile, String acceptType, String capture) {
mCallback = uploadFile;
mAcceptType = acceptType;
mCapture = capture;
}
public UploadFile getUploadFile() {
return mCallback;
}
public String getAcceptType() {
return mAcceptType;
}
public String getCapture() {
return mCapture;
}
}
private class UploadFile implements ValueCallback<Uri> {
private Uri mValue;
public void onReceiveValue(Uri value) {
mValue = value;
synchronized (CallbackProxy.this) {
CallbackProxy.this.notify();
}
}
public Uri getResult() {
return mValue;
}
}
/**
* Called by WebViewCore to open a file chooser.
*/
/* package */ Uri openFileChooser(String acceptType, String capture) {
if (mWebChromeClient == null) {
return null;
}
Message myMessage = obtainMessage(OPEN_FILE_CHOOSER);
UploadFile uploadFile = new UploadFile();
UploadFileMessageData data = new UploadFileMessageData(uploadFile, acceptType, capture);
myMessage.obj = data;
sendMessageToUiThreadSync(myMessage);
return uploadFile.getResult();
}
void onNewHistoryItem(WebHistoryItem item) {
if (mWebBackForwardListClient == null) {
return;
}
Message msg = obtainMessage(ADD_HISTORY_ITEM, item);
sendMessage(msg);
}
void onIndexChanged(WebHistoryItem item, int index) {
if (mWebBackForwardListClient == null) {
return;
}
Message msg = obtainMessage(HISTORY_INDEX_CHANGED, index, 0, item);
sendMessage(msg);
}
private synchronized void sendMessageToUiThreadSync(Message msg) {
sendMessage(msg);
WebCoreThreadWatchdog.pause();
try {
wait();
} catch (InterruptedException e) {
Log.e(LOGTAG, "Caught exception waiting for synchronous UI message to be processed");
Log.e(LOGTAG, Log.getStackTraceString(e));
}
WebCoreThreadWatchdog.resume();
}
}
| true | true | public void handleMessage(Message msg) {
// We don't have to do synchronization because this function operates
// in the UI thread. The WebViewClient and WebChromeClient functions
// that check for a non-null callback are ok because java ensures atomic
// 32-bit reads and writes.
if (messagesBlocked()) return;
switch (msg.what) {
case PAGE_STARTED:
String startedUrl = msg.getData().getString("url");
mWebView.onPageStarted(startedUrl);
if (mWebViewClient != null) {
mWebViewClient.onPageStarted(mWebView.getWebView(), startedUrl,
(Bitmap) msg.obj);
}
break;
case PAGE_FINISHED:
String finishedUrl = (String) msg.obj;
mWebView.onPageFinished(finishedUrl);
if (mWebViewClient != null) {
mWebViewClient.onPageFinished(mWebView.getWebView(), finishedUrl);
}
break;
case RECEIVED_ICON:
if (mWebChromeClient != null) {
mWebChromeClient.onReceivedIcon(mWebView.getWebView(), (Bitmap) msg.obj);
}
break;
case RECEIVED_TOUCH_ICON_URL:
if (mWebChromeClient != null) {
mWebChromeClient.onReceivedTouchIconUrl(mWebView.getWebView(),
(String) msg.obj, msg.arg1 == 1);
}
break;
case RECEIVED_TITLE:
if (mWebChromeClient != null) {
mWebChromeClient.onReceivedTitle(mWebView.getWebView(),
(String) msg.obj);
}
break;
case REPORT_ERROR:
if (mWebViewClient != null) {
int reasonCode = msg.arg1;
final String description = msg.getData().getString("description");
final String failUrl = msg.getData().getString("failingUrl");
mWebViewClient.onReceivedError(mWebView.getWebView(), reasonCode,
description, failUrl);
}
break;
case RESEND_POST_DATA:
Message resend =
(Message) msg.getData().getParcelable("resend");
Message dontResend =
(Message) msg.getData().getParcelable("dontResend");
if (mWebViewClient != null) {
mWebViewClient.onFormResubmission(mWebView.getWebView(), dontResend,
resend);
} else {
dontResend.sendToTarget();
}
break;
case OVERRIDE_URL:
String overrideUrl = msg.getData().getString("url");
boolean override = uiOverrideUrlLoading(overrideUrl);
ResultTransport<Boolean> result =
(ResultTransport<Boolean>) msg.obj;
synchronized (this) {
result.setResult(override);
notify();
}
break;
case AUTH_REQUEST:
if (mWebViewClient != null) {
HttpAuthHandler handler = (HttpAuthHandler) msg.obj;
String host = msg.getData().getString("host");
String realm = msg.getData().getString("realm");
mWebViewClient.onReceivedHttpAuthRequest(mWebView.getWebView(), handler,
host, realm);
}
break;
case SSL_ERROR:
if (mWebViewClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
mWebViewClient.onReceivedSslError(mWebView.getWebView(),
(SslErrorHandler) map.get("handler"),
(SslError) map.get("error"));
}
break;
case PROCEEDED_AFTER_SSL_ERROR:
if (mWebViewClient != null && mWebViewClient instanceof WebViewClientClassicExt) {
((WebViewClientClassicExt) mWebViewClient).onProceededAfterSslError(
mWebView.getWebView(),
(SslError) msg.obj);
}
break;
case CLIENT_CERT_REQUEST:
if (mWebViewClient != null && mWebViewClient instanceof WebViewClientClassicExt) {
HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
((WebViewClientClassicExt) mWebViewClient).onReceivedClientCertRequest(
mWebView.getWebView(),
(ClientCertRequestHandler) map.get("handler"),
(String) map.get("host_and_port"));
}
break;
case PROGRESS:
// Synchronize to ensure mLatestProgress is not modified after
// setProgress is called and before mProgressUpdatePending is
// changed.
synchronized (this) {
if (mWebChromeClient != null) {
mWebChromeClient.onProgressChanged(mWebView.getWebView(),
mLatestProgress);
}
mProgressUpdatePending = false;
}
break;
case UPDATE_VISITED:
if (mWebViewClient != null) {
mWebViewClient.doUpdateVisitedHistory(mWebView.getWebView(),
(String) msg.obj, msg.arg1 != 0);
}
break;
case LOAD_RESOURCE:
if (mWebViewClient != null) {
mWebViewClient.onLoadResource(mWebView.getWebView(), (String) msg.obj);
}
break;
case DOWNLOAD_FILE:
if (mDownloadListener != null) {
String url = msg.getData().getString("url");
String userAgent = msg.getData().getString("userAgent");
String contentDisposition =
msg.getData().getString("contentDisposition");
String mimetype = msg.getData().getString("mimetype");
String referer = msg.getData().getString("referer");
Long contentLength = msg.getData().getLong("contentLength");
if (mDownloadListener instanceof BrowserDownloadListener) {
((BrowserDownloadListener) mDownloadListener).onDownloadStart(url,
userAgent, contentDisposition, mimetype, referer, contentLength);
} else {
mDownloadListener.onDownloadStart(url, userAgent,
contentDisposition, mimetype, contentLength);
}
}
break;
case CREATE_WINDOW:
if (mWebChromeClient != null) {
if (!mWebChromeClient.onCreateWindow(mWebView.getWebView(),
msg.arg1 == 1, msg.arg2 == 1,
(Message) msg.obj)) {
synchronized (this) {
notify();
}
}
mWebView.dismissZoomControl();
}
break;
case REQUEST_FOCUS:
if (mWebChromeClient != null) {
mWebChromeClient.onRequestFocus(mWebView.getWebView());
}
break;
case CLOSE_WINDOW:
if (mWebChromeClient != null) {
mWebChromeClient.onCloseWindow(((WebViewClassic) msg.obj).getWebView());
}
break;
case SAVE_PASSWORD:
Bundle bundle = msg.getData();
String schemePlusHost = bundle.getString("host");
String username = bundle.getString("username");
String password = bundle.getString("password");
// If the client returned false it means that the notify message
// will not be sent and we should notify WebCore ourselves.
if (!mWebView.onSavePassword(schemePlusHost, username, password,
(Message) msg.obj)) {
synchronized (this) {
notify();
}
}
break;
case ASYNC_KEYEVENTS:
if (mWebViewClient != null) {
mWebViewClient.onUnhandledKeyEvent(mWebView.getWebView(),
(KeyEvent) msg.obj);
}
break;
case EXCEEDED_DATABASE_QUOTA:
if (mWebChromeClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
String databaseIdentifier =
(String) map.get("databaseIdentifier");
String url = (String) map.get("url");
long quota =
((Long) map.get("quota")).longValue();
long totalQuota =
((Long) map.get("totalQuota")).longValue();
long estimatedDatabaseSize =
((Long) map.get("estimatedDatabaseSize")).longValue();
WebStorage.QuotaUpdater quotaUpdater =
(WebStorage.QuotaUpdater) map.get("quotaUpdater");
mWebChromeClient.onExceededDatabaseQuota(url,
databaseIdentifier, quota, estimatedDatabaseSize,
totalQuota, quotaUpdater);
}
break;
case REACHED_APPCACHE_MAXSIZE:
if (mWebChromeClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
long requiredStorage =
((Long) map.get("requiredStorage")).longValue();
long quota =
((Long) map.get("quota")).longValue();
WebStorage.QuotaUpdater quotaUpdater =
(WebStorage.QuotaUpdater) map.get("quotaUpdater");
mWebChromeClient.onReachedMaxAppCacheSize(requiredStorage,
quota, quotaUpdater);
}
break;
case GEOLOCATION_PERMISSIONS_SHOW_PROMPT:
if (mWebChromeClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
String origin = (String) map.get("origin");
GeolocationPermissions.Callback callback =
(GeolocationPermissions.Callback)
map.get("callback");
mWebChromeClient.onGeolocationPermissionsShowPrompt(origin,
callback);
}
break;
case GEOLOCATION_PERMISSIONS_HIDE_PROMPT:
if (mWebChromeClient != null) {
mWebChromeClient.onGeolocationPermissionsHidePrompt();
}
break;
case JS_DIALOG:
if (mWebChromeClient != null) {
final JsResultReceiver receiver = (JsResultReceiver) msg.obj;
JsDialogHelper helper = new JsDialogHelper(receiver.mJsResult, msg);
if (!helper.invokeCallback(mWebChromeClient, mWebView.getWebView())) {
helper.showDialog(mContext);
}
receiver.setReady();
}
break;
case JS_TIMEOUT:
if(mWebChromeClient != null) {
final JsResultReceiver receiver = (JsResultReceiver) msg.obj;
final JsResult res = receiver.mJsResult;
if (mWebChromeClient.onJsTimeout()) {
res.confirm();
} else {
res.cancel();
}
receiver.setReady();
}
break;
case RECEIVED_CERTIFICATE:
mWebView.setCertificate((SslCertificate) msg.obj);
break;
case NOTIFY:
synchronized (this) {
notify();
}
break;
case SCALE_CHANGED:
if (mWebViewClient != null) {
mWebViewClient.onScaleChanged(mWebView.getWebView(), msg.getData()
.getFloat("old"), msg.getData().getFloat("new"));
}
break;
case SWITCH_OUT_HISTORY:
mWebView.switchOutDrawHistory();
break;
case ADD_MESSAGE_TO_CONSOLE:
if (mWebChromeClient == null) {
break;
}
String message = msg.getData().getString("message");
String sourceID = msg.getData().getString("sourceID");
int lineNumber = msg.getData().getInt("lineNumber");
int msgLevel = msg.getData().getInt("msgLevel");
int numberOfMessageLevels = ConsoleMessage.MessageLevel.values().length;
// Sanity bounds check as we'll index an array with msgLevel
if (msgLevel < 0 || msgLevel >= numberOfMessageLevels) {
msgLevel = 0;
}
ConsoleMessage.MessageLevel messageLevel =
ConsoleMessage.MessageLevel.values()[msgLevel];
if (!mWebChromeClient.onConsoleMessage(new ConsoleMessage(message, sourceID,
lineNumber, messageLevel))) {
// If false was returned the user did not provide their own console function so
// we should output some default messages to the system log.
String logTag = "Web Console";
String logMessage = message + " at " + sourceID + ":" + lineNumber;
switch (messageLevel) {
case TIP:
Log.v(logTag, logMessage);
break;
case LOG:
Log.i(logTag, logMessage);
break;
case WARNING:
Log.w(logTag, logMessage);
break;
case ERROR:
Log.e(logTag, logMessage);
break;
case DEBUG:
Log.d(logTag, logMessage);
break;
}
}
break;
case GET_VISITED_HISTORY:
if (mWebChromeClient != null) {
mWebChromeClient.getVisitedHistory((ValueCallback<String[]>)msg.obj);
}
break;
case OPEN_FILE_CHOOSER:
if (mWebChromeClient != null) {
UploadFileMessageData data = (UploadFileMessageData)msg.obj;
mWebChromeClient.openFileChooser(data.getUploadFile(), data.getAcceptType(),
data.getCapture());
}
break;
case ADD_HISTORY_ITEM:
if (mWebBackForwardListClient != null) {
mWebBackForwardListClient.onNewHistoryItem(
(WebHistoryItem) msg.obj);
}
break;
case HISTORY_INDEX_CHANGED:
if (mWebBackForwardListClient != null) {
mWebBackForwardListClient.onIndexChanged(
(WebHistoryItem) msg.obj, msg.arg1);
}
break;
case AUTH_CREDENTIALS: {
String host = msg.getData().getString("host");
String realm = msg.getData().getString("realm");
username = msg.getData().getString("username");
password = msg.getData().getString("password");
mWebView.setHttpAuthUsernamePassword(
host, realm, username, password);
break;
}
case AUTO_LOGIN: {
if (mWebViewClient != null) {
String realm = msg.getData().getString("realm");
String account = msg.getData().getString("account");
String args = msg.getData().getString("args");
mWebViewClient.onReceivedLoginRequest(mWebView.getWebView(), realm,
account, args);
}
break;
}
}
}
| public void handleMessage(Message msg) {
// We don't have to do synchronization because this function operates
// in the UI thread. The WebViewClient and WebChromeClient functions
// that check for a non-null callback are ok because java ensures atomic
// 32-bit reads and writes.
if (messagesBlocked()) {
synchronized (this) {
notify();
}
return;
}
switch (msg.what) {
case PAGE_STARTED:
String startedUrl = msg.getData().getString("url");
mWebView.onPageStarted(startedUrl);
if (mWebViewClient != null) {
mWebViewClient.onPageStarted(mWebView.getWebView(), startedUrl,
(Bitmap) msg.obj);
}
break;
case PAGE_FINISHED:
String finishedUrl = (String) msg.obj;
mWebView.onPageFinished(finishedUrl);
if (mWebViewClient != null) {
mWebViewClient.onPageFinished(mWebView.getWebView(), finishedUrl);
}
break;
case RECEIVED_ICON:
if (mWebChromeClient != null) {
mWebChromeClient.onReceivedIcon(mWebView.getWebView(), (Bitmap) msg.obj);
}
break;
case RECEIVED_TOUCH_ICON_URL:
if (mWebChromeClient != null) {
mWebChromeClient.onReceivedTouchIconUrl(mWebView.getWebView(),
(String) msg.obj, msg.arg1 == 1);
}
break;
case RECEIVED_TITLE:
if (mWebChromeClient != null) {
mWebChromeClient.onReceivedTitle(mWebView.getWebView(),
(String) msg.obj);
}
break;
case REPORT_ERROR:
if (mWebViewClient != null) {
int reasonCode = msg.arg1;
final String description = msg.getData().getString("description");
final String failUrl = msg.getData().getString("failingUrl");
mWebViewClient.onReceivedError(mWebView.getWebView(), reasonCode,
description, failUrl);
}
break;
case RESEND_POST_DATA:
Message resend =
(Message) msg.getData().getParcelable("resend");
Message dontResend =
(Message) msg.getData().getParcelable("dontResend");
if (mWebViewClient != null) {
mWebViewClient.onFormResubmission(mWebView.getWebView(), dontResend,
resend);
} else {
dontResend.sendToTarget();
}
break;
case OVERRIDE_URL:
String overrideUrl = msg.getData().getString("url");
boolean override = uiOverrideUrlLoading(overrideUrl);
ResultTransport<Boolean> result =
(ResultTransport<Boolean>) msg.obj;
synchronized (this) {
result.setResult(override);
notify();
}
break;
case AUTH_REQUEST:
if (mWebViewClient != null) {
HttpAuthHandler handler = (HttpAuthHandler) msg.obj;
String host = msg.getData().getString("host");
String realm = msg.getData().getString("realm");
mWebViewClient.onReceivedHttpAuthRequest(mWebView.getWebView(), handler,
host, realm);
}
break;
case SSL_ERROR:
if (mWebViewClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
mWebViewClient.onReceivedSslError(mWebView.getWebView(),
(SslErrorHandler) map.get("handler"),
(SslError) map.get("error"));
}
break;
case PROCEEDED_AFTER_SSL_ERROR:
if (mWebViewClient != null && mWebViewClient instanceof WebViewClientClassicExt) {
((WebViewClientClassicExt) mWebViewClient).onProceededAfterSslError(
mWebView.getWebView(),
(SslError) msg.obj);
}
break;
case CLIENT_CERT_REQUEST:
if (mWebViewClient != null && mWebViewClient instanceof WebViewClientClassicExt) {
HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
((WebViewClientClassicExt) mWebViewClient).onReceivedClientCertRequest(
mWebView.getWebView(),
(ClientCertRequestHandler) map.get("handler"),
(String) map.get("host_and_port"));
}
break;
case PROGRESS:
// Synchronize to ensure mLatestProgress is not modified after
// setProgress is called and before mProgressUpdatePending is
// changed.
synchronized (this) {
if (mWebChromeClient != null) {
mWebChromeClient.onProgressChanged(mWebView.getWebView(),
mLatestProgress);
}
mProgressUpdatePending = false;
}
break;
case UPDATE_VISITED:
if (mWebViewClient != null) {
mWebViewClient.doUpdateVisitedHistory(mWebView.getWebView(),
(String) msg.obj, msg.arg1 != 0);
}
break;
case LOAD_RESOURCE:
if (mWebViewClient != null) {
mWebViewClient.onLoadResource(mWebView.getWebView(), (String) msg.obj);
}
break;
case DOWNLOAD_FILE:
if (mDownloadListener != null) {
String url = msg.getData().getString("url");
String userAgent = msg.getData().getString("userAgent");
String contentDisposition =
msg.getData().getString("contentDisposition");
String mimetype = msg.getData().getString("mimetype");
String referer = msg.getData().getString("referer");
Long contentLength = msg.getData().getLong("contentLength");
if (mDownloadListener instanceof BrowserDownloadListener) {
((BrowserDownloadListener) mDownloadListener).onDownloadStart(url,
userAgent, contentDisposition, mimetype, referer, contentLength);
} else {
mDownloadListener.onDownloadStart(url, userAgent,
contentDisposition, mimetype, contentLength);
}
}
break;
case CREATE_WINDOW:
if (mWebChromeClient != null) {
if (!mWebChromeClient.onCreateWindow(mWebView.getWebView(),
msg.arg1 == 1, msg.arg2 == 1,
(Message) msg.obj)) {
synchronized (this) {
notify();
}
}
mWebView.dismissZoomControl();
}
break;
case REQUEST_FOCUS:
if (mWebChromeClient != null) {
mWebChromeClient.onRequestFocus(mWebView.getWebView());
}
break;
case CLOSE_WINDOW:
if (mWebChromeClient != null) {
mWebChromeClient.onCloseWindow(((WebViewClassic) msg.obj).getWebView());
}
break;
case SAVE_PASSWORD:
Bundle bundle = msg.getData();
String schemePlusHost = bundle.getString("host");
String username = bundle.getString("username");
String password = bundle.getString("password");
// If the client returned false it means that the notify message
// will not be sent and we should notify WebCore ourselves.
if (!mWebView.onSavePassword(schemePlusHost, username, password,
(Message) msg.obj)) {
synchronized (this) {
notify();
}
}
break;
case ASYNC_KEYEVENTS:
if (mWebViewClient != null) {
mWebViewClient.onUnhandledKeyEvent(mWebView.getWebView(),
(KeyEvent) msg.obj);
}
break;
case EXCEEDED_DATABASE_QUOTA:
if (mWebChromeClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
String databaseIdentifier =
(String) map.get("databaseIdentifier");
String url = (String) map.get("url");
long quota =
((Long) map.get("quota")).longValue();
long totalQuota =
((Long) map.get("totalQuota")).longValue();
long estimatedDatabaseSize =
((Long) map.get("estimatedDatabaseSize")).longValue();
WebStorage.QuotaUpdater quotaUpdater =
(WebStorage.QuotaUpdater) map.get("quotaUpdater");
mWebChromeClient.onExceededDatabaseQuota(url,
databaseIdentifier, quota, estimatedDatabaseSize,
totalQuota, quotaUpdater);
}
break;
case REACHED_APPCACHE_MAXSIZE:
if (mWebChromeClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
long requiredStorage =
((Long) map.get("requiredStorage")).longValue();
long quota =
((Long) map.get("quota")).longValue();
WebStorage.QuotaUpdater quotaUpdater =
(WebStorage.QuotaUpdater) map.get("quotaUpdater");
mWebChromeClient.onReachedMaxAppCacheSize(requiredStorage,
quota, quotaUpdater);
}
break;
case GEOLOCATION_PERMISSIONS_SHOW_PROMPT:
if (mWebChromeClient != null) {
HashMap<String, Object> map =
(HashMap<String, Object>) msg.obj;
String origin = (String) map.get("origin");
GeolocationPermissions.Callback callback =
(GeolocationPermissions.Callback)
map.get("callback");
mWebChromeClient.onGeolocationPermissionsShowPrompt(origin,
callback);
}
break;
case GEOLOCATION_PERMISSIONS_HIDE_PROMPT:
if (mWebChromeClient != null) {
mWebChromeClient.onGeolocationPermissionsHidePrompt();
}
break;
case JS_DIALOG:
if (mWebChromeClient != null) {
final JsResultReceiver receiver = (JsResultReceiver) msg.obj;
JsDialogHelper helper = new JsDialogHelper(receiver.mJsResult, msg);
if (!helper.invokeCallback(mWebChromeClient, mWebView.getWebView())) {
helper.showDialog(mContext);
}
receiver.setReady();
}
break;
case JS_TIMEOUT:
if(mWebChromeClient != null) {
final JsResultReceiver receiver = (JsResultReceiver) msg.obj;
final JsResult res = receiver.mJsResult;
if (mWebChromeClient.onJsTimeout()) {
res.confirm();
} else {
res.cancel();
}
receiver.setReady();
}
break;
case RECEIVED_CERTIFICATE:
mWebView.setCertificate((SslCertificate) msg.obj);
break;
case NOTIFY:
synchronized (this) {
notify();
}
break;
case SCALE_CHANGED:
if (mWebViewClient != null) {
mWebViewClient.onScaleChanged(mWebView.getWebView(), msg.getData()
.getFloat("old"), msg.getData().getFloat("new"));
}
break;
case SWITCH_OUT_HISTORY:
mWebView.switchOutDrawHistory();
break;
case ADD_MESSAGE_TO_CONSOLE:
if (mWebChromeClient == null) {
break;
}
String message = msg.getData().getString("message");
String sourceID = msg.getData().getString("sourceID");
int lineNumber = msg.getData().getInt("lineNumber");
int msgLevel = msg.getData().getInt("msgLevel");
int numberOfMessageLevels = ConsoleMessage.MessageLevel.values().length;
// Sanity bounds check as we'll index an array with msgLevel
if (msgLevel < 0 || msgLevel >= numberOfMessageLevels) {
msgLevel = 0;
}
ConsoleMessage.MessageLevel messageLevel =
ConsoleMessage.MessageLevel.values()[msgLevel];
if (!mWebChromeClient.onConsoleMessage(new ConsoleMessage(message, sourceID,
lineNumber, messageLevel))) {
// If false was returned the user did not provide their own console function so
// we should output some default messages to the system log.
String logTag = "Web Console";
String logMessage = message + " at " + sourceID + ":" + lineNumber;
switch (messageLevel) {
case TIP:
Log.v(logTag, logMessage);
break;
case LOG:
Log.i(logTag, logMessage);
break;
case WARNING:
Log.w(logTag, logMessage);
break;
case ERROR:
Log.e(logTag, logMessage);
break;
case DEBUG:
Log.d(logTag, logMessage);
break;
}
}
break;
case GET_VISITED_HISTORY:
if (mWebChromeClient != null) {
mWebChromeClient.getVisitedHistory((ValueCallback<String[]>)msg.obj);
}
break;
case OPEN_FILE_CHOOSER:
if (mWebChromeClient != null) {
UploadFileMessageData data = (UploadFileMessageData)msg.obj;
mWebChromeClient.openFileChooser(data.getUploadFile(), data.getAcceptType(),
data.getCapture());
}
break;
case ADD_HISTORY_ITEM:
if (mWebBackForwardListClient != null) {
mWebBackForwardListClient.onNewHistoryItem(
(WebHistoryItem) msg.obj);
}
break;
case HISTORY_INDEX_CHANGED:
if (mWebBackForwardListClient != null) {
mWebBackForwardListClient.onIndexChanged(
(WebHistoryItem) msg.obj, msg.arg1);
}
break;
case AUTH_CREDENTIALS: {
String host = msg.getData().getString("host");
String realm = msg.getData().getString("realm");
username = msg.getData().getString("username");
password = msg.getData().getString("password");
mWebView.setHttpAuthUsernamePassword(
host, realm, username, password);
break;
}
case AUTO_LOGIN: {
if (mWebViewClient != null) {
String realm = msg.getData().getString("realm");
String account = msg.getData().getString("account");
String args = msg.getData().getString("args");
mWebViewClient.onReceivedLoginRequest(mWebView.getWebView(), realm,
account, args);
}
break;
}
}
}
|
diff --git a/src/main/java/net/h31ix/anticheat/manage/Backend.java b/src/main/java/net/h31ix/anticheat/manage/Backend.java
index 0afce67..31c0ee0 100644
--- a/src/main/java/net/h31ix/anticheat/manage/Backend.java
+++ b/src/main/java/net/h31ix/anticheat/manage/Backend.java
@@ -1,1310 +1,1310 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012 AntiCheat Team | http://gravitydevelopment.net
*
* 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 net.h31ix.anticheat.manage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.h31ix.anticheat.util.Distance;
import net.h31ix.anticheat.util.Language;
import net.h31ix.anticheat.util.Magic;
import net.h31ix.anticheat.util.Utilities;
import net.h31ix.anticheat.util.yaml.CommentedConfiguration;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.craftbukkit.entity.CraftEntity;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerToggleSprintEvent;
import org.bukkit.potion.PotionEffectType;
public class Backend
{
private List<String> isInWater = new ArrayList<String>();
private List<String> isInWaterCache = new ArrayList<String>();
private List<String> isAscending = new ArrayList<String>();
private Map<String, Integer> ascensionCount = new HashMap<String, Integer>();
private Map<String, String> oldMessage = new HashMap<String, String>();
private Map<String, String> lastMessage = new HashMap<String, String>();
private Map<String, Double> blocksOverFlight = new HashMap<String, Double>();
private Map<String, Integer> chatLevel = new HashMap<String, Integer>();
private Map<String, Integer> chatKicks = new HashMap<String, Integer>();
private Map<String, Integer> nofallViolation = new HashMap<String, Integer>();
private Map<String, Integer> speedViolation = new HashMap<String, Integer>();
private Map<String, Integer> fastBreakViolation = new HashMap<String, Integer>();
private Map<String, Integer> yAxisViolations = new HashMap<String, Integer>();
private Map<String, Long> yAxisLastViolation = new HashMap<String, Long>();
private Map<String, Double> lastYcoord = new HashMap<String, Double>();
private Map<String, Long> lastYtime = new HashMap<String, Long>();
private Map<String, Integer> fastBreaks = new HashMap<String, Integer>();
private Map<String, Boolean> blockBreakHolder = new HashMap<String, Boolean>();
private Map<String, Long> lastBlockBroken = new HashMap<String, Long>();
private Map<String, Integer> fastPlaceViolation = new HashMap<String, Integer>();
private Map<String, Integer> lastZeroHitPlace = new HashMap<String, Integer>();
private Map<String, Long> lastBlockPlaced = new HashMap<String, Long>();
private Map<String, Long> lastBlockPlaceTime = new HashMap<String, Long>();
private Map<String, Integer> blockPunches = new HashMap<String, Integer>();
private Map<String, Integer> waterAscensionViolation = new HashMap<String, Integer>();
private Map<String, Integer> waterSpeedViolation = new HashMap<String, Integer>();
private Map<String, Integer> projectilesShot = new HashMap<String, Integer>();
private Map<String, Long> velocitized = new HashMap<String, Long>();
private Map<String, Integer> velocitytrack = new HashMap<String, Integer>();
private Map<String, Long> animated = new HashMap<String, Long>();
private Map<String, Long> startEat = new HashMap<String, Long>();
private Map<String, Long> lastHeal = new HashMap<String, Long>();
private Map<String, Long> projectileTime = new HashMap<String, Long>();
private Map<String, Long> bowWindUp = new HashMap<String, Long>();
private Map<String, Long> instantBreakExempt = new HashMap<String, Long>();
private Map<String, Long> sprinted = new HashMap<String, Long>();
private Map<String, Long> brokenBlock = new HashMap<String, Long>();
private Map<String, Long> placedBlock = new HashMap<String, Long>();
private Map<String, Long> movingExempt = new HashMap<String, Long>();
private Map<String, Long> blockTime = new HashMap<String, Long>();
private Map<String, Integer> blocksDropped = new HashMap<String, Integer>();
private Map<String, Long> lastInventoryTime = new HashMap<String, Long>();
private Map<String, Long> inventoryTime = new HashMap<String, Long>();
private Map<String, Integer> inventoryChanges = new HashMap<String, Integer>();
private Magic magic;
private AnticheatManager micromanage = null;
private Language lang = null;
public Backend(AnticheatManager instance)
{
magic = new Magic(instance.getConfiguration().getMagic(), instance.getConfiguration(), CommentedConfiguration.loadConfiguration(instance.getPlugin().getResource("magic.yml")));
micromanage = instance;
lang = micromanage.getConfiguration().getLang();
}
public void garbageClean(Player player)
{
String pN = player.getName();
User user = micromanage.getUserManager().getUser(pN);
if (user != null)
{
micromanage.getUserManager().remove(user);
}
blocksDropped.remove(pN);
blockTime.remove(pN);
movingExempt.remove(pN);
brokenBlock.remove(pN);
placedBlock.remove(pN);
bowWindUp.remove(pN);
startEat.remove(pN);
lastHeal.remove(pN);
sprinted.remove(pN);
isInWater.remove(pN);
isInWaterCache.remove(pN);
instantBreakExempt.remove(pN);
isAscending.remove(pN);
ascensionCount.remove(pN);
oldMessage.remove(pN);
lastMessage.remove(pN);
blocksOverFlight.remove(pN);
chatLevel.remove(pN);
nofallViolation.remove(pN);
fastBreakViolation.remove(pN);
yAxisViolations.remove(pN);
yAxisLastViolation.remove(pN);
lastYcoord.remove(pN);
lastYtime.remove(pN);
fastBreaks.remove(pN);
blockBreakHolder.remove(pN);
lastBlockBroken.remove(pN);
fastPlaceViolation.remove(pN);
lastZeroHitPlace.remove(pN);
lastBlockPlaced.remove(pN);
lastBlockPlaceTime.remove(pN);
blockPunches.remove(pN);
waterAscensionViolation.remove(pN);
waterSpeedViolation.remove(pN);
projectilesShot.remove(pN);
velocitized.remove(pN);
velocitytrack.remove(pN);
animated.remove(pN);
startEat.remove(pN);
lastHeal.remove(pN);
projectileTime.remove(pN);
bowWindUp.remove(pN);
instantBreakExempt.remove(pN);
sprinted.remove(pN);
brokenBlock.remove(pN);
placedBlock.remove(pN);
movingExempt.remove(pN);
blockTime.remove(pN);
blocksDropped.remove(pN);
lastInventoryTime.remove(pN);
inventoryTime.remove(pN);
inventoryChanges.remove(pN);
}
public boolean checkFastBow(Player player, float force)
{
// Ignore magic numbers here, they are minecrafty vanilla stuff.
int ticks = (int) ((((System.currentTimeMillis() - bowWindUp.get(player.getName())) * 20) / 1000) + 3);
bowWindUp.remove(player.getName());
float f = (float) ticks / 20.0F;
f = (f * f + f * 2.0F) / 3.0F;
f = f > 1.0F ? 1.0F : f;
return Math.abs(force - f) > magic.BOW_ERROR;
}
public boolean checkProjectile(Player player)
{
increment(player, projectilesShot, 10);
if (!projectileTime.containsKey(player.getName()))
{
projectileTime.put(player.getName(), System.currentTimeMillis());
return false;
}
else if (projectilesShot.get(player.getName()) == magic.PROJECTILE_CHECK)
{
long time = System.currentTimeMillis() - projectileTime.get(player.getName());
projectileTime.remove(player.getName());
projectilesShot.remove(player.getName());
return time < magic.PROJECTILE_TIME_MIN;
}
return false;
}
public boolean checkFastDrop(Player player)
{
increment(player, blocksDropped, 10);
if (!blockTime.containsKey(player.getName()))
{
blockTime.put(player.getName(), System.currentTimeMillis());
return false;
}
else if (blocksDropped.get(player.getName()) == magic.DROP_CHECK)
{
long time = System.currentTimeMillis() - blockTime.get(player.getName());
blockTime.remove(player.getName());
blocksDropped.remove(player.getName());
return time < magic.DROP_TIME_MIN;
}
return false;
}
public boolean checkLongReachBlock(Player player, double x, double y, double z)
{
if (isInstantBreakExempt(player))
{
return false;
}
else
{
return (x >= magic.BLOCK_MAX_DISTANCE || y > magic.BLOCK_MAX_DISTANCE || z > magic.BLOCK_MAX_DISTANCE);
}
}
public boolean checkLongReachDamage(double x, double y, double z)
{
return x >= magic.ENTITY_MAX_DISTANCE || y > magic.ENTITY_MAX_DISTANCE || z > magic.ENTITY_MAX_DISTANCE;
}
public boolean checkSpider(Player player, double y)
{
if (y <= magic.LADDER_Y_MAX && y >= magic.LADDER_Y_MIN && !Utilities.isClimbableBlock(player.getLocation().getBlock()))
{
return true;
}
return false;
}
public boolean checkYSpeed(Player player, double y)
{
if (!player.isInsideVehicle() && !player.isSleeping() && y > magic.Y_SPEED_MAX && !isDoing(player, velocitized, magic.VELOCITY_TIME) && !player.hasPotionEffect(PotionEffectType.JUMP))
{
return true;
}
return false;
}
public boolean checkNoFall(Player player, double y)
{
String name = player.getName();
if (player.getGameMode() != GameMode.CREATIVE && !player.isInsideVehicle() && !player.isSleeping() && !isMovingExempt(player) && !justPlaced(player) && !Utilities.isInWater(player))
{
if (player.getFallDistance() == 0)
{
if (nofallViolation.get(name) == null)
{
nofallViolation.put(name, 1);
}
else
{
nofallViolation.put(name, nofallViolation.get(player.getName()) + 1);
}
if (nofallViolation.get(name) >= magic.NOFALL_LIMIT)
{
nofallViolation.put(player.getName(), 1);
return true;
}
else
{
return false;
}
}
else
{
nofallViolation.put(name, 0);
return false;
}
}
return false;
}
public boolean checkXZSpeed(Player player, double x, double z)
{
if (!isSpeedExempt(player) && player.getVehicle() == null)
{
boolean speed = false;
if (player.isFlying())
{
speed = x > magic.XZ_SPEED_MAX_FLY || z > magic.XZ_SPEED_MAX_FLY;
}
else if (player.hasPotionEffect(PotionEffectType.SPEED))
{
speed = x > magic.XZ_SPEED_MAX_POTION || z > magic.XZ_SPEED_MAX_POTION;
}
else if (player.isSprinting())
{
speed = x > magic.XZ_SPEED_MAX_SPRINT || z > magic.XZ_SPEED_MAX_SPRINT;
}
else
{
speed = x > magic.XZ_SPEED_MAX || z > magic.XZ_SPEED_MAX;
}
if (speed)
{
int num = this.increment(player, speedViolation, magic.SPEED_MAX);
return num >= magic.SPEED_MAX;
}
else
{
speedViolation.put(player.getName(), 0);
return false;
}
}
else
{
return false;
}
}
public boolean checkSneak(Player player, double x, double z)
{
if (player.isSneaking() && !player.isFlying() && !isMovingExempt(player))
{
return x > magic.XZ_SPEED_MAX_SNEAK || z > magic.XZ_SPEED_MAX_SNEAK;
}
else
{
return false;
}
}
public boolean checkSprint(PlayerToggleSprintEvent event)
{
Player player = event.getPlayer();
if (event.isSprinting())
{
return player.getFoodLevel() <= magic.SPRINT_FOOD_MIN && player.getGameMode() != GameMode.CREATIVE;
}
else
{
return false;
}
}
public boolean checkWaterWalk(Player player, double x, double y, double z)
{
Block block = player.getLocation().getBlock();
if (player.getVehicle() == null && !player.isFlying())
{
if (block.isLiquid())
{
if (isInWater.contains(player.getName()))
{
if (isInWaterCache.contains(player.getName()))
{
if (player.getNearbyEntities(1, 1, 1).isEmpty())
{
boolean b = false;
if (!Utilities.sprintFly(player) && x > magic.XZ_SPEED_MAX_WATER || z > magic.XZ_SPEED_MAX_WATER)
{
b = true;
}
else if (x > magic.XZ_SPEED_MAX_WATER_SPRINT || z > magic.XZ_SPEED_MAX_WATER_SPRINT)
{
b = true;
}
else if (!Utilities.isFullyInWater(player.getLocation()) && Utilities.isHoveringOverWater(player.getLocation(), 1) && y == 0D && !block.getType().equals(Material.WATER_LILY))
{
b = true;
}
if (b)
{
if (waterSpeedViolation.containsKey(player.getName()))
{
int v = waterSpeedViolation.get(player.getName());
if (v >= magic.WATER_SPEED_VIOLATION_MAX)
{
waterSpeedViolation.put(player.getName(), 0);
return true;
}
else
{
waterSpeedViolation.put(player.getName(), v + 1);
}
}
else
{
waterSpeedViolation.put(player.getName(), 1);
}
}
}
}
else
{
isInWaterCache.add(player.getName());
return false;
}
}
else
{
isInWater.add(player.getName());
return false;
}
}
else if (block.getRelative(BlockFace.DOWN).isLiquid() && isAscending(player) && Utilities.cantStandAt(block) && Utilities.cantStandAt(block.getRelative(BlockFace.DOWN)))
{
if (waterAscensionViolation.containsKey(player.getName()))
{
int v = waterAscensionViolation.get(player.getName());
if (v >= magic.WATER_ASCENSION_VIOLATION_MAX)
{
waterAscensionViolation.put(player.getName(), 0);
return true;
}
else
{
waterAscensionViolation.put(player.getName(), v + 1);
return true;
}
}
else
{
waterAscensionViolation.put(player.getName(), 1);
}
}
else
{
isInWater.remove(player.getName());
isInWaterCache.remove(player.getName());
}
}
return false;
}
// The first check in Anticheat with a integer as a result :O!
public int checkVClip(Player player, Distance distance)
{
double from = Math.round(distance.fromY());
double to = Math.round(distance.toY());
boolean bs = false;
if (player.isInsideVehicle())
{
return 0;
}
if (from == to || from < to)
{
return 0;
}
if (Math.round(distance.getYDifference()) < 2)
{
return 0;
}
for (int i = 0; i < (Math.round(distance.getYDifference())) + 1; i++)
{
Location l = new Location(player.getWorld(), player.getLocation().getX(), to + i, player.getLocation().getZ());
if (l.getBlock().getTypeId() != 0 && net.minecraft.server.Block.byId[l.getBlock().getTypeId()].material.isSolid() && !l.getBlock().isLiquid())
{
bs = true;
}
if (bs)
{
return (int) from + 3;
}
}
return 0;
}
public boolean checkYAxis(Player player, Distance distance)
{
if (distance.getYDifference() > 400 || distance.getYDifference() < 0)
{
return false;
}
if (!isMovingExempt(player) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && !Utilities.isClimbableBlock(player.getLocation().add(0, -1, 0).getBlock()) && !player.isInsideVehicle() && !Utilities.isInWater(player))
{
double y1 = player.getLocation().getY();
String name = player.getName();
//Fix Y axis spam.
if (!lastYcoord.containsKey(name) || !lastYtime.containsKey(name) || !yAxisLastViolation.containsKey(name) || !yAxisLastViolation.containsKey(name))
{
lastYcoord.put(name, y1);
yAxisViolations.put(name, 0);
yAxisLastViolation.put(name, 0L);
lastYtime.put(name, System.currentTimeMillis());
}
else
{
if (y1 > lastYcoord.get(name) && yAxisViolations.get(name) > magic.Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) < magic.Y_MAXVIOTIME)
{
Location g = player.getLocation();
g.setY(lastYcoord.get(name));
player.sendMessage(ChatColor.RED + "[AntiCheat] Fly hacking on the y-axis detected. Please wait 5 seconds to prevent getting damage.");
yAxisViolations.put(name, yAxisViolations.get(name) + 1);
yAxisLastViolation.put(name, System.currentTimeMillis());
if (g.getBlock().getTypeId() == 0)
{
player.teleport(g);
}
return true;
}
else
{
if (yAxisViolations.get(name) > magic.Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) > magic.Y_MAXVIOTIME)
{
yAxisViolations.put(name, 0);
yAxisLastViolation.put(name, 0L);
}
}
if ((y1 - lastYcoord.get(name)) > magic.Y_MAXDIFF && (System.currentTimeMillis() - lastYtime.get(name)) < magic.Y_TIME)
{
Location g = player.getLocation();
g.setY(lastYcoord.get(name));
yAxisViolations.put(name, yAxisViolations.get(name) + 1);
yAxisLastViolation.put(name, System.currentTimeMillis());
if (g.getBlock().getTypeId() == 0)
{
player.teleport(g);
}
return true;
}
else
{
if ((y1 - lastYcoord.get(name)) > magic.Y_MAXDIFF + 1 || (System.currentTimeMillis() - lastYtime.get(name)) > magic.Y_TIME)
{
lastYtime.put(name, System.currentTimeMillis());
lastYcoord.put(name, y1);
}
}
}
}
//Fix Y axis spam
return false;
}
public boolean checkTimer(Player player)
{
/*
String name = player.getName();
int step = 1;
if(steps.containsKey(name))
{
step = steps.get(name)+1;
}
if(step == 1)
{
lastTime.put(name,System.currentTimeMillis());
}
increment(player, steps, step);
if(step >= STEP_CHECK)
{
long time = System.currentTimeMillis()-lastTime.get(name);
steps.put(name, 0);
if(time < TIME_MIN)
{
return true;
}
}*/
return false;
}
public boolean checkSight(Player player, Entity entity)
{
// Check to make sure the entity's head is not surrounded
Block head = entity.getWorld().getBlockAt((int) entity.getLocation().getX(), (int) (entity.getLocation().getY() + ((CraftEntity) entity).getHandle().getHeadHeight()), (int) entity.getLocation().getZ());
boolean solid = false;
//TODO: This sucks. See if it's possible to not have as many false-positives while still retaining most of the check.
for (int x = -2; x <= 2; x++)
{
for (int z = -2; z <= 2; z++)
{
for (int y = -1; y < 2; y++)
{
if (head.getRelative(x, y, z).getTypeId() != 0)
{
if (net.minecraft.server.Block.byId[head.getRelative(x, y, z).getTypeId()].material.isSolid())
{
solid = true;
break;
}
}
}
}
}
return solid ? true : player.hasLineOfSight(entity);
}
public boolean checkFlight(Player player, Distance distance)
{
if (distance.getYDifference() > 400)
{
//This was a teleport, so we don't care about it.
return false;
}
String name = player.getName();
double y1 = distance.fromY();
double y2 = distance.toY();
//Check if the player is climbing up water.
/* if (block.getRelative(BlockFace.NORTH).isLiquid() || block.getRelative(BlockFace.SOUTH).isLiquid() || block.getRelative(BlockFace.EAST).isLiquid() || block.getRelative(BlockFace.WEST).isLiquid())
{
if (y1 < y2)
{
//Even if they are using a hacked client and flying next to water to abuse this, they can't be go past the speed limit so they might as well swim
return distance.getYDifference() > magic.WATER_CLIMB_MAX;
}
} */
if (!isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) && Utilities.cantStandAtExp(player.getLocation()))
{
/* if (y1 == y2 || y1 < y2)
{
if (y1 == y2)
{
//Check if the player is on slabs or crouching on stairs
if (Utilities.isSlab(block.getRelative(BlockFace.NORTH)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH)) || Utilities.isSlab(block.getRelative(BlockFace.EAST)) || Utilities.isSlab(block.getRelative(BlockFace.WEST)) || Utilities.isSlab(block.getRelative(BlockFace.NORTH_EAST)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH_EAST)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH_WEST)) || Utilities.isSlab(block.getRelative(BlockFace.NORTH_WEST)))
{
return false;
}
else if (player.isSneaking() && (Utilities.isStair(block.getRelative(BlockFace.NORTH)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH)) || Utilities.isStair(block.getRelative(BlockFace.EAST)) || Utilities.isStair(block.getRelative(BlockFace.WEST)) || Utilities.isStair(block.getRelative(BlockFace.NORTH_EAST)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH_EAST)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH_WEST)) || Utilities.isStair(block.getRelative(BlockFace.NORTH_WEST))))
{
return false;
}
int violation = flightViolation.containsKey(name) ? flightViolation.get(name) + 1 : 1;
increment(player, flightViolation, violation);
return violation > magic.FLIGHT_LIMIT;
} */
if (!blocksOverFlight.containsKey(name))
{
blocksOverFlight.put(name, 0D);
}
blocksOverFlight.put(name, (blocksOverFlight.get(name) + distance.getXDifference() + distance.getYDifference() + distance.getZDifference()));
if (y1 > y2)
{
blocksOverFlight.put(name, (blocksOverFlight.get(name) - distance.getYDifference()));
}
if (blocksOverFlight.get(name) > magic.FLIGHT_BLOCK_LIMIT && (y1 <= y2))
{
return true;
}
}
else
{
blocksOverFlight.put(name, 0D);
}
return false;
}
public void logAscension(Player player, double y1, double y2)
{
String name = player.getName();
if (y1 < y2 && !isAscending.contains(name))
{
isAscending.add(name);
}
else
{
isAscending.remove(player.getName());
}
}
public boolean checkAscension(Player player, double y1, double y2)
{
int max = magic.ASCENSION_COUNT_MAX;
if (player.hasPotionEffect(PotionEffectType.JUMP))
{
max += 12;
}
Block block = player.getLocation().getBlock();
if (!isMovingExempt(player) && !Utilities.isInWater(player) && !justBroke(player) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && !player.isInsideVehicle())
{
String name = player.getName();
if (y1 < y2)
{
if (!block.getRelative(BlockFace.NORTH).isLiquid() && !block.getRelative(BlockFace.SOUTH).isLiquid() && !block.getRelative(BlockFace.EAST).isLiquid() && !block.getRelative(BlockFace.WEST).isLiquid())
{
increment(player, ascensionCount, max);
if (ascensionCount.get(name) >= max)
{
return true;
}
}
}
else
{
ascensionCount.put(name, 0);
}
}
return false;
}
public boolean checkSwing(Player player, Block block)
{
String name = player.getName();
if (!isInstantBreakExempt(player))
{
if (!player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !(player.getInventory().getItemInHand().getType() == Material.SHEARS && block.getType() == Material.LEAVES))
{
if (blockPunches.get(name) != null && player.getGameMode() != GameMode.CREATIVE)
{
int i = blockPunches.get(name);
if (i < magic.BLOCK_PUNCH_MIN)
{
return true;
}
else
{
blockPunches.put(name, 0); // it should reset after EACH block break.
}
}
}
}
return !justAnimated(player); //TODO: best way to implement other option?
}
public boolean checkFastBreak(Player player, Block block)
{
int violations = magic.FASTBREAK_MAXVIOLATIONS;
int timemax = magic.FASTBREAK_TIMEMAX;
if (player.getGameMode() == GameMode.CREATIVE)
{
violations = magic.FASTBREAK_MAXVIOLATIONS_CREATIVE;
timemax = magic.FASTBREAK_TIMEMAX_CREATIVE;
}
String name = player.getName();
if (!player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !Utilities.isInstantBreak(block.getType()) && !isInstantBreakExempt(player) && !(player.getInventory().getItemInHand().getType() == Material.SHEARS && block.getType() == Material.LEAVES))
{
if (!fastBreakViolation.containsKey(name))
{
fastBreakViolation.put(name, 0);
}
else
{
Long math = System.currentTimeMillis() - lastBlockBroken.get(name);
if (fastBreakViolation.get(name) > violations && math < magic.FASTBREAK_MAXVIOLATIONTIME)
{
lastBlockBroken.put(name, System.currentTimeMillis());
player.sendMessage(ChatColor.RED + "[AntiCheat] Fastbreaking detected. Please wait 10 seconds before breaking blocks.");
return true;
}
else if (fastBreakViolation.get(name) > 0 && math > magic.FASTBREAK_MAXVIOLATIONTIME)
{
fastBreakViolation.put(name, 0);
}
}
if (!fastBreaks.containsKey(name) || !lastBlockBroken.containsKey(name))
{
if (!lastBlockBroken.containsKey(name))
{
lastBlockBroken.put(name, System.currentTimeMillis());
}
fastBreaks.put(name, 0);
}
else
{
Long math = System.currentTimeMillis() - lastBlockBroken.get(name);
if (math < timemax && (math != 0L && player.getGameMode() != GameMode.CREATIVE))
{
fastBreaks.put(name, fastBreaks.get(name) + 1);
blockBreakHolder.put(name, false);
}
if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT && math < timemax)
{
fastBreaks.put(name, 1);
fastBreakViolation.put(name, fastBreakViolation.get(name) + 1);
return true;
}
else if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT)
{
if (!blockBreakHolder.containsKey(name) || !blockBreakHolder.get(name))
{
blockBreakHolder.put(name, true);
}
else
{
fastBreaks.put(name, fastBreaks.get(name) - 1);
blockBreakHolder.put(name, false);
}
}
}
lastBlockBroken.put(name, System.currentTimeMillis()); // always keep a log going.
}
return false;
}
public boolean checkFastPlace(Player player)
{
int violations = magic.FASTPLACE_MAXVIOLATIONS;
if (player.getGameMode() == GameMode.CREATIVE)
{
violations = magic.FASTPLACE_MAXVIOLATIONS_CREATIVE;
}
long time = System.currentTimeMillis();
String name = player.getName();
if (!lastBlockPlaceTime.containsKey(name) || !fastPlaceViolation.containsKey(name))
{
lastBlockPlaceTime.put(name, Long.parseLong("0"));
if (!fastPlaceViolation.containsKey(name))
{
fastPlaceViolation.put(name, 0);
}
}
else if (fastPlaceViolation.containsKey(name) && fastPlaceViolation.get(name) > violations)
{
Long math = System.currentTimeMillis() - lastBlockPlaced.get(name);
if (lastBlockPlaced.get(name) > 0 && math < magic.FASTPLACE_MAXVIOLATIONTIME)
{
lastBlockPlaced.put(name, time);
player.sendMessage(ChatColor.RED + "[AntiCheat] Fastplacing detected. Please wait 10 seconds before placing blocks.");
return true;
}
else if (lastBlockPlaced.get(name) > 0 && math > magic.FASTPLACE_MAXVIOLATIONTIME)
{
fastPlaceViolation.put(name, 0);
}
}
else if (lastBlockPlaced.containsKey(name))
{
long last = lastBlockPlaced.get(name);
long lastTime = lastBlockPlaceTime.get(name);
long thisTime = time - last;
boolean nocheck = thisTime < 1 || lastTime < 1;
if (!lastZeroHitPlace.containsKey(name))
{
lastZeroHitPlace.put(name, 0);
}
if (nocheck)
{
if (!lastZeroHitPlace.containsKey(name))
{
lastZeroHitPlace.put(name, 1);
}
else
{
lastZeroHitPlace.put(name, lastZeroHitPlace.get(name) + 1);
}
}
if (thisTime < magic.FASTPLACE_TIMEMAX && lastTime < magic.FASTPLACE_TIMEMAX && nocheck && lastZeroHitPlace.get(name) > magic.FASTPLACE_ZEROLIMIT)
{
lastBlockPlaceTime.put(name, (time - last));
lastBlockPlaced.put(name, time);
fastPlaceViolation.put(name, fastPlaceViolation.get(name) + 1);
return true;
}
lastBlockPlaceTime.put(name, (time - last));
}
lastBlockPlaced.put(name, time);
return false;
}
public void logBowWindUp(Player player)
{
bowWindUp.put(player.getName(), System.currentTimeMillis());
}
public void logEatingStart(Player player)
{
startEat.put(player.getName(), System.currentTimeMillis());
}
public boolean justStartedEating(Player player)
{
if (startEat.containsKey(player.getName())) // Otherwise it was modified by a plugin, don't worry about it.
{
long l = startEat.get(player.getName());
startEat.remove(player.getName());
return (System.currentTimeMillis() - l) < magic.EAT_TIME_MIN;
}
return false;
}
public void logHeal(Player player)
{
lastHeal.put(player.getName(), System.currentTimeMillis());
}
public boolean justHealed(Player player)
{
if (lastHeal.containsKey(player.getName())) // Otherwise it was modified by a plugin, don't worry about it.
{
long l = lastHeal.get(player.getName());
lastHeal.remove(player.getName());
return (System.currentTimeMillis() - l) < magic.HEAL_TIME_MIN;
}
return false;
}
public void logChat(Player player)
{
String name = player.getName();
if (chatLevel.get(name) == null)
{
logEvent(chatLevel, player, 1, magic.CHAT_MIN);
}
else
{
int amount = chatLevel.get(name) + 1;
logEvent(chatLevel, player, amount, magic.CHAT_MIN);
checkChatLevel(player, amount);
}
}
public boolean checkSpam(Player player, String msg)
{
String name = player.getName();
if (lastMessage.get(name) == null)
{
logEvent(lastMessage, player, msg, magic.CHAT_REPEAT_MIN);
}
else
{
if (oldMessage.get(name) != null && lastMessage.get(name).equals(msg) && oldMessage.get(name).equals(msg))
{
return true;
}
else
{
logEvent(oldMessage, player, lastMessage.get(name), magic.CHAT_REPEAT_MIN);
- logEvent(oldMessage, player, msg, magic.CHAT_REPEAT_MIN);
+ logEvent(lastMessage, player, msg, magic.CHAT_REPEAT_MIN);
return false;
}
}
return false;
}
public boolean checkInventoryClicks(Player player)
{
String name = player.getName();
long time = System.currentTimeMillis();
if (!inventoryTime.containsKey(name) || !inventoryChanges.containsKey(name))
{
inventoryTime.put(name, 0l);
if (!inventoryChanges.containsKey(name))
{
inventoryChanges.put(name, 0);
}
}
else if (inventoryChanges.containsKey(name) && inventoryChanges.get(name) > magic.INVENTORY_MAXVIOLATIONS)
{
long diff = System.currentTimeMillis() - lastInventoryTime.get(name);
if (inventoryTime.get(name) > 0 && diff < magic.INVENTORY_MAXVIOLATIONTIME)
{
inventoryTime.put(name, diff);
player.sendMessage(ChatColor.RED + "[AntiCheat] Inventory hack detected. Please wait 10 seconds before using inventories.");
return true;
}
else if (inventoryTime.get(name) > 0 && diff > magic.INVENTORY_MAXVIOLATIONTIME)
{
inventoryChanges.put(name, 0);
}
}
else if (inventoryTime.containsKey(name))
{
long last = lastInventoryTime.get(name);
long thisTime = time - last;
if (thisTime < magic.INVENTORY_TIMEMAX)
{
inventoryChanges.put(name, inventoryChanges.get(name) + 1);
if (inventoryChanges.get(name) > magic.INVENTORY_MAXVIOLATIONS)
{
inventoryTime.put(name, thisTime);
player.sendMessage(ChatColor.RED + "[AntiCheat] Inventory hack detected. Please wait 10 seconds before using inventories.");
return true;
}
}
inventoryTime.put(name, thisTime);
}
lastInventoryTime.put(name, time);
return false;
}
public void clearChatLevel(Player player)
{
chatLevel.remove(player.getName());
}
public void logInstantBreak(final Player player)
{
instantBreakExempt.put(player.getName(), System.currentTimeMillis());
}
public boolean isInstantBreakExempt(Player player)
{
return isDoing(player, instantBreakExempt, magic.INSTANT_BREAK_TIME);
}
public void logSprint(final Player player)
{
sprinted.put(player.getName(), System.currentTimeMillis());
}
public boolean justSprinted(Player player)
{
return isDoing(player, sprinted, magic.SPRINT_MIN);
}
public boolean isHoveringOverWaterAfterViolation(Player player)
{
if (waterSpeedViolation.containsKey(player.getName()))
{
if (waterSpeedViolation.get(player.getName()) >= magic.WATER_SPEED_VIOLATION_MAX && Utilities.isHoveringOverWater(player.getLocation()))
{
return true;
}
}
return false;
}
public void logBlockBreak(final Player player)
{
brokenBlock.put(player.getName(), System.currentTimeMillis());
resetAnimation(player);
}
public boolean justBroke(Player player)
{
return isDoing(player, brokenBlock, magic.BLOCK_BREAK_MIN);
}
public void logVelocity(final Player player)
{
velocitized.put(player.getName(), System.currentTimeMillis());
}
public boolean justVelocity(Player player)
{
return (velocitized.containsKey(player.getName()) ? (System.currentTimeMillis() - velocitized.get(player.getName())) < magic.VELOCITY_CHECKTIME : false);
}
public boolean extendVelocityTime(final Player player)
{
if (velocitytrack.containsKey(player.getName()))
{
velocitytrack.put(player.getName(), velocitytrack.get(player.getName()) + 1);
if (velocitytrack.get(player.getName()) > magic.VELOCITY_MAXTIMES)
{
velocitized.put(player.getName(), System.currentTimeMillis() + magic.VELOCITY_PREVENT);
micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable()
{
@Override
public void run()
{
velocitytrack.put(player.getName(), 0);
}
}, magic.VELOCITY_SCHETIME * 20L);
return true;
}
}
else
{
velocitytrack.put(player.getName(), 0);
}
return false;
}
public void logBlockPlace(final Player player)
{
placedBlock.put(player.getName(), System.currentTimeMillis());
}
public boolean justPlaced(Player player)
{
return isDoing(player, placedBlock, magic.BLOCK_PLACE_MIN);
}
public void logAnimation(final Player player)
{
animated.put(player.getName(), System.currentTimeMillis());
increment(player, blockPunches, magic.BLOCK_PUNCH_MIN);
}
public void resetAnimation(final Player player)
{
animated.remove(player.getName());
blockPunches.put(player.getName(), 0);
}
public boolean justAnimated(Player player)
{
String name = player.getName();
if (animated.containsKey(name))
{
long time = System.currentTimeMillis() - animated.get(name);
animated.remove(player.getName());
return time < magic.ANIMATION_MIN;
}
else
{
return false;
}
}
public void logDamage(final Player player, int type)
{
long time;
switch (type)
{
case 1:
time = magic.DAMAGE_TIME;
break;
case 2:
time = magic.KNOCKBACK_DAMAGE_TIME;
break;
case 3:
time = magic.EXPLOSION_DAMAGE_TIME;
break;
default:
time = magic.DAMAGE_TIME;
break;
}
movingExempt.put(player.getName(), System.currentTimeMillis() + time);
// Only map in which termination time is calculated beforehand.
}
public void logEnterExit(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.ENTERED_EXITED_TIME);
}
public void logToggleSneak(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.SNEAK_TIME);
}
public void logTeleport(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.TELEPORT_TIME);
/* Data for fly/speed should be reset */
nofallViolation.remove(player.getName());
blocksOverFlight.remove(player.getName());
yAxisViolations.remove(player.getName());
yAxisLastViolation.remove(player.getName());
lastYcoord.remove(player.getName());
lastYtime.remove(player.getName());
}
public void logExitFly(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.EXIT_FLY_TIME);
}
public void logJoin(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.JOIN_TIME);
}
public boolean isMovingExempt(Player player)
{
return isDoing(player, movingExempt, -1);
}
public boolean isAscending(Player player)
{
return isAscending.contains(player.getName());
}
public boolean isSpeedExempt(Player player)
{
return isMovingExempt(player) || justVelocity(player);
}
private <E> void logEvent(final Map<String, E> map, final Player player, final E obj, long time)
{
map.put(player.getName(), obj);
micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable()
{
@Override
public void run()
{
if (map.get(player.getName()) == obj)
{
map.remove(player.getName());
}
else
{
//Don't remove this, for some reason it's fixing chat bugs.
}
}
}, time);
}
private boolean isDoing(Player player, Map<String, Long> map, double max)
{
if (map.containsKey(player.getName()))
{
if (max != -1)
{
if (((System.currentTimeMillis() - map.get(player.getName())) / 1000) > max)
{
map.remove(player.getName());
return false;
}
else
{
return true;
}
}
else
{
// Termination time has already been calculated
if (map.get(player.getName()) < System.currentTimeMillis())
{
map.remove(player.getName());
return false;
}
else
{
return true;
}
}
}
else
{
return false;
}
}
private void checkChatLevel(Player player, int amount)
{
if (amount >= magic.CHAT_KICK_LEVEL)
{
String name = player.getName();
int kick;
if (chatKicks.get(name) == null || chatKicks.get(name) == 0)
{
kick = 1;
chatKicks.put(name, kick);
}
else
{
kick = chatKicks.get(name) + 1;
chatKicks.put(name, kick);
}
String event = kick <= magic.CHAT_BAN_LEVEL ? micromanage.getConfiguration().chatActionKick() : micromanage.getConfiguration().chatActionBan();
// Set string variables
event = event.replaceAll("&player", name).replaceAll("&world", player.getWorld().getName());
if (event.startsWith("COMMAND["))
{
String command = event.replaceAll("COMMAND\\[", "").replaceAll("]", "");
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
}
else if (event.equalsIgnoreCase("KICK"))
{
String msg = kick <= magic.CHAT_BAN_LEVEL ? ChatColor.RED + lang.getChatKickReason() + " (" + kick + "/" + magic.CHAT_BAN_LEVEL + ")" : ChatColor.RED + lang.getChatBanReason();
player.kickPlayer(msg);
msg = kick <= magic.CHAT_BAN_LEVEL ? ChatColor.RED + lang.getChatKickBroadcast() + " (" + kick + "/" + magic.CHAT_BAN_LEVEL + ")" : ChatColor.RED + lang.getChatBanBroadcast();
msg = msg.replaceAll("&player", name);
if (!msg.equals(""))
{
Bukkit.broadcastMessage(msg);
}
}
else if (event.equalsIgnoreCase("BAN"))
{
player.setBanned(true);
player.kickPlayer(ChatColor.RED + lang.getChatBanReason());
String msg = ChatColor.RED + lang.getChatBanBroadcast();
msg = msg.replaceAll("&player", name);
if (!msg.equals(""))
{
Bukkit.broadcastMessage(msg);
}
}
}
}
public int increment(Player player, Map<String, Integer> map, int num)
{
String name = player.getName();
if (map.get(name) == null)
{
map.put(name, 1);
return 1;
}
else
{
int amount = map.get(name) + 1;
if (amount < num + 1)
{
map.put(name, amount);
return amount;
}
else
{
map.put(name, num);
return num;
}
}
}
}
| true | true | public boolean checkFlight(Player player, Distance distance)
{
if (distance.getYDifference() > 400)
{
//This was a teleport, so we don't care about it.
return false;
}
String name = player.getName();
double y1 = distance.fromY();
double y2 = distance.toY();
//Check if the player is climbing up water.
/* if (block.getRelative(BlockFace.NORTH).isLiquid() || block.getRelative(BlockFace.SOUTH).isLiquid() || block.getRelative(BlockFace.EAST).isLiquid() || block.getRelative(BlockFace.WEST).isLiquid())
{
if (y1 < y2)
{
//Even if they are using a hacked client and flying next to water to abuse this, they can't be go past the speed limit so they might as well swim
return distance.getYDifference() > magic.WATER_CLIMB_MAX;
}
} */
if (!isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) && Utilities.cantStandAtExp(player.getLocation()))
{
/* if (y1 == y2 || y1 < y2)
{
if (y1 == y2)
{
//Check if the player is on slabs or crouching on stairs
if (Utilities.isSlab(block.getRelative(BlockFace.NORTH)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH)) || Utilities.isSlab(block.getRelative(BlockFace.EAST)) || Utilities.isSlab(block.getRelative(BlockFace.WEST)) || Utilities.isSlab(block.getRelative(BlockFace.NORTH_EAST)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH_EAST)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH_WEST)) || Utilities.isSlab(block.getRelative(BlockFace.NORTH_WEST)))
{
return false;
}
else if (player.isSneaking() && (Utilities.isStair(block.getRelative(BlockFace.NORTH)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH)) || Utilities.isStair(block.getRelative(BlockFace.EAST)) || Utilities.isStair(block.getRelative(BlockFace.WEST)) || Utilities.isStair(block.getRelative(BlockFace.NORTH_EAST)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH_EAST)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH_WEST)) || Utilities.isStair(block.getRelative(BlockFace.NORTH_WEST))))
{
return false;
}
int violation = flightViolation.containsKey(name) ? flightViolation.get(name) + 1 : 1;
increment(player, flightViolation, violation);
return violation > magic.FLIGHT_LIMIT;
} */
if (!blocksOverFlight.containsKey(name))
{
blocksOverFlight.put(name, 0D);
}
blocksOverFlight.put(name, (blocksOverFlight.get(name) + distance.getXDifference() + distance.getYDifference() + distance.getZDifference()));
if (y1 > y2)
{
blocksOverFlight.put(name, (blocksOverFlight.get(name) - distance.getYDifference()));
}
if (blocksOverFlight.get(name) > magic.FLIGHT_BLOCK_LIMIT && (y1 <= y2))
{
return true;
}
}
else
{
blocksOverFlight.put(name, 0D);
}
return false;
}
public void logAscension(Player player, double y1, double y2)
{
String name = player.getName();
if (y1 < y2 && !isAscending.contains(name))
{
isAscending.add(name);
}
else
{
isAscending.remove(player.getName());
}
}
public boolean checkAscension(Player player, double y1, double y2)
{
int max = magic.ASCENSION_COUNT_MAX;
if (player.hasPotionEffect(PotionEffectType.JUMP))
{
max += 12;
}
Block block = player.getLocation().getBlock();
if (!isMovingExempt(player) && !Utilities.isInWater(player) && !justBroke(player) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && !player.isInsideVehicle())
{
String name = player.getName();
if (y1 < y2)
{
if (!block.getRelative(BlockFace.NORTH).isLiquid() && !block.getRelative(BlockFace.SOUTH).isLiquid() && !block.getRelative(BlockFace.EAST).isLiquid() && !block.getRelative(BlockFace.WEST).isLiquid())
{
increment(player, ascensionCount, max);
if (ascensionCount.get(name) >= max)
{
return true;
}
}
}
else
{
ascensionCount.put(name, 0);
}
}
return false;
}
public boolean checkSwing(Player player, Block block)
{
String name = player.getName();
if (!isInstantBreakExempt(player))
{
if (!player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !(player.getInventory().getItemInHand().getType() == Material.SHEARS && block.getType() == Material.LEAVES))
{
if (blockPunches.get(name) != null && player.getGameMode() != GameMode.CREATIVE)
{
int i = blockPunches.get(name);
if (i < magic.BLOCK_PUNCH_MIN)
{
return true;
}
else
{
blockPunches.put(name, 0); // it should reset after EACH block break.
}
}
}
}
return !justAnimated(player); //TODO: best way to implement other option?
}
public boolean checkFastBreak(Player player, Block block)
{
int violations = magic.FASTBREAK_MAXVIOLATIONS;
int timemax = magic.FASTBREAK_TIMEMAX;
if (player.getGameMode() == GameMode.CREATIVE)
{
violations = magic.FASTBREAK_MAXVIOLATIONS_CREATIVE;
timemax = magic.FASTBREAK_TIMEMAX_CREATIVE;
}
String name = player.getName();
if (!player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !Utilities.isInstantBreak(block.getType()) && !isInstantBreakExempt(player) && !(player.getInventory().getItemInHand().getType() == Material.SHEARS && block.getType() == Material.LEAVES))
{
if (!fastBreakViolation.containsKey(name))
{
fastBreakViolation.put(name, 0);
}
else
{
Long math = System.currentTimeMillis() - lastBlockBroken.get(name);
if (fastBreakViolation.get(name) > violations && math < magic.FASTBREAK_MAXVIOLATIONTIME)
{
lastBlockBroken.put(name, System.currentTimeMillis());
player.sendMessage(ChatColor.RED + "[AntiCheat] Fastbreaking detected. Please wait 10 seconds before breaking blocks.");
return true;
}
else if (fastBreakViolation.get(name) > 0 && math > magic.FASTBREAK_MAXVIOLATIONTIME)
{
fastBreakViolation.put(name, 0);
}
}
if (!fastBreaks.containsKey(name) || !lastBlockBroken.containsKey(name))
{
if (!lastBlockBroken.containsKey(name))
{
lastBlockBroken.put(name, System.currentTimeMillis());
}
fastBreaks.put(name, 0);
}
else
{
Long math = System.currentTimeMillis() - lastBlockBroken.get(name);
if (math < timemax && (math != 0L && player.getGameMode() != GameMode.CREATIVE))
{
fastBreaks.put(name, fastBreaks.get(name) + 1);
blockBreakHolder.put(name, false);
}
if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT && math < timemax)
{
fastBreaks.put(name, 1);
fastBreakViolation.put(name, fastBreakViolation.get(name) + 1);
return true;
}
else if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT)
{
if (!blockBreakHolder.containsKey(name) || !blockBreakHolder.get(name))
{
blockBreakHolder.put(name, true);
}
else
{
fastBreaks.put(name, fastBreaks.get(name) - 1);
blockBreakHolder.put(name, false);
}
}
}
lastBlockBroken.put(name, System.currentTimeMillis()); // always keep a log going.
}
return false;
}
public boolean checkFastPlace(Player player)
{
int violations = magic.FASTPLACE_MAXVIOLATIONS;
if (player.getGameMode() == GameMode.CREATIVE)
{
violations = magic.FASTPLACE_MAXVIOLATIONS_CREATIVE;
}
long time = System.currentTimeMillis();
String name = player.getName();
if (!lastBlockPlaceTime.containsKey(name) || !fastPlaceViolation.containsKey(name))
{
lastBlockPlaceTime.put(name, Long.parseLong("0"));
if (!fastPlaceViolation.containsKey(name))
{
fastPlaceViolation.put(name, 0);
}
}
else if (fastPlaceViolation.containsKey(name) && fastPlaceViolation.get(name) > violations)
{
Long math = System.currentTimeMillis() - lastBlockPlaced.get(name);
if (lastBlockPlaced.get(name) > 0 && math < magic.FASTPLACE_MAXVIOLATIONTIME)
{
lastBlockPlaced.put(name, time);
player.sendMessage(ChatColor.RED + "[AntiCheat] Fastplacing detected. Please wait 10 seconds before placing blocks.");
return true;
}
else if (lastBlockPlaced.get(name) > 0 && math > magic.FASTPLACE_MAXVIOLATIONTIME)
{
fastPlaceViolation.put(name, 0);
}
}
else if (lastBlockPlaced.containsKey(name))
{
long last = lastBlockPlaced.get(name);
long lastTime = lastBlockPlaceTime.get(name);
long thisTime = time - last;
boolean nocheck = thisTime < 1 || lastTime < 1;
if (!lastZeroHitPlace.containsKey(name))
{
lastZeroHitPlace.put(name, 0);
}
if (nocheck)
{
if (!lastZeroHitPlace.containsKey(name))
{
lastZeroHitPlace.put(name, 1);
}
else
{
lastZeroHitPlace.put(name, lastZeroHitPlace.get(name) + 1);
}
}
if (thisTime < magic.FASTPLACE_TIMEMAX && lastTime < magic.FASTPLACE_TIMEMAX && nocheck && lastZeroHitPlace.get(name) > magic.FASTPLACE_ZEROLIMIT)
{
lastBlockPlaceTime.put(name, (time - last));
lastBlockPlaced.put(name, time);
fastPlaceViolation.put(name, fastPlaceViolation.get(name) + 1);
return true;
}
lastBlockPlaceTime.put(name, (time - last));
}
lastBlockPlaced.put(name, time);
return false;
}
public void logBowWindUp(Player player)
{
bowWindUp.put(player.getName(), System.currentTimeMillis());
}
public void logEatingStart(Player player)
{
startEat.put(player.getName(), System.currentTimeMillis());
}
public boolean justStartedEating(Player player)
{
if (startEat.containsKey(player.getName())) // Otherwise it was modified by a plugin, don't worry about it.
{
long l = startEat.get(player.getName());
startEat.remove(player.getName());
return (System.currentTimeMillis() - l) < magic.EAT_TIME_MIN;
}
return false;
}
public void logHeal(Player player)
{
lastHeal.put(player.getName(), System.currentTimeMillis());
}
public boolean justHealed(Player player)
{
if (lastHeal.containsKey(player.getName())) // Otherwise it was modified by a plugin, don't worry about it.
{
long l = lastHeal.get(player.getName());
lastHeal.remove(player.getName());
return (System.currentTimeMillis() - l) < magic.HEAL_TIME_MIN;
}
return false;
}
public void logChat(Player player)
{
String name = player.getName();
if (chatLevel.get(name) == null)
{
logEvent(chatLevel, player, 1, magic.CHAT_MIN);
}
else
{
int amount = chatLevel.get(name) + 1;
logEvent(chatLevel, player, amount, magic.CHAT_MIN);
checkChatLevel(player, amount);
}
}
public boolean checkSpam(Player player, String msg)
{
String name = player.getName();
if (lastMessage.get(name) == null)
{
logEvent(lastMessage, player, msg, magic.CHAT_REPEAT_MIN);
}
else
{
if (oldMessage.get(name) != null && lastMessage.get(name).equals(msg) && oldMessage.get(name).equals(msg))
{
return true;
}
else
{
logEvent(oldMessage, player, lastMessage.get(name), magic.CHAT_REPEAT_MIN);
logEvent(oldMessage, player, msg, magic.CHAT_REPEAT_MIN);
return false;
}
}
return false;
}
public boolean checkInventoryClicks(Player player)
{
String name = player.getName();
long time = System.currentTimeMillis();
if (!inventoryTime.containsKey(name) || !inventoryChanges.containsKey(name))
{
inventoryTime.put(name, 0l);
if (!inventoryChanges.containsKey(name))
{
inventoryChanges.put(name, 0);
}
}
else if (inventoryChanges.containsKey(name) && inventoryChanges.get(name) > magic.INVENTORY_MAXVIOLATIONS)
{
long diff = System.currentTimeMillis() - lastInventoryTime.get(name);
if (inventoryTime.get(name) > 0 && diff < magic.INVENTORY_MAXVIOLATIONTIME)
{
inventoryTime.put(name, diff);
player.sendMessage(ChatColor.RED + "[AntiCheat] Inventory hack detected. Please wait 10 seconds before using inventories.");
return true;
}
else if (inventoryTime.get(name) > 0 && diff > magic.INVENTORY_MAXVIOLATIONTIME)
{
inventoryChanges.put(name, 0);
}
}
else if (inventoryTime.containsKey(name))
{
long last = lastInventoryTime.get(name);
long thisTime = time - last;
if (thisTime < magic.INVENTORY_TIMEMAX)
{
inventoryChanges.put(name, inventoryChanges.get(name) + 1);
if (inventoryChanges.get(name) > magic.INVENTORY_MAXVIOLATIONS)
{
inventoryTime.put(name, thisTime);
player.sendMessage(ChatColor.RED + "[AntiCheat] Inventory hack detected. Please wait 10 seconds before using inventories.");
return true;
}
}
inventoryTime.put(name, thisTime);
}
lastInventoryTime.put(name, time);
return false;
}
public void clearChatLevel(Player player)
{
chatLevel.remove(player.getName());
}
public void logInstantBreak(final Player player)
{
instantBreakExempt.put(player.getName(), System.currentTimeMillis());
}
public boolean isInstantBreakExempt(Player player)
{
return isDoing(player, instantBreakExempt, magic.INSTANT_BREAK_TIME);
}
public void logSprint(final Player player)
{
sprinted.put(player.getName(), System.currentTimeMillis());
}
public boolean justSprinted(Player player)
{
return isDoing(player, sprinted, magic.SPRINT_MIN);
}
public boolean isHoveringOverWaterAfterViolation(Player player)
{
if (waterSpeedViolation.containsKey(player.getName()))
{
if (waterSpeedViolation.get(player.getName()) >= magic.WATER_SPEED_VIOLATION_MAX && Utilities.isHoveringOverWater(player.getLocation()))
{
return true;
}
}
return false;
}
public void logBlockBreak(final Player player)
{
brokenBlock.put(player.getName(), System.currentTimeMillis());
resetAnimation(player);
}
public boolean justBroke(Player player)
{
return isDoing(player, brokenBlock, magic.BLOCK_BREAK_MIN);
}
public void logVelocity(final Player player)
{
velocitized.put(player.getName(), System.currentTimeMillis());
}
public boolean justVelocity(Player player)
{
return (velocitized.containsKey(player.getName()) ? (System.currentTimeMillis() - velocitized.get(player.getName())) < magic.VELOCITY_CHECKTIME : false);
}
public boolean extendVelocityTime(final Player player)
{
if (velocitytrack.containsKey(player.getName()))
{
velocitytrack.put(player.getName(), velocitytrack.get(player.getName()) + 1);
if (velocitytrack.get(player.getName()) > magic.VELOCITY_MAXTIMES)
{
velocitized.put(player.getName(), System.currentTimeMillis() + magic.VELOCITY_PREVENT);
micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable()
{
@Override
public void run()
{
velocitytrack.put(player.getName(), 0);
}
}, magic.VELOCITY_SCHETIME * 20L);
return true;
}
}
else
{
velocitytrack.put(player.getName(), 0);
}
return false;
}
public void logBlockPlace(final Player player)
{
placedBlock.put(player.getName(), System.currentTimeMillis());
}
public boolean justPlaced(Player player)
{
return isDoing(player, placedBlock, magic.BLOCK_PLACE_MIN);
}
public void logAnimation(final Player player)
{
animated.put(player.getName(), System.currentTimeMillis());
increment(player, blockPunches, magic.BLOCK_PUNCH_MIN);
}
public void resetAnimation(final Player player)
{
animated.remove(player.getName());
blockPunches.put(player.getName(), 0);
}
public boolean justAnimated(Player player)
{
String name = player.getName();
if (animated.containsKey(name))
{
long time = System.currentTimeMillis() - animated.get(name);
animated.remove(player.getName());
return time < magic.ANIMATION_MIN;
}
else
{
return false;
}
}
public void logDamage(final Player player, int type)
{
long time;
switch (type)
{
case 1:
time = magic.DAMAGE_TIME;
break;
case 2:
time = magic.KNOCKBACK_DAMAGE_TIME;
break;
case 3:
time = magic.EXPLOSION_DAMAGE_TIME;
break;
default:
time = magic.DAMAGE_TIME;
break;
}
movingExempt.put(player.getName(), System.currentTimeMillis() + time);
// Only map in which termination time is calculated beforehand.
}
public void logEnterExit(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.ENTERED_EXITED_TIME);
}
public void logToggleSneak(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.SNEAK_TIME);
}
public void logTeleport(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.TELEPORT_TIME);
/* Data for fly/speed should be reset */
nofallViolation.remove(player.getName());
blocksOverFlight.remove(player.getName());
yAxisViolations.remove(player.getName());
yAxisLastViolation.remove(player.getName());
lastYcoord.remove(player.getName());
lastYtime.remove(player.getName());
}
public void logExitFly(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.EXIT_FLY_TIME);
}
public void logJoin(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.JOIN_TIME);
}
public boolean isMovingExempt(Player player)
{
return isDoing(player, movingExempt, -1);
}
public boolean isAscending(Player player)
{
return isAscending.contains(player.getName());
}
public boolean isSpeedExempt(Player player)
{
return isMovingExempt(player) || justVelocity(player);
}
private <E> void logEvent(final Map<String, E> map, final Player player, final E obj, long time)
{
map.put(player.getName(), obj);
micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable()
{
@Override
public void run()
{
if (map.get(player.getName()) == obj)
{
map.remove(player.getName());
}
else
{
//Don't remove this, for some reason it's fixing chat bugs.
}
}
}, time);
}
private boolean isDoing(Player player, Map<String, Long> map, double max)
{
if (map.containsKey(player.getName()))
{
if (max != -1)
{
if (((System.currentTimeMillis() - map.get(player.getName())) / 1000) > max)
{
map.remove(player.getName());
return false;
}
else
{
return true;
}
}
else
{
// Termination time has already been calculated
if (map.get(player.getName()) < System.currentTimeMillis())
{
map.remove(player.getName());
return false;
}
else
{
return true;
}
}
}
else
{
return false;
}
}
private void checkChatLevel(Player player, int amount)
{
if (amount >= magic.CHAT_KICK_LEVEL)
{
String name = player.getName();
int kick;
if (chatKicks.get(name) == null || chatKicks.get(name) == 0)
{
kick = 1;
chatKicks.put(name, kick);
}
else
{
kick = chatKicks.get(name) + 1;
chatKicks.put(name, kick);
}
String event = kick <= magic.CHAT_BAN_LEVEL ? micromanage.getConfiguration().chatActionKick() : micromanage.getConfiguration().chatActionBan();
// Set string variables
event = event.replaceAll("&player", name).replaceAll("&world", player.getWorld().getName());
if (event.startsWith("COMMAND["))
{
String command = event.replaceAll("COMMAND\\[", "").replaceAll("]", "");
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
}
else if (event.equalsIgnoreCase("KICK"))
{
String msg = kick <= magic.CHAT_BAN_LEVEL ? ChatColor.RED + lang.getChatKickReason() + " (" + kick + "/" + magic.CHAT_BAN_LEVEL + ")" : ChatColor.RED + lang.getChatBanReason();
player.kickPlayer(msg);
msg = kick <= magic.CHAT_BAN_LEVEL ? ChatColor.RED + lang.getChatKickBroadcast() + " (" + kick + "/" + magic.CHAT_BAN_LEVEL + ")" : ChatColor.RED + lang.getChatBanBroadcast();
msg = msg.replaceAll("&player", name);
if (!msg.equals(""))
{
Bukkit.broadcastMessage(msg);
}
}
else if (event.equalsIgnoreCase("BAN"))
{
player.setBanned(true);
player.kickPlayer(ChatColor.RED + lang.getChatBanReason());
String msg = ChatColor.RED + lang.getChatBanBroadcast();
msg = msg.replaceAll("&player", name);
if (!msg.equals(""))
{
Bukkit.broadcastMessage(msg);
}
}
}
}
public int increment(Player player, Map<String, Integer> map, int num)
{
String name = player.getName();
if (map.get(name) == null)
{
map.put(name, 1);
return 1;
}
else
{
int amount = map.get(name) + 1;
if (amount < num + 1)
{
map.put(name, amount);
return amount;
}
else
{
map.put(name, num);
return num;
}
}
}
}
| public boolean checkFlight(Player player, Distance distance)
{
if (distance.getYDifference() > 400)
{
//This was a teleport, so we don't care about it.
return false;
}
String name = player.getName();
double y1 = distance.fromY();
double y2 = distance.toY();
//Check if the player is climbing up water.
/* if (block.getRelative(BlockFace.NORTH).isLiquid() || block.getRelative(BlockFace.SOUTH).isLiquid() || block.getRelative(BlockFace.EAST).isLiquid() || block.getRelative(BlockFace.WEST).isLiquid())
{
if (y1 < y2)
{
//Even if they are using a hacked client and flying next to water to abuse this, they can't be go past the speed limit so they might as well swim
return distance.getYDifference() > magic.WATER_CLIMB_MAX;
}
} */
if (!isMovingExempt(player) && !Utilities.isHoveringOverWater(player.getLocation(), 1) && Utilities.cantStandAtExp(player.getLocation()))
{
/* if (y1 == y2 || y1 < y2)
{
if (y1 == y2)
{
//Check if the player is on slabs or crouching on stairs
if (Utilities.isSlab(block.getRelative(BlockFace.NORTH)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH)) || Utilities.isSlab(block.getRelative(BlockFace.EAST)) || Utilities.isSlab(block.getRelative(BlockFace.WEST)) || Utilities.isSlab(block.getRelative(BlockFace.NORTH_EAST)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH_EAST)) || Utilities.isSlab(block.getRelative(BlockFace.SOUTH_WEST)) || Utilities.isSlab(block.getRelative(BlockFace.NORTH_WEST)))
{
return false;
}
else if (player.isSneaking() && (Utilities.isStair(block.getRelative(BlockFace.NORTH)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH)) || Utilities.isStair(block.getRelative(BlockFace.EAST)) || Utilities.isStair(block.getRelative(BlockFace.WEST)) || Utilities.isStair(block.getRelative(BlockFace.NORTH_EAST)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH_EAST)) || Utilities.isStair(block.getRelative(BlockFace.SOUTH_WEST)) || Utilities.isStair(block.getRelative(BlockFace.NORTH_WEST))))
{
return false;
}
int violation = flightViolation.containsKey(name) ? flightViolation.get(name) + 1 : 1;
increment(player, flightViolation, violation);
return violation > magic.FLIGHT_LIMIT;
} */
if (!blocksOverFlight.containsKey(name))
{
blocksOverFlight.put(name, 0D);
}
blocksOverFlight.put(name, (blocksOverFlight.get(name) + distance.getXDifference() + distance.getYDifference() + distance.getZDifference()));
if (y1 > y2)
{
blocksOverFlight.put(name, (blocksOverFlight.get(name) - distance.getYDifference()));
}
if (blocksOverFlight.get(name) > magic.FLIGHT_BLOCK_LIMIT && (y1 <= y2))
{
return true;
}
}
else
{
blocksOverFlight.put(name, 0D);
}
return false;
}
public void logAscension(Player player, double y1, double y2)
{
String name = player.getName();
if (y1 < y2 && !isAscending.contains(name))
{
isAscending.add(name);
}
else
{
isAscending.remove(player.getName());
}
}
public boolean checkAscension(Player player, double y1, double y2)
{
int max = magic.ASCENSION_COUNT_MAX;
if (player.hasPotionEffect(PotionEffectType.JUMP))
{
max += 12;
}
Block block = player.getLocation().getBlock();
if (!isMovingExempt(player) && !Utilities.isInWater(player) && !justBroke(player) && !Utilities.isClimbableBlock(player.getLocation().getBlock()) && !player.isInsideVehicle())
{
String name = player.getName();
if (y1 < y2)
{
if (!block.getRelative(BlockFace.NORTH).isLiquid() && !block.getRelative(BlockFace.SOUTH).isLiquid() && !block.getRelative(BlockFace.EAST).isLiquid() && !block.getRelative(BlockFace.WEST).isLiquid())
{
increment(player, ascensionCount, max);
if (ascensionCount.get(name) >= max)
{
return true;
}
}
}
else
{
ascensionCount.put(name, 0);
}
}
return false;
}
public boolean checkSwing(Player player, Block block)
{
String name = player.getName();
if (!isInstantBreakExempt(player))
{
if (!player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !(player.getInventory().getItemInHand().getType() == Material.SHEARS && block.getType() == Material.LEAVES))
{
if (blockPunches.get(name) != null && player.getGameMode() != GameMode.CREATIVE)
{
int i = blockPunches.get(name);
if (i < magic.BLOCK_PUNCH_MIN)
{
return true;
}
else
{
blockPunches.put(name, 0); // it should reset after EACH block break.
}
}
}
}
return !justAnimated(player); //TODO: best way to implement other option?
}
public boolean checkFastBreak(Player player, Block block)
{
int violations = magic.FASTBREAK_MAXVIOLATIONS;
int timemax = magic.FASTBREAK_TIMEMAX;
if (player.getGameMode() == GameMode.CREATIVE)
{
violations = magic.FASTBREAK_MAXVIOLATIONS_CREATIVE;
timemax = magic.FASTBREAK_TIMEMAX_CREATIVE;
}
String name = player.getName();
if (!player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !Utilities.isInstantBreak(block.getType()) && !isInstantBreakExempt(player) && !(player.getInventory().getItemInHand().getType() == Material.SHEARS && block.getType() == Material.LEAVES))
{
if (!fastBreakViolation.containsKey(name))
{
fastBreakViolation.put(name, 0);
}
else
{
Long math = System.currentTimeMillis() - lastBlockBroken.get(name);
if (fastBreakViolation.get(name) > violations && math < magic.FASTBREAK_MAXVIOLATIONTIME)
{
lastBlockBroken.put(name, System.currentTimeMillis());
player.sendMessage(ChatColor.RED + "[AntiCheat] Fastbreaking detected. Please wait 10 seconds before breaking blocks.");
return true;
}
else if (fastBreakViolation.get(name) > 0 && math > magic.FASTBREAK_MAXVIOLATIONTIME)
{
fastBreakViolation.put(name, 0);
}
}
if (!fastBreaks.containsKey(name) || !lastBlockBroken.containsKey(name))
{
if (!lastBlockBroken.containsKey(name))
{
lastBlockBroken.put(name, System.currentTimeMillis());
}
fastBreaks.put(name, 0);
}
else
{
Long math = System.currentTimeMillis() - lastBlockBroken.get(name);
if (math < timemax && (math != 0L && player.getGameMode() != GameMode.CREATIVE))
{
fastBreaks.put(name, fastBreaks.get(name) + 1);
blockBreakHolder.put(name, false);
}
if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT && math < timemax)
{
fastBreaks.put(name, 1);
fastBreakViolation.put(name, fastBreakViolation.get(name) + 1);
return true;
}
else if (fastBreaks.get(name) >= magic.FASTBREAK_LIMIT)
{
if (!blockBreakHolder.containsKey(name) || !blockBreakHolder.get(name))
{
blockBreakHolder.put(name, true);
}
else
{
fastBreaks.put(name, fastBreaks.get(name) - 1);
blockBreakHolder.put(name, false);
}
}
}
lastBlockBroken.put(name, System.currentTimeMillis()); // always keep a log going.
}
return false;
}
public boolean checkFastPlace(Player player)
{
int violations = magic.FASTPLACE_MAXVIOLATIONS;
if (player.getGameMode() == GameMode.CREATIVE)
{
violations = magic.FASTPLACE_MAXVIOLATIONS_CREATIVE;
}
long time = System.currentTimeMillis();
String name = player.getName();
if (!lastBlockPlaceTime.containsKey(name) || !fastPlaceViolation.containsKey(name))
{
lastBlockPlaceTime.put(name, Long.parseLong("0"));
if (!fastPlaceViolation.containsKey(name))
{
fastPlaceViolation.put(name, 0);
}
}
else if (fastPlaceViolation.containsKey(name) && fastPlaceViolation.get(name) > violations)
{
Long math = System.currentTimeMillis() - lastBlockPlaced.get(name);
if (lastBlockPlaced.get(name) > 0 && math < magic.FASTPLACE_MAXVIOLATIONTIME)
{
lastBlockPlaced.put(name, time);
player.sendMessage(ChatColor.RED + "[AntiCheat] Fastplacing detected. Please wait 10 seconds before placing blocks.");
return true;
}
else if (lastBlockPlaced.get(name) > 0 && math > magic.FASTPLACE_MAXVIOLATIONTIME)
{
fastPlaceViolation.put(name, 0);
}
}
else if (lastBlockPlaced.containsKey(name))
{
long last = lastBlockPlaced.get(name);
long lastTime = lastBlockPlaceTime.get(name);
long thisTime = time - last;
boolean nocheck = thisTime < 1 || lastTime < 1;
if (!lastZeroHitPlace.containsKey(name))
{
lastZeroHitPlace.put(name, 0);
}
if (nocheck)
{
if (!lastZeroHitPlace.containsKey(name))
{
lastZeroHitPlace.put(name, 1);
}
else
{
lastZeroHitPlace.put(name, lastZeroHitPlace.get(name) + 1);
}
}
if (thisTime < magic.FASTPLACE_TIMEMAX && lastTime < magic.FASTPLACE_TIMEMAX && nocheck && lastZeroHitPlace.get(name) > magic.FASTPLACE_ZEROLIMIT)
{
lastBlockPlaceTime.put(name, (time - last));
lastBlockPlaced.put(name, time);
fastPlaceViolation.put(name, fastPlaceViolation.get(name) + 1);
return true;
}
lastBlockPlaceTime.put(name, (time - last));
}
lastBlockPlaced.put(name, time);
return false;
}
public void logBowWindUp(Player player)
{
bowWindUp.put(player.getName(), System.currentTimeMillis());
}
public void logEatingStart(Player player)
{
startEat.put(player.getName(), System.currentTimeMillis());
}
public boolean justStartedEating(Player player)
{
if (startEat.containsKey(player.getName())) // Otherwise it was modified by a plugin, don't worry about it.
{
long l = startEat.get(player.getName());
startEat.remove(player.getName());
return (System.currentTimeMillis() - l) < magic.EAT_TIME_MIN;
}
return false;
}
public void logHeal(Player player)
{
lastHeal.put(player.getName(), System.currentTimeMillis());
}
public boolean justHealed(Player player)
{
if (lastHeal.containsKey(player.getName())) // Otherwise it was modified by a plugin, don't worry about it.
{
long l = lastHeal.get(player.getName());
lastHeal.remove(player.getName());
return (System.currentTimeMillis() - l) < magic.HEAL_TIME_MIN;
}
return false;
}
public void logChat(Player player)
{
String name = player.getName();
if (chatLevel.get(name) == null)
{
logEvent(chatLevel, player, 1, magic.CHAT_MIN);
}
else
{
int amount = chatLevel.get(name) + 1;
logEvent(chatLevel, player, amount, magic.CHAT_MIN);
checkChatLevel(player, amount);
}
}
public boolean checkSpam(Player player, String msg)
{
String name = player.getName();
if (lastMessage.get(name) == null)
{
logEvent(lastMessage, player, msg, magic.CHAT_REPEAT_MIN);
}
else
{
if (oldMessage.get(name) != null && lastMessage.get(name).equals(msg) && oldMessage.get(name).equals(msg))
{
return true;
}
else
{
logEvent(oldMessage, player, lastMessage.get(name), magic.CHAT_REPEAT_MIN);
logEvent(lastMessage, player, msg, magic.CHAT_REPEAT_MIN);
return false;
}
}
return false;
}
public boolean checkInventoryClicks(Player player)
{
String name = player.getName();
long time = System.currentTimeMillis();
if (!inventoryTime.containsKey(name) || !inventoryChanges.containsKey(name))
{
inventoryTime.put(name, 0l);
if (!inventoryChanges.containsKey(name))
{
inventoryChanges.put(name, 0);
}
}
else if (inventoryChanges.containsKey(name) && inventoryChanges.get(name) > magic.INVENTORY_MAXVIOLATIONS)
{
long diff = System.currentTimeMillis() - lastInventoryTime.get(name);
if (inventoryTime.get(name) > 0 && diff < magic.INVENTORY_MAXVIOLATIONTIME)
{
inventoryTime.put(name, diff);
player.sendMessage(ChatColor.RED + "[AntiCheat] Inventory hack detected. Please wait 10 seconds before using inventories.");
return true;
}
else if (inventoryTime.get(name) > 0 && diff > magic.INVENTORY_MAXVIOLATIONTIME)
{
inventoryChanges.put(name, 0);
}
}
else if (inventoryTime.containsKey(name))
{
long last = lastInventoryTime.get(name);
long thisTime = time - last;
if (thisTime < magic.INVENTORY_TIMEMAX)
{
inventoryChanges.put(name, inventoryChanges.get(name) + 1);
if (inventoryChanges.get(name) > magic.INVENTORY_MAXVIOLATIONS)
{
inventoryTime.put(name, thisTime);
player.sendMessage(ChatColor.RED + "[AntiCheat] Inventory hack detected. Please wait 10 seconds before using inventories.");
return true;
}
}
inventoryTime.put(name, thisTime);
}
lastInventoryTime.put(name, time);
return false;
}
public void clearChatLevel(Player player)
{
chatLevel.remove(player.getName());
}
public void logInstantBreak(final Player player)
{
instantBreakExempt.put(player.getName(), System.currentTimeMillis());
}
public boolean isInstantBreakExempt(Player player)
{
return isDoing(player, instantBreakExempt, magic.INSTANT_BREAK_TIME);
}
public void logSprint(final Player player)
{
sprinted.put(player.getName(), System.currentTimeMillis());
}
public boolean justSprinted(Player player)
{
return isDoing(player, sprinted, magic.SPRINT_MIN);
}
public boolean isHoveringOverWaterAfterViolation(Player player)
{
if (waterSpeedViolation.containsKey(player.getName()))
{
if (waterSpeedViolation.get(player.getName()) >= magic.WATER_SPEED_VIOLATION_MAX && Utilities.isHoveringOverWater(player.getLocation()))
{
return true;
}
}
return false;
}
public void logBlockBreak(final Player player)
{
brokenBlock.put(player.getName(), System.currentTimeMillis());
resetAnimation(player);
}
public boolean justBroke(Player player)
{
return isDoing(player, brokenBlock, magic.BLOCK_BREAK_MIN);
}
public void logVelocity(final Player player)
{
velocitized.put(player.getName(), System.currentTimeMillis());
}
public boolean justVelocity(Player player)
{
return (velocitized.containsKey(player.getName()) ? (System.currentTimeMillis() - velocitized.get(player.getName())) < magic.VELOCITY_CHECKTIME : false);
}
public boolean extendVelocityTime(final Player player)
{
if (velocitytrack.containsKey(player.getName()))
{
velocitytrack.put(player.getName(), velocitytrack.get(player.getName()) + 1);
if (velocitytrack.get(player.getName()) > magic.VELOCITY_MAXTIMES)
{
velocitized.put(player.getName(), System.currentTimeMillis() + magic.VELOCITY_PREVENT);
micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable()
{
@Override
public void run()
{
velocitytrack.put(player.getName(), 0);
}
}, magic.VELOCITY_SCHETIME * 20L);
return true;
}
}
else
{
velocitytrack.put(player.getName(), 0);
}
return false;
}
public void logBlockPlace(final Player player)
{
placedBlock.put(player.getName(), System.currentTimeMillis());
}
public boolean justPlaced(Player player)
{
return isDoing(player, placedBlock, magic.BLOCK_PLACE_MIN);
}
public void logAnimation(final Player player)
{
animated.put(player.getName(), System.currentTimeMillis());
increment(player, blockPunches, magic.BLOCK_PUNCH_MIN);
}
public void resetAnimation(final Player player)
{
animated.remove(player.getName());
blockPunches.put(player.getName(), 0);
}
public boolean justAnimated(Player player)
{
String name = player.getName();
if (animated.containsKey(name))
{
long time = System.currentTimeMillis() - animated.get(name);
animated.remove(player.getName());
return time < magic.ANIMATION_MIN;
}
else
{
return false;
}
}
public void logDamage(final Player player, int type)
{
long time;
switch (type)
{
case 1:
time = magic.DAMAGE_TIME;
break;
case 2:
time = magic.KNOCKBACK_DAMAGE_TIME;
break;
case 3:
time = magic.EXPLOSION_DAMAGE_TIME;
break;
default:
time = magic.DAMAGE_TIME;
break;
}
movingExempt.put(player.getName(), System.currentTimeMillis() + time);
// Only map in which termination time is calculated beforehand.
}
public void logEnterExit(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.ENTERED_EXITED_TIME);
}
public void logToggleSneak(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.SNEAK_TIME);
}
public void logTeleport(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.TELEPORT_TIME);
/* Data for fly/speed should be reset */
nofallViolation.remove(player.getName());
blocksOverFlight.remove(player.getName());
yAxisViolations.remove(player.getName());
yAxisLastViolation.remove(player.getName());
lastYcoord.remove(player.getName());
lastYtime.remove(player.getName());
}
public void logExitFly(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.EXIT_FLY_TIME);
}
public void logJoin(final Player player)
{
movingExempt.put(player.getName(), System.currentTimeMillis() + magic.JOIN_TIME);
}
public boolean isMovingExempt(Player player)
{
return isDoing(player, movingExempt, -1);
}
public boolean isAscending(Player player)
{
return isAscending.contains(player.getName());
}
public boolean isSpeedExempt(Player player)
{
return isMovingExempt(player) || justVelocity(player);
}
private <E> void logEvent(final Map<String, E> map, final Player player, final E obj, long time)
{
map.put(player.getName(), obj);
micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable()
{
@Override
public void run()
{
if (map.get(player.getName()) == obj)
{
map.remove(player.getName());
}
else
{
//Don't remove this, for some reason it's fixing chat bugs.
}
}
}, time);
}
private boolean isDoing(Player player, Map<String, Long> map, double max)
{
if (map.containsKey(player.getName()))
{
if (max != -1)
{
if (((System.currentTimeMillis() - map.get(player.getName())) / 1000) > max)
{
map.remove(player.getName());
return false;
}
else
{
return true;
}
}
else
{
// Termination time has already been calculated
if (map.get(player.getName()) < System.currentTimeMillis())
{
map.remove(player.getName());
return false;
}
else
{
return true;
}
}
}
else
{
return false;
}
}
private void checkChatLevel(Player player, int amount)
{
if (amount >= magic.CHAT_KICK_LEVEL)
{
String name = player.getName();
int kick;
if (chatKicks.get(name) == null || chatKicks.get(name) == 0)
{
kick = 1;
chatKicks.put(name, kick);
}
else
{
kick = chatKicks.get(name) + 1;
chatKicks.put(name, kick);
}
String event = kick <= magic.CHAT_BAN_LEVEL ? micromanage.getConfiguration().chatActionKick() : micromanage.getConfiguration().chatActionBan();
// Set string variables
event = event.replaceAll("&player", name).replaceAll("&world", player.getWorld().getName());
if (event.startsWith("COMMAND["))
{
String command = event.replaceAll("COMMAND\\[", "").replaceAll("]", "");
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
}
else if (event.equalsIgnoreCase("KICK"))
{
String msg = kick <= magic.CHAT_BAN_LEVEL ? ChatColor.RED + lang.getChatKickReason() + " (" + kick + "/" + magic.CHAT_BAN_LEVEL + ")" : ChatColor.RED + lang.getChatBanReason();
player.kickPlayer(msg);
msg = kick <= magic.CHAT_BAN_LEVEL ? ChatColor.RED + lang.getChatKickBroadcast() + " (" + kick + "/" + magic.CHAT_BAN_LEVEL + ")" : ChatColor.RED + lang.getChatBanBroadcast();
msg = msg.replaceAll("&player", name);
if (!msg.equals(""))
{
Bukkit.broadcastMessage(msg);
}
}
else if (event.equalsIgnoreCase("BAN"))
{
player.setBanned(true);
player.kickPlayer(ChatColor.RED + lang.getChatBanReason());
String msg = ChatColor.RED + lang.getChatBanBroadcast();
msg = msg.replaceAll("&player", name);
if (!msg.equals(""))
{
Bukkit.broadcastMessage(msg);
}
}
}
}
public int increment(Player player, Map<String, Integer> map, int num)
{
String name = player.getName();
if (map.get(name) == null)
{
map.put(name, 1);
return 1;
}
else
{
int amount = map.get(name) + 1;
if (amount < num + 1)
{
map.put(name, amount);
return amount;
}
else
{
map.put(name, num);
return num;
}
}
}
}
|
diff --git a/ui_swing/src/com/dmdirc/addons/ui_swing/textpane/BasicTextLineRenderer.java b/ui_swing/src/com/dmdirc/addons/ui_swing/textpane/BasicTextLineRenderer.java
index 0ceab49d..39a3c3ed 100644
--- a/ui_swing/src/com/dmdirc/addons/ui_swing/textpane/BasicTextLineRenderer.java
+++ b/ui_swing/src/com/dmdirc/addons/ui_swing/textpane/BasicTextLineRenderer.java
@@ -1,235 +1,236 @@
/*
* Copyright (c) 2006-2014 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.ui_swing.textpane;
import com.dmdirc.ui.messages.IRCDocument;
import com.dmdirc.ui.messages.LinePosition;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Renders basic text, line wrapping where appropriate.
*/
public class BasicTextLineRenderer implements LineRenderer {
/** Padding to add to line height. */
private static final double LINE_PADDING = 0.2;
/** Single Side padding for textpane. */
private static final int SINGLE_SIDE_PADDING = 3;
/** Both Side padding for textpane. */
private static final int DOUBLE_SIDE_PADDING = SINGLE_SIDE_PADDING * 2;
/** Render result to use. This instance is recycled for each render call. */
private final RenderResult result = new RenderResult();
private final TextPane textPane;
private final TextPaneCanvas textPaneCanvas;
private final IRCDocument document;
public BasicTextLineRenderer(final TextPane textPane, final TextPaneCanvas textPaneCanvas,
final IRCDocument document) {
this.textPane = textPane;
this.textPaneCanvas = textPaneCanvas;
this.document = document;
}
@Override
public RenderResult render(final Graphics2D graphics, final float canvasWidth,
final float canvasHeight, final float drawPosY, final int line,
final boolean bottomLine) {
result.drawnAreas.clear();
+ result.textLayouts.clear();
result.totalHeight = 0;
final AttributedCharacterIterator iterator = document.getStyledLine(line);
final int lineHeight = (int) (document.getLineHeight(line) * (LINE_PADDING + 1));
final int paragraphStart = iterator.getBeginIndex();
final int paragraphEnd = iterator.getEndIndex();
final LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(iterator,
graphics.getFontRenderContext());
lineMeasurer.setPosition(paragraphStart);
final int wrappedLine = getNumWrappedLines(lineMeasurer, paragraphStart,
paragraphEnd, canvasWidth);
float newDrawPosY = drawPosY;
if (wrappedLine > 1) {
newDrawPosY -= lineHeight * wrappedLine;
}
if (bottomLine) {
newDrawPosY += DOUBLE_SIDE_PADDING;
}
int numberOfWraps = 0;
int chars = 0;
// Loop through each wrapped line
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = checkNotNull(lineMeasurer.nextLayout(canvasWidth));
// Calculate the Y offset
if (wrappedLine == 1) {
newDrawPosY -= lineHeight;
} else if (numberOfWraps != 0) {
newDrawPosY += lineHeight;
}
// Calculate the initial X position
final float drawPosX;
if (layout.isLeftToRight()) {
drawPosX = SINGLE_SIDE_PADDING;
} else {
drawPosX = canvasWidth - layout.getAdvance();
}
// Check if the target is in range
if (newDrawPosY >= 0 || newDrawPosY <= canvasHeight) {
renderLine(graphics, (int) canvasWidth, line, drawPosX, newDrawPosY,
numberOfWraps, chars, layout);
}
numberOfWraps++;
chars += layout.getCharacterCount();
}
if (numberOfWraps > 1) {
newDrawPosY -= lineHeight * (wrappedLine - 1);
}
result.totalHeight = drawPosY - newDrawPosY;
return result;
}
protected void renderLine(final Graphics2D graphics, final int canvasWidth, final int line,
final float drawPosX, final float drawPosY, final int numberOfWraps, final int chars,
final TextLayout layout) {
graphics.setColor(textPane.getForeground());
layout.draw(graphics, drawPosX, drawPosY + layout.getDescent());
doHighlight(line, chars, layout, graphics, drawPosX, drawPosY);
result.firstVisibleLine = line;
final LineInfo lineInfo = new LineInfo(line, numberOfWraps);
result.textLayouts.put(lineInfo, layout);
result.drawnAreas.put(lineInfo,
new Rectangle(0,
(int) (drawPosY + 1.5 - layout.getAscent() + layout.getDescent()),
canvasWidth + DOUBLE_SIDE_PADDING,
(int) (layout.getAscent() + layout.getDescent())));
}
/**
* Returns the number of times a line will wrap.
*
* @param lineMeasurer LineBreakMeasurer to work out wrapping for
* @param paragraphStart Start index of the paragraph
* @param paragraphEnd End index of the paragraph
* @param formatWidth Width to wrap at
*
* @return Number of times the line wraps
*/
private int getNumWrappedLines(final LineBreakMeasurer lineMeasurer,
final int paragraphStart,
final int paragraphEnd,
final float formatWidth) {
int wrappedLine = 0;
while (lineMeasurer.getPosition() < paragraphEnd) {
lineMeasurer.nextLayout(formatWidth);
wrappedLine++;
}
lineMeasurer.setPosition(paragraphStart);
return wrappedLine;
}
/**
* Redraws the text that has been highlighted.
*
* @param line Line number
* @param chars Number of characters already handled in a wrapped line
* @param layout Current wrapped line's textlayout
* @param g Graphics surface to draw highlight on
* @param drawPosX current x location of the line
* @param drawPosY current y location of the line
*/
protected void doHighlight(final int line, final int chars,
final TextLayout layout, final Graphics2D g,
final float drawPosX, final float drawPosY) {
final LinePosition selectedRange = textPaneCanvas.getSelectedRange();
final int selectionStartLine = selectedRange.getStartLine();
final int selectionStartChar = selectedRange.getStartPos();
final int selectionEndLine = selectedRange.getEndLine();
final int selectionEndChar = selectedRange.getEndPos();
// Does this line need highlighting?
if (selectionStartLine <= line && selectionEndLine >= line) {
final int firstChar;
// Determine the first char we care about
if (selectionStartLine < line || selectionStartChar < chars) {
firstChar = 0;
} else {
firstChar = selectionStartChar - chars;
}
// ... And the last
final int lastChar;
if (selectionEndLine > line || selectionEndChar > chars + layout.getCharacterCount()) {
lastChar = layout.getCharacterCount();
} else {
lastChar = selectionEndChar - chars;
}
// If the selection includes the chars we're showing
if (lastChar > 0 && firstChar < layout.getCharacterCount() && lastChar > firstChar) {
doHighlight(line,
layout.getLogicalHighlightShape(firstChar, lastChar), g,
drawPosY, drawPosX, chars + firstChar, chars + lastChar);
}
}
}
private void doHighlight(final int line, final Shape logicalHighlightShape, final Graphics2D g,
final float drawPosY, final float drawPosX, final int firstChar, final int lastChar) {
final AttributedCharacterIterator iterator = document.getStyledLine(line);
final AttributedString as = new AttributedString(iterator, firstChar, lastChar);
as.addAttribute(TextAttribute.FOREGROUND, textPane.getBackground());
as.addAttribute(TextAttribute.BACKGROUND, textPane.getForeground());
final TextLayout newLayout = new TextLayout(as.getIterator(),
g.getFontRenderContext());
final int trans = (int) (newLayout.getDescent() + drawPosY);
g.translate(logicalHighlightShape.getBounds().getX(), 0);
newLayout.draw(g, drawPosX, trans);
g.translate(-1 * logicalHighlightShape.getBounds().getX(), 0);
}
}
| true | true | public RenderResult render(final Graphics2D graphics, final float canvasWidth,
final float canvasHeight, final float drawPosY, final int line,
final boolean bottomLine) {
result.drawnAreas.clear();
result.totalHeight = 0;
final AttributedCharacterIterator iterator = document.getStyledLine(line);
final int lineHeight = (int) (document.getLineHeight(line) * (LINE_PADDING + 1));
final int paragraphStart = iterator.getBeginIndex();
final int paragraphEnd = iterator.getEndIndex();
final LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(iterator,
graphics.getFontRenderContext());
lineMeasurer.setPosition(paragraphStart);
final int wrappedLine = getNumWrappedLines(lineMeasurer, paragraphStart,
paragraphEnd, canvasWidth);
float newDrawPosY = drawPosY;
if (wrappedLine > 1) {
newDrawPosY -= lineHeight * wrappedLine;
}
if (bottomLine) {
newDrawPosY += DOUBLE_SIDE_PADDING;
}
int numberOfWraps = 0;
int chars = 0;
// Loop through each wrapped line
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = checkNotNull(lineMeasurer.nextLayout(canvasWidth));
// Calculate the Y offset
if (wrappedLine == 1) {
newDrawPosY -= lineHeight;
} else if (numberOfWraps != 0) {
newDrawPosY += lineHeight;
}
// Calculate the initial X position
final float drawPosX;
if (layout.isLeftToRight()) {
drawPosX = SINGLE_SIDE_PADDING;
} else {
drawPosX = canvasWidth - layout.getAdvance();
}
// Check if the target is in range
if (newDrawPosY >= 0 || newDrawPosY <= canvasHeight) {
renderLine(graphics, (int) canvasWidth, line, drawPosX, newDrawPosY,
numberOfWraps, chars, layout);
}
numberOfWraps++;
chars += layout.getCharacterCount();
}
if (numberOfWraps > 1) {
newDrawPosY -= lineHeight * (wrappedLine - 1);
}
result.totalHeight = drawPosY - newDrawPosY;
return result;
}
| public RenderResult render(final Graphics2D graphics, final float canvasWidth,
final float canvasHeight, final float drawPosY, final int line,
final boolean bottomLine) {
result.drawnAreas.clear();
result.textLayouts.clear();
result.totalHeight = 0;
final AttributedCharacterIterator iterator = document.getStyledLine(line);
final int lineHeight = (int) (document.getLineHeight(line) * (LINE_PADDING + 1));
final int paragraphStart = iterator.getBeginIndex();
final int paragraphEnd = iterator.getEndIndex();
final LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(iterator,
graphics.getFontRenderContext());
lineMeasurer.setPosition(paragraphStart);
final int wrappedLine = getNumWrappedLines(lineMeasurer, paragraphStart,
paragraphEnd, canvasWidth);
float newDrawPosY = drawPosY;
if (wrappedLine > 1) {
newDrawPosY -= lineHeight * wrappedLine;
}
if (bottomLine) {
newDrawPosY += DOUBLE_SIDE_PADDING;
}
int numberOfWraps = 0;
int chars = 0;
// Loop through each wrapped line
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = checkNotNull(lineMeasurer.nextLayout(canvasWidth));
// Calculate the Y offset
if (wrappedLine == 1) {
newDrawPosY -= lineHeight;
} else if (numberOfWraps != 0) {
newDrawPosY += lineHeight;
}
// Calculate the initial X position
final float drawPosX;
if (layout.isLeftToRight()) {
drawPosX = SINGLE_SIDE_PADDING;
} else {
drawPosX = canvasWidth - layout.getAdvance();
}
// Check if the target is in range
if (newDrawPosY >= 0 || newDrawPosY <= canvasHeight) {
renderLine(graphics, (int) canvasWidth, line, drawPosX, newDrawPosY,
numberOfWraps, chars, layout);
}
numberOfWraps++;
chars += layout.getCharacterCount();
}
if (numberOfWraps > 1) {
newDrawPosY -= lineHeight * (wrappedLine - 1);
}
result.totalHeight = drawPosY - newDrawPosY;
return result;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.